full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PoshCode/Read-Choice_2.ps1
Read-Choice_2.ps1
# function Read-Choice { [CmdletBinding()] param( [Parameter(Mandatory=$true, ValueFromRemainingArguments=$true)] [hashtable[]]$Choices , [Parameter(Mandatory=$False)] [string]$Caption = "Please choose!" , [Parameter(Mandatory=$False)] [string]$Message = "Choose one of the following options:" , [Parameter(Mandatory=$False)] [int[]]$Default = 0 , [Switch]$MultipleChoice , [Switch]$Passthru ) begin { [System.Collections.DictionaryEntry[]]$choices = $choices | % { $_.GetEnumerator() } } process { $Descriptions = [System.Management.Automation.Host.ChoiceDescription[]]( $( foreach($choice in $choices) { New-Object System.Management.Automation.Host.ChoiceDescription $choice.Key,$choice.Value } ) ) if(!$MultipleChoice) { [int]$Default = $Default[0] } [int[]]$Answer = $Host.UI.PromptForChoice($Caption,$Message,$Descriptions,$Default) if($Passthru) { Write-Verbose "$Answer" Write-Output $Descriptions[$Answer] } else { Write-Output $Answer } } # }
PowerShellCorpus/PoshCode/Get-Path_1.ps1
Get-Path_1.ps1
function Get-Path { [CmdletBinding(DefaultParameterSetName="DriveQualified")] Param( [Parameter(Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [Alias("PSPath")] [String] $Path, [Parameter()] [Switch]$ResolvedPath, [Parameter(ParameterSetName="ProviderQualified")] [Switch]$ProviderQualified ) $Drive = $Provider = $null $PSPath = $PSCmdlet.SessionState.Path if($ResolvedPath -and $ProviderQualified) { $ProviderPaths = $PSPath.GetResolvedProviderPathFromPSPath($Path, [ref]$Provider) } else { $ProviderPaths = @($PSPath.GetUnresolvedProviderPathFromPSPath($Path, [ref]$Provider, [ref]$Drive)) if($ResolvedPath) { $ProviderPaths = $PSPath.GetResolvedProviderPathFromProviderPath($ProviderPaths[0], $Provider) } } foreach($p in $ProviderPaths) { if($ProviderQualified -or ($Drive -eq $null)) { if(!$PSPath.IsProviderQualified($p)) { $p = $Provider.Name + '::' + $p } } else { if($PSPath.IsProviderQualified($p)) { $p = $p -replace [regex]::Escape( ($Provider.Name + "::") ) } $p = $p.Replace($Drive.Root, $Drive.Name + ":\\") } $p } }
PowerShellCorpus/PoshCode/Backup-ModifiedGPOs_2.ps1
Backup-ModifiedGPOs_2.ps1
###########################################################################" # # NAME: Backup-ModifiedGPOs.ps1 # # AUTHOR: Jan Egil Ring # EMAIL: jan.egil.ring@powershell.no # # COMMENT: All Group Policy Objects modified in the specified timespan are backup up to the specified backup path. # For more details, see the following blog-post: # http://blog.powershell.no/2010/06/15/backing-up-group-policy-objects-using-windows-powershell # # You have a royalty-free right to use, modify, reproduce, and # distribute this script file in any way you find useful, provided that # you agree that the creator, owner above has no warranty, obligations, # or liability for such use. # # VERSION HISTORY: # 1.0 15.06.2010 - Initial release # # 1.1 17.11.2010 - Andy Helsby - Added check to create backup directory and report directory if it does not exist. # - Added optional parameter to allow backups of gpo's modified in last X days (defaults to 1 otherwise) # - Note if no group policies were modified in the previous X days, the script does throw an error about Name not being provided. # # 1.2 24.11.2010 - Added the -FirstRun switch parameter to backup all GPO`s. Added additional logic. # Requires Windows7 or 2008R2 due to grouppolicy module prerequisite. ###########################################################################" #Requires -Version 2.0 Param([switch]$FirstRun) Import-Module grouppolicy $BackupPath = "C:\\GPO Backup" $ReportPath = "C:\\GPO Backup\\Reports\\" if (!(Test-Path -path $BackupPath)) {New-Item $BackupPath -type directory} if (!(Test-Path -path $ReportPath)) {New-Item $ReportPath -type directory} if ($FirstRun) { $Timespan = (Get-Date).AddDays(-5000) } else { $Timespan = (Get-Date).AddDays(-1) } $ModifiedGPOs = Get-GPO -all | Where-Object {$_.ModificationTime -gt $Timespan} if ($ModifiedGPOs) { Write-Host "The following "$ModifiedGPOs.count" GPOs were successfully backed up:" -ForegroundColor yellow Foreach ($GPO in $ModifiedGPOs) { $GPOBackup = Backup-GPO $GPO.DisplayName -Path $BackupPath $Path = $ReportPath + $GPO.ModificationTime.Month + "-"+ $GPO.ModificationTime.Day + "-" + $GPO.ModificationTime.Year + "_" + $GPO.Displayname + "_" + $GPOBackup.Id + ".html" Get-GPOReport -Name $GPO.DisplayName -path $Path -ReportType HTML Write-Host $GPO.DisplayName } } else { Write-Host "No GPO`s modified since $Timespan. If this is your initial backup, run the script with the -FirstRun switch parameter to backup all GPO`s" -ForegroundColor yellow }
PowerShellCorpus/PoshCode/Invoke-Command on subnet.ps1
Invoke-Command on subnet.ps1
$secpasswd = ConvertTo-SecureString "here the password" -AsPlainText -Force $mycreds = New-Object System.Management.Automation.PSCredential ("Administrator@domain", $secpasswd) $subnet="192.168.0." $hosts=( New-IPRange -start ($subnet + 1) -end ($subnet + 255) | Test-Online | Get-HostName | ForEach-Object { $_.HostName.ToString() } ) $hosts Invoke-Command -ComputerName $hosts -Credential $mycreds -ScriptBlock { Write-host "Starting on host"$env:computername dir # Start-Process -wait myCommand } # ---------------------------- needed functions --------------------------- #http://powershell.com/cs/blogs/tobias/archive/2011/03/09/analyzing-networks-with-powershell.aspx function Get-IPAddress { # created by Dr. Tobias Weltner, MVP PowerShell param( [switch] $first, [Parameter(ParameterSetName='IPV4')] [switch] $IPv4, [Parameter(ParameterSetName='IPV4')] [switch] $IPv6 ) $ip = @(Get-WmiObject -Filter 'IPEnabled=true' Win32_NetworkAdapterConfiguration | Select-Object -ExpandProperty IPAddress) if ($IPv4) { $ip = $ip | Where-Object { $_ -like '*.*' }} if ($IPv6) { $ip = $ip | Where-Object { $_ -like '*:*' }} if ($ip.Count -gt 1 -and $first) { $ip[0] } else { $ip } } function New-IPRange { # created by Dr. Tobias Weltner, MVP PowerShell [CmdletBinding(DefaultParameterSetName='Automatic')] param( [Parameter(ParameterSetName='Manual')] [String] $start, [Parameter(ParameterSetName='Manual')] [String] $end, [Parameter(ParameterSetName='Automatic')] [switch] $first ) function Get-IPRange($start, $end) { $ip1 = ([System.Net.IPAddress]$start).GetAddressBytes() [Array]::Reverse($ip1) $ip1 = ([System.Net.IPAddress]($ip1 -join '.')).Address $ip2 = ([System.Net.IPAddress]$end).GetAddressBytes() [Array]::Reverse($ip2) $ip2 = ([System.Net.IPAddress]($ip2 -join '.')).Address for ($x = $ip1; $x -le $ip2; $x++) { $ip = ([System.Net.IPAddress]$x).GetAddressBytes() [Array]::Reverse($ip) $ip -join '.' } } if ($PSCmdlet.ParameterSetName -eq 'Automatic') { @(Get-IPAddress -first:$first -IPv4) | ForEach-Object { $temp = ([System.Net.IPAddress]$_).GetAddressBytes() $temp[3] = 1 [System.Net.IPAddress]$start = $temp -join '.' $temp[3] = 255 [System.Net.IPAddress]$end = $temp -join '.' Get-IPRange $start $end } } else { Get-IPRange $start $end } } function Test-Online { # created by Dr. Tobias Weltner, MVP PowerShell param( [Parameter(Mandatory=$true, ValueFromPipeline=$true)] [String] $computername, [Int32] $throttleLimit = 300 ) begin { $list = New-Object System.Collections.ArrayList } process { [void]$list.Add($computername) } end { & { do { $number = [Math]::Min($list.Count, $throttleLimit) $chunk = $list.GetRange(0, $number) $job = Test-Connection $chunk –Count 1 –asJob $job | Wait-Job | Receive-Job | Where-Object { $_.StatusCode –eq 0 } | Select-Object –expandProperty Address Remove-Job $job $list.RemoveRange(0, $number) } while ($list.Count -gt 0) } | Sort-Object { [System.Version]$_ } } } function Get-HostName { # created by Dr. Tobias Weltner, MVP PowerShell param( [Parameter(Mandatory=$true, ValueFromPipeline=$true)] [String[]] $IPAddress ) process { $IPAddress | Foreach-Object { $ip = $_ try { [System.Net.DNS]::GetHostByAddress($ip) } catch { Write-Warning “IP $ip did not return DNS information” } } } } #New-IPRange | Test-Online | Get-HostName
PowerShellCorpus/PoshCode/Get-NextPrime.ps1
Get-NextPrime.ps1
## Start with a seed list of primes you know: $global:primes = 2,3,5 #,7,11,13,17,19,23 ## This function will get the "next" one, add it to the list, and return it function Get-NextPrime { $p = $primes[-1] while($p = $p+1){ if(!$(foreach($i in $primes) { if($p%$i-eq0) { $i } })) { $global:primes += $p return $p }} }
PowerShellCorpus/PoshCode/UCS_FaultReport.ps1
UCS_FaultReport.ps1
<# .Synopsis Connects to multiple UCS environments listed in a text file and generates a basic fault report for each one, then sends one email with the results. In the report are unacknowledged faults, hardware locator LEDs that are on, and if you are short on port licenses it will show that. Variables and paths will have to be changed to match your environment. .Blog batchlife.wordpress.com #> param($CredentialFile=$null) if ($CredentialFile -eq $null) { Write-Host "Missing the path to the credential file." -BackgroundColor DarkYellow -ForegroundColor DarkRed; break } #----------------------------- # Prep #----------------------------- function Get-Now { (get-date -uformat %Y%m%d) + "_" + (get-date -uformat %H%M%S) } if ((Get-Module -Name CiscoUcsPS) -eq $null) { Import-Module -Name C:\\Ops\\Modules\\CiscoUCSPowerTool\\CiscoUcsPS.psd1 } #Static parameters Set-Variable -Name ScriptDir -Value "C:\\Scripts" -Scope Local Set-Variable -Name ReportPath -Value "C:\\Scripts\\Reports\\UCS_Fault_Reports" -Scope Local Set-Variable -Name ReportFile -Value "$($ReportPath)\\UCS_Fault_Report_$(Get-Now).html" -Scope Local Write-Verbose "`nStatic parameters`n-----------------`nScriptDir = $($ScriptDir)`nReportFile = $($ReportFile)`n" $mailTo = "alertsdistgroup@yourcompany.com" $mailFrom = "UCS_Fault_Reports@yourcompany.com" $mailSMTP = "smtp.yourcompany.com" If ( !(Test-Path $ReportPath) ) { mkdir $ReportPath } . $ScriptDir\\Hals_PSCredentials.ps1 # Setup credentials as described in http://batchlife.wordpress.com/2012/11/14/powershell-script-to-backup-a-cisco-ucs-fabric-interconnect-using-the-cisco-powertool-cmdlets/ $UcsCred = Import-PsCredential -Path $CredentialFile #----------------------------- # Start doing the real work. #----------------------------- Disconnect-Ucs 2>$null # Connect-Ucs will fail if you're already connected to a UCS "<pre>" | Out-File -FilePath $ReportFile -Width 400 Get-Date | Out-File -FilePath $ReportFile -Append -Width 400 Get-Content C:\\Scripts\\Repo\\StaticInfo\\UCSs.txt | ForEach-Object { Write-Output "==========================================================================================================" Connect-Ucs -Name $_ -Credential $UcsCred | select name,version,username,virtualipv4address | ft -a if ($DefaultUcs -eq $null) { $mailBody = @() $mailBody += "$(Get-Now) - Error connecting to UCS`n`n" $mailBody += $_ Send-MailMessage -From $mailFrom -To $mailTo -Subject "Backup-mUcs Error-- Failed connecting to $($Ucs)" -Body ($mailBody | Out-String) -SmtpServer $mailSMTP } else { Get-UcsFault | Where-Object { ($_.Severity -ne 'cleared') -and ($_.Ack -ne 'yes') } | sort lasttransition -Descending | select lasttransition,severity,status,type,dn,descr | ft -a Get-UcsLocatorLed | ? { $_.operstate -eq 'on' } | sort dn | select dn,adminstate,color,operstate,id | ft -a If (Get-UcsFault | Where-Object { ($_.Severity -ne 'cleared') -and ($_.Dn -match 'F0676') } ) { "`n------ Port Licenses Needed ----------------------------------------------------------------------------" Get-UcsLicense | Select-Object Ucs,Scope,Feature,Sku,AbsQuant,DefQuant,UsedQuant,@{n="RemQuant";e={$_.AbsQuant-$_.UsedQuant}},Status,PeerStatus,OperState,GracePeriodUsed | ft -a Get-UcsLicenseServerHostId | select ucs,rn,hostid | ft -a } Disconnect-Ucs } } | Out-File -FilePath $ReportFile -Append -Width 400 "</pre>" | Out-File -FilePath $ReportFile -Append -Width 400 $body = Get-Content $ReportFile Send-MailMessage -From $mailFrom -To $mailTo -Subject "UCS Fault Report $(Get-Date)" -Body ($body | Out-String) -BodyAsHTML -SmtpServer $mailSMTP
PowerShellCorpus/PoshCode/Require-Function.ps1
Require-Function.ps1
function Require-Function { <# .SYNOPSIS Load function when not already loaded .DESCRIPTION When a function is not loaded and there is a file <functionname>.ps1 in one of the directories listed in $env:Path it is dot sourced. To get the function in your environment you must dot source the Require-Function too. .NOTES File Name : Require-Function.ps1 Author : Bernd Kriszio - http://pauerschell.blogspot.com/ .PARAMETER FunctionName The name of the function you want to import .EXAMPLE . Require-Function <any_function_script_in_your_path> .EXAMPLE . Require-Function New-ISEFile -verbose .EXAMPLE . Require-Function New-ISEFile .EXAMPLE . Require-Function unbekanntn -verbose #> [cmdletbinding()] param ( [string] $FunctionName ) if (! (Test-Path function:$FunctionName)) { try{ Write-Verbose "Function $FunctionName not loaded" $cmd = "$($FunctionName).ps1" #"$cmd" . $cmd } catch { "$cmd could not be loaded" break; } Write-Verbose "Function $FunctionName is loaded" } else { Write-Verbose "Function $FunctionName was loaded" } }
PowerShellCorpus/PoshCode/Manual DNS Scavenging_1.ps1
Manual DNS Scavenging_1.ps1
#========================================================================== # # PowerShell Source File # # AUTHOR: Stephen Wheet # NAME: dnsscavenge.ps1 # Version: 1.2 # Date: 8/12/10 # # COMMENT: # This script was created to manually scavenge DNS records for a given # period. Specify the date of last registration and everything older # than that will be deleted. # # v1.1 - Added Network Range to filter based on network range (good for # doing one site/floor at a time) # v1.2 - Added the ability to do multiple ranges at the same time. # #========================================================================== $DeleteKey = 0 #change to 0 for only a report, 1 to delete the records #Define network range to filter on $NetworkRange = "192.168.1.*","192.168.2.*" # No-Refresh + Refresh (in Days) $TotalAgingInterval = 60 $ServerName = "DNSSERVER" #DC to connect to $ContainerName = "Domain.local" #domain name to scavenge from #Place Headers on out-put file ForEach ($Network in $NetworkRange){ $filename = "DC-" + $ServerName + "--DOMAIN-" + $ContainerName + "--AGE-" + $TotalAgingInterval + ` "--RANGE-" + $Network.Replace("*","") + ".csv" $logfile = "D:\\reports\\DNSscavenge\\$filename" $list = "Ownername,TimeStamp,Deleted" $list | format-table | Out-File "$logfile" } #end for each $MinTimeStamp = [Int](New-TimeSpan ` -Start $(Get-Date("01/01/1601 00:00")) ` -End $((Get-Date).AddDays(-$TotalAgingInterval))).TotalHours $records = Get-WMIObject -Computer $ServerName ` -Namespace "root\\MicrosoftDNS" -Class "MicrosoftDNS_AType" ` -Filter ` "ContainerName='$ContainerName' AND TimeStamp<$MinTimeStamp AND TimeStamp<>0 " ForEach ($record in $records){ $IPA = $record.IPAddress ForEach ($Network in $NetworkRange){ If ( $IPA -like $Network ){ $Ownername = $record.Ownername $TimeStamp = (Get-Date("01/01/1601")).AddHours($record.TimeStamp) Write-host "$Ownername,$IPA,$TimeStamp" $filename = "DC-" + $ServerName + "--DOMAIN-" + $ContainerName + "--AGE-" + $TotalAgingInterval + ` "--RANGE-" + $Network.Replace("*","") + ".csv" $logfile = "D:\\reports\\DNSscavenge\\$filename" # Logfile location If ($DeleteKey){ $record.psbase.Delete() If($?) { Write-host "Successfully deleted A record: $Ownername" }Else { Write-host "Could not delete A record: $Ownername, error: $($error[0])" } $list = ("$Ownername,$TimeStamp,$?") $list | format-table | Out-File -append "$logfile" }Else{ $list = ("$Ownername,$TimeStamp,No") $list | format-table | Out-File -append "$logfile" } #end if/else } #end if } #end for each } #end for each
PowerShellCorpus/PoshCode/Vim25 Crazy Magic.ps1
Vim25 Crazy Magic.ps1
cls [void][Reflection.Assembly]::LoadWithPartialName("VMware.Vim"); # generate the proxy $ws = New-WebServiceProxy -Uri "http://172.16.0.33/sdk/vimService?wsdl" ; $ws.Url = "http://172.16.0.33/sdk/vimService"; $ws.UserAgent = "VMware VI Client/4.0.0"; # I modded the host to accept HTTP requests (too big of a mess with SSL) # http://www.vmware.com/support/developer/vc-sdk/visdk400pubs/sdk40setupguide.pdf $vimClient = New-Object Vmware.Vim.VimClient; $servicecontent = $vimClient.Connect("http://172.16.0.33/sdk"); $usersession = $vimClient.Login("root","root"); # the below type will be unique to your host. for some reason the VimApi_25.ManagedObjectReference did not want to pass to the web service $myMoRef = new-object Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxy172_16_0_33_sdk_vimService_wsdl.ManagedObjectReference; $myMoRef.type = "HostSystem"; $myMoRef.Value = "ha-host"; # yet to figure out where ha-host comes from... # cookie monster your session cookies $ws.CookieContainer = $vimClient.VimService.CookieContainer; # call your favorite web service method $ret = New-Object Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxy172_16_0_33_sdk_vimService_wsdl.ManagedObjectReference; $ret = $ws.RebootHost_Task($a,$true); $ret; $vimClient.Logout(); exit # thanks jaykul for your omniscent guidance
PowerShellCorpus/PoshCode/Start-AtomToJabber.ps1
Start-AtomToJabber.ps1
########################################################################################## ## Depends on PoshXmpp.dll from http://CodePlex.com/PowerXmpp #requires -pssnapin PoshXmpp ########################################################################################## # Start-AtomToChat PowerBot@im.flosoft.biz SuperBot -ChatNick PowerBot param ( $JabberId = $( Read-Host "Bot's Jabber ID" ) ,$Password = $( Read-Host "Bot's Password" -asSecure) ,$AtomFeeds[] = @("http://groups.google.com/group/microsoft.public.windows.powershell/feed/atom_v1_0_topics.xml") ,$Chat = "PowerShell%irc.FreeNode.net@irc.im.flosoft.biz" # An IRC channel to join! ,$ChatNick = $("PowerBot$((new-object Random).Next(0,9999))") # Your nickname in IRC ) $ErrorActionPreference = "Stop" $global:PoshXmppClient = PoshXmpp\\New-Client $JabberId $Password # http://im.flosoft.biz:5280/http-poll/ PoshXmpp\\Connect-Chat $Chat $ChatNick $nnc = $global:LastNewsCheck = [DateTime]::Now.AddHours(-10) # start $feedReader = new-object Xml.XmlDocument "PRESS ANY KEY TO STOP" while(!$Host.UI.RawUI.KeyAvailable) { "Checking feeds..." foreach($feed in $AtomFeeds) { $feedReader.Load($feed) for($i = $feedReader.feed.entry.count - 1; $i -ge 0; $i--) { $e = $feedReader.feed.entry[$i] if([datetime]$e.updated -gt $global:LastNewsCheck) { PoshXmpp\\Send-Message $Chat $("{0} {1} (Posted at {2:hh:mm} by {3})" -f $e.title."#text", $e.link.href, [datetime]$e.updated, $e.author.name) [Threading.Thread]::Sleep( 1000 ) } } if( [datetime]$feedReader.feed.entry[0].updated -gt $nnc ) { $nnc = [datetime]$feedReader.feed.entry[0].updated } } $global:LastNewsCheck = $nnc # the most recent item in any feed $counter = 0 "PRESS ANY KEY TO STOP" # we're going to wait 10 * 60 seconds while(!$Host.UI.RawUI.KeyAvailable -and ($counter++ -lt 600)) { [Threading.Thread]::Sleep( 1000 ) } } $global:PoshXmppClient.Close()
PowerShellCorpus/PoshCode/Get-Path.ps1
Get-Path.ps1
function Get-Path { [CmdletBinding(DefaultParameterSetName="DriveQualified")] Param( [Parameter(Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [Alias("PSPath")] [String] $Path, [Parameter()] [Switch]$ResolvedPath, [Parameter(ParameterSetName="ProviderQualified")] [Switch]$ProviderQualified ) $Drive = $Provider = $null $PSPath = $PSCmdlet.SessionState.Path if($ResolvedPath -and $ProviderQualified) { $ProviderPaths = $PSPath.GetResolvedProviderPathFromPSPath($Path, [ref]$Provider) } else { $ProviderPaths = @($PSPath.GetUnresolvedProviderPathFromPSPath($Path, [ref]$Provider, [ref]$Drive)) if($ResolvedPath) { $ProviderPaths = $PSPath.GetResolvedProviderPathFromProviderPath($ProviderPaths[0], $Provider) } } foreach($p in $ProviderPaths) { if($ProviderQualified -or ($Drive -eq $null)) { if(!$PSPath.IsProviderQualified($p)) { $p = $Provider.Name + '::' + $p } } else { if($PSPath.IsProviderQualified($p)) { $p = $p -replace [regex]::Escape( ($Provider.Name + "::") ) } $p = $p.Replace($Drive.Root, $Drive.Name + ":") } $p } }
PowerShellCorpus/PoshCode/Set Logfile length_3.ps1
Set Logfile length_3.ps1
################################################################################ # Set-FileLines.ps1 (V 1005) # This script will maintain the PS Transcript file (default setting), or any # text file, at a fixed length, ie matching the number of lines entered. # However, omitting the lines parameter will just remove any blank lines; and # using the -Blanks switch will remove blanks from the desired length. Can be # included in $profile. # Examples: # Set-FileLines -File c:\\Scripts\\anyfile.txt # Set-FileLines 1500 -Blanks # Set-FileLines # The author can be contacted via www.SeaStarDevelopmet.Bravehost.com ################################################################################ Param ([int] $lines = 0, [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 - please enter valid filename." Exit 1 } [int]$count = 0 [int]$blankLines = 0 $encoding = 'Default' $errorActionPreference = 'SilentlyContinue' $content = (Get-Content $file) If ($lines -eq 0) { #A value of 0 lines will just remove blanks. [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) { $date = "{0:g}" -f [DateTime]::Now $tempfile = [IO.Path]::GetTempFileName() Write-Output "$date Starting maintenance on file <$file>" If ($file -like "*transcript.txt") { $encoding = 'Unicode' Stop-Transcript | Out-Null $status = $? #True if we are running transcript. } $content | ForEach-Object { $count += 1 If($count -gt $extra) { #Ignore the first $extra lines. If (($blanks) -and ($_ -match '^\\s*$')) { #Skip blank lines. $blankLines++ } Else { #Create new file. $_ | Out-File $tempfile -encoding $encoding -Append -Force } } } #End ForEach Remove-Item $file -Force If (!$?) { [System.Media.SystemSounds]::Hand.Play() Write-Warning "$($error[0]) Application terminating." Remove-Item $tempfile Break } Move-Item $tempfile -Destination $file -Force If ($lines -eq 0) { #Only interested in blank lines here. $tag = "$blankLines blank lines removed." } ElseIf ($blanks) { $tag = "$extra lines removed (+ $blankLines blank)." } Else { $tag = "$extra lines removed." } If (($file -like "*transcript.txt") -and $status) { Start-Transcript -append -path $file -force | Out-Null } Write-Output "Maintenance of file completed: $tag" } $ErrorActionPreference = 'Continue'
PowerShellCorpus/PoshCode/ASP Security Flaw Detect.ps1
ASP Security Flaw Detect.ps1
# # This script will help detect vulnerable configuration for the Padding Oracle # ASP.Net vulnerability documented in MS advisory 2416728. # cls function List-WebServerPaths($server_instance) { foreach($child in $server_instance.get_Children()) { if($child.get_SchemaClassName() -eq "IIsWebVirtualDir") { $out = $child | select SchemaClassName, Path $parent = new-object System.DirectoryServices.DirectoryEntry($child.Parent) if($root_path -ne $child.Path) { Detect-OraclePaddingSecurityFlaw $child.Path $parent.Properties["ServerComment"].ToString() } } if($child.get_SchemaClassName() -eq "IIsWebServer") { List-WebServerPaths $child } } } function Detect-OraclePaddingSecurityFlaw($virtual_directory_path, $server_comment) { $out = New-Object psobject $count = (Get-ChildItem $virtual_directory_path -Recurse | ? { $_.Name -eq "web.config" }).count Get-ChildItem $virtual_directory_path -Recurse | ? { $_.Name -eq "web.config" } | select FullName | %{ $root_web_config = $virtual_directory_path.ToString() +"\\" +"web.config" $CurrentPath = $_ if(Test-Path $CurrentPath.FullName) { if($root_web_config -eq $CurrentPath.FullName) { $resultant_obj = Check-WebConfig $server_comment $virtual_directory_path $CurrentPath.FullName $true $index = $list.Add($resultant_obj); } else { $resultant_obj = Check-WebConfig $server_comment $virtual_directory_path $CurrentPath.FullName $false $index = $list.Add($resultant_obj); } } } } # Check the web.config function Check-WebConfig($name, $server_comment, $webconfig_path, $is_root) { $out = New-Object psobject $out | add-member -MemberType NoteProperty -Name "Path" -Value $webconfig_path $out | add-member -MemberType NoteProperty -Name "Is Root" -Value $is_root $xml = [xml](Get-Content $webconfig_path); $root = $xml.get_DocumentElement(); $custom_errors = $root."system.web".customErrors; if($is_root) { $siteName = "{" +$name +"}" $out | add-member -MemberType NoteProperty -Name "Name" -Value $siteName } else { $dirName = (Get-Item $webconfig_path).DirectoryName $dirName = $dirName.Substring($dirName.LastIndexOf("\\") + 1) $siteName = "{" +$name +" - " +$dirName +"}" $out | add-member -MemberType NoteProperty -Name "Name" -Value $siteName } if($custom_errors -eq $null -and $is_root) { $out | add-member -MemberType NoteProperty -Name "Disabled" -Value $true $out | add-member -MemberType NoteProperty -Name "Non Homogenous" -Value $false } else { $status = Check-CustomErrorsMode $custom_errors $is_root $disabled_status = -not $status $out | add-member -MemberType NoteProperty -Name "Disabled" -Value $disabled_status $HomogeneityStatus = Check-CustomErrorsHomogeneity $custom_errors $out | add-member -MemberType NoteProperty -Name "Non Homogenous" -Value $HomogeneityStatus } return $out; } # Get the Page Url given the HTTP Error Code function Get-ErrorPages($error_nodes_list,$error_num) { $pageUrl = "" foreach($error_node in $error_nodes_list) { if($error_node.statusCode -ne $null) { if($error_node.statusCode -eq $error_num) { $pageUrl = $error_node.redirect } } } return $pageUrl; } # Check Error Homogeneity # Comparing the Default Error Page, 404 & 500 Error Pages function Check-CustomErrorsHomogeneity($custom_errors_list) { $HomogeneityStatusResult = $false; $error_nodes_list = ($custom_errors_list.error) $count = $error_nodes_list.Count if($count -gt 0) { $404Pages = Get-ErrorPages($error_nodes_list,404) $500Pages = Get-ErrorPages($error_nodes_list,500) } else { $404Pages = "" $500Pages = "" } $defaultRedirect = $custom_errors_list.defaultRedirect if($404Pages -eq "" -and $500Pages -eq "" -and $defaultRedirect -eq $null) { # Missing defaultRedirect in this case will cause config to be vulnerable $HomogeneityStatusResult = $true } elseif($404Pages -eq "" -and $500Pages -ne "" -and $500Pages -notcontains $defaultRedirect) { # 500 and default error pages $HomogeneityStatusResult = $true } elseif($500Pages -eq "" -and $404Pages -ne "" -and $404Pages -notcontains $defaultRedirect) { # 404 and default error pages differ $HomogeneityStatusResult = $true } elseif($500Pages -ne $404Pages) { # 404 and 500 error pages differ $HomogeneityStatusResult = $true } return $HomogeneityStatusResult; } function Get-ApplicationUsage($invalidInput, $userInput) { Write-Host -ForegroundColor Green "Note the Configuration Items Numbers above and enter the items that you need to fix for which either Attribute is true." Write-Host -ForegroundColor DarkGreen -------------------------------------------------------------- Write-Host -ForegroundColor Green - USAGE ******************************************************** Write-Host -ForegroundColor DarkGreen -------------------------------------------------------------- Write-Host -ForegroundColor Green "**** Valid User Input Example: 1-2,3,4-5 <<VALID>> *******" Write-Host -ForegroundColor Red "**** InValid User Input Example: -2,-3,, <<INVALID>>*******" Write-Host Write-Host -ForegroundColor DarkGreen "Note: Enter 0(zero) or 'exit' to terminate the shell instance." Write-Host Write-Host -ForegroundColor Blue "* Disabled - Indicates that the customError Section of the Configuration is disabled and needs to be rearmed with defaultRedirect Attribute" Write-Host -ForegroundColor DarkBlue "* Non Homogenous - Indicates that the customError Section of the Configuration is either disabled or has different Urls for different error types, it needs to be same so that the attacker does not do a differential analysis of the response." Write-Host if($invalidInput -ne $null -and $invalidInput) { Write-Host Write-Host -ForegroundColor Red $userInput " is invalid User Input. Please refer USAGE details above." Write-Host } $userInput = Read-Host -Prompt "Enter your items to fix: " return $userInput; } function Check-CustomErrorsMode($custom_errors_node, $is_root) { $mode = $custom_errors_node.mode; $defaultRedirect = $custom_errors_node.defaultRedirect if($mode -eq "off") { return $false; } elseif($defaultRedirect -eq $null -and $is_root) { return $false; } else { return $true; } } $root_path_obj = New-Object System.DirectoryServices.DirectoryEntry("IIS://localhost/W3SVC/1") foreach($child in $root_path_obj.get_Children()) { if($child.get_SchemaClassName() -eq "IIsWebVirtualDir") { $root_path = $child.Path } } $list = new-Object system.Collections.ArrayList $fix_numbers = new-Object system.Collections.ArrayList $root = New-Object System.DirectoryServices.DirectoryEntry("IIS://localhost/W3SVC") List-WebServerPaths $root [int]$arrIndex = 1; $list | %{ $_ | add-member -MemberType NoteProperty -Name "No" -Value $arrIndex;$arrIndex++; }; [string]$userInput = "" $list | select No, Name, "Is Root","Disabled", "Non Homogenous", Path | Format-Table -Wrap No, Name, "Is Root","Disabled", "Non Homogenous", Path
PowerShellCorpus/PoshCode/Get-NistNtpServer.ps1
Get-NistNtpServer.ps1
function Get-NistNtpServer { <# .SYNOPSIS Gets the list NIST NTP servers. .DESCRIPTION The Get-NistNtpServer function retrieves the list of NIST NTP server names, IP addresses, and locations. .EXAMPLE Get-NistNtpServer Returns the list of NIST NTP servers. .INPUTS None .OUTPUTS PSObject .NOTES Name: Get-NistNtpServer Author: Rich Kusak Created: 2011-12-31 LastEdit: 2011-12-31 20:46 Version: 1.0.0.0 .LINK http://tf.nist.gov/tf-cgi/servers.cgi #> [CmdletBinding()] param () begin { $uri = 'http://tf.nist.gov/tf-cgi/servers.cgi' $webClient = New-Object System.Net.WebClient $filter = "$null", 'time.nist.gov', 'global address for all servers', 'Multiple locations' $i = 0 } # begin end { try { $webpage = $webClient.DownloadString($uri) } catch { throw $_ } $list = ([regex]::Matches($webpage, 'td align = "center">.*') | Select -ExpandProperty Value) -replace '.*>' | Where { $filter -notcontains $_ } $names = $list | Select-String '.*\\.\\D{2,3}$' $ips = $list | Select-String '^(\\d{1,3}\\.){3}\\d{1,3}$' $locations = $list -like '*,*' foreach ($name in $names) { New-Object PSObject -Property @{ 'Name' = $name 'IPAddress' = $ips[$i] 'Location' = $locations[$i] } $i++ } # foreach } # end } # function Get-NistNtpServer
PowerShellCorpus/PoshCode/Set-KeepAliveTime.ps1
Set-KeepAliveTime.ps1
<# .SYNOPSIS Change the setting for TCPIP KeepAliveTime on a server or several servers. .DESCRIPTION Change the setting for TCPIP KeepAliveTime on a server or several servers. When moving mailboxes with large number of folders or very large number of items it can take a very long time to enumerate the items. Sometimes it takes over 2 hours and the connection times out. We set the TCOPIP KeepAliveTime to it's max for the move or we reset it back to normal after a move is complete. .PARAMETER Name A collection of servers to set, reset, or read the KeepAliveTime registry setting. .PARAMETER KeepAliveTime The value to set KeepAliveTime. (A decimal number can be used.) Default is '0x000dbba0' - 15 Minutes 0x000dbba0 ( 900000 decimal) 15 mnutes 0x006ddd00 (7200000 decimal) is the installed default setting of 2 hours .PARAMETER ReadOnly Read the KeepAliveTime setting for each server in the collection of Servers (should be a "get" but I am too lazy to write another script.) .PARAMETER Hours Set the collection of servers to TCPIP KeepAliveTime of <N> hours. .PARAMETER Max Set the collection of servers to the maximum TCPIP KeepAliveTime setting. Defined as 0xffffffff - essentially "Forever" .EXAMPLE $Servers = Get-MailboxServer | ?{$_.AdminDisplayVersion -match "^Version 14"} Set-KeepAliveTime -Name $Servers Sets the KeepAliveTime on all the Mailbox servers to the Default setting. .EXAMPLE $servers = get-mailboxserver | ?{$_.AdminDisplayVersion -match "^Version 14"} Set-KeepAliveTime -Name $Servers -SetMax Sets the KeepAliveTime on all the Mailbox servers to the Maximum setting. .EXAMPLE $servers = Get-ExchangeServer |?{$_.ServerRole -ne "Mailbox" -and $_.AdminDisplayVersion -match "^Version 14"} Set-KeepAliveTime -Name $Servers -Reset Sets the KeepAliveTime on all the Exchamge 2010 Servers servers (CAS, HUB, Mailbox)to the reset setting. Which can be different from default. Suppose you find a setting of 4 hours is fine for moving large mailboxes. Change the script to The 21600000 for 6 hours .NOTES This script requires PSRemoteRegistry http://psremoteregistry.codeplex.com/releases/view/65928 Explaination for TCPIP settings: http://technet.microsoft.com/en-us/library/dd349797(v=WS.10).aspx Microsoft recomends is 5 Minutes for KeepAliveTime (2/17/2010) HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Services\\Tcpip\\Parameters\\ KeepAliveTime | Reg_DWORD | 0x000493e0 (300000) Symantec recomends 15 minutes (July 15, 2011) HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Services\\Tcpip\\Parameters\\ KeepAliveTime | Reg_DWORD | 0x000dbba0 (900000) We use Symantic's recomendation as our default. #> [CmdletBinding()] Param ( [Parameter(Position = 0, Mandatory = $true,ValueFromPipeLineByPropertyName=$true)] [String[]] $Name, [Parameter(Position = 1, Mandatory = $false)] [String] $KeepAliveTime = '0x000dbba0', [Parameter(Position = 3, Mandatory = $false)] [ValidateRange(1,24)] [Int] $Hours = 0, [Parameter(Position = 2, Mandatory = $false)] [Switch] $ReadOnly, [Parameter(Position = 4, Mandatory = $false)] [Switch] $Max ) #inorder to user PSRemoteRegistry Module you must be running from <server> # this was to keep my helpers in check, of course, do whatever you need to do if($(Hostname) -match '<server>') { Import-Module PSRemoteRegistry } Else { Write-Warning "You must run this on <server> to work." Exit } # Location of KeepAliveTime Value $Key = 'System\\CurrentControlSet\\Services\\Tcpip\\Parameters\\' $Value = 'KeepAliveTime' if ($Name){ ForEach ($Server in $Name) { if (Test-Connection -Count 1 -Quiet -ComputerName $Server){ if ($ReadOnly){ Write-Verbose "Checking Server: $($Server)" Get-RegValue -ComputerName $Server -Key $key -Value $Value } ElseIf ($Max){ $KeepAliveTime = '0xffffffff' Write-Verbose "Set Max Server: $($Server)" Set-RegDWord -ComputerName $Server -Key $Key -Value $Value -Data $KeepAliveTime -Force } Else { If ($Hours -gt 0){ $KeepAliveTime = 3600000*$Hours Write-Verbose "Set Server: $($Server) to $($Hours) hours" Set-RegDWord -ComputerName $Server -Key $Key -Value $Value -Data $KeepAliveTime -Force } Else { Set-RegDWord -ComputerName $Server -Key $Key -Value $Value -Data $KeepAliveTime -Force } } } Else { Write-Warning "Server $($Server) is not responding to pings." } } } Else { Write-Warning "Could not find any servers to process." }
PowerShellCorpus/PoshCode/Select-Random v2.2.ps1
Select-Random v2.2.ps1
# --------------------------------------------------------------------------- ### <Script> ### <Author> ### Joel "Jaykul" Bennett ### </Author> ### <Description> ### Selects a random element from the collection either passed as a parameter or input via the pipeline. ### If the collection is passed in as an argument, we simply pick a random number between 0 and count-1 ### for each element you want to return, but when processing pipeline input we want to keep memory use ### to a minimum, so we use a "reservoir sampling" algorithm[1]. ### ### [1] http://gregable.com/2007/10/reservoir-sampling.html ### ### The script stores $count elements (the eventual result) at all times. It continues processing ### elements until it reaches the end of the input. For each input element $n (the count of the inputs ### so far) there is a $count/$n chance that it becomes part of the result. ### * For each previously selected element, there is a $count/($n-1) chance of it being selected ### * For the ones selected, there's a ($count/$n * 1/$count = 1/$n) chance of it being replaced, so a ### ($n-1)/$n chance of it remaining ... thus, it's cumulative probability of being among the selected ### elements after the nth input is processed is $count/($n-1) * ($n-1)/$n = $count/$n, as it should be. ### ### </Description> ### <Usage> ### $arr = 1..5; Select-Random $arr ### 1..10 | Select-Random -Count 2 ### </Usage> ### <Version>2.2.0.0</Version> ### <History> ### <V id="2.0.0.0">Rewrote using the reservoir sampling technique</V> ### <V id="2.1.0.0">Fixed a bug in 2.0 which inverted the probability and resulted in the last n items being selected with VERY high probability</V> ### <V id="2.2.0.0">Use more efficient direct random sampling if the collection is passed as an argument</V> ### </History> ### </Script> # --------------------------------------------------------------------------- param([int]$count=1, [switch]$collectionMethod, [array]$inputObject=$null) BEGIN { if ($args -eq '-?') { @" Usage: Select-Random [[-Count] <int>] [-inputObject] <array> (from pipeline) [-?] Parameters: -Count : The number of elements to select. -inputObject : The collection from which to select a random element. -collectionMethod : Collect the pipeline input instead of using reservoir -? : Display this usage information and exit Examples: PS> $arr = 1..5; Select-Random $arr PS> 1..10 | Select-Random -Count 2 "@ exit } else { $rand = new-object Random if ($inputObject) { # Write-Output $inputObject | &($MyInvocation.InvocationName) -Count $count } elseif($collectionMethod) { Write-Verbose "Collecting from the pipeline " [Collections.ArrayList]$inputObject = new-object Collections.ArrayList } else { $seen = 0 $selected = new-object object[] $count } } } PROCESS { if($_) { if($collectionMethod) { $inputObject.Add($_) | out-null } else { $seen++ if($seen -lt $count) { $selected[$seen-1] = $_ } ## For each input element $n there is a $count/$n chance that it becomes part of the result. elseif($rand.NextDouble() -lt ($count/$seen)) { ## For the ones previously selected, there's a 1/$n chance of it being replaced $selected[$rand.Next(0,$count)] = $_ } } } } END { if (-not $inputObject) { ## DO ONCE: (only on the re-invoke, not when using -inputObject) Write-Verbose "Selected $count of $seen elements." Write-Output $selected # foreach($el in $selected) { Write-Output $el } } else { Write-Verbose ("{0} elements, selecting {1}." -f $inputObject.Count, $Count) foreach($i in 1..$Count) { Write-Output $inputObject[$rand.Next(0,$inputObject.Count)] } } }
PowerShellCorpus/PoshCode/Disable hotadd-hotplug.ps1
Disable hotadd-hotplug.ps1
#Script to add a value to the VMX file of a virtual client. #This is to remove the ability to eject the network card as described in #http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1012225 # #Values within <> are relevant to the environment the script is run in. ######################################################################################################## FunctionCheckVMX { ForEach ($vmCHECK in $vmLIST) { $Error.psbase.clear()$Option = $vmCHECK.extensionData.config.extraconfig | where {$_.Key -eq "devices.hotplug"} If ($Option.value -match "false") { "Value already present in VMX file for " + $vmCHECK } Else { EditVMX } } }########################################################################################################FunctionEditVMX{ $Error.psbase.clear() $vm = Get-View (Get-VM $vmCHECK).ID $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec $vmConfigSpec.extraconfig += New-Object VMware.Vim.optionvalue $vmConfigSpec.extraconfig[0].Key="devices.hotplug" $vmConfigSpec.extraconfig[0].Value="false" $vm.ReconfigVM($vmConfigSpec) If ($Error.Count -eq 0){ "Updated VMX File for " + $vmCHECK } Else { "Error deleting " + $vmCHECK$Error[0].exception } }######################################################################################################## #Main Part of the Script #Add VMware PowerCLI Snapin add-pssnapinVMware.VimAutomation.Core #Ignore vCenter certificate error and connect to single vCenter Instance Set-PowerCLIConfiguration-InvalidCertificateAction "Ignore" -DefaultVIServerMode "single" -Confirm:$false #Connect to vCenter InstanceConnect-VIServer<vCenter IP> -user "<vCenter Logon>" -pass <password> #Create list of VM's file and log file paths $Date= get-date -uformat "%d-%m-%Y" $LogDir= "<Log Location>" $Log= $LogDir + "\\EditVM-" + $Date + ".log" $vmLIST= Get-VM | Where-Object {$_.PowerState -eq "PoweredOff"} | Where-Object {$_.Name -like "<Client Name>"} #Set error action preference to silently continue $ErrorActionPreference= 'SilentlyContinue' #Run function and write output to logfile CheckVMX| Out-File $Log #Disconnect from vCenter Instance Disconnect-VIServer-Server * -Force -Confirm:$false #Script End
PowerShellCorpus/PoshCode/Start-Verify_1.ps1
Start-Verify_1.ps1
# Author: Steven Murawski http://www.mindofroot.com # This script creates two functions (and a helper function). One starts logging all commands entered, # and the second removes the logging. # This script is similar to the Start-Transcript, but only logs the command line and not the output. # Added ";" before the command, since the "`n" did not seem to be sufficient to distinguish the lines function New-ScriptBlock() { param ([string]$scriptblock) $executioncontext.InvokeCommand.NewScriptBlock($scriptblock.trim()) } function Start-Verify () { param ($logfile = 'c:\\scripts\\powershell\\logs\\verify.txt') $lastcmd = '; get-history | select -property CommandLine -Last 1 | Out-File -Append {0}' -f $logfile Get-Content -Path function:\\prompt | ForEach-Object { $function:prompt = New-ScriptBlock ($_.toString() +"`n$lastcmd") } | Out-Null } function Stop-Verify () { $lastcmd = '; get-history.*$' Get-Content -Path function:\\prompt | ForEach-Object { $function:prompt = New-ScriptBlock ($_.tostring() -replace "$lastcmd")} | Out-Null }
PowerShellCorpus/PoshCode/VMWare Quick Migration_3.ps1
VMWare Quick Migration_3.ps1
######################################### #Name: VMWare Quick Migration Function #Author: Justin Grote <jgrote NOSPAMAT enpointe DOT com> #Credit: Inspired by Mike DiPetrillo's Quick Migration Script: http://www.mikedipetrillo.com/mikedvirtualization/2008/10/quick-migration-for-vmware-the-power-of-powershell.html #Version: 0.1 #Last Revised: 31 July 2009 # #Description: Performs the fucntional equivalent of a Hyper-V Quick Migration by suspending a VM, # moving it to a new host, and resuming it. This does not require vMotion licensing. # it works by providing required VM objects via the pipeline or the second argument, # and specifying the Destination host in the first argument. # The commeand accepts both text strings and VMHost objects for the VMHost Parameter # #Prerequisites: # Powershell v1 # VMWare PowerCLI 4.0 (May work with earlier version but not tested) # VMWare Foundation Edition or Better (for API support). May work with VMWare Server 2 but not tested. # #Instructions to Install: Save this script and import into your session with, for example, . C:\\temp\\quickmigrate.ps1 # You can also include it in your PowerCLI profile to have it automatically included. #Command Usage: get-vm MyTestVM | Quick-MigrateVM "MyTestHost2" ######################################### function QuickMigrate-VM { PARAM( $NewVMHost = "" , [VMware.VimAutomation.Client20.VirtualMachineImpl]$VMsToMigrate = $null ) BEGIN { if (!$NewVMHost){ Write-Error "No Destination VMHost Specified. You must specify a host to migrate to. `n Example: Get-VM `"Test`" | QuickMigrate-VM `"Host1`"" break } elseif ($VMsToMigrate) { Write-Output $InputObject | &($MyInvocation.InvocationName) -NewVMHost $newVMHost } else { #If NewVMHost was provided as a String, convert it into a VMHost Object. if ($NewVMHost.GetType().Name -eq "String") { set-variable -name destinationVMHost -value (get-vmhost $NewVMHost) -scope 1 } #Make sure that we have a VMHost object to work with. if (! $destinationVMHost -or (! $destinationVMHost.GetType().Name -eq "VMHostImpl")) { write-error "Destination VM Host was not found or you provided the wrong object type. Please provide a VMHostImpl object or specify the fully qualified name of a VM Host" break } write-host -fore white "===Begin Quick Migration===" } } PROCESS { $step = 0 $skip = $false #In the Event of an error, output the error, and skip the rest of the current item. #This is a workaround for the fact that "continue" doesn't work in a function process loop. trap { write-host -fore yellow "`tSKIPPED: "$_.Exception.Message set-variable -name skip -value ($true) -scope 1 continue } $vmToMigrate = $_ ### Validation Checks if($_ -is [VMware.VimAutomation.Client20.VirtualMachineImpl]) { write-host -fore white "Quick Migrating $($vmToMigrate.Name) to $NewVMHost..." } else { throw "Object Passed was not a Virtual Machine object. Object must be of type VMware.VimAutomation.Client20.VirtualMachineImpl." } # Check for connected devices if (! $skip -and (get-cddrive $vmToMigrate).ConnectionState.Connected -ieq "TRUE") { throw "Connected CD Drive. Please disconnect and try again." } if (! $skip -and (get-floppydrive $vmToMigrate).ConnectionState.Connected -ieq "TRUE") { throw "Connected Floppy Drive. Please disconnect and try again." } # Make sure the current VM Host and the Destination Host are different. $sourceVMHost = get-vmhost -vm $vmToMigrate if (! $skip -and ($sourceVMHost.Name -eq $destinationVMHost.Name)) { throw "Source and Destination Hosts are the same." } ###Validation Complete, begin Migration if (! $skip) { $step++ write-host -fore cyan "`t$($step. Suspending" $vmToMigrate.Name"..." $suspend = Suspend-VM -VM $vmToMigrate -confirm:$false } if (! $skip) { $step++ write-host -fore cyan "`t($step). Moving" $vmToMigrate.Name "to" $destinationVMHost.Name"..." $migrate = Get-VM $vmToMigrate | Move-VM -Destination $destinationVMHost } if (! $skip) { $step++ write-host -fore cyan "`t($step). Resuming" $vmToMigrate.Name"..." $resume = Start-VM -VM $vmToMigrate } write-host -fore green "`tCOMPLETED" } END { write-host -fore white "===END Quick Migration===" } }
PowerShellCorpus/PoshCode/New-ISEScript.ps1
New-ISEScript.ps1
Function New-ISEScript { $strName = $env:username $date = get-date -format d $name = Read-Host "Filename" if ($name -eq "") { $name="NewScriptTemplate_ISECommentBased" } $synopsis = Read-Host "Synopsis" if ($synopsis -eq "") { $synopsis="enter your synopsis of this script activity here" } $description = Read-Host "Description" if ($description -eq "") { $description="enter a brief description of this script here" } $syntax = Read-Host "Syntax" if ($syntax -eq "") { $syntax="enter syntax here" } $email = Read-Host "eMail Address" if ($email -eq "") { $email='myemail@mycompanyemail.com' } $example1 = Read-Host "Example 1" if ($example1 -eq "") { $example1="enter example 1 here" } $example2 = Read-Host "Example 2" if ($example2 -eq "") { $example2="enter example 2 here" } $helpurl1 = Read-Host "enter the help url 1 here" if ($helpurl1 -eq "") { $helpurl1="enter help url 1 here" } $helpurl2 = Read-Host "enter the help url 2 here" if ($helpurl2 -eq "") { $helpurl2="enter help url 2 here" } $seealso1 = Read-Host "See Also 1" if ($seealso1 -eq "") { $seealso1="enter see also 1 here" } $seealso2 = Read-Host "See Also 2" if ($seealso2 -eq "") { $seealso2="enter see also 2 here" } $seealso3 = Read-Host "See Also 3" if ($seealso3 -eq "") { $seealso3="enter see also 3 here" } $comment=@(); while($s = (Read-Host "Comment").Trim()){$comment+="$s`r`n#"} $file = New-Item -type file "$name.ps1" -force $template=@" <# .NAME $name.ps1 .SYNOPSIS $synopsis .DESCRIPTION $description .SYNTAX $syntax .EXAMPLES $example1 $example2 .NOTES AUTHOR: $strName EMAIL: $email DATE: $date COMMENT: $comment .HELPURL $helpurl1 $helpurl2 .SEEALSO $seealso1 $seealso2 $seealso3 #> #region-----royalty and version info----- ########################################################################### # # You have a royalty-free right to use, modify, reproduce, and # distribute this script file in any way you find useful, provided that # you agree that the creator, owner above has no warranty, obligations, # or liability for such use. # # VERSION HISTORY: # 1.0 $date - Initial release # ########################################################################### #endregion-----royalty and version info----- #region-----code begins here------- #todo---enter your code here #endregion-----code begins here------- "@ | out-file $file ii $file } Set-Alias new New-ISEScript
PowerShellCorpus/PoshCode/Vim25 Crazy Magic_1.ps1
Vim25 Crazy Magic_1.ps1
cls [void][Reflection.Assembly]::LoadWithPartialName("VMware.Vim"); # generate the proxy $ws = New-WebServiceProxy -Uri "http://172.16.0.33/sdk/vimService?wsdl" ; $ws.Url = "http://172.16.0.33/sdk/vimService"; $ws.UserAgent = "VMware VI Client/4.0.0"; # I modded the host to accept HTTP requests (too big of a mess with SSL) # http://www.vmware.com/support/developer/vc-sdk/visdk400pubs/sdk40setupguide.pdf $vimClient = New-Object Vmware.Vim.VimClient; $servicecontent = $vimClient.Connect("http://172.16.0.33/sdk"); $usersession = $vimClient.Login("root","root"); # the below type will be unique to your host. for some reason the VimApi_25.ManagedObjectReference did not want to pass to the web service $myMoRef = new-object Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxy172_16_0_33_sdk_vimService_wsdl.ManagedObjectReference; $myMoRef.type = "HostSystem"; $myMoRef.Value = "ha-host"; # yet to figure out where ha-host comes from... # cookie monster your session cookies $ws.CookieContainer = $vimClient.VimService.CookieContainer; # call your favorite web service method $ret = New-Object Microsoft.PowerShell.Commands.NewWebserviceProxy.AutogeneratedTypes.WebServiceProxy172_16_0_33_sdk_vimService_wsdl.ManagedObjectReference; $ret = $ws.RebootHost_Task($myMoRef,$true); $ret; $vimClient.Logout(); exit # thanks jaykul for your omniscent guidance
PowerShellCorpus/PoshCode/New-XVM_2.ps1
New-XVM_2.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/Reflection Module 4.5.ps1
Reflection Module 4.5.ps1
#requires -version 2.0 # ALSO REQUIRES Autoload for some functionality (Latest version: http://poshcode.org/3173) # You should create a Reflection.psd1 with the contents: # @{ ModuleToProcess="Reflection.psm1"; RequiredModules = @("Autoload"); GUID="64b5f609-970f-4e65-b02f-93ccf3e60cbb"; ModuleVersion="4.5.0.0" } #History: # 1.0 - First public release (March 19, 2010) # 2.0 - Private Build # - Included the Accelerator function inline # - Added a few default aliases # 3.0 - September 3, 2010 # - Included the New-ConstructorFunction feature (ripped from PowerBoots to serve a more generic and powerful purpose!) # - New-ConstructorFunction and Import-ConstructorFunctions depend on the Autoload Module: http://poshcode.org/2312 # 3.5 - January 28, 2011 # - Fixed several bugs in Add-Assembly, Get-Assembly, Get-MemberSignature # - Fixed alias exporting so aliases will show up now # - Added New-ModuleManifestFromSnapin to create module manifests from snapin assemblies # 3.6 - January 28, 2011 # - Added *basic* support for CustomPSSnapin to New-ModuleManifestFromSnapin # 3.7 - February 1, 2001 - NOT RELEASED # - Added [TransformAttribute] type # 3.8 - May 4, 2011 - NOT RELEASED # - Huge rewrite of Invoke-Generic (also published separately: http://poshcode.org/2649) # 3.9 - May 25, 2011 - NOT RELEASED # - Added "Interface" parameter to Get-Type # 4.0 - Sept 27, 2011 # - Fix conflicts with PowerShell 3 # 4.1 - Oct 27, 2011 # - Fix PowerShell 3 changes so they don't break PowerShell 2 (huy!) # 4.2 - Added Add-Enum and Add-Struct -- even though they're really more CodeGen than reflection # # 4.5 - March 2, 2013 # - Added Test-AssignableToGeneric and Get-ExtensionMethod # - Updated Read-Choice from the standalone script I use. Add-Type -TypeDefinition @" using System; using System.ComponentModel; using System.Management.Automation; using System.Collections.ObjectModel; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class TransformAttribute : ArgumentTransformationAttribute { private ScriptBlock _scriptblock; private string _noOutputMessage = "Transform Script had no output."; public override string ToString() { return string.Format("[Transform(Script='{{{0}}}')]", Script); } public override Object Transform( EngineIntrinsics engine, Object inputData) { try { Collection<PSObject> output = engine.InvokeCommand.InvokeScript( engine.SessionState, Script, inputData ); if(output.Count > 1) { Object[] transformed = new Object[output.Count]; for(int i =0; i < output.Count;i++) { transformed[i] = output[i].BaseObject; } return transformed; } else if(output.Count == 1) { return output[0].BaseObject; } else { throw new ArgumentTransformationMetadataException(NoOutputMessage); } } catch (ArgumentTransformationMetadataException) { throw; } catch (Exception e) { throw new ArgumentTransformationMetadataException(string.Format("Transform Script threw an exception ('{0}'). See `$Error[0].Exception.InnerException.InnerException for more details.",e.Message), e); } } public TransformAttribute() { this.Script = ScriptBlock.Create("{`$args}"); } public TransformAttribute( ScriptBlock Script ) { this.Script = Script; } public ScriptBlock Script { get { return _scriptblock; } set { _scriptblock = value; } } public string NoOutputMessage { get { return _noOutputMessage; } set { _noOutputMessage = value; } } } "@ function Get-Type { <# .Synopsis Gets the types that are currenty loaded in .NET, or gets information about a specific type .Description Gets information about one or more loaded types, or gets the possible values for an enumerated type or value. .Example Get-Type Gets all loaded types (takes a VERY long time to print out) .Example Get-Type -Assembly ([PSObject].Assembly) Gets types from System.Management.Automation .Example [Threading.Thread]::CurrentThread.ApartmentState | Get-Type Gets all of the possible values for the ApartmentState property .Example [Threading.ApartmentState] | Get-Type Gets all of the possible values for an apartmentstate #> [CmdletBinding(DefaultParameterSetName="Assembly")] param( # The Assemblies to search for types. # Can be an actual Assembly object or a regex to pass to Get-Assembly. [Parameter(ValueFromPipeline=$true)] [PsObject[]]$Assembly, # The type name(s) to search for (wildcard patterns allowed). [Parameter(Mandatory=$false,Position=0)] [SupportsWildCards()] [String[]]$TypeName, # A namespace to restrict where we selsect types from (wildcard patterns allowed). [Parameter(Mandatory=$false)] [SupportsWildCards()] [String[]]$Namespace, # A Base type they should derive from (wildcard patterns allowed). [Parameter(Mandatory=$false)] [SupportsWildCards()] [String[]]$BaseType, # An interface they should implement (wildcard patterns allowed). [Parameter(Mandatory=$false)] [SupportsWildCards()] [String[]]$Interface, # An Custom Attribute which should decorate the class [Parameter(Mandatory=$false)] [SupportsWildCards()] [String[]]$Attribute, # The enumerated value to get all of the possible values of [Parameter(ParameterSetName="Enum")] [PSObject]$Enum, # Causes Private types to be included [Parameter()][Alias("Private","ShowPrivate")] [Switch]$Force ) process { if($psCmdlet.ParameterSetName -eq 'Enum') { if($Enum -is [Enum]) { [Enum]::GetValues($enum.GetType()) } elseif($Enum -is [Type] -and $Enum.IsEnum) { [Enum]::GetValues($enum) } else { throw "Specified Enum is neither an enum value nor an enumerable type" } } else { if($Assembly -as [Reflection.Assembly[]]) { ## This is what we expected, move along } elseif($Assembly -as [String[]]) { $Assembly = Get-Assembly $Assembly } elseif(!$Assembly) { $Assembly = [AppDomain]::CurrentDomain.GetAssemblies() } :asm foreach ($asm in $assembly) { Write-Verbose "Testing Types from Assembly: $($asm.Location)" if ($asm) { trap { if( $_.Exception.LoaderExceptions -and $_.Exception.LoaderExceptions[0] -is [System.IO.FileNotFoundException] ) { $PSCmdlet.WriteWarning( "Unable to load some types from $($asm.Location), required assemblies were not found. Use -Debug to see more detail") continue asm } Write-Error "Unable to load some types from $($asm.Location). Try with -Debug to see more detail" Write-Debug $( $_.Exception.LoaderExceptions | Out-String ) continue asm } $asm.GetTypes() | Where { ( $Force -or $_.IsPublic ) -AND ( !$Namespace -or $( foreach($n in $Namespace) { $_.Namespace -like $n } ) ) -AND ( !$TypeName -or $( foreach($n in $TypeName) { $_.Name -like $n -or $_.FullName -like $n } ) -contains $True ) -AND ( !$Attribute -or $( foreach($n in $Attribute) { $_.CustomAttributes | ForEach { $_.AttributeType.Name -like $n -or $_.AttributeType.FullName -like $n } } ) -contains $True ) -AND ( !$BaseType -or $( foreach($n in $BaseType) { $_.BaseType -like $n } ) -contains $True ) -AND ( !$Interface -or @( foreach($n in $Interface) { $_.GetInterfaces() -like $n } ).Count -gt 0 ) } } } } } } function Add-Assembly { #.Synopsis # Load assemblies #.Description # Load assemblies from a folder #.Parameter Path # Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.). #.Parameter Passthru # Returns System.Runtime objects that represent the types that were added. By default, this cmdlet does not generate any output. # Aliased to -Types #.Parameter Recurse # Gets the items in the specified locations and in all child items of the locations. # # Recurse works only when the path points to a container that has child items, such as C:\\Windows or C:\\Windows\\*, and not when it points to items that do not have child items, such as C:\\Windows\\*.dll [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("PSPath")] [string[]]$Path = ".", [Alias("Types")] [Switch]$Passthru, [Switch]$Recurse ) process { foreach($file in Get-ChildItem $Path -Filter *.dll -Recurse:$Recurse) { Add-Type -Path $file.FullName -Passthru:$Passthru | Where { $_.IsPublic } } } } function Get-Assembly { <# .Synopsis Get a list of assemblies available in the runspace .Description Returns AssemblyInfo for all the assemblies available in the current AppDomain, optionally filtered by partial name match .Parameter Name A regex to filter the returned assemblies. This is matched against the .FullName or Location (path) of the assembly. #> [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true, Position=0)] [string[]]$Name = '' ) process { [appdomain]::CurrentDomain.GetAssemblies() | Where { $Assembly = $_ if($Name){ $( foreach($n in $Name){ if(Resolve-Path $n -ErrorAction 0) { $n = [Regex]::Escape( (Resolve-Path $n).Path ) } $Assembly.FullName -match $n -or $Assembly.Location -match $n -or ($Assembly.Location -and (Split-Path $Assembly.Location) -match $n) } ) -contains $True } else { $true } } } } function Update-PSBoundParameters { #.Synopsis # Ensure a parameter value is set #.Description # Update-PSBoundParameters takes the name of a parameter, a default value, and optionally a min and max value, and ensures that PSBoundParameters has a value for it. #.Parameter Name # The name (key) of the parameter you want to set in PSBoundParameters #.Parameter Default # A Default value for the parameter, in case it's not already set #.Parameter Min # The Minimum allowed value for the parameter #.Parameter Max # The Maximum allowed value for the parameter #.Parameter PSBoundParameters # The PSBoundParameters you want to affect (this picks the local PSBoundParameters object, so you shouldn't have to set it) Param( [Parameter(Mandatory=$true, Position=0)] [String]$Name, [Parameter(Mandatory=$false, Position=1)] $Default, [Parameter()] $Min, [Parameter()] $Max, [Parameter(Mandatory=$true, Position=99)] $PSBoundParameters=$PSBoundParameters ) end { $outBuffer = $null ## If it's not set, and you passed a default, we set it to the default if($Default) { if (!$PSBoundParameters.TryGetValue($Name, [ref]$outBuffer)) { $PSBoundParameters[$Name] = $Default } } ## If you passed a $max, and it's set greater than $max, we set it to $max if($Max) { if ($PSBoundParameters.TryGetValue($Name, [ref]$outBuffer) -and $outBuffer -gt $Max) { $PSBoundParameters[$Name] = $Max } } ## If you passed a $min, and it's set less than $min, we set it to $min if($Min) { if ($PSBoundParameters.TryGetValue($Name, [ref]$outBuffer) -and $outBuffer -lt $Min) { $PSBoundParameters[$Name] = $Min } } $PSBoundParameters } } function Get-Constructor { <# .Synopsis Returns RuntimeConstructorInfo for the (public) constructor methods of the specified Type. .Description Get the RuntimeConstructorInfo for a type and add members "Syntax," "SimpleSyntax," and "Definition" to each one containing the syntax information that can use to call that constructor. .Parameter Type The type to get the constructor for .Parameter Force Force inclusion of Private and Static constructors which are hidden by default. .Parameter NoWarn Serves as the replacement for the broken -WarningAction. If specified, no warnings will be written for types without public constructors. .Example Get-Constructor System.IO.FileInfo Description ----------- Gets all the information about the single constructor for a FileInfo object. .Example Get-Type System.IO.*info mscorlib | Get-Constructor -NoWarn | Select Syntax Description ----------- Displays the constructor syntax for all of the *Info objects in the System.IO namespace. Using -NoWarn supresses the warning about System.IO.FileSystemInfo not having constructors. .Example $path = $pwd $driveName = $pwd.Drive $fileName = "$Profile" Get-Type System.IO.*info mscorlib | Get-Constructor -NoWarn | ForEach-Object { Invoke-Expression $_.Syntax } Description ----------- Finds and invokes the constructors for DirectoryInfo, DriveInfo, and FileInfo. Note that we pre-set the parameters for the constructors, otherwise they would fail with null arguments, so this example isn't really very practical. #> [CmdletBinding()] param( [Parameter(Mandatory=$true, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("ParameterType")] [Type]$Type, [Switch]$Force, [Switch]$NoWarn ) process { $type.GetConstructors() | Where-Object { $Force -or $_.IsPublic -and -not $_.IsStatic } -OutVariable ctor if(!$ctor -and !$NoWarn) { Write-Warning "There are no public constructors for $($type.FullName)" } } } function Get-ExtensionMethod { <# .Synopsis Finds Extension Methods which target the specified type .Example Get-ExtensionMethod String Finds all extension methods which target strings #> [CmdletBinding()] param( # The type name to find Extension Methods for [Parameter(Mandatory=$false,Position=0)] [SupportsWildCards()] [String[]]$TargetTypeName, # A filter for the Extension Method name [Parameter(Mandatory=$false)] [SupportsWildCards()] [String[]]$Name = "*", # The type to search for Extension Methods (defaults to search all types) [Parameter(Mandatory=$false,Position=99)] [SupportsWildCards()] [String[]]$TypeName = "*" ) process { Get-Type -TypeName $TypeName -Attribute ExtensionAttribute | Get-Method -Name $Name -BindingFlags "Static,Public,NonPublic" -Attribute ExtensionAttribute | ForEach-Object { $Method = $_ $ParameterType = $_.GetParameters()[0].ParameterType ForEach($T in $TargetTypeName) { Write-Verbose "Is '$T' a '$ParameterType'?" if($ParameterType.Name -like $T -or $ParameterType.FullName -like $T) { Write-Verbose "The name '$T' matches '$ParameterType'" Add-Member -Input $Method -Type NoteProperty -Name ParamBlock -Value (Get-MemberSignature $Method -ParamBlock) -Force Write-Output $Method continue } if($ParameterType.IsGenericType) { $interface = $null if(Test-AssignableToGeneric $T $ParameterType -interface ([ref]$interface)) { # if([GenericHelper]::IsAssignableToGenericType( $T, $ParameterType )) { Write-Verbose "'$T' is a generic that's assignable to '$ParameterType'" Add-Member -Input $Method -Type NoteProperty -Name Extends -Value $interface.Value -Force Add-Member -Input $Method -Type NoteProperty -Name ParamBlock -Value (Get-MemberSignature $Method -GenericArguments $interface.GetGenericArguments() -ParamBlock) -Force Write-Output $Method continue } } else { if($ParameterType.IsAssignableFrom($T)) { Write-Verbose "'$ParameterType' is assignable from '$T'" Add-Member -Input $Method -Type NoteProperty -Name ParamBlock -Value (Get-MemberSignature $Method -ParamBlock) -Force Write-Output $Method continue } } } } } } function Test-AssignableToGeneric { <# .Synopsis Determine if a specific type can be cast to the given generic type #> param( # The concrete type you want to test generics against [Parameter(Position=0, Mandatory = $true)] [Type]$type, # A Generic Type to test [Parameter(ValueFromPipeline=$true, Position=1, Mandatory = $true)] [Type]$genericType, # Check the GenericTypeDefinition of the GenericType (in case it's typed) [Switch]$force, # If the type is assignable because of an interface, return that interface here [Parameter(Position=2)] [ref]$interface = [ref]$null ) process { $interfaces = $type.GetInterfaces() if($type.IsGenericType -and ($type.GetGenericTypeDefinition().equals($genericType))) { return $true } foreach($i in $interfaces) { if($i.IsGenericType -and $i.GetGenericTypeDefinition().Equals($genericType)) { $interface.Value = $i return $true } if($i.IsGenericType -and $i.GetGenericTypeDefinition().Equals($genericType.GetGenericTypeDefinition())) { $genericTypeArgs = @($genericType.GetGenericArguments())[0] if(($genericTypeArgs.IsGenericParameter -and $genericTypeArgs.BaseType.IsAssignableFrom( @($i.GetGenericArguments())[0] ) ) -or $genericTypeArgs.IsAssignableFrom( @($i.GetGenericArguments())[0] )) { $interface.Value = $i return $true } } } if($force -and $genericType -ne $genericType.GetGenericTypeDefinition()) { if(Test-AssignableToGeneric $type $genericType.GetGenericTypeDefinition()) { return $true } } $base = $type.BaseType if(!$base) { return $false } Test-AssignableToGeneric $base $genericType } } function Get-Method { <# .Synopsis Returns MethodInfo for the (public) methods of the specified Type. .Description Get the MethodInfo for a type and add members "Syntax," "SimpleSyntax," and "Definition" to each one containing the syntax information that can use to call that method. .Parameter Type .Parameter Name .Parameter Force #> [CmdletBinding(DefaultParameterSetName="Type")] param( # The type to get methods from [Parameter(ParameterSetName="Type", Mandatory=$true, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$true, Position=0)] [Type]$Type, # The name(s) of the method(s) you want to retrieve (Accepts Wildcard Patterns) [Parameter(Mandatory=$false, Position=1)] [SupportsWildCards()] [PSDefaultValue(Help='*')] [String[]]$Name ="*", # Force inclusion of Private methods and property accessors which are hidden by default. [Switch]$Force, # The Binding Flags filter the output. defaults to returning all methods, static or instance [PSDefaultValue(Help='Instance,Static,Public')] [System.Reflection.BindingFlags]$BindingFlags = $(if($Force){"Instance,Static,Public,NonPublic"} else {"Instance,Static,Public"}), # An Custom Attribute which should decorate the class [Parameter(Mandatory=$false)] [SupportsWildCards()] [String[]]$Attribute ) process { Write-Verbose "[$($type.FullName)].GetMethods(`"$BindingFlags`")" Write-Verbose "[$($type.FullName)].GetConstructors(`"$BindingFlags`")" Write-Verbose "Filter by Name -like '$Name'" $Type.GetMethods($BindingFlags) + $type.GetConstructors($BindingFlags) | Where-Object { # Hide the Property accessor methods ($Force -or !$_.IsSpecialName -or $_.Name -notmatch "^get_|^set_") -AND # And Filter by Name, if necessary ($Name -eq "*" -or ($( foreach($n in $Name) { $_.Name -like $n } ) -contains $True)) -AND (!$Attribute -or $( foreach($n in $Attribute) { $_.CustomAttributes | ForEach { $_.AttributeType.Name -like $n -or $_.AttributeType.FullName -like $n } } ) -contains $True ) } } } if(!($RMI = Get-TypeData System.Reflection.RuntimeMethodInfo) -or !$RMI.Members.ContainsKey("TypeName")) { Update-TypeData -TypeName System.Reflection.RuntimeMethodInfo -MemberName "TypeName" -MemberType ScriptProperty -Value { $this.ReflectedType.FullName } Update-TypeData -TypeName System.Reflection.RuntimeMethodInfo -MemberName "Definition" -MemberType ScriptProperty -Value { Get-MemberSignature $this -Simple } Update-TypeData -TypeName System.Reflection.RuntimeMethodInfo -MemberName "Syntax" -MemberType AliasProperty -Value "Definition" Update-TypeData -TypeName System.Reflection.RuntimeMethodInfo -MemberName "SafeSyntax" -MemberType ScriptProperty -Value { Get-MemberSignature $this } } function Get-MemberSignature { <# .Synopsis Get the powershell signature for calling a member. #> [CmdletBinding(DefaultParameterSetName="CallSignature")] param( # The Method we're getting the signature for [Parameter(ValueFromPipeline=$true,Mandatory=$true,Position=0)] [System.Reflection.MethodBase]$MethodBase, [Parameter(Mandatory=$false, Position=1)] [Type[]]$GenericArguments, # Return the simplified markup [Parameter(ParameterSetName="CallSignature")] [Switch]$Simple, # Return a param block [Parameter(ParameterSetName="ParamBlock")] [Switch]$ParamBlock ) process { if($PSCmdlet.ParameterSetName -eq "ParamBlock") { $Simple = $true } $parameters = $( foreach($param in $MethodBase.GetParameters()) { # Write-Host $param.ParameterType.FullName.TrimEnd('&'), $param.Name -fore cyan # Write-Verbose "$($param.ParameterType.UnderlyingSystemType.FullName) - $($param.ParameterType)" $paramType = $param.ParameterType Write-Verbose "$(if($paramType.IsGenericType){'Generic: '})$($GenericArguments)" if($paramType.IsGenericType -and $GenericArguments) { try { $paramType = $paramType.GetGenericTypeDefinition().MakeGenericType( $GenericArguments ) } catch { continue } } if($paramType.Name.EndsWith('&')) { $ref = '[ref]' } else { $ref = '' } if($paramType.IsArray) { $array = ',' } else { $array = '' } if($ParamBlock) { '[Parameter(Mandatory=$true)]{0}[{1}]${2}' -f $ref, $paramType.ToString().TrimEnd('&'), $param.Name } elseif($Simple) { '[{0}] {2}' -f $paramType.ToString().TrimEnd('&'), $param.Name } else { '{0}({1}[{2}]${3})' -f $ref, $array, $paramType.ToString().TrimEnd('&'), $param.Name } } ) if($PSCmdlet.ParameterSetName -eq "ParamBlock") { $parameters -join ', ' } elseif($MethodBase.IsConstructor) { "New-Object $($MethodBase.ReflectedType.FullName) $($parameters -join ', ')" } elseif($Simple) { "$($MethodBase.ReturnType.FullName) $($MethodBase.Name)($($parameters -join ', '))" } elseif($MethodBase.IsStatic) { "[$($MethodBase.ReturnType.FullName)] [$($MethodBase.ReflectedType.FullName)]::$($MethodBase.Name)($($parameters -join ', '))" } else { "[$($MethodBase.ReturnType.FullName)] `$$($MethodBase.ReflectedType.Name)Object.$($MethodBase.Name)($($parameters -join ', '))" } } } function Read-Choice { [CmdletBinding()] param( [Parameter(Mandatory=$true, ValueFromRemainingArguments=$true)] [hashtable[]]$Choices, [Parameter(Mandatory=$False)] [string]$Caption = "Please choose!", [Parameter(Mandatory=$False)] [string]$Message = "Choose one of the following options:", [Parameter(Mandatory=$False)] [int[]]$Default = 0, [Switch]$MultipleChoice, [Switch]$Passthru ) begin { [System.Collections.DictionaryEntry[]]$choices = $choices | % { $_.GetEnumerator() } } process { $Descriptions = [System.Management.Automation.Host.ChoiceDescription[]]( $( foreach($choice in $choices) { New-Object System.Management.Automation.Host.ChoiceDescription $choice.Key,$choice.Value } ) ) if(!$MultipleChoice) { [int]$Default = $Default[0] } [int[]]$Answer = $Host.UI.PromptForChoice($Caption,$Message,$Descriptions,$Default) if($Passthru) { Write-Verbose "$Answer" Write-Output $Descriptions[$Answer] } else { Write-Output $Answer } } } function Read-Choice { <# .Synopsis Prompt the user for a choice, and return the (0-based) index of the selected item .Parameter Message This is the prompt that will be presented to the user. Basically, the question you're asking. .Parameter Choices An array of strings representing the choices (or menu items), with optional ampersands (&) in them to mark (unique) characters which can be used to select each item. .Parameter ChoicesWithHelp A Hashtable where the keys represent the choices (or menu items), with optional ampersands (&) in them to mark (unique) characters which can be used to select each item, and the values represent help text to be displayed to the user when they ask for help making their decision. .Parameter Default The (0-based) index of the menu item to select by default (defaults to zero). .Parameter MultipleChoice Prompt the user to select more than one option. This changes the prompt display for the default PowerShell.exe host to show the options in a column and allows them to choose multiple times. Note: when you specify MultipleChoice you may also specify multiple options as the default! .Parameter Caption An additional caption that can be displayed (usually above the Message) as part of the prompt .Parameter Passthru Causes the Choices objects to be output instead of just the indexes .Example Read-Choice "WEBPAGE BUILDER MENU" "&Create Webpage","&View HTML code","&Publish Webpage","&Remove Webpage","E&xit" .Example [bool](Read-Choice "Do you really want to do this?" "&No","&Yes" -Default 1) This example takes advantage of the 0-based index to convert No (0) to False, and Yes (1) to True. It also specifies YES as the default, since that's the norm in PowerShell. .Example Read-Choice "Do you really want to delete them all?" @{"&No"="Do not delete all files. You will be prompted to delete each file individually."; "&Yes"="Confirm that you want to delete all of the files"} Note that with hashtables, order is not guaranteed, so "Yes" will probably be the first item in the prompt, and thus will output as index 0. Because of thise, when a hashtable is passed in, we default to Passthru output. #> [CmdletBinding(DefaultParameterSetName="HashtableWithHelp")] param( [Parameter(Mandatory=$true, Position = 10, ParameterSetName="HashtableWithHelp")] [Hashtable]$ChoicesWithHelp , [Parameter(Mandatory=$true, Position = 10, ParameterSetName="StringArray")] [String[]]$Choices , [Parameter(Mandatory=$False)] [string]$Caption = "Please choose!" , [Parameter(Mandatory=$False, Position=0)] [string]$Message = "Choose one of the following options:" , [Parameter(Mandatory=$False)] [int[]]$Default = 0 , [Switch]$MultipleChoice , [Switch]$Passthru ) begin { if($ChoicesWithHelp) { [System.Collections.DictionaryEntry[]]$choices = $ChoicesWithHelp.GetEnumerator() | %{$_} } } process { $Descriptions = [System.Management.Automation.Host.ChoiceDescription[]]( $( if($choices -is [String[]]) { foreach($choice in $choices) { New-Object System.Management.Automation.Host.ChoiceDescription $choice } } else { foreach($choice in $choices) { New-Object System.Management.Automation.Host.ChoiceDescription $choice.Key, $choice.Value } } ) ) # Passing an array as the $Default triggers multiple choice prompting. if(!$MultipleChoice) { [int]$Default = $Default[0] } [int[]]$Answer = $Host.UI.PromptForChoice($Caption,$Message,$Descriptions,$Default) if($Passthru -or !($choices -is [String[]])) { Write-Verbose "$Answer" Write-Output $Descriptions[$Answer] } else { Write-Output $Answer } } } function Get-Argument { param( [Type]$Target, [ref]$Method, [Array]$Arguments ) end { trap { write-error $_ break } $flags = [System.Reflection.BindingFlags]"public,ignorecase,invokemethod,instance" [Type[]]$Types = @( foreach($arg in $Arguments) { if($arg -is [type]) { $arg } else { $arg.GetType() } } ) try { Write-Verbose "[$($Target.FullName)].GetMethod('$($Method.Value)', [$($Flags.GetType())]'$flags', `$null, ([Type[]]($(@($Types|%{$_.Name}) -join ','))), `$null)" $MethodBase = $Target.GetMethod($($Method.Value), $flags, $null, $types, $null) $Arguments if($MethodBase) { $Method.Value = $MethodBase.Name } } catch { } if(!$MethodBase) { Write-Verbose "Try again to get $($Method.Value) Method on $($Target.FullName):" $MethodBase = Get-Method $target $($Method.Value) if(@($MethodBase).Count -gt 1) { $i = 0 $i = Read-Choice -Choices $(foreach($mb in $MethodBase) { @{ "$($mb.SafeSyntax) &$($i = $i+1;$i)`b`n" = $mb.SafeSyntax } }) -Default ($MethodBase.Count-1) -Caption "Choose a Method." -Message "Please choose which method overload to invoke:" [System.Reflection.MethodBase]$MethodBase = $MethodBase[$i] } ForEach($parameter in $MethodBase.GetParameters()) { $found = $false For($a =0;$a -lt $Arguments.Count;$a++) { if($argument[$a] -as $parameter.ParameterType) { Write-Output $argument[$a] if($a -gt 0 -and $a -lt $Arguments.Count) { $Arguments = $Arguments | Select -First ($a-1) -Last ($Arguments.Count -$a) } elseif($a -eq 0) { $Arguments = $Arguments | Select -Last ($Arguments.Count - 1) } else { # a -eq count $Arguments = $Arguments | Select -First ($Arguments.Count - 1) } $found = $true break } } if(!$Found) { $userInput = Read-Host "Please enter a [$($parameter.ParameterType.FullName)] value for $($parameter.Name)" if($userInput -match '^{.*}$' -and !($userInput -as $parameter.ParameterType)) { Write-Output ((Invoke-Expression $userInput) -as $parameter.ParameterType) } else { Write-Output ($userInput -as $parameter.ParameterType) } } } } } } function Invoke-Member { [CmdletBinding()] param( [parameter(position=10, valuefrompipeline=$true, mandatory=$true)] [allowemptystring()] $InputObject, [parameter(position=0, mandatory=$true)] [validatenotnullorempty()] $Member, [parameter(position=1, valuefromremainingarguments=$true)] [allowemptycollection()] $Arguments, [parameter()] [switch]$Static ) # begin { # if(!(get-member SafeSyntax -input $Member -type Property)){ # if(get-member Name -inpup $Member -Type Property) { # $Member = Get-Method $InputObject $Member.Name # } else { # $Member = Get-Method $InputObject $Member # } # } # $SafeSyntax = [ScriptBlock]::Create( $Member.SafeSyntax ) # } process { # if ($InputObject) # { # if ($InputObject | Get-Member $Member -static:$static) # { if ($InputObject -is [type]) { $target = $InputObject } else { $target = $InputObject.GetType() } if(Get-Member $Member -InputObject $InputObject -Type Properties) { $_.$Member } elseif($Member -match "ctor|constructor") { $Member = ".ctor" [System.Reflection.BindingFlags]$flags = "CreateInstance" $InputObject = $Null } else { [System.Reflection.BindingFlags]$flags = "IgnoreCase,Public,InvokeMethod" if($Static) { $flags = "$Flags,Static" } else { $flags = "$Flags,Instance" } } [ref]$Member = $Member [Object[]]$Parameters = Get-Argument $Target $Member $Arguments [string]$Member = $Member.Value Write-Verbose $(($Parameters | %{ '[' + $_.GetType().FullName + ']' + $_ }) -Join ", ") try { Write-Verbose "Invoking $Member on [$target]$InputObject with [$($Flags.GetType())]'$flags' and [$($Parameters.GetType())]($($Parameters -join ','))" Write-Verbose "[$($target.FullName)].InvokeMember('$Member', [System.Reflection.BindingFlags]'$flags', `$null, '$InputObject', ([object[]]($(($Parameters | %{ '[' + $_.GetType().FullName + ']''' + $_ + ''''}) -join', '))))" $target.InvokeMember($Member, [System.Reflection.BindingFlags]"$flags", $null, $InputObject, $Parameters) } catch { Write-Warning $_.Exception if ($_.Exception.Innerexception -is [MissingMethodException]) { write-warning "Method argument count (or type) mismatch." } } # } else { # write-warning "Method $Member not found." # } # } } } function Invoke-Generic { #.Synopsis # Invoke Generic method definitions via reflection: [CmdletBinding()] param( [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [Alias('On')] $InputObject, [Parameter(Position=1,ValueFromPipelineByPropertyName=$true)] [Alias('Named')] [string]$MethodName, [Parameter(Position=2)] [Alias("Types")] [Type[]]$ParameterTypes, [Parameter(Position=4, ValueFromRemainingArguments=$true, ValueFromPipelineByPropertyName=$true)] [Object[]]$WithArgs, [Switch]$Static ) begin { if($Static) { $BindingFlags = [System.Reflection.BindingFlags]"IgnoreCase,Public,Static" } else { $BindingFlags = [System.Reflection.BindingFlags]"IgnoreCase,Public,Instance" } } process { $Type = $InputObject -as [Type] if(!$Type) { $Type = $InputObject.GetType() } if($WithArgs -and -not $ParameterTypes) { $ParameterTypes = $withArgs | % { $_.GetType() } } elseif(!$ParameterTypes) { $ParameterTypes = [Type]::EmptyTypes } trap { continue } $MemberInfo = $Type.GetMethod($MethodName, $BindingFlags) if(!$MemberInfo) { $MemberInfo = $Type.GetMethod($MethodName, $BindingFlags, $null, $NonGenericArgumentTypes, $null) } if(!$MemberInfo) { $MemberInfo = $Type.GetMethods($BindingFlags) | Where-Object { $MI = $_ [bool]$Accept = $MI.Name -eq $MethodName if($Accept){ Write-Verbose "$Accept = $($MI.Name) -eq $($MethodName)" [Array]$GenericTypes = @($MI.GetGenericArguments() | Select -Expand Name) [Array]$Parameters = @($MI.GetParameters() | Add-Member ScriptProperty -Name IsGeneric -Value { $GenericTypes -Contains $this.ParameterType } -Passthru) $Accept = $ParameterTypes.Count -eq $Parameters.Count Write-Verbose " $Accept = $($Parameters.Count) Arguments" if($Accept) { for($i=0;$i -lt $Parameters.Count;$i++) { $Accept = $Accept -and ( $Parameters[$i].IsGeneric -or ($ParameterTypes[$i] -eq $Parameters[$i].ParameterType)) Write-Verbose " $Accept =$(if($Parameters[$i].IsGeneric){' GENERIC or'}) $($ParameterTypes[$i]) -eq $($Parameters[$i].ParameterType)" } } } return $Accept } | Sort { @($_.GetGenericArguments()).Count } | Select -First 1 } Write-Verbose "Time to make generic methods." Write-Verbose $MemberInfo [Type[]]$GenericParameters = @() [Array]$ConcreteTypes = @($MemberInfo.GetParameters() | Select -Expand ParameterType) for($i=0;$i -lt $ParameterTypes.Count;$i++){ Write-Verbose "$($ParameterTypes[$i]) ? $($ConcreteTypes[$i] -eq $ParameterTypes[$i])" if($ConcreteTypes[$i] -ne $ParameterTypes[$i]) { $GenericParameters += $ParameterTypes[$i] } $ParameterTypes[$i] = Add-Member -in $ParameterTypes[$i] -Type NoteProperty -Name IsGeneric -Value $($ConcreteTypes[$i] -ne $ParameterTypes[$i]) -Passthru } $ParameterTypes | Where-Object { $_.IsGeneric } Write-Verbose "$($GenericParameters -join ', ') generic parameters" $MemberInfo = $MemberInfo.MakeGenericMethod( $GenericParameters ) Write-Verbose $MemberInfo if($WithArgs) { [Object[]]$Arguments = $withArgs | %{ $_.PSObject.BaseObject } Write-Verbose "Arguments: $(($Arguments | %{ $_.GetType().Name }) -Join ', ')" $MemberInfo.Invoke( $InputObject, $Arguments ) } else { $MemberInfo.Invoke( $InputObject ) } } } # get a reference to the Type $xlr8r = [psobject].assembly.gettype("System.Management.Automation.TypeAccelerators") function Import-Namespace { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] [string]$Namespace, [Switch]$Force ) end { Get-Type -Namespace $Namespace -Force:$Force | Add-Accelerator } } function Add-Accelerator { <# .Synopsis Add a type accelerator to the current session .Description The Add-Accelerator function allows you to add a simple type accelerator (like [regex]) for a longer type (like [System.Text.RegularExpressions.Regex]). .Example Add-Accelerator list System.Collections.Generic.List``1 $list = New-Object list[string] Creates an accelerator for the generic List[T] collection type, and then creates a list of strings. .Example Add-Accelerator "List T", "GList" System.Collections.Generic.List``1 $list = New-Object "list t[string]" Creates two accelerators for the Generic List[T] collection type. .Parameter Accelerator The short form accelerator should be just the name you want to use (without square brackets). .Parameter Type The type you want the accelerator to accelerate (without square brackets) .Notes When specifying multiple values for a parameter, use commas to separate the values. For example, "-Accelerator string, regex". PowerShell requires arguments that are "types" to NOT have the square bracket type notation, because of the way the parsing engine works. You can either just type in the type as System.Int64, or you can put parentheses around it to help the parser out: ([System.Int64]) Also see the help for Get-Accelerator and Remove-Accelerator .Link http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/ #> [CmdletBinding()] param( [Parameter(Position=0,ValueFromPipelineByPropertyName=$true)] [Alias("Key","Name")] [string[]]$Accelerator, [Parameter(Position=1,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [Alias("Value","FullName")] [type]$Type ) process { # add a user-defined accelerator foreach($a in $Accelerator) { if($xlr8r::AddReplace) { $xlr8r::AddReplace( $a, $Type) } else { $null = $xlr8r::Remove( $a ) $xlr8r::Add( $a, $Type) } trap [System.Management.Automation.MethodInvocationException] { if($xlr8r::get.keys -contains $a) { if($xlr8r::get[$a] -ne $Type) { Write-Error "Cannot add accelerator [$a] for [$($Type.FullName)]`n [$a] is already defined as [$($xlr8r::get[$a].FullName)]" } Continue; } throw } } } } function Get-Accelerator { <# .Synopsis Get one or more type accelerator definitions .Description The Get-Accelerator function allows you to look up the type accelerators (like [regex]) defined on your system by their short form or by type .Example Get-Accelerator System.String Returns the KeyValue pair for the [System.String] accelerator(s) .Example Get-Accelerator ps*,wmi* Returns the KeyValue pairs for the matching accelerator definition(s) .Parameter Accelerator One or more short form accelerators to search for (Accept wildcard characters). .Parameter Type One or more types to search for. .Notes When specifying multiple values for a parameter, use commas to separate the values. For example, "-Accelerator string, regex". Also see the help for Add-Accelerator and Remove-Accelerator .Link http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/ #> [CmdletBinding(DefaultParameterSetName="ByType")] param( [Parameter(Position=0, ParameterSetName="ByAccelerator", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Key","Name")] [string[]]$Accelerator, [Parameter(Position=0, ParameterSetName="ByType", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Value","FullName")] [type[]]$Type ) process { # add a user-defined accelerator switch($PSCmdlet.ParameterSetName) { "ByAccelerator" { $xlr8r::get.GetEnumerator() | % { foreach($a in $Accelerator) { if($_.Key -like $a) { $_ } } } break } "ByType" { if($Type -and $Type.Count) { $xlr8r::get.GetEnumerator() | ? { $Type -contains $_.Value } } else { $xlr8r::get.GetEnumerator() | %{ $_ } } break } } } } function Remove-Accelerator { <# .Synopsis Remove a type accelerator from the current session .Description The Remove-Accelerator function allows you to remove a simple type accelerator (like [regex]) from the current session. You can pass one or more accelerators, and even wildcards, but you should be aware that you can remove even the built-in accelerators. .Example Remove-Accelerator int Add-Accelerator int Int64 Removes the "int" accelerator for Int32 and adds a new one for Int64. I can't recommend doing this, but it's pretty cool that it works: So now, "$(([int]3.4).GetType().FullName)" would return "System.Int64" .Example Get-Accelerator System.Single | Remove-Accelerator Removes both of the default accelerators for System.Single: [float] and [single] .Example Get-Accelerator System.Single | Remove-Accelerator -WhatIf Demonstrates that Remove-Accelerator supports -Confirm and -Whatif. Will Print: What if: Removes the alias [float] for type [System.Single] What if: Removes the alias [single] for type [System.Single] .Parameter Accelerator The short form accelerator that you want to remove (Accept wildcard characters). .Notes When specifying multiple values for a parameter, use commas to separate the values. For example, "-Accel string, regex". Also see the help for Add-Accelerator and Get-Accelerator .Link http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/ #> [CmdletBinding(SupportsShouldProcess=$true)] param( [Parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Key","FullName")] [string[]]$Accelerator ) process { foreach($a in $Accelerator) { foreach($key in $xlr8r::Get.Keys -like $a) { if($PSCmdlet.ShouldProcess( "Removes the alias [$($Key)] for type [$($xlr8r::Get[$key].FullName)]", "Remove the alias [$($Key)] for type [$($xlr8r::Get[$key].FullName)]?", "Removing Type Accelerator" )) { # remove a user-defined accelerator $xlr8r::remove($key) } } } } } ############################################################################### ##### Imported from PowerBoots $Script:CodeGenContentProperties = 'Content','Child','Children','Frames','Items','Pages','Blocks','Inlines','GradientStops','Source','DataPoints', 'Series', 'VisualTree' $DependencyProperties = @{} if(Test-Path $PSScriptRoot\\DependencyPropertyCache.xml) { #$DependencyProperties = [System.Windows.Markup.XamlReader]::Parse( (gc $PSScriptRoot\\DependencyPropertyCache.xml) ) $DependencyProperties = Import-CliXml $PSScriptRoot\\DependencyPropertyCache.xml } function Get-ReflectionModule { $executioncontext.sessionstate.module } function Set-ObjectProperties { [CmdletBinding()] param( $Parameters, [ref]$DObject ) if($DObject.Value -is [System.ComponentModel.ISupportInitialize]) { $DObject.Value.BeginInit() } if($DebugPreference -ne "SilentlyContinue") { Write-Host; Write-Host ">>>> $($Dobject.Value.GetType().FullName)" -fore Black -back White } foreach ($param in $Parameters) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "Processing Param: $($param|Out-String )" } ## INGORE DEPENDENCY PROPERTIES FOR NOW :) if($param.Key -eq "DependencyProps") { ## HANDLE EVENTS .... } elseif ($param.Key.StartsWith("On_")) { $EventName = $param.Key.SubString(3) if($DebugPreference -ne "SilentlyContinue") { Write-Host "Event handler $($param.Key) Type: $(@($param.Value)[0].GetType().FullName)" } $sb = $param.Value -as [ScriptBlock] if(!$sb) { $sb = (Get-Command $param.Value -CommandType Function,ExternalScript).ScriptBlock } $Dobject.Value."Add_$EventName".Invoke( $sb ); # $Dobject.Value."Add_$EventName".Invoke( ($sb.GetNewClosure()) ); # $Dobject.Value."Add_$EventName".Invoke( $PSCmdlet.MyInvocation.MyCommand.Module.NewBoundScriptBlock( $sb.GetNewClosure() ) ); } ## HANDLE PROPERTIES .... else { try { ## TODO: File a BUG because Write-DEBUG and Write-VERBOSE die here. if($DebugPreference -ne "SilentlyContinue") { Write-Host "Setting $($param.Key) of $($Dobject.Value.GetType().Name) to $($param.Value.GetType().FullName): $($param.Value)" -fore Gray } if(@(foreach($sb in $param.Value) { $sb -is [ScriptBlock] }) -contains $true) { $Values = @() foreach($sb in $param.Value) { $Values += & (Get-ReflectionModule) $sb } } else { $Values = $param.Value } if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject.Value )) -foreground green } if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( @($Values)[0] )) -foreground green } Set-Property $Dobject $Param.Key $Values if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject.Value )) -foreground magenta } if($DebugPreference -ne "SilentlyContinue") { if( $Dobject.Value.$($param.Key) -ne $null ) { Write-Host $Dobject.Value.$($param.Key).GetType().FullName -fore Green } } } catch [Exception] { Write-Host "COUGHT AN EXCEPTION" -fore Red Write-Host $_ -fore Red Write-Host $this -fore DarkRed } } while($DependencyProps) { $name, $value, $DependencyProps = $DependencyProps $name = ([string]@($name)[0]).Trim("-") if($name -and $value) { Set-DependencyProperty -Element $Dobject.Value -Property $name -Value $Value } } } if($DebugPreference -ne "SilentlyContinue") { Write-Host "<<<< $($Dobject.Value.GetType().FullName)" -fore Black -back White; Write-Host } if($DObject.Value -is [System.ComponentModel.ISupportInitialize]) { $DObject.Value.EndInit() } } function Set-Property { PARAM([ref]$TheObject, $Name, $Values) $DObject = $TheObject.Value if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $DObject )) -foreground DarkMagenta } if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( @($Values)[0] )) -foreground DarkMagenta } $PropertyType = $DObject.GetType().GetProperty($Name).PropertyType if('System.Windows.FrameworkElementFactory' -as [Type] -and $PropertyType -eq [System.Windows.FrameworkElementFactory] -and $DObject -is [System.Windows.FrameworkTemplate]) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "Loading a FrameworkElementFactory" -foreground Green} # [Xml]$Template = [PoshWpf.XamlHelper]::ConvertToXaml( $DObject ) # [Xml]$Content = [PoshWpf.XamlHelper]::ConvertToXaml( (@($Values)[0]) ) # In .Net 3.5 the recommended way to programmatically create a template is to load XAML from a string or a memory stream using the Load method of the XamlReader class. [Xml]$Template = [System.Windows.Markup.XamlWriter]::Save( $DObject ) [Xml]$Content = [System.Windows.Markup.XamlWriter]::Save( (@($Values)[0]) ) $Template.DocumentElement.PrependChild( $Template.ImportNode($Content.DocumentElement, $true) ) | Out-Null $TheObject.Value = [System.Windows.Markup.XamlReader]::Parse( $Template.get_OuterXml() ) } elseif('System.Windows.Data.Binding' -as [Type] -and @($Values)[0] -is [System.Windows.Data.Binding] -and !$PropertyType.IsAssignableFrom([System.Windows.Data.BindingBase])) { $Binding = @($Values)[0]; if($DebugPreference -ne "SilentlyContinue") { Write-Host "$($DObject.GetType())::$Name is $PropertyType and the value is a Binding: $Binding" -fore Cyan} if(!$Binding.Source -and !$Binding.ElementName) { $Binding.Source = $DObject.DataContext } if($DependencyProperties.ContainsKey($Name)) { $field = @($DependencyProperties.$Name.Keys | Where { $DObject -is $_ -and $PropertyType -eq ([type]$DependencyProperties.$Name.$_.PropertyType)})[0] # -or -like "*$Class" -and ($Param1.Value -as ([type]$_.PropertyType) if($field) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "$($field)" -fore Blue } if($DebugPreference -ne "SilentlyContinue") { Write-Host "Binding: ($field)::`"$($DependencyProperties.$Name.$field.Name)`" to $Binding" -fore Blue} $DObject.SetBinding( ([type]$field)::"$($DependencyProperties.$Name.$field.Name)", $Binding ) | Out-Null } else { throw "Couldn't figure out $( @($DependencyProperties.$Name.Keys) -join ', ' )" } } else { if($DebugPreference -ne "SilentlyContinue") { Write-Host "But $($DObject.GetType())::${Name}Property is not a Dependency Property, so it probably can't be bound?" -fore Cyan } try { $DObject.SetBinding( ($DObject.GetType()::"${Name}Property"), $Binding ) | Out-Null if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject )) -foreground yellow } } catch { Write-Host "Nope, was not able to set it." -fore Red Write-Host $_ -fore Red Write-Host $this -fore DarkRed } } } elseif($PropertyType -ne [Object] -and $PropertyType.IsAssignableFrom( [System.Collections.IEnumerable] ) -and ($DObject.$($Name) -eq $null)) { if($Values -is [System.Collections.IEnumerable]) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "$Name is $PropertyType which is IEnumerable, and the value is too!" -fore Cyan } $DObject.$($Name) = $Values } else { if($DebugPreference -ne "SilentlyContinue") { Write-Host "$Name is $PropertyType which is IEnumerable, but the value is not." -fore Cyan } $DObject.$($Name) = new-object "System.Collections.ObjectModel.ObservableCollection[$(@($Values)[0].GetType().FullName)]" $DObject.$($Name).Add($Values) } } elseif($DObject.$($Name) -is [System.Collections.IList]) { foreach ($value in @($Values)) { try { $null = $DObject.$($Name).Add($value) } catch { # Write-Host "CAUGHT array problem" -fore Red if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") { $null = $DObject.$($Name).Add( (New-System.Windows.Controls.TextBlock $value) ) } else { Write-Error $_.Exception throw } } } } else { ## If they pass an array of 1 when we only want one, we just use the first value if($Values -is [System.Collections.IList] -and $Values.Count -eq 1) { if($DebugPreference -ne "SilentlyContinue") { Write-Host "Value is an IList ($($Values.GetType().FullName))" -fore Cyan} if($DebugPreference -ne "SilentlyContinue") { Write-Host "But we'll just use the first ($($Values[0].GetType().FullName))" -fore Cyan} if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Values[0] )) -foreground White} try { $DObject.$($Name) = $Values[0] } catch [Exception] { # Write-Host "CAUGHT collection value problem" -fore Red if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") { $null = $DObject.$($Name).Add( (TextBlock $Values[0]) ) }else { throw } } } else ## If they pass an array when we only want one, we try to use it, and failing that, cast it to strings { if($DebugPreference -ne "SilentlyContinue") { Write-Host "Value is just $Values" -fore Cyan} try { $DObject.$($Name) = $Values } catch [Exception] { # Write-Host "CAUGHT value problem" -fore Red if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") { $null = $DObject.$($Name).Add( (TextBlock $values) ) }else { throw } } } } } function Set-DependencyProperty { [CmdletBinding()] PARAM( [Parameter(Position=0,Mandatory=$true)] $Property, [Parameter(Mandatory=$true,ValueFromPipeline=$true)] $Element, [Parameter()] [Switch]$Passthru ) DYNAMICPARAM { $paramDictionary = new-object System.Management.Automation.RuntimeDefinedParameterDictionary $Param1 = new-object System.Management.Automation.RuntimeDefinedParameter $Param1.Name = "Value" # $Param1.Attributes.Add( (New-ParameterAttribute -Position 1) ) $Param1.Attributes.Add( (New-Object System.Management.Automation.ParameterAttribute -Property @{ Position = 1 }) ) if( $Property ) { if($Property.GetType() -eq ([System.Windows.DependencyProperty]) -or $Property.GetType().IsSubclassOf(([System.Windows.DependencyProperty]))) { $Param1.ParameterType = $Property.PropertyType } elseif($Property -is [string] -and $Property.Contains(".")) { $Class,$Property = $Property.Split(".") if($DependencyProperties.ContainsKey($Property)){ $type = $DependencyProperties.$Property.Keys -like "*$Class" if($type) { $Param1.ParameterType = [type]@($DependencyProperties.$Property.$type)[0].PropertyType } } } elseif($DependencyProperties.ContainsKey($Property)){ if($Element) { if($DependencyProperties.$Property.ContainsKey( $element.GetType().FullName )) { $Param1.ParameterType = [type]$DependencyProperties.$Property.($element.GetType().FullName).PropertyType } } else { $Param1.ParameterType = [type]$DependencyProperties.$Property.Values[0].PropertyType } } else { $Param1.ParameterType = [PSObject] } } else { $Param1.ParameterType = [PSObject] } $paramDictionary.Add("Value", $Param1) return $paramDictionary } PROCESS { trap { Write-Host "ERROR Setting Dependency Property" -Fore Red Write-Host "Trying to set $Property to $($Param1.Value)" -Fore Red continue } if($Property.GetType() -eq ([System.Windows.DependencyProperty]) -or $Property.GetType().IsSubclassOf(([System.Windows.DependencyProperty])) ){ trap { Write-Host "ERROR Setting Dependency Property" -Fore Red Write-Host "Trying to set $($Property.FullName) to $($Param1.Value)" -Fore Red continue } $Element.SetValue($Property, ($Param1.Value -as $Property.PropertyType)) } else { if("$Property".Contains(".")) { $Class,$Property = "$Property".Split(".") } if( $DependencyProperties.ContainsKey("$Property" ) ) { $fields = @( $DependencyProperties.$Property.Keys -like "*$Class" | ? { $Param1.Value -as ([type]$DependencyProperties.$Property.$_.PropertyType) } ) if($fields.Count -eq 0 ) { $fields = @($DependencyProperties.$Property.Keys -like "*$Class" ) } if($fields.Count) { $success = $false foreach($field in $fields) { trap { Write-Host "ERROR Setting Dependency Property" -Fore Red Write-Host "Trying to set $($field)::$($DependencyProperties.$Property.$field.Name) to $($Param1.Value) -as $($DependencyProperties.$Property.$field.PropertyType)" -Fore Red continue } $Element.SetValue( ([type]$field)::"$($DependencyProperties.$Property.$field.Name)", ($Param1.Value -as ([type]$DependencyProperties.$Property.$field.PropertyType))) if($?) { $success = $true; break } } if(!$success) { throw "food" } } else { Write-Host "Couldn't find the right property: $Class.$Property on $( $Element.GetType().Name ) of type $( $Param1.Value.GetType().FullName )" -Fore Red } } else { Write-Host "Unknown Dependency Property Key: $Property on $($Element.GetType().Name)" -Fore Red } } if( $Passthru ) { $Element } } } function Add-Struct { #.Synopsis # Creates Struct types from a list of types and properties #.Description # Add-Struct is a wrapper for Add-Type to create struct types. #.Example # New-Struct Song { # [string]$Artist # [string]$Album # [string]$Name # [TimeSpan]$Length # } -CreateConstructorFunction # # Description # ----------- # Creates a "Song" type with strongly typed Artist, Album, Name, and Length properties, with a simple constructor and a constructor function #.Example # New-Struct @{ # >> Product = { [string]$Name; [double]$Price; } # >> Order = { [Guid]$Id; [Product]$Product; [int]$Quantity } # >> Customer = { # >> [string]$FirstName # >> [string]$LastName # >> [int]$Age # >> [Order[]]$OrderHistory # >> } # >> } # >> # # Description # ----------- # To create a series of related struct types (where one type is a property of another type), you need to use the -Types hashtable parameter set. That way, all of the types will compiled together at once, so the compiler will be able to find them all. # [CmdletBinding(DefaultParameterSetName="Multiple")] param( # The name of the TYPE you are creating. Must be unique per PowerShell session. [ValidateScript({ if($_ -notmatch '^[a-z][a-z1-9_]*$') { throw "'$_' is invalid. A valid name identifier must start with a letter, and contain only alpha-numeric or the underscore (_)." } return $true })] [Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName = "Single")] [string]$Name, # A Scriptblock full of "[Type]$Name" definitions to show what properties you want on your Struct type [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName = "Single")] [ScriptBlock]$Property, # A Hashtable in the form @{Name={Properties}} with multiple
PowerShellCorpus/PoshCode/Restart-IISAppPool.ps1
Restart-IISAppPool.ps1
function Restart-IISAppPool { [CmdletBinding(SupportsShouldProcess=$true)] #.Synopsis # Restarts an IIS AppPool #.Parameter ComputerName # The name of a web server to restart the AppPool on #.Parameter Pool # The name of the AppPool to recycle (if you include wildcards, results in an initial call to list all app pools) param( [Parameter(ValueFromPipelineByPropertyName=$true)] [Alias("CN","Server","__Server")] [String]$ComputerName , [Parameter(ValueFromPipelineByPropertyName=$true, Mandatory= $true)] [Alias("Name","Pool")] [String[]]$AppPool , [Parameter()] [System.Management.Automation.Credential()] $Credential = [System.Management.Automation.PSCredential]::Empty ) begin { if ($Credential -and ($Credential -ne [System.Management.Automation.PSCredential]::Empty)) { $Credential = $Credential.GetNetworkCredential() } Write-Debug ("BEGIN:`n{0}" -f ($PSBoundParameters | Out-String)) $Skip = $false ## Need to test for AppPool existence (it's not defined in BEGIN if it's piped in) if($PSBoundParameters.ContainsKey("AppPool") -and $AppPool -match "\\*") { $null = $PSBoundParameters.Remove("AppPool") $null = $PSBoundParameters.Remove("WhatIf") $null = $PSBoundParameters.Remove("Confirm") Get-WmiObject IISApplicationPool -Namespace root\\MicrosoftIISv2 -Authentication PacketPrivacy @PSBoundParameters | Where-Object { @(foreach($pool in $AppPool){ $_.Name -like $Pool -or $_.Name -like "W3SVC/APPPOOLS/$Pool" }) -contains $true } | Restart-IISAppPool $Skip = $true } $ProcessNone = $ProcessAll = $false; } process { Write-Debug ("PROCESS:`n{0}" -f ($PSBoundParameters | Out-String)) if(!$Skip) { $null = $PSBoundParameters.Remove("AppPool") $null = $PSBoundParameters.Remove("WhatIf") $null = $PSBoundParameters.Remove("Confirm") foreach($pool in $AppPool) { Write-Verbose "Restarting $Pool" if($PSCmdlet.ShouldProcess("Would restart the AppPool '$Pool' on the '$(if($ComputerName){$ComputerName}else{'local'})' server.", "Restart $AppPool?", "Restarting IIS App Pools on $ComputerName")) { # if($PSCmdlet.ShouldContinue("Do you want to restart $Pool?", "Restarting IIS App Pools on $ComputerName", [ref]$ProcessAll, [ref]$ProcessNone)) { Invoke-WMIMethod Recycle -Path "IISApplicationPool.Name='$Pool'" -Namespace root\\MicrosoftIISv2 -Authentication PacketPrivacy @PSBoundParameters # } } } } } }
PowerShellCorpus/PoshCode/Select w_ subproperties.ps1
Select w_ subproperties.ps1
<# This is a proxy function enhancing Select-Object by adding the ability to use subproperties in the Property parameters. For example: Set-Process | Select-Object ProcessName, StartTime.DayOfWeek This is the only changed behavior (properties with dots get evaluated as expressions) - everything else stays intact. For more information see: http://dmitrysotnikov.wordpress.com/2010/01/25/select-object-with-subproperties #> function Select-Object { [CmdletBinding(DefaultParameterSetName='DefaultParameter')] param( [Parameter(ValueFromPipeline=$true)] [System.Management.Automation.PSObject] ${InputObject}, [Parameter(ParameterSetName='DefaultParameter', Position=0)] [System.Object[]] ${Property}, [Parameter(ParameterSetName='DefaultParameter')] [System.String[]] ${ExcludeProperty}, [Parameter(ParameterSetName='DefaultParameter')] [System.String] ${ExpandProperty}, [Switch] ${Unique}, [Parameter(ParameterSetName='DefaultParameter')] [ValidateRange(0, 2147483647)] [System.Int32] ${Last}, [Parameter(ParameterSetName='DefaultParameter')] [ValidateRange(0, 2147483647)] [System.Int32] ${First}, [Parameter(ParameterSetName='DefaultParameter')] [ValidateRange(0, 2147483647)] [System.Int32] ${Skip}, [Parameter(ParameterSetName='IndexParameter')] [ValidateRange(0, 2147483647)] [System.Int32[]] ${Index}) begin { try { $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } #region: Dmitry Sotnikov: substitute dotted properties with expressions if ($Property -ne $null) { # Iterate through properties and substitute those with dots $NewProperty = @() foreach ( $prop in $Property ) { if ($prop.GetType().Name -eq 'String') { if ($prop.Contains('.')) { [String] $exp = '$_.' + $prop $prop = @{Name=$prop; Expression = {Invoke-Expression ($exp)}} } } $NewProperty += $prop } $PSBoundParameters['Property'] = $NewProperty } #endregion $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Select-Object', [System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = {& $wrappedCmd @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } <# .ForwardHelpTargetName Select-Object .ForwardHelpCategory Cmdlet #> }
PowerShellCorpus/PoshCode/Set-FT.ps1
Set-FT.ps1
#Some Parameters param([string]$ftVM, [string]$ftState) #Load the PowerCLI Snapin add-pssnapin VMware.VimAutomation.Core #Load the creds file $creds = Get-VICredentialStoreItem -file c:\\test #Connect to the host connect-viserver -Server $creds.Host -User $creds.User -Password $creds.Password #Based on $ftState, turn FT on or off for $ftVM $ftState = $ftState.ToLower() if ($ftState -eq "on"){ #Turn FT On Get-VM X | Get-View | % { $_.CreateSecondaryVM($null) } } elseif ($ftstate -eq "off"){ #Turn FT Off Get-VM X | Select -First 1 | Get-View | % { $_.TurnOffFaultToleranceForVM() } } else { Write-Error "FT State must be either On or Off" }
PowerShellCorpus/PoshCode/New-NamedPipe.ps1
New-NamedPipe.ps1
# .NET 3.5 is required to use the System.IO.Pipes namespace [reflection.Assembly]::LoadWithPartialName("system.core") | Out-Null $pipeName = "pipename" $pipeDir = [System.IO.Pipes.PipeDirection]::InOut $pipe = New-Object system.IO.Pipes.NamedPipeServerStream( $pipeName, $pipeDir )
PowerShellCorpus/PoshCode/Get-OLEDBData.ps1
Get-OLEDBData.ps1
########################################################################### # Get-OLEDBData # -------------------------------------------- # Description: This function is used to retrieve data via an OLEDB data # connection. # # Inputs: $connectstring - Connection String. # $sql - SQL statement to be executed to retrieve data. # # Usage: Get-OLEDBData <connction string> <SQL statement> # #Connection String for Excel 2007: #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=`"$filepath`";Extended Properties=`"Excel 12.0 Xml;HDR=YES`";" #Connection String for Excel 2003: #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=`"$filepath`";Extended Properties=`"Excel 8.0;HDR=Yes;IMEX=1`";" #Excel query #'select * from [sheet1$]' #Informix #"password=$password;User ID=$userName;Data Source=$dbName@$serverName;Persist Security Info=true;Provider=Ifxoledbc.2" #Oracle #"password=$password;User ID=$userName;Data Source=$serverName;Provider=OraOLEDB.Oracle" #SQL Server #"Server=$serverName;Trusted_connection=yes;database=$dbname;Provider=SQLNCLI;" ########################################################################### function Get-OLEDBData ($connectstring, $sql) { $OLEDBConn = New-Object System.Data.OleDb.OleDbConnection($connectstring) $OLEDBConn.open() $readcmd = New-Object system.Data.OleDb.OleDbCommand($sql,$OLEDBConn) $readcmd.CommandTimeout = '300' $da = New-Object system.Data.OleDb.OleDbDataAdapter($readcmd) $dt = New-Object system.Data.datatable [void]$da.fill($dt) $OLEDBConn.close() return $dt }
PowerShellCorpus/PoshCode/Colorize Subversion SVN_4.ps1
Colorize Subversion SVN_4.ps1
# detect source control management software function findscm { $scm = '' :selectscm foreach ($_ in @('svn', 'hg')) { $dir = (Get-Location).Path while ($dir.Length -gt 3) { if (Test-Path ([IO.Path]::combine($dir, ".$_"))) { $scm = $_ break selectscm } $dir = $dir -Replace '\\\\[^\\\\]+$', '' } } return $scm } # draw output function drawlines($colors, $cmd) { $scm = findscm if (!$cmd -or !$scm) { return } foreach ($line in (&$scm $cmd)) { $color = $colors[[string]$line[0]] if ($color) { write-host $line -Fore $color } else { write-host $line } } } # svn stat function st { drawlines @{ "A"="Magenta"; "D"="Red"; "C"="Yellow"; "G"="Blue"; "M"="Cyan"; "U"="Green"; "?"="DarkGray"; "!"="DarkRed" } "stat" } # svn update function su { drawlines @{ "A"="Magenta"; "D"="Red"; "U"="Green"; "C"="Yellow"; "G"="Blue"; } "up" } # svn diff function sd { drawlines @{ "@"="Magenta"; "-"="Red"; "+"="Green"; "="="DarkGray"; } "diff" }
PowerShellCorpus/PoshCode/Get-AliasSuggestion.ps1
Get-AliasSuggestion.ps1
##############################################################################\n##\n## Get-AliasSuggestion\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\nGet an alias suggestion from the full text of the last command. Intended to\nbe added to your prompt function to help learn aliases for commands.\n\n.EXAMPLE\n\nGet-AliasSuggestion Remove-ItemProperty\nSuggestion: An alias for Remove-ItemProperty is rp\n\n#>\n\nparam(\n ## The full text of the last command\n $LastCommand\n)\n\nSet-StrictMode -Version Latest\n\n$helpMatches = @()\n\n## Find all of the commands in their last input\n$tokens = [Management.Automation.PSParser]::Tokenize(\n $lastCommand, [ref] $null)\n$commands = $tokens | Where-Object { $_.Type -eq "Command" }\n\n## Go through each command\nforeach($command in $commands)\n{\n ## Get the alias suggestions\n foreach($alias in Get-Alias -Definition $command.Content)\n {\n $helpMatches += "Suggestion: An alias for " +\n "$($alias.Definition) is $($alias.Name)"\n }\n}\n\n$helpMatches
PowerShellCorpus/PoshCode/Get-PrinterInfo_1.ps1
Get-PrinterInfo_1.ps1
$strComputer = "PrinterName" $Ports = get-wmiobject -class "win32_tcpipprinterport" -namespace "root\\CIMV2" -computername $strComputer $Printers = get-wmiobject -class "Win32_Printer" -namespace "root\\CIMV2" -computername $strComputer $ports | Select-Object Name,Hostaddress | Set-Variable port $Printers | Select-Object Name,PortName,DriverName,location,Description | Set-Variable print $num = 0 $hash = @{} do { $hash.Add($port.name[$num], $port.hostaddress[$num]) $num = $num + 1 } until ($num -eq $ports.Count) # Creates Table $table = New-Object system.Data.DataTable “$PrinterInfo” $colName = New-Object system.Data.DataColumn PrinterName,([string]) $colIP = New-Object system.Data.DataColumn IP,([string]) $colDrive = New-Object system.Data.DataColumn DriverName,([string]) $colLoc = New-Object system.Data.DataColumn location,([string]) $colDesc = New-Object system.Data.DataColumn Description,([string]) $table.columns.add($colName) $table.columns.add($colIP) $table.columns.add($colDrive) $table.columns.add($colLoc) $table.columns.add($colDesc) $num = 0 Do { $row = $table.NewRow() $row.PrinterName = $printers.name[$num] $row.IP = $hash.get_item($printers.PortName[$num]) $row.DriverName = $printers.drivername[$num] $row.Location = $printers.Location[$num] $row.Description = $printers.Description[$num] $table.Rows.Add($row) $num = $num + 1 } until ($num -eq $printers.Count) $table | Select-Object PrinterName,IP,DriverName,Location,Description | Export-Csv C:\\Printers.csv
PowerShellCorpus/PoshCode/Get VMware Information.ps1
Get VMware Information.ps1
Get-VIServer YOURSERVER $Excel = New-Object -Com Excel.Application $Excel.visible = $True $Excel = $Excel.Workbooks.Add() $Addsheet = $Excel.sheets.Add() $Sheet = $Excel.WorkSheets.Item(1) $Sheet.Cells.Item(1,1) = "Name" $Sheet.Cells.Item(1,2) = "Power State" $Sheet.Cells.Item(1,3) = "Description" $Sheet.Cells.Item(1,4) = "Number of CPUs" $Sheet.Cells.Item(1,5) = "Memory (MB)" $WorkBook = $Sheet.UsedRange $WorkBook.Font.Bold = $True $intRow = 2 $colItems = Get-VM | Select-Object -property "Name","PowerState","Description","NumCPU","MemoryMB" foreach ($objItem in $colItems) { $Sheet.Cells.Item($intRow,1) = $objItem.Name $powerstate = $objItem.PowerState If ($PowerState -eq 1) {$power = "Powerd On"} Else {$power = "Powerd Off"} $Sheet.Cells.Item($intRow,2) = $power $Sheet.Cells.Item($intRow,3) = $objItem.Description $Sheet.Cells.Item($intRow,4) = $objItem.NumCPU $Sheet.Cells.Item($intRow,5) = $objItem.MemoryMB $intRow = $intRow + 1 } $WorkBook.EntireColumn.AutoFit() $Sheet = $Excel.WorkSheets.Item(2) $Sheet.Cells.Item(1,1) = "Name" $Sheet.Cells.Item(1,2) = "Free Space" $Sheet.Cells.Item(1,3) = "Capacity" $WorkBook = $Sheet.UsedRange $WorkBook.Font.Bold = $True $intRow = 2 $colItems = Get-Datastore | Select-Object -property "Name","FreeSpaceMB","CapacityMB" foreach ($objItem in $colItems) { $Sheet.Cells.Item($intRow,1) = $objItem.Name $Sheet.Cells.Item($intRow,2) = $objItem.FreeSpaceMB $Sheet.Cells.Item($intRow,3) = $objItem.CapacityMB $intRow = $intRow + 1 } $WorkBook.EntireColumn.AutoFit() $Sheet = $Excel.WorkSheets.Item(3) $Sheet.Cells.Item(1,1) = "Name" $Sheet.Cells.Item(1,2) = "State" $WorkBook = $Sheet.UsedRange $WorkBook.Font.Bold = $True $intRow = 2 $colItems = Get-VMhost | Select-Object -property "Name","State" foreach ($objItem in $colItems) { $Sheet.Cells.Item($intRow,1) = $objItem.Name $state = $objItem.State If ($state -eq 0) {$status = "Connected"} Else {$status = "Disconnected"} $Sheet.Cells.Item($intRow,2) = $status $intRow = $intRow + 1 } $WorkBook.EntireColumn.AutoFit()
PowerShellCorpus/PoshCode/Script-Proc_1.sql.ps1
Script-Proc_1.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( [string] $ProcedureName, [string] $Path = "$($ProcedureName).sql", [string] $ConnectionString = 'Data Source=.\\sqlexpress;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]; } $sproc_text | Out-File -FilePath $Path; } finally { if ($cmd -ne $null) { $cmd.Dispose(); } if ($cn -ne $null) { $cn.Dispose(); } }
PowerShellCorpus/PoshCode/Get-ProcessCount.ps1
Get-ProcessCount.ps1
# Get-ProcessCount uses 2 main variables, server and process name. # Process name is typically the end exe, such as "svchost.exe" # Will accept unnamed args (Get-ProcessCount servername processname) # or named args (Get-ProcessCount -Computer servername -Process processname) Function Get-ProcessCount([string]$process, [string]$computer = "localhost", [switch]$guess) { $i = 0 $procList = Get-WmiObject -Class Win32_Process -Computer $computer foreach($proc in $procList) { If($proc.name -eq $process) { $i++ } } Function Try-Guessing([string]$process) { foreach($proc in $procList) { If($proc.Name -match $process) { $possible += @($($proc.name)) } } If($possible.Count -ge 1) { $uniq = $possible | Get-Unique foreach($proc in $uniq) { Write-Host "Did you mean $($proc)?" -ForeGroundColor Magenta } } else { Write-Host "I tried guessing, but I couldn't find $($process) that way, either. Sorry." -ForeGroundColor Green } } If($i -ge 1) { Write-Host "There are $i instances of $process on $computer" -ForegroundColor Green } else { Write-Host "0 instances of $process found on $computer" -ForegroundColor Green Try-Guessing $process } }
PowerShellCorpus/PoshCode/Get-Sysinternals_2.ps1
Get-Sysinternals_2.ps1
function Get-SysInternals { param ( $sysIntDir=(join-path $env:systemroot "\\Sysinternals\\") ) if(!(Test-Path -Path $sysIntDir -PathType Container)) { $null = New-Item -Type Directory -Path $sysIntDir -Force } $log = join-path $sysIntDir "changes.log" Add-Content -force $log -value "`n`n[$(get-date)]SysInternals sync has been started" net use \\\\live.sysinternals.com\\tools /persistent:no New-PSDrive -Name SYS -PSProvider filesystem -Root \\\\live.sysinternals.com\\tools dir Sys: -recurse | foreach { $fileName = $_.name $localFile = join-path $sysIntDir $_.name $exist = test-path $localFile $msgNew = "new utility found: $fileName , downloading..." $msgUpdate = "file : $fileName is newer, updating..." $msgNoChange = "nothing changed for: $fileName" if($exist){ if($_.lastWriteTime -gt (Get-Item $localFile).lastWriteTime) { Copy-Item $_.fullname $sysIntDir -force Write-Host $msgUpdate -fore yellow Add-Content -force $log -value $msgUpdate } else { Add-Content $log -force -value $msgNoChange Write-Host $msgNoChange } } else { if($_.extension -eq ".exe") { Write-Host $msgNew -fore green Add-Content -force $log -value $msgNew } Copy-Item $_.fullname $sysIntDir -force } } Update-Path "Sysinternals" $sysIntDir "" net use \\\\live.sysinternals.com\\tools\\ /delete } function Update-Path ( [string] $Product, [string] $productPath, [string] $Property) { # Get our existing path as an array $pathArray = @() foreach ($pathItem in [Environment]::GetEnvironmentVariable('Path', 'Machine').Split(';')) { # Remove trailing \\ if any $pathItem = $pathItem.TrimEnd(('\\')); $pathItem = $pathItem.Replace('"',""); #$pathItem =('"{0}"' -f $pathItem) if ($pathArray -contains $pathItem) { "Removing duplicate item: " + $pathItem; } else { "Keeping item: " + $pathItem; $pathArray += $pathItem } } # Append new paths. "test path "+$productPath #TODO: encapsulate to a function if (Test-Path $productPath) { if ([string]::IsNullOrEmpty($Property)) { [string] $path = $productPath } else { [string] $path = (Get-ItemProperty $produuctPath).($Property) } #$path if (-not [string]::IsNullOrEmpty($path)) { $Product + " found" $path = $path.TrimEnd(('\\')); $path = $path.Replace('"',""); #$path =('"{0}"' -f $path) if ($pathArray -notcontains $path ) { " Appending " + $path + " to path" $pathArray += $path } else { " " + $path + " already in path" } } } else { $product + " not found" } [Array]::Sort([array]$pathArray) #$pathArray "" "Old Path: " ([Environment]::GetEnvironmentVariable('Path', 'Machine').Split(';'))|format-list "" "" [string] $newPath = [string]::Join(';', $pathArray); [Environment]::SetEnvironmentVariable('Path', $newPath, 'Machine'); "New Path: " ([Environment]::GetEnvironmentVariable('Path', 'Machine').Split(';'))|format-list } $wid=[System.Security.Principal.WindowsIdentity]::GetCurrent() $prp=new-object System.Security.Principal.WindowsPrincipal($wid) $adm=[System.Security.Principal.WindowsBuiltInRole]::Administrator $IsAdmin=$prp.IsInRole($adm) if($IsAdmin) { if ($args.Length -eq 0) { Get-Sysinternals } else { Get-Sysinternals $args[0] } #Get-Sysinternals "c:\\sys\\" } else { Write-Warning "This script requires running as an elevated administrator." }
PowerShellCorpus/PoshCode/Get-NTStatusException.ps1
Get-NTStatusException.ps1
function Get-NTStatusException { <# .SYNOPSIS Resolves an NTSTATUS error code. Author: Matthew Graeber (@mattifestation) .DESCRIPTION Get-NTStatusException returns a friendly error message based on the NTSTATUS code passed in. This function is useful when interacting with Windows Native API functions with NTSTATUS return codes. .PARAMETER ErrorCode An NTSTATUS code returned by a native API function (Nt or Rtl prefixed functions) .EXAMPLE C:\\PS> Get-NTStatusException -ErrorCode 0xC0000005 Invalid access to memory location. .EXAMPLE C:\\PS> 0xC0000005, 0xC0000017, 0x00000000 | Get-NTStatusException Invalid access to memory location. Not enough storage is available to process this command. The operation completed successfully. .LINK http://www.exploit-monday.com/ #> [CmdletBinding()] Param ( [Parameter(Position = 0, Mandatory = $True, ValueFromPipeline = $True)] [Int32[]] $ErrorCode ) BEGIN { Set-StrictMode -Version 2 $Win32Native = [AppDomain]::CurrentDomain.GetAssemblies() | %{ $_.GetTypes() } | ? { $_.FullName -eq 'Microsoft.Win32.Win32Native' } if ($Win32Native -eq $null) { throw "Unable to get a reference to type: Microsoft.Win32.Win32Native" } $LsaNtStatusToWinError = $Win32Native.GetMethod('LsaNtStatusToWinError', [Reflection.BindingFlags] 'NonPublic, Static') $GetMessage = $Win32Native.GetMethod('GetMessage', [Reflection.BindingFlags] 'NonPublic, Static') } PROCESS { foreach ($Error in $ErrorCode) { $WinErrorCode = $LsaNtStatusToWinError.Invoke($null, @($ErrorCode)) Write-Output $GetMessage.Invoke($null, @($WinErrorCode)) } } END{} }
PowerShellCorpus/PoshCode/Install-Solarized_1.ps1
Install-Solarized_1.ps1
[CmdletBinding()] param($Path = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Accessories\\Windows PowerShell\\Windows PowerShell.lnk" ) # SOLARIZED HEX 16/8 TERMCOL XTERM/HEX L*A*B RGB HSB # --------- ------- ---- ------- ----------- ---------- ----------- ----------- $base03 = "#002b36" # 8/4 brblack 234 #1c1c1c 15 -12 -12 0 43 54 193 100 21 $base02 = "#073642" # 0/4 black 235 #262626 20 -12 -12 7 54 66 192 90 26 $base01 = "#586e75" # 10/7 brgreen 240 #585858 45 -07 -07 88 110 117 194 25 46 $base00 = "#657b83" # 11/7 bryellow 241 #626262 50 -07 -07 101 123 131 195 23 51 $base0 = "#839496" # 12/6 brblue 244 #808080 60 -06 -03 131 148 150 186 13 59 $base1 = "#93a1a1" # 14/4 brcyan 245 #8a8a8a 65 -05 -02 147 161 161 180 9 63 $base2 = "#eee8d5" # 7/7 white 254 #e4e4e4 92 -00 10 238 232 213 44 11 93 $base3 = "#fdf6e3" # 15/7 brwhite 230 #ffffd7 97 00 10 253 246 227 44 10 99 $yellow = "#b58900" # 3/3 yellow 136 #af8700 60 10 65 181 137 0 45 100 71 $orange = "#cb4b16" # 9/3 brred 166 #d75f00 50 50 55 203 75 22 18 89 80 $red = "#dc322f" # 1/1 red 160 #d70000 50 65 45 220 50 47 1 79 86 $magenta = "#d33682" # 5/5 magenta 125 #af005f 50 65 -05 211 54 130 331 74 83 $violet = "#6c71c4" # 13/5 brmagenta 61 #5f5faf 50 15 -45 108 113 196 237 45 77 $blue = "#268bd2" # 4/4 blue 33 #0087ff 55 -10 -45 38 139 210 205 82 82 $cyan = "#2aa198" # 6/6 cyan 37 #00afaf 60 -35 -05 42 161 152 175 74 63 $green = "#859900" # 2/2 green 64 #5f8700 60 -20 65 133 153 0 68 100 60 # Requires the "Get-Link script":http://poshcode.org/2493 $lnk = Get-Link $Path ## On Windows, we don't have "Magenta" and "BrightMagenta" -- We have "Magenta" and "DarkMagenta" ## In any case, the Solarized order is confusing, so we'll use the .Net ConsoleColor order instead $lnk.ConsoleColors[0] = $Base03 $lnk.ConsoleColors[1] = $Base02 $lnk.ConsoleColors[2] = $Base01 $lnk.ConsoleColors[3] = $Base00 $lnk.ConsoleColors[4] = $Base0 $lnk.ConsoleColors[5] = $Violet $lnk.ConsoleColors[6] = $Orange ## Yes, these really are switched, numerically speaking ... ## They're really DarkWhite (Gray) and LightBlack (DarkGray) $lnk.ConsoleColors[7] = $Base2 $lnk.ConsoleColors[8] = $Base1 $lnk.ConsoleColors[9] = $Blue $lnk.ConsoleColors[10] = $Green $lnk.ConsoleColors[11] = $Cyan $lnk.ConsoleColors[12] = $Red $lnk.ConsoleColors[13] = $Magenta $lnk.ConsoleColors[14] = $Yellow $lnk.ConsoleColors[15] = $Base3 $lnk.Save()
PowerShellCorpus/PoshCode/PSTUtility_2.psm1.ps1
PSTUtility_2.psm1.ps1
#============================================================================= # # PST Utilities - For Discovery, Import, Removal # # Dan Thompson # dethompson71 at live dot com # # This collection of tools for importing PSTs has been pieced together # over many months of trial and error. # # Goal is to get PST files off the user's home share and into an archive mailbox. # # Throughout these scripts, what Microsoft calls a "Personal Archive" and # "Archive Mailbox," we call an "Online PST" or "Online Archive PST." # All these terms are the same thing. # # We used the name "Online PST" due to the user's fear of the word "Archive" # # They thought we were pushing their mail down some hole and they would # never see it again. "Online PST" is more friendly and helps them understand # the overall goal. Once we started importing PSTs for users, others saw the # increased quota, as well as seeing the mail in OWA, and many requests # started pouring in. # # All part of our evil plan to erradicate PST files. ;) # # The reason we created these scripts and made particular choices are detailed here: # http://powershellatwork.blogspot.com/2012/01/enterprise-wide-pst-import-beginnings.html # # Yes, we know about the tool PST Capture, but it just wasn't going to work for us. # # requires Quest Powershell Commands for Active Directory # (Active Roles Management Shell) # http://www.quest.com/powershell/activeroles-server.aspx # # I don't claim any of this to be perfect or work for every person out of the # box. You will certainly have to modify some settings to begin using this set # of tools in your environment. # # I hope someone can use this as a starting point if they are in a # similar situation. # # I also suggest you at least try PST Capture first. It did not work for me for # varous reasons. Your mileage may vary. # # #============================================================================= #============================================================================= # File Locations: PSTImportJobQueue; ReportJobQueue; PSTFileLogQueue #============================================================================= #====> TO DO -- add your servername and drive location $Script:PSTServer = '<ServerBIOSName>' # example 'Ex01' $Script:PSTDrive = '<drive>' # admin share example: 'd$' $Script:PSTShareDir = '\\\\' + $Script:PSTServer + '\\PSTImports' #Exchange servers must have rights to this share $Script:PSTUNCDir = '\\\\' + $Script:PSTServer + '\\' + $Script:PSTDrive + '\\Web\\Data\\pstimports' #UNC path to same share $Script:CASConnectLogDir = '\\\\' + $Script:PSTServer + '\\' + $Script:PSTDrive + '\\Web\\Data\\CASConnectLogs' # where 'Connect' logs are kept $Script:ReportsUNCDir = '\\\\' + $Script:PSTServer + '\\' + $Script:PSTDrive + '\\Web\\Data\\Current' #UNC path to report results $Script:PSTQueueFile = $Script:PSTShareDir + '\\PSTImportJobQueue.csv' $Script:PSTCompeletDir = $Script:PSTShareDir + '\\^Completed' # so it always shows at the top $Script:PSTCompleteFile = $Script:PSTShareDir + '\\PSTImportCompleteQueue.csv' # Completed PST Import Jobs $Script:NotifiedFile = $Script:PSTShareDir + '\\PSTImportJobNotified.txt' # Users who have been notified $Script:ArchReportFile = $Script:PSTUNCDir + '\\ArchiveReport.csv' # The daily archive report (also a webpage) $Script:ArchPSTFile = $Script:PSTUNCDir + '\\ArchivePSTHistory.csv' # history of PSTs owned by Archive Mailbox users $Script:MoveFileLog = $Script:PSTUNCDir + '\\MovePSTFIles-' + $Script:T + '.log' # the Move log created when run $Script:AllPSTFileLog = $Script:PSTUNCDir + '\\AllPSTHistory.csv' # the history of ALL PST files discovered # always shows at the bottom of directory listings $Script:ImportQueueFileBU = $Script:PSTShareDir + '\\ZZSavedQueueLogs\\PSTImportJobQueue' + "-" + $Script:TE + ".csv" # backup of ImportQueue $Script:CompleteQueueFileBU = $Script:PSTShareDir + '\\ZZSavedQueueLogs\\PSTImportCompleteQueue' + "-" + $Script:TE + ".csv" #backup of Completed Jobs $Script:ArchReportFileBU = $Script:PSTUNCDir + '\\ZZSavedQueueLogs\\ArchiveReport-' + $Script:TE + '.csv' #back up of a report that is generated daily? $Script:ArchPSTFileBU = $Script:PSTUNCDir + '\\ZZSavedQueueLogs\\ArchivePSTHistory-' + $Script:TE + '.csv' # back up of ArchiveMailboxOwners PSTs $Script:AllPSTFileLogBU = $Script:PSTUNCDir + '\\ZZSavedQueueLogs\\AllPSTHistory-' + $Script:TE + '.csv' # backup of history of ALL psts discovered #============================================================================= # Variables #============================================================================= # This site name is used to determine what tool is used to copy files. # Copy-item is used for local PST files; BITS is used for distant files. $Script:LocalADSite = 'HQ' $Script:PSTUtilityVersion = "14.1.20121015" $Script:MinRunJobs = 9 # minimum jobs running before we start more - 0 means no jobs can be running $Script:MaxRunJobs = 19 # how many job can run at once $Script:FreeSpaceLimit = 199471 # set in MB, the lowest you want free space to go on the Import Share $Script:T = Get-Date -Format yyyyMMdd # today $Script:TE = Get-Date -Format yyyyMMddhhmmss # today extended $Script:SMTPServer = "smtpserver.domain.com" # where to send $Script:AdminEmail = "admin1@domain.com, admin2@domain.com" # gets notified, sent daily summary report email $Script:BossEmail = "boss@domain.com" # send daily report on Wednesday only (Weekly Summary Report) $Script:FromEmail = "EmailTeam@domain.com" # from address of reports to porcessed users $Script:FromReportEmail = "PSTReports@domain.com" # from Address of manager's summary reports #============================================================================= # these are all the people that have applications which generate and process .PST files # but are Java configuration files. Not Mail. Ignore anything not in an "Outlook" directory # --> Add DisplayName of user... $Script:SpecialPeople = @("<DisplayName1>","<Displayname2>") #============================================================================= # These users will be ignored and not 'messed with' # There will be some ;) $Script:IgnoreUsers = @("<DisplayName1>","<DisplayName2>") #============================================================================= # Job Objects: PSTJob; ReportJob; PSTFileLog #============================================================================= Function New-PSTFileLogObject(){ <# .SYNOPSIS Return a new object to track a PST file. .DESCRIPTION Return a new object to track a PST file. This is created for each new PST discovered for any user #> $PSTObj = New-Object PSObject $PSTObj | Add-Member -type NoteProperty -name UNCFullPathName -value (0) $PSTObj | Add-Member -type NoteProperty -name LastWriteTime -value ("") $PSTObj | Add-Member -type NoteProperty -name Size -value (0) $PSTObj | Add-Member -type NoteProperty -name IgnoreFile -value ("FALSE") $PSTObj | Add-Member -type NoteProperty -name DateRemoved -value ("") $PSTObj | Add-Member -type NoteProperty -name BackupFolksNotified -value ("FALSE") $PSTObj | Add-Member -type NoteProperty -name AgeInDays -value (0) $PSTObj } Function Get-ArchPSTIndex ($PST=$null) { <# .SYNOPSIS Creates or finds an index number for PST name. .DESCRIPTION Creates or finds an index number for PST name. Uses the full UNC path for index building #> $Return = $null` If ($Script:PSTIndex.ContainsKey($PST.VersionInfo.FileName)) { # return the Index number $Return = $PSTIndex.Item($PST.VersionInfo.FileName) } Else { # not found so this is a never before see file # create the entry for the file $PSTLog = New-ArchPSTFileLogObject $PSTLog.UNCFullPathName = $PST.VersionInfo.FileName $Script:ArchPSTQueue += $PSTLog # create the index and add it to $Script:PSTIndex.Add($PSTLog.UNCFullPathName,$Script:ArchPSTQueue.Count) $Return = $Script:ArchPSTQueue.Count } $Return } Function New-ArchPSTFileLogObject(){ <# .SYNOPSIS Return a new object to track PST file. .DESCRIPTION Return a new object to track a PST file. This is created for each new PST discovered for any users with an Archive Mailbox #> $PSTObj = New-Object PSObject $PSTObj | Add-Member -type NoteProperty -name UNCFullPathName -value (0) $PSTObj | Add-Member -type NoteProperty -name LastWriteTime -value ("") $PSTObj | Add-Member -type NoteProperty -name Size -value (0) $PSTObj | Add-Member -type NoteProperty -name IgnoreFile -value ("FALSE") $PSTObj | Add-Member -type NoteProperty -name DateChecked -value ("") $PSTObj | Add-Member -type NoteProperty -name BackupFolksNotified -value ("FALSE") $PSTObj | Add-Member -type NoteProperty -name AgeInDays -value (0) $PSTObj | Add-Member -type NoteProperty -name AcctName -value ("") $PSTObj | Add-Member -type NoteProperty -name Dept -value ("") $PSTObj | Add-Member -type NoteProperty -name Server -value ("") $PSTObj | Add-Member -type NoteProperty -name DateDiscovered -value (Get-date) $PSTObj | Add-Member -type NoteProperty -name DateCreated -value ("") $PSTObj } Function Get-PSTFileIndex ($PST=$null) { <# .SYNOPSIS Creates or finds an index number for PST name. .DESCRIPTION Creates or finds an index number for PST name. Uses the full UNC path for index building #> $Return = $null` Write-Host "Enter [Get-PSTFileIndex]: $(($PST).VersionInfo.FileName) Count: $(($Script:AllPSTQueue).Count)" If ($Script:PSTIndex.ContainsKey($PST.VersionInfo.FileName)) { # return the Index number $Return = $Script:PSTIndex.Item($PST.VersionInfo.FileName) Write-Host "Found [Get-PSTFileIndex]: $($Return)" } Else { # not found so this is a never before seen file # create the entry for the file $PSTLog = New-PSTFileLogObject $PSTLog.UNCFullPathName = $PST.VersionInfo.FileName Write-Host "Fullname $(($PSTLog).UNCFullPathName)" Write-Host "Before: " $PSTLog $Script:AllPSTQueue += $PSTLog Write-host "After: " $Script:AllPSTQueue[-1] # create the index and add it to #$Script:PSTIndex.Add($_.UNCFullPathName,$i) $Script:PSTIndex.Add($PSTLog.UNCFullPathName,($Script:AllPSTQueue).Count-1) Write-Host "Added? : " $Script:PSTIndex.Get_item($PSTLog.UNCFullPathName) $Return = ($Script:AllPSTQueue).Count -1 Write-host "Try to reindex in: " $Script:AllPSTQueue[($Return)] Write-Host "Add [Get-PSTFileIndex]: $($Return)" } Write-Host "Leave [Get-PSTFileIndex]" $Return } Function New-PSTJobObject() { <# .SYNOPSIS Object for storing information about a PST Import Job. .DESCRIPTION Object for storing information about a PST Import Job. A user many have many Jobs, one for each PST file being imported. #> $PSTJob = New-Object PSObject # User Related $PSTJob | Add-Member -type NoteProperty -name JobName -value ("") # <userobj>-<filename> $PSTJob | Add-Member -type NoteProperty -name JobStatus -value ("") # <> $PSTJob | Add-Member -type NoteProperty -name UserMBX -value ("") # DisplayName $PSTJob | Add-Member -type NoteProperty -name UserEmail -value ("") # PrimarySMTPAddress $PSTJob | Add-Member -type NoteProperty -name UserObj -value ("") # NTAccopuntName $PSTJob | Add-Member -type NoteProperty -name HomeDir -value ("") # from QADuser $PSTJob | Add-Member -type NoteProperty -name ClientVer -value ("") # from CAS logs if found $PSTJob | Add-Member -type NoteProperty -name ClientVerOK -value ("") # True/False # User PC Related $PSTJob | Add-Member -type NoteProperty -name IP -value ("") # ComputerName, IP, or None (order of preference) $PSTJob | Add-Member -type NoteProperty -name OSname -value ("") # X, 7, or none # PST File Related $PSTJob | Add-Member -type NoteProperty -name ProcessFile -value ($True) # for potentially turning off one PST in a group $PSTJob | Add-Member -type NoteProperty -name OrgFileName -value ("") # should be file name only $PSTJob | Add-Member -type NoteProperty -name OrgUNCName -value ("") # UNC file name Original location $PSTJob | Add-Member -type NoteProperty -name TargetDir -value ("") # target directory for creation $PSTJob | Add-Member -type NoteProperty -name TargetUNCName -value ("") # UNC file name Target location $PSTJob | Add-Member -type NoteProperty -name FileSize -value (0) # file size in MB $PSTJob | Add-Member -type NoteProperty -name FileLastWrite -value ("") # last write time of file # Migration Related $PSTJob | Add-Member -type NoteProperty -name TargetDB -value ("") # target archive mailbox location $PSTJob | Add-Member -type NoteProperty -name MRServer -value ("") # which MRS server to use - depends on AD site $PSTJob | Add-Member -type NoteProperty -name LastNumBI -value (0) # from results, how many bad items did we encounter? $PSTJob | Add-Member -type NoteProperty -name UseTargetRootFolder -value ($true) # True/False $PSTJob | Add-Member -type NoteProperty -name TargetRootFolder -value ("") # True/False $PSTJob | Add-Member -type NoteProperty -name JobCreationTime -value ($null) # Update Related $PSTJob | Add-Member -type NoteProperty -name LastCheckTime -value ($null) # last time this entry processed $PSTJob | Add-Member -type NoteProperty -name InProgressTime -value ($null) # from results $PSTJob | Add-Member -type NoteProperty -name OverAllTime -value ($null) # from results $PSTJob | Add-Member -type NoteProperty -name ExpandedErrs -value ($null) # any encountered errors $PSTJob | Add-Member -type NoteProperty -name RegPSTGrow -value ($false) # has been added to group for GPO to PSTDisableGrow?- my signal this user is complete - check membership $PSTJob | Add-Member -type NoteProperty -name SkipReason -value ("") # when a file is skipped, Size, Age, or Failed $PSTJob } Function New-PSTReportObj (){ <# .SYNOPSIS PST Report Object for tracking the progress of PST migration. .DESCRIPTION PST Report Object for tracking the progress of users with an Archive Mailbox and their progress at removing PST files from their home drives. #> $ReportObj = New-Object PSObject # OverallUser Info $ReportObj | Add-Member -type NoteProperty -name DisplayName -value ("") # PST Information $ReportObj | Add-Member -type NoteProperty -name InUsePST -value (0) $ReportObj | Add-Member -type NoteProperty -name HDrvPST -value (0) $ReportObj | Add-Member -type NoteProperty -name HDrvSize -value (0) $ReportObj | Add-Member -type NoteProperty -name ImpPST -value (0) $ReportObj | Add-Member -type NoteProperty -name ImpSize -value (0) $ReportObj | Add-Member -type NoteProperty -name TotalSize -value (0) $ReportObj | Add-Member -type NoteProperty -name SkippedPST -value (0) $ReportObj | Add-Member -type NoteProperty -name DaysSinceImport -value (0) $ReportObj | Add-Member -type NoteProperty -name GPO -value ("") $ReportObj | Add-Member -type NoteProperty -name '-' -value ("") # General MBX INfo $ReportObj | Add-Member -type NoteProperty -name MBXDB -value ("") $ReportObj | Add-Member -type NoteProperty -name ArchDB -value ("") $ReportObj | Add-Member -type NoteProperty -name MBXSize -value (0) $ReportObj | Add-Member -type NoteProperty -name MBXQuota -value (0) $ReportObj | Add-Member -type NoteProperty -name ArchSize -value (0) $ReportObj | Add-Member -type NoteProperty -name ArchQuota -value (0) $ReportObj | Add-Member -type NoteProperty -name InitArchSize -value (0) $ReportObj | Add-Member -type NoteProperty -name ArchGrowth -value (0) $ReportObj | Add-Member -type NoteProperty -name DateCreated -value ((Get-Date)) $ReportObj } Function Reset-PSTBackupFileNames () { <# .SYNOPSIS Reset Backup file names to current time .DESCRIPTION Reset them all so that you'll be guaranteed to have the correct name each time #> $Script:TE = Get-Date -Format yyyyMMddhhmmss # today extended $Script:ImportQueueFileBU = $Script:PSTShareDir + '\\ZZSavedQueueLogs\\PSTImportJobQueue' + "-" + $Script:TE + ".csv" $Script:CompleteQueueFileBU = $Script:PSTShareDir + '\\ZZSavedQueueLogs\\PSTImportCompleteQueue' + "-" + $Script:TE + ".csv" $Script:ArchReportFileBU = $Script:PSTUNCDir + '\\ZZSavedQueueLogs\\ArchiveReport-' + $Script:TE + '.csv' $Script:ArchPSTFileBU = $Script:PSTUNCDir + '\\ZZSavedQueueLogs\\ArchivePSTHistory-' + $Script:TE + '.csv' $Script:AllPSTFileLogBU = $Script:PSTUNCDir + '\\ZZSavedQueueLogs\\AllPSTHistory-' + $Script:TE + '.csv' } #============================================================================= # Helper Functions #============================================================================= Function CC () { <# .SYNOPSIS a utility to return the count of members in a collection .DESCRIPTION a utility to return the count of members in a collection 0, 1, or many ... #> Param ( $Col ) if ($Col) { if ($Col.Count -eq $null) { $Cnt = 1 } Else { $Cnt = $Col.Count } } Else { $Cnt = 0 } $Cnt } Function isMemberOf() { <# .SYNOPSIS A utility to check if a mailbox is a member of a group. .DESCRIPTION A utility to check if a mailbox is a member of a group. #> Param ( [string] $groupName, [string] $MemberName # displayname ) $m = Get-QADGroupMember $groupName -SizeLimit 0 | where { $_.Displayname -eq $memberName } if($m) {$true} else {$false} } Function WhoAmI () { <# .SYNOPSIS sometimes you want to know who is running this job ;) .DESCRIPTION ometimes you want to know who is running this job ;) #> ([System.Security.Principal.WindowsIdentity]::GetCurrent()).Name } Function Get-ISODayOfWeek { <# .SYNOPSIS Get the correct (according to ISO 8601) day of the week .DESCRIPTION For any given date you get the day of the week, according to ISO8610 .PARAMETER Date The date you want to analyze. Accepts dates on the pipeline #> Param([DateTime]$date=$(Get-Date)) Process { if($_){$date=$_} @(7,1,2,3,4,5,6)[$date.DayOfWeek] } } Function Get-FreeDiskSpace($drive,$computer) { <# .SYNOPSIS Utility to discover the free space of a drive .DESCRIPTION Utility to discover the free space of a drive Used to decide if there is enough space to copy a PST file to either the Temp processing area, or to the local PC for backup. #> $driveData = Get-WmiObject -class win32_LogicalDisk -computername $computer -filter "Name = '$drive'" #"$computer free disk space on drive $drive" "{0:n2}" -f ($driveData.FreeSpace/1MB) } Function ConvertTo-ComputerName() { <# .SYNOPSIS Resolve the IP to a computer name .DESCRIPTION CAS logs record IP address for a user, but those can change over time resolve the IP to a computer name to save in the PST Job Queue - try to look up in DNS - 90% of time this will be an IP #> Param ( $FindName ) $Return = $null $ErrorActionPreference = "SilentlyContinue" $c = [System.Net.Dns]::GetHostbyAddress($FindName).HostName $ErrorActionPreference = "Continue" if ($c) { $Return = ($c.Split(".")[0]).ToUpper() } Else { $Return = $FindName } $Return } Function ConvertTo-IP () { <# .SYNOPSIS Lookup IP using the ComputerName .DESCRIPTION CAS logs record IP address for a user, but those can change over time resolve the IP to a computer name to save in the PST Job Queue #> Param ($FindName) $Return = $null $ErrorActionPreference = "SilentlyContinue" $c = [System.Net.Dns]::GetHostEntry($FindName).Addresslist[0].ToString() $ErrorActionPreference = "Continue" if ($c) { $Return = ($c.Split(".")[0]).ToUpper() } Else { $Return = $FindName } $Return } Function Clean-OnlinePSTGPO(){ <# .SYNOPSIS Clear up GPO group and make sure it has only the correct members .DESCRIPTION Clear up GPO group and make sure it has only the correct members .Notes In our world, there are 2 types of PST file users: Controled and Non-Controlled Controled Users: New users created after a certain date (1FEB2012) and Users migrated to Online PSTs Non-Controlled Users: Those users created befor 1FEB2012 and not having been migrated. Eventually the Non-Controlled user will disappear. At least, we can hope. #> $GPO = get-group 'GPO-ReadOnlyPST' | select -ExpandProperty Members $GPO | %{ Write-Host "Working " $_.ToString() $Dumpable = $false $Reason = "None" $MBX = get-mailbox $_.ToString() # Does User even have a mailbox? if(! (($MBX).DataBase.Name)) { $Dumpable = $true $Reason = "NoMailbox" } Elseif (!(($MBX).ArchiveDataBase.Name)) { #Has Mailbox but No Archive if ((get-date '2/1/2012') -gt (get-date ($MBX).WhenMailboxCreated)){ $Dumpable = $true $Reason = "No archive and 2/1/2012 is greater than " + $(($MBX).WhenMailboxCreated) } } if ($Dumpable){ #remove them from the group (GPO). Write-Host "Removing: " ($MBX).Displayname " - " $Reason Remove-QADGroupMember -Identity 'GPO-ReadONlyPST' -Member $_.ToString() } } # "{0,30}`t{1,10}`t{2,25}" -f (($MBX).DataBase.Name), (($MBX).ArchiveDataBase.Name),((get-date '2/1/2012') -gt ($MBX).WhenMailboxCreated)} } #============================================================================= # User Obj Functions - Done #============================================================================= Function Add-ToGPO ($User = $null) { <# .SYNOPSIS Add user to a group that defines scope of GPO to Disallow PST Growth .DESCRIPTION In our organization our GPO that disallows PST growth is governed by a group during the transition, later we can apply that setting worldwide. For users to be comfortable, they need to Read their old PST files They can then check our work for themselves. #WarmAndFuzzyFactor These skipped users are legal discovery people that need to continue to create PSTs as they gather info for Lawyer types. #> if ($User) { if (-not ($Script:IgnoreUser -contains (get-mailbox $User).SamAccountName)) { Add-QADGroupMember -Identity 'gpo-ReadonlyPST' -Member (get-mailbox $User).SamAccountName } } } Function Adjust-Quota ($User = $null) { <# .SYNOPSIS Make sure people are not hit by a quota during their transition. .DESCRIPTION Make sure people are not hit by a quota during their transition Set new quota to 500MB -- unless theie quota is already huge #> if ($User) { $MBX = get-mailbox $User # what is current quota $UsingDBQuotas = $MBX.UseDatabaseQuotaDefaults if ($UsingDBQuotas -eq $True){ $Database = Get-MailboxDatabase -Identity $MBX.Database $ProhibitSendQuota = $Database.ProhibitSendQuota.value.ToMB() -as [Int] $IssueWarningQuota = $Database.IssueWarningQuota.value.ToMB() -as [Int] } Else { $ProhibitSendQuota = $MBX.ProhibitSendQuota.value.ToMB() -as [Int] $IssueWarningQuota = $MBX.IssueWarningQuota.value.ToMB() -as [Int] } $NewProhibitSendQuota = 500 -as [int] $NewIssueWarningQuota = 450 -as [int] # this has bit me b4, so changed it to "-as [int]" above for better results if($NewIssueWarningQuota -gt $IssueWarningQuota) { Set-Mailbox -Identity $MBX -UseDatabaseQuotaDefaults:$False -ProhibitSendQuota 500MB -IssueWarningQuota 450MB -ProhibitSendReceiveQuota "Unlimited" } } } Function Get-ClientAccessUserLog () { <# .SYNOPSIS Discover a user's Client and IP information. .DESCRIPTION Discover a user's client and IP information. Script uses this function too. There is also nightly process that runs which gets all the "connect" log entries for OUTLOOK.EXE. It's run overnight. Initially we were looking at all the logs and that was very teadious. Now we search an already created subset. It's best to pass in the LegacyExchangeDN and SAMAccountName from the mailbox object from testing it seems to get better results right now using both There is no way of knowing where this user logged in so we must search all CAS servers until we find a "connect" entry and pass the full line back Also users can log in from many PCs -- we only want the most used so look thru the full day and get all info you can, then group by IP and take the one with the most connects. alas, sometimes you won't find anything ... #> param ( $DisplayName = $null, $SamName = $null, $LegacyName = $null, $IP = $null, $SearchDays = 14, [switch]$Quiet ) #----------------------------------------------------------------- $Results = @() If($DisplayName) { #ignore all the other cmdline entries and use this to grab those $MB = Get-SingleMailboxObject $DisplayName $LegacyName = $MB.LegacyExchangeDN $SamName = $MB.SamAccountName } Elseif ($IP) { $LegacyName = $IP } $Days = -1 Do { $Y = Get-Date $((get-date).adddays($Days)) -Format yyyyMMdd if (!($Quiet)) {Write-Host "Searching "$Y} if(Test-path ($Script:CASConnectLogDir + "\\olConnect-"+$Y+"*")) { $tmpResults = gc (gci ($Script:CASConnectLogDir + "\\olConnect-"+$Y+"*")) | ?{($_ -match ($LegacyName + ",")) -and ($_ -match ",,Outlook") -and ($_ -match "Connect,")} #Write-Verbose "Found: [$($tmpResults.count)]" if($tmpResults) { $tmpResults | %{$Results += $_} } } $Days-- } While (!($Results) -And ($Days -gt ($SearchDays * (-1)))) if ($Results) { #split the line(s) found into Name, Version, and IP, and mode $c = $Results | %{"{0};{1};{2};{3}" -f $_.Split(",")[3],$_.Split(",")[6],$_.Split(",")[8],$_.Split(",")[7]} # this will sort the ips to the most common one, ie: users logs into 6 machines, # but 1 was 12 times and all the others was 1 each, we get the 12 times $d = $c | %{if($_.split(";")[2]){$_.Split(";")[2]}} | group -NoElement | sort -Descending if($d){ #Just give me the entries with my most common IP $e = $c | ?{$_ -match $d.Values} } #return what you found... if ($e.count) { # Returning 1st entry in array with ips $e[0] } Elseif ($e) { # Returning only entry with ip $e } Else { if ($c.count) { # Returning 1st entry in array with no IP $c[0] } Else { # Returning only entry with no IP $c } } } } Function Get-MRServer ($MBX = $null) { <# .SYNOPSIS Pick an MRSServer in the same AD Site as the destination MBX Database. .DESCRIPTION If you are using deticated CAS servers to import the PST files use this function to pick the correct one. Pick the wrong MRServer and the Import will never start - here I pick the an MR Server in the Same AD Site using the CAS as a guide we have dediticated "pst import" CAS servers. We are chosing the One CAS server we have designated to heap many request upon so we don't effect user's normal performance on production CAS servers. .NOTES We have since moved all our live copies of each Archive Mailboxdatabase to the same AD site. It is also possible to skip this step, and let exchange pick a cas server. Depends on how much you are moving and how you feel that will effect your users See "Import-PSTFromShare" #> #--------------------------------------------------------------------- $Return = $null # If ($MBX) { # if (((get-mailboxdatabase $mbx.database.Name).RpcClientAccessServer) -match "^ad01") { # $Return = "cas02.domain.com" # } Else { # $Return = "cas04.domain.com" # } # } # ====> TO DO ==== # you will need to replace this with your cas server # or adjust the code above to pick the correct one $Return = "cas02.domain.com" $Return } Function Get-OutlookEXEVersion () { <# .SYNOPSIS Discover the version of Outlook on a PC .DESCRIPTION Discover the version of Outlook on a PC There are many version and many people do not have a compatible version with Exchange 2010 Archive Mailbox #> param( $ComputerName = $null ) $OL = $Null if($ComputerName) { if (Test-Connection -ComputerName $ComputerName -Quiet -Count 1) { Write-Verbose "Trying $ComputerName" If ( Test-path ('\\\\' + $ComputerName + '\\C$\\Program Files (x86)\\Microsoft Office\\Office14\\outlook.exe')) {# office 2010 (32b) on 64bit Write-Verbose "Office 2010 on 64bit" $OL = gci ('\\\\' + $ComputerName + '\\c$\\Program Files (x86)\\Microsoft Office\\Office14\\outlook.exe') } ElseIf (Test-path ('\\\\' + $ComputerName + '\\c$\\Program Files\\Microsoft Office\\Office14\\outlook.exe')) { # office 2010 on 32bit Write-Verbose "Office 2010" $OL = gci ('\\\\' + $ComputerName + '\\c$\\Program Files\\Microsoft Office\\Office14\\outlook.exe') } ElseIf (Test-path ('\\\\' + $ComputerName + '\\c$\\Program Files\\Microsoft Office\\Office12\\outlook.exe')) { # office 2007 Write-Verbose "Office 2007" $OL = gci ('\\\\' + $ComputerName + '\\c$\\Program Files\\Microsoft Office\\Office12\\outlook.exe') } Else { #check to see if this is (oh my god!) a 2003 client if (Test-Path ('\\\\' + $ComputerName + '\\c$\\Program Files\\Microsoft Office\\OFFICE11\\outlook.exe')) { Write-Verbose "Office 2003" $OL = gci ('\\\\' + $ComputerName + '\\c$\\Program Files\\Microsoft Office\\OFFICE11\\outlook.exe') } Else { Write-Verbose "Can't determine Outlook version [$ComputerName]" } } } Else { Write-Warning "[$ComputerName] is not responding" } } Else { Write-Verbose "missing computername [$ComputerName]" } $OL.VersionInfo.ProductVersion } Function Get-SingleMailboxObject($Name = $null) { <# .SYNOPSIS Return a single mailbox .DESCRIPTION Since we are importing mail and humans can be error prone, make absolutely sure we only get one hit on the requested mailbox #> #----------------------------------------------------------------- $ReturnMBX = $null if ($Name) { $MBX = get-mailbox $Name -EA 0 if (!($MBX.Count)) { # is it less than two? if ($MBX) { # is it more than zero $ReturnMBX = $MBX # Return the one } } } $ReturnMBX } Function New-OnlineArchiveByJob($JobObj = $null) { <# .SYNOPSIS Based on Job information, give user Online PST feature. .DESCRIPTION If this job's user is not enabled for online archive then create one in the smallest database. The smallest DB was determined during the "add-PSTImportQueue" ($JobObj.TargetDB) #> $Return = $false if ($JobObj) { $MBXObj = Get-SingleMailboxObject $JobObj.UserEmail #Write-Verbose "User DisplayName : $($mbxObj).Displayname) Derived from $($JobObj.UserEmail)" # this will either fail, create, or do nothing ;) Enable-Mailbox -Archive -Identity $mbxObj -ArchiveDatabase ($JobObj.TargetDB) -ArchiveName $('Online PST - ' + ($mbxObj).Displayname) -ea 0 # just a buffer sleep -Seconds 5 # Adjust Quota so this user is not prohibited during migration Adjust-Quota $MBXObj # reload to capture changes $MBXObj = Get-SingleMailboxObject $JobObj.UserEmail If ($MBXObj.ArchiveDatabase) { $Return = $true #Write-Verbose "User has Archve!" } Else { $Return = $false #Write-Verbose "User has NO Archve!" } } $Return } Function Test-OutlookClientVersion ($V = $null) { <# .SYNOPSIS Test Oulook.exe version .DESCRIPTION older outlook clients can't see the "Online Archive" so flag those users who need an upgrade 12.0.6550.5000 is the minimum level - buggy 12.0.6607.xxxx is Office 2007 SP3 -- preferred level there are search bugs in earlier versions 14.0.6109.5005 is outlook 14 patched to Nov 8, 2011 14.0.6117.5xxx is patched thru April 2012 -- preferred #> $VOK = $False if($V) { if ($V.Split(".")[0] -eq 14) { # Outlook 2010 (32bit) 14.0.4760.1000 if ($V.Split(".")[2] -ge 4760) {$VOK = $true} } Elseif ($V.Split(".")[0] -eq 12) { # Outlook 2007 (32bit) 12.0.6550.5000 (or above) if ($V.Split(".")[2] -ge 6550) {$VOK = $true} } } $VOK } #============================================================================= # PST File Functions #============================================================================= Function Copy-PSTtoImportShare($Path=$Null, $Dest=$null){ <# .SYNOPSIS copy the pst to our share folder .DESCRIPTION Copy the pst to our share folder using Copy-item in the same local AD site works fine. Using BITS when copying over WAN lines #> $Result = "Fail" # Copied or Error(s) #Write-Verbose "Copy From: $Path To: $Dest" if($Path -and $Dest ) { $NewFile = Copy-Item -Path $Path -Destination $Dest -PassThru if ($NewFile){ $Result = "Copied" } Else { # return the last error $Result = $error[0].Exception Write-Verbose "Copy ResultFrom: $($error[0].Exception)" } } $Result } Function Copy-PSTusingBITS ($JobObj = $null) { <# .SYNOPSIS copy the pst to our share folder .DESCRIPTION Copy the pst to our share folder using Copy-item in the same local AD site works fine. Using BITS when copying over WAN lines #> $Result = $false if ($JobObj) { $params = @{ Source = ($Jobobj.OrgUNCName) Destination = ($Jobobj.TargetUNCName) Description = ("Online PST BITS Copy") DisplayName = ($JobObj.JobName) Asynchronous = $true Priority = "Normal" } $Result = Start-BitsTransfer @params } $Result = $null sleep 2 $Result = Get-BitsTransfer | Where-Object { $_.DisplayName -eq ($ThisJob.JobName) } $Result } Function Get-PSTFileList() { <# .SYNOPSIS Discover PST Files in folders .DESCRIPTION Discover PST Files in folders .NOTES - Some AD objects do not have a home directory - Allowed for some results of *.pst being directories #> param( $Homedir = $null, $PCIP = $null, $SearchPC = $false, $OS = $null, $UN = $null, $SourceDir=$null ) $HDFiles = $null $PCFIles = $null #Write-Verbose "Get-PSTFileList $HomeDir $PCIP $SearchPC $OS $UN" # assuming SourceDir is a specific target dir if(!($SearchPC) -and $SourceDir) { Write-host "`t-> Override HomeDir: $HomeDir to $SourceDir" $Homedir = $SourceDir } If ($Homedir){ if(Test-Path $HomeDir) { Write-Verbose "`t`t-> Searching $HomeDir" # ensure this is an array even if we have only one entry [array]$HDFiles = gci -path $HomeDir -Filter '*.pst' -Recurse -Force -EA 0 | ?{$_.PSIsContainer -eq $false} } } if($SearchPC -and $PCIP) { if(Test-Connection $PCIP -Count 1 -Quiet) { $PCDir = $null if($SourceDir) { $PCDir = $SourceDir } Else { if($OS -match "7") { Write-Verbose "`t`t-> Searching Windows7 PC $UN" $PCDir = $("\\\\" + $PCIP + "\\C$\\Users\\" + $UN + "\\AppData\\Local\\Microsoft\\Outlook") } Elseif ($OS -match "XP") { Write-Verbose "`t`t-> Searching WindowsXP PC $UN" $PCDir = $("\\\\" + $PCIP + "\\C$\\Documents And Settings\\" + $UN) } Else { #we don't know OS, so test them and see which flies Write-Verbose "`t`t-> OS not known, testing for OS :" if(Test-Path ("\\\\" + $PCIP + "\\C$\\Users\\" + $UN + "\\AppData\\Local\\Microsoft\\Outlook")) { Write-Verbose "`t`t-> Try Windows7" $PCDir = "\\\\" + $PCIP + "\\C$\\Users\\" + $UN + "\\AppData\\Local\\Microsoft\\Outlook" } Elseif (Test-Path ("\\\\" + $PCIP + "\\C$\\Documents And Settings\\" + $UN)){ Write-Verbose "`t`t-> Try WindowsXP" $PCDir = $("\\\\" + $PCIP + "\\C$\\Documents And Settings\\" + $UN) } Else { Write-Verbose "`t`t-> OS Unknown" $PCDir = $("\\\\" + $PCIP + "\\c$") } } } #if have a legit dir or just the whole c drive ... Write-Verbose "`t`t-> Searching $PCDir" If(Test-Path $PCDir) { [array]$PCFIles = gci -path ($PCDir) -Filter '*.pst' -Recurse -Force -EA 0 | ?{$_.PSIsContainer -eq $false} } } Else { Write-Output ("`t-> $PCIP is not responding.") } } if($HDFiles -and $PCFIles){ $Files = $HDFiles + $PCFIles } Elseif ($HDFiles -and (-not $PCFIles)){ $Files = $HDFiles } Elseif ((-not $HDFiles) -and $PCFIles){ $Files = $PCFIles } Else { $Files = $null } $Files } Function Import-PSTFromShare($JobObj){ <# .SYNOPSIS import into the Archive mailbox .DESCRIPTION import into the Archive mailbox .NOTES We found that 99% of the people wanted to keep their data separate after the import, just like it was in their PST files, so UseTargetRootFolder was defaulted to true in the NEw-PSTJobObject function We check here for false. #> $Return = "Failed" $Error.Clear | Out-Null $MBXName = $JobObj.UserObj $User = $JobObj.UserObj.Split("\\")[1] $File = $JobObj.TargetUNCName $JobName = $JobObj.JobName $CAS = $JobObj.MRServer if ($JobObj.TargetRootFolder) { $Folder = $JobObj.TargetRootFolder } Else { $Folder = $JobObj.OrgFileName } Write-Debug "$MBXName -Name $JobName -Batchname $USER -MRSServer $CAS -TargetDB $JobObj.TargetDB" # import the pst #======= TO DO ============ # remove the -MRSServer $CAS - if you want Exchange to choose the CAS server every time. if($JobObj.UseTargetRootFolder -eq "TRUE") { $PSTQueued = New-MailboxImportRequest -Name $JobName -BatchName $USER -Mailbox "$MBXName" -FilePath "$File" -IsArchive -MRSServer $CAS -BadItemLimit 9999 -AcceptLargeDataLoss -Confirm:$false -targetrootfolder $Folder } Else { $PSTQueued = New-MailboxImportRequest -Name $JobName -BatchName $USER -Mailbox "$MBXName" -FilePath "$File" -IsArchive -MRSServer $CAS -BadItemLimit 9999 -AcceptLargeDataLoss -Confirm:$false } If($PSTQueued) { $Return = $PSTQueued.Status } Else { $Return = $Error[0].ToString() } sleep -Seconds 5 $Return } Function Move-PSTToLocal ($IP=$null, $PSTFiles=$null, $SamAcct=$null, $IgnoreAge=$False) { <# .SYNOPSIS clear PST files off the Home shares .DESCRIPTION The botton line of this project is to clear PST files off the Home shares If the PST file has been imported the file itself has become a backup and as such is safe to put on the local PC of the user. .NOTES Move PSTs If this is a windows 7 box and has 2010 this might be the place to put them \\\\172.18.20.1\\c$\\Users\\<user>\\Documents\\Outlook Files but this is good for XP \\\\172.18.20.1\\c$\\D9ocuments and Settings\\<user>\\My Docuemtns\\Outlok Files If this user is in a far away place, then do NOT push the data back to the PC #> Write-Host "Starting = Who:($SamAcct), Count:($(($PSTFiles).Count)), Computer:($IP)" $HQUser = $true $Region = (get-mailbox $SamAcct).CustomAttribute2 If (($Region -eq "Asia") -or ($Region -eq "Europe")) {$HQUser = $false} if ($IP -eq "None") {$IP = $null} if($IP -and $PSTFIles -and $SamAcct -and $HQUser) { #make sure we can ping the PC Write-Host $("$SamAcct; Starting Move-PSTFiles $(get-date)") $("$SamAcct; Starting Move-PSTFiles $(get-date)") >> $Script:MoveFileLog if (Test-Connection -ComputerName $IP -Quiet){ Write-Host $("$SamAcct; Connect to $IP passed") $("$SamAcct; Connect to $IP passed") >> $Script:MoveFileLog # both return MB $AvailableSpace = [int](get-freediskspace 'c:' $IP)/2 $PSTFiles = $PSTFiles | Sort Length $PSTSize = (($PSTFIles | Measure-Object Length -sum).Sum)/(1024*1024) $OldPSTSize = ((($PSTFIles | ?{$_.LastWriteTime -le (get-date ((get-date).adddays(-90))) } | Measure-Object Length -sum).Sum)/(1024*1024)) $Continue = $false if (Test-Path $('\\\\' + $IP + '\\c$\\users\\' + $SamAcct)) { # Put them in this dir structure, create or use Outlook Files dir $LocalBU = $('\\\\' + $IP + '\\c$\\users\\' + $SamAcct+ '\\Documents\\Outlook Files') if (!(Test-Path $LocalBU)){ mkdir $LocalBU } $Continue = $true Write-Host $("$SamAcct; Connect to $IP passed") $("$SamAcct; LocalBU is $LocalBU") >> $Script:MoveFileLog } Elseif (Test-Path $('\\\\' + $IP + '\\c$\\documents and settings\\' + $SamAcct)) { # Put them in this dir structure, create or use Outlook Files dir $LocalBU = $('\\\\' + $IP + '\\c$\\documents and settings\\' + $SamAcct + '\\Outlook Files') if (!(Test-Path $LocalBU)){ mkdir $LocalBU } $Continue = $true Write-Host $("$SamAcct; LocalBU is $LocalBU") $("$SamAcct; LocalBU is $LocalBU") >> $Script:MoveFileLog } Else { # crap! i give up... #I hope i have the right IP -- log it Write-Host "Can not find a secure directory for $SamAcct" $Continue = $false $("$SamAcct; LocalBU is Can not find a secure directory; Fail") >> $Script:MoveFileLog } if ($Continue) { # move the files $FileNames = @() $PSTFiles | %{ $ThisPST = $_ $FN = $ThisPST.Name $PSTBackups = $LocalBU $FileAge = (((get-date) - ($ThisPST.LastWriteTime)).Days) Write-Host "Working: $FN" Write-Host "(($AvailableSpace) -gt ($PSTSize))" Write-Host "IgnoreAge is $IgnoreAge" if($AvailableSpace -gt $PSTSize) { # there is enough space on the drive to hanlde all the PSTs If($IgnoreAge) { # if we are moving a lot of files, many can be named the same, as in backups and crap like that # so allow by adding a random number to the filename if($FileNames -contains $FN -or (Test-Path $($PSTBackups + "\\" + $FN))){ #rename it in the move $rn = "{0:00}" -f (Get-Random -maximum 10000) [string]$FN = $ThisPST.Name.Split(".")[0] + "-" + $RN + "." + ($ThisPST.Name.Split(".")[1]) $PSTBackups = $PSTBackups + "\\" + $FN $("$SamAcct; Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)") >> $Script:MoveFileLog Write-Host "Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)" #Read-Host "Continue" Move-Item -Path $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups) } Else { # Just Move It Move It $PSTBackups = $PSTBackups + "\\" + $FN $("$SamAcct; Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)") >> $Script:MoveFileLog Write-Host "Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)" #Read-Host "Continue" Move-Item -Path $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups) } } Else { #don't move if younger than 30 days If ($ThisPST.LastWriteTime -le (get-date ((get-date).adddays(-30)))){ #meaning it's older, so move it # if we are moving a lot of files, many can be named the same, as in backups and crap like that # so allow by adding a random number to the filename if($FileNames -contains $FN -or (Test-Path $($PSTBackups + "\\" + $FN))){ #rename it in the move $rn = "{0:00}" -f (Get-Random -maximum 10000) [string]$FN = $ThisPST.Name.Split(".")[0] + "-" + $RN + "." + ($ThisPST.Name.Split(".")[1]) $PSTBackups = $PSTBackups + "\\" + $FN $("$SamAcct; Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)") >> $Script:MoveFileLog Write-Host "Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)" #Read-Host "Continue" Move-Item -Path $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups) } Else { # Just Move It Move It $PSTBackups = $PSTBackups + "\\" + $FN $("$SamAcct;Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)") >> $Script:MoveFileLog Write-Host "Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)" #Read-Host "Continue" Move-Item -Path $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups) } } Else { # file is too young $("$SamAcct; Age [$($FileAge)] Skipping due to Age<30 $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)") >> $Script:MoveFileLog Write-Host "Age [$($FileAge)] Skipping due to Age<30 $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)" } } } Else { # there is NOT enough space on the drive to handle all the PSTs # Psts are sorted by smallest to largest so do what you can $AvailableSpace = [int](get-freediskspace 'c:' $IP)/2 $PSTSize = (($ThisPST | Measure-Object Length -sum).Sum)/(1024*1024) If($AvailableSpace -gt $PSTSize) { Write-Host "(($AvailableSpace) -gt ($PSTSize))" If($IgnoreAge) { # if we are moving a lot of files, many can be named the same, as in backups and crap like that # so allow by adding a random number to the filename if($FileNames -contains $FN -or (Test-Path $($PSTBackups + "\\" + $FN))){ #rename it in the move $rn = "{0:00}" -f (Get-Random -maximum 10000) [string]$FN = $ThisPST.Name.Split(".")[0] + "-" + $RN + "." + ($ThisPST.Name.Split(".")[1]) $PSTBackups = $PSTBackups + "\\" + $FN $("$SamAcct; Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)") >> $Script:MoveFileLog Write-Host "Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)" #Read-Host "Continue" Move-Item -Path $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups) } Else { # Just Move It Move It $PSTBackups = $PSTBackups + "\\" + $FN $("$SamAcct; Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)") >> $Script:MoveFileLog Write-Host "Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)" #Read-Host "Continue" Move-Item -Path $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups) } } Else { #don't move if younger than 90 days If ($ThisPST.LastWriteTime -le (get-date ((get-date).adddays(-30)))){ #meaning it's older, so move it # if we are moving a lot of files, many can be named the same, as in backups and crap like that # so allow by adding a random number to the filename if($FileNames -contains $FN -or (Test-Path $($PSTBackups + "\\" + $FN))){ #rename it in the move $rn = "{0:00}" -f (Get-Random -maximum 10000) [string]$FN = $ThisPST.Name.Split(".")[0] + "-" + $RN + "." + ($ThisPST.Name.Split(".")[1]) $PSTBackups = $PSTBackups + "\\" + $FN $("$SamAcct; Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)") >> $Script:MoveFileLog Write-Host "Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)" #Read-Host "Continue" Move-Item -Path $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups) } Else { # Just Move It Move It $PSTBackups = $PSTBackups + "\\" + $FN $("$SamAcct; Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)") >> $Script:MoveFileLog Write-Host "Age [$($FileAge)] Moving $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)" #Read-Host "Continue" Move-Item -Path $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups) } } Else { # file is too young $("$SamAcct; Age [$($FileAge)] Skipping due to Age<30 $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)") >> $Script:MoveFileLog } } } Else { $("$SamAcct; Age [$($FileAge)] Skipping due to AvailableSpace $($ThisPST.VersionInfo.Filename) -Destination $($PSTBackups)") >> $Script:MoveFileLog } } $FileNames += $FN } } Else { Write-Host "No Files Moved." $("$SamAcct; No Files Moved.") >> $Script:MoveFileLog } } Else { Write-Host "Computer [$IP] seems dead" $("$SamAcct; Computer [$IP] seems dead.") >> $Script:MoveFileLog } } Else { if (!($PSTFiles)) { Write-Host "No PST Files found." $("$SamAcct; No PST Files found.") >> $Script:MoveFileLog } Else { Write-Host "Bad Parameters or Not CONUS User." $("$SamAcct; Bad Parameters or Not CONUS User.") >> $Script:MoveFileLog } } } #============================================================================= # PST Queue Functions #============================================================================= Function Format-JobStatus($JobObj) { <# .SYNOPSIS Query the queue for info on a particular user. .DESCRIPTION Query the queue for info on a particular user. Count the number of jobs in each status category, incoming JobObj is a collection. #> # # # # $JobsCount = 0 $StatusNew = 0 $StatusCopied = 0 $StatusBITS = 0 $StatusInQueue = 0 $StatusImported = 0 $StatusCleanedup = 0 $StatusNotified = 0 $LastError = $null $JobSize = 0 $StatusSkipped = 0 $JobObj | %{ $ClientOK = $_.ClientVerOK $UName = $_.UserMBX $TargetDB = $_.TargetDB $a = [int]($_.FileSize) $JobSize += $a $skip=$false if(($_.ProcessFile -eq "FALSE")){$Skip=$true} Switch ($_.JobStatus) { New { if(($Skip)){$StatusSkipped++} Else {$StatusNew++} } NewBits { if(($Skip)){$StatusSkipped++} Else {$StatusNew++} } Copied {$StatusCopied++} InBits {$StatusBITS++} InQueue {$StatusInQueue++} Imported {$StatusImported++} CleanedUp {$StatusCleanedup++} Notified {$StatusNotified++} } $JobsCount++ } $StatusEntry = New-Object PSObject $StatusEntry | Add-Member -type NoteProperty -name Name -value ($UName) $StatusEntry | Add-Member -type NoteProperty -name Client -value ($ClientOK) $StatusEntry | Add-Member -type NoteProperty -name Size -value ($JobSize) $StatusEntry | Add-Member -type NoteProperty -name Jobs -value ($JobsCount) $StatusEntry | Add-Member -type NoteProperty -name New -value ($StatusNew) $StatusEntry | Add-Member -type NoteProperty -name Skip -value ($StatusSkipped) $StatusEntry | Add-Member -type NoteProperty -name BITS -value ($StatusBITS) $StatusEntry | Add-Member -type NoteProperty -name Copied -value ($StatusCopied) $StatusEntry | Add-Member -type NoteProperty -name InQue -value ($StatusInQueue) $StatusEntry | Add-Member -type NoteProperty -name Imptd -value ($StatusImported) $StatusEntry | Add-Member -type NoteProperty -name ClndUp -value ($StatusCleanedup) $StatusEntry | Add-Member -type NoteProperty -name Notifd -value ($StatusNotified) $StatusEntry | Add-Member -type NoteProperty -name Target -value ($TargetDB) #$StatusEntry | Add-Member -type NoteProperty -name Errors -value ($LastError) $StatusEntry } Function Get-ArchDB() { <# .SYNOPSIS Find the smallest Archive mailbox database .DESCRIPTION Find the smallest Archive mailbox database, not necesarily the smallest now, but even after all the current jobs are processed #> #get current sizes - include or exclude certain DBs $ArchSize = @{} # get all database that Start with "arch", 3 digits, and end with character "b-z" like "Arch101B" for example # excluding arch102* for now, no more users there... (get-mailboxdatabase |?{$_.name -match 'arch\\d{3}[acdef]' -and $_.name -notmatch 'arch102'} | Get-MailboxDatabase -Status) | %{$ArchSize.Add($_.Name, $_.DatabaseSize.ToMB())} # need to account for pending items... if($OldJobQueue) { $OldJobQueue | %{ $tmp = $ArchSize.item($_.TargetDB) $Tmp += [int]$_.FileSize $ArchSize.remove($_.TargetDB) $ArchSize.add($_.TargetDB, $tmp) } } # return the smallest one ($ArchSize.GetEnumerator() | sort Value)[0].Name } Function Lock-PSTIQ() { <# .SYNOPSIS Signal the queue file is in use by creating a file. .DESCRIPTION Signal the queue file is in use by creating a file. #> if(!(Test-PSTIQLock)) {$a = New-Item $($Script:PSTUNCDir + '\\PSTImportQueue.Lock') -itemtype "file"} } Function New-TargetPSTDirectory($MBX = $null) { <# .SYNOPSIS Create a directory to hold the PST file while they are importing. .DESCRIPTION Create a directory to hold the PST file while they are importing. These psts are deleted at the end, but reports for each PST file are left in the directory. #> $Return = "Error" If ($MBX) { $dir = $Script:PSTShareDir + "\\" + $MBX.samaccountname if(!(Test-Path $dir)) { $newdir = ni -ItemType Directory -Path $dir } Else { $Return = $dir } } #Test new dir and make sure it's there If($newdir) { $Return = (resolve-path $newdir).ProviderPath } $Return } Function Test-PSTIQLock () { <# .SYNOPSIS Test to see if PST Import Queue is in use. .DESCRIPTION Test to see if PST Import Queue is in use. #> Test-Path $($Script:PSTUNCDir + '\\PSTImportQueue.Lock') } Function Unlock-PSTIQ() { <# .SYNOPSIS Remove the lock when the PST Import Queue is no longer in use. .DESCRIPTION Remove the lock when the PST Import Queue is no longer in use. #> if(Test-PSTIQLock) {Remove-Item $($Script:PSTUNCDir + '\\PSTImportQueue.Lock')} } #============================================================================= # Send Notification Functions #============================================================================= Function Send-NotificationInitialReport($JobObj) { <# .SYNOPSIS Send the User a notification of PST files found and the work to be done. .DESCRIPTION Send the User a notification of PST files found and the work to be done. Incoming JobObj will give us the information we needed to the report. #> $AllProcessFiles = $JobObj | ?{$_.ProcessFile -eq $true} $AllSkippedJobs = $JobObj | ?{$_.ProcessFile -ne $true} $JobObj | %{$User = $_.UserMBX; $CLOK = $_.ClientVerOK } Write-Host $User Write-Host $CLOK $Subject = "Requested PST Import: Initial Report for " + $User $From = "EmailTeam@domain.com" $Body = "Note: This process will not delete or alter your original PSTs in any way.`n" if ($JobObj.ClientVer -match "^14.") { $Body = $Body + "Your offline PST files will be copied into your new " + '"Archive - ' + $JogObj.UserEmail + '"' + " folder in Outlook.`n" } Else { $Body = $Body + "Your offline PST files will be copied into your new " + '"Online PST"' + " folder in Outlook.`n" } $Body = $Body + "`n" $Body = $Body + "The copy may take a few nights to complete. The process will start tonight about 7PM (1900). `n" $Body = $Body + "`t- Do not add any messages to your PSTs during this process.`n" $Body = $Body + "`t- Please shut down Outlook before leaving each night.`n" $Body = $Body + "`t- You do not need to turn off your PC.`n" $Body = $Body + "`n" $Body = $Body + "You will be notified when the copies are complete.`n" $Body = $Body + "`n" # you may want to comment this out, or create one of your own #$Body = $Body + "Click below to read the FAQ about Online PSTs." #$Body = $Body + "`n" #$Body = $Body + '"' + 'http://<link to self help doc on sharepoint> #$Body = $Body + "`n" $Body = $Body + "Once you see your new Online PST, use it as you would any PST.`n" $Body = $Body + "`n" $Body = $Body + "The procedure for finding your PST files has finished and found " + $JobObj.Count + " files. The ones scheduled for import, are:`n`n" #location of How to remove password on PST #"`n(http://office.microsoft.com/en-us/outlook-help/remove-a-password-from-a-personal-folders-file-pst-HA001151725.aspx)" if ($AllProcessFiles) { $NUm = 0 $tmp = $null $tmp = "{0,3}`t{1,-25}`t{2}`t`t{3}`n" -f ("Num"),("FileName"),("Size"),("Directory") $Body = $Body + $tmp $AllProcessFiles | %{ $NUm++ $To = $_.UserEmail $temp = '"' + (split-path $_.OrgUNCName) + '"' $temp1 = $_.OrgFileName $tempS = $_.FileSize $tmp = $null $tmp = "{0,3}`t{1,-25}`t({2,7} M)`t{3}`n" -f ($Num),($temp1),($tempS), ($temp) $Body = $Body + $tmp } } Else { $Body = $Body + "(None)" } $Body = $Body + "`n`nSkipped Files: `n" if($AllSkippedJobs) { $NUm = 0 $tmp = $null $tmp = "{0,3}`t{1,6}`t{2,-25}`t{3}`t`t{4}`n" -f ("Num"),("Reason"),("FileName"),("Size"),("Directory") $Body = $Body + $tmp $AllSkippedJobs | %{ $NUm++ $To = $_.UserEmail $temp = '"' + (split-path $_.OrgUNCName) + '"' $temp1 = $_.OrgFileName $tempS = $_.FileSize $skip = $_.SkipReason $tmp = $null $tmp = "{0,3}`t{1,6}`t{2,-25}`t({3,7} M)`t{4}`n" -f ($Num),($skip),($temp1),($tempS),($temp) $Body = $Body + $tmp } } Else { $Body = $Body + "(None)" } $Body = $Body + "`n`n" $Body = $Body + "Files are skipped due to either size (empty file) or not opened by Outlook in the last 2 years.`n" $Body = $Body + "Files also can be skipped if they look like Backups (BU) or Sharepoint Lists (SP).`n" $Body = $Body + "(Skipping files is just a suggestion. You can opt to include them.)`n" if($JobObj.Count){ $Body = $Body + "`n[Run on: " + $(Hostname) + "; Client is " + (($JobObj)[0].ClientVerOK) + " " + (($JobObj)[0].ClientVer) + "]["+(($JobObj)[0].IP)+"]["+(($JobObj)[0].OSName)+"]" } Else { $Body = $Body + "`n[Run on: " + $(Hostname) + "; Client is " + (($JobObj).ClientVerOK) + " " + (($JobObj).ClientVer) + "]["+(($JobObj).IP)+"]["+(($JobObj).OSName)+"]" } If ($NoNotify) { Send-MailMessage -Body $body -From $From -SmtpServer $Script:SMTPServer -Subject $Subject -To $Script:AdminEmail } Else { Send-MailMessage -Body $body -To $To -From $From -SmtpServer $Script:SMTPServer -Subject $Subject -cc $Script:AdminEmail #Send-MailMessage -Body $body -To $JobObj.UserEmail -From $From -SmtpServer $Script:SMTPServer -Subject $Subject } } Function Send-NotificationFinalReport($JobObj) { <# .SYNOPSIS Send User the Final report detailing the work done. .DESCRIPTION Send User the Final report detailing the work done. #> $AllProcessFiles = $JobObj | ?{$_.ProcessFile -eq "TRUE"} $AllSkippedJobs = $JobObj | ?{$_.ProcessFile -eq "FALSE"} if($JobObj.Count) { $Subject = "Requested PST Import: Final Results for: " + $JobObj[0].UserMBX $ClientVer = $JobObj[0].ClientVer $Email = $($JobObj[0].UserEmail.ToString()) } Else { $Subject = "Requested PST Import: Final Results for: " + $JobObj.UserMBX $ClientVer = $JobObj.ClientVer $Email = $($JobObj.UserEmail.ToString()) } $From = "EmailTeam@domain.com" $Body = "The process for copying your PST files has finished. Please take a few moments to complete the final steps:`n" $Body = $Body + "`n" if ($ClientVer -match "^14." -or $ClientVer -match "Ignore") { $Body = $Body + "`t1. Review messages in the " + '"Archive - ' + $Email + '"' + " folder in Outlook and confirm all have been copied correctly.`n" } Else { $Body = $Body + "`t1. Review messages in the " + '"Online PST"' + " folder in Outlook and confirm all have been copied correctly.`n" } #$Body = $Body + "`t1. Review messages in the " + '"Online PST - <yourname>" or "Archive - <yourname>"' + " folder in Outlook and confirm all have been copied correctly.`n" $Body = $Body + "`t2. Disconnect the old PSTs from Outlook. (right click the name and choose: Close <pstname>)`n" $Body = $Body + "`t3. Restart Outlook - to release the lock on the file.`n" $Body = $Body + "`t4. Move the old PST files from your Home Drive (H:\\) to a local drive. This will improve your Outlook performance!`n" $Body = $Body + "`t (For example, create a directory in " + '"My Documents"' + " called " + '"Outlook Files"' + " and move the files listed below from your H:\\ to the new Outlook Files directory.)`n" if ($ClientVer -match "^14." -or $ClientVer -match "Ignore") { $Body = $Body + "`t5. Begin storing messages in your " + '"Archive - ' + $Email + '"' + " folder instead of your old PSTs.`n" } Else { $Body = $Body + "`t5. Begin storing messages in your " + '"Online PST"' + " folder instead of your old PSTs.`n" } #$Body = $Body + "`n`tFor detailed instructions, click this link:`n" #$Body = $Body + "`n`t" + '"http://<sharepointsite>/Self-Help/Standard Application Issues/How do I Disconnect My Personal Folders.pdf"' + "`n" #$Body = $Body + "`n" $Body = $Body + "`tNote: Remember you can read your old PSTs at any time. In a few days you will not be able to add any new emails to these old PST files.`n" $Body = $Body + "`t You are now using the Online PST instead.`n" $Body = $Body + "`n" $Body = $Body + "`nThe files which can be moved off your home drive:`n" $Body = $Body + "`n" $Body = $Body + "`nIf you need assistance or have any questions, simply reply-all to this email.`n" $Body = $Body + "`n" $Body = $Body + "Imported Files:`n" $NUm = 0 $tmp = "{0,3}`t{1,-40}`t{2,-35}`t{3}`t{4}`n" -f ("Num"),("FileName"),("Target Folder"),("Size"),("Directory") $Body = $Body + $tmp $AllProcessFiles | %{ $NUm++ $To = $_.UserEmail $temp = '"' + (split-path $_.OrgUNCName) + '"' $temp1 = $_.OrgFileName $tempS = $_.FileSize $tempT = $_.TargetRootFolder $tmp = $null $tmp = "{0,3}`t{1,-40}`t{2,-35}`t({3,7} M)`t{4}`n" -f ($Num),($temp1),($tempT),($tempS),($temp) $Body = $Body + $tmp } $Body = $Body + "`n`nSkipped Files:`n" if($AllSkippedJobs) { $NUm = 0 $tmp = $null $tmp = "{0,3}`t{1,6}`t{2,-40}`t{3}`t`t{4}`n" -f ("Num"),("Reason"),("FileName"),("Size"),("Directory") $Body = $Body + $tmp $AllSkippedJobs | %{ $NUm++ $To = $_.UserEmail $temp = '"' + (split-path $_.OrgUNCName) + '"' $temp1 = $_.OrgFileName $tempS = $_.FileSize $skip = $_.SkipReason $tmp = $null $tmp = "{0,3}`t{1,6}`t{2,-40}`t({3,7} M)`t{4}`n" -f ($Num),($skip),($temp1),($tempS),($temp) $Body = $Body + $tmp } } Else { $Body = $Body + "(None) " } #$Body = $Body + "`n`nIf you have any questions, reply to this email." $Body = $Body + "`n" $Body = $Body + "`Thank You -- The Email Group" $Body = $Body + "`n" if($JobObj.Count){ $Body = $Body + "`n[Run on: " + $(Hostname) + "; Client is " + (($JobObj)[0].ClientVerOK) + " " + (($JobObj)[0].ClientVer) + "]["+(($JobObj)[0].IP)+"]["+(($JobObj)[0].OSName)+"]" } Else { $Body = $Body + "`n[Run on: " + $(Hostname) + "; Client is " + (($JobObj).ClientVerOK) + " " + (($JobObj).ClientVer) + "]["+(($JobObj).IP)+"]["+(($JobObj).OSName)+"]" } Send-MailMessage -Body $body -To $To -From $From -SmtpServer $Script:SMTPServer -Subject $Subject -Cc $Script:AdminEmail } Function Send-NotificationPSTRemoval() { <# .SYNOPSIS Send user a report showing the files that are still 'connected' to Outlook .DESCRIPTION Send user a report showing the files that are still 'connected' to Outlook Connected means the LastWriteTime was within the last 24 hours. User gets this email every 14 days as a reminder to disconnect their Old PST files and optionaly remove those PST files from Home Share. #> #------------------------------------------------------------------------ Param( $ArchObj, [array]$PSTFilesInUse, [array]$PSTFilesALL, [array]$PSTFilesMovable ) $Subject = "Online PST -- Possible Outlook Issue : " + $ArchObj.DisplayName + " (" + $ArchObj.DaysSinceImport + ")" $From = "EmailTeam@domain.com" $To = $((get-mailbox $ArchObj.DisplayName).PrimarySMTPAddress.ToString()) $CC = $Script:AdminEmail [int]$InUse = cc $PSTFilesInUse; Write-Verbose "[SendNotification] Inuse - $InUse" [int]$AllPSTs = cc $PSTFilesALL; Write-Verbose "[SendNotification] AllPST - $AllPSTs" [int]$Movable = cc $PSTFilesMovable; Write-Verbose "[SendNotification] AllPST - $AllPSTs" #grab this user's latest client version $Vers = (import-csv $Script:PSTCompleteFile | ?{$_.UserMBX -match ($ArchObj.DisplayName)} | sort LastCheckTime -Descending) If ($Vers.Count) { $ClientVer = $Vers[0].ClientVer } Else { If ($Vers){ $ClientVer = $Vers.ClientVer } Else { $ClientVer = "Ignore" } } Write-Verbose "[SendNotification] $(($ArchObj).DisplayName) : Client Ver is $($ClientVer)" If ($ClientVer -match "^14." -or $ClientVer -match "Ignore") { $Archive =
PowerShellCorpus/PoshCode/Windows Startup Script_1.ps1
Windows Startup Script_1.ps1
<#====================================================================================== File Name : Startup.ps1 Original Author : Kenneth C. Mazie : Description : This is a Windows startup script with pop-up notification and checks to : assure things are not exectuted if already running or set. It can be run : as a personal startup script or as a domain startup (with some editing). : It is intended to be executed from the Start Menu "All Programs\\Startup" folder. : : The script will Start programs, map shares, set routes, and can email the results : if desired. The email subroutine is commented out. You'll need to edit it yourself. : When run with the "debug" variable set to TRUE it also displays staus in the : PowerShell command window. Other wise all operation statuses are displayed in pop-up : ballons near the system tray. : : To call the script use the following in a shortcut or in the RUN registry key. : "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -WindowStyle Hidden –Noninteractive -NoLogo -Command "&{C:\\Startup.ps1}" : Change the script name and path as needed to suit your environment. : : Be sure to edit all sections to suit your needs before executing. Be sure to : enable sections you wish to run by uncommenting them at the bottom of the script. : : Route setting is done as a function of selecting a specific Network Adapter with the intent : of manually altering your routes for hardline or WiFi connectivity. This section you will : need to customize to suit your needs or leave commented out. This allowed me to : alter the routing for my office (Wifi) or lab (hardline) by detecting whether my : laptop was docked or not. The hardline is ALWAYS favored as written. : : To identify process names to use run "get-process" by itself to list process : names that PowerShell will be happy with, just make sure each app you want to : identify a process name for is already running first. : : A 2 second sleep delay is added to smooth out processing but can be removed if needed. : Notes : Sample script is safe to run as written, it will only load taskmanager and firefox. : In general, I did not write this script for ease of readability. Most commands are : one-liner style, sorry if that causes you grief. : Warnings : Drive mapping passwords are clear text within the script. : : Last Update by : Kenneth C. Mazie (kcmjr) Version History : v1.0 - 05-03-12 - Original Change History : v2.0 - 11-15-12 - Minor edits : v3.0 - 12-10-12 - Converted application commands to arrays : v4.0 - 02-14-13 - Converted all other sections to arrays : =======================================================================================#> clear-host $Debug = $True $CloudStor = $False $ScriptName = "Startup Script" #--[ Prep Pop-up Notifications ]-- [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") $Icon = [System.Drawing.SystemIcons]::Information $Notify = new-object system.windows.forms.notifyicon $Notify.icon = $Icon #--[ NOTE: Available tooltip icons are = warning, info, error, and none $Notify.visible = $true #--[ Force to execute with admin priviledge ]-- $identity = [Security.Principal.WindowsIdentity]::GetCurrent() $principal = new-object Security.Principal.WindowsPrincipal $identity if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -eq $false) {$Args = '-noprofile -nologo -executionpolicy bypass -file "{0}"' -f $MyInvocation.MyCommand.Path;Start-Process -FilePath 'powershell.exe' -ArgumentList $Args -Verb RunAs;exit} if ($debug){write-host "`n------[ Running with Admin Privileges ]------`n" -ForegroundColor DarkCyan} $Notify.ShowBalloonTip(2500,$ScriptName,"Script is running with full admin priviledges",[system.windows.forms.tooltipicon]::Info) if ($debug){write-host "Running in DEBUG Mode..." -ForegroundColor DarkCyan} function Pause-Host { #--[ Only use if you need a countdown timer ]-- param($Delay = 10) $counter = 0; While(!$host.UI.RawUI.KeyAvailable -and ($Delay-- -ne $counter )) #--count down #While(!$host.UI.RawUI.KeyAvailable -and ($counter++ -lt $Delay )) #--count up { clear-host if ($debug){Write-Host "testing... $Delay"} #--count down #Write-Host "testing... $counter" #--count up [Threading.Thread]::Sleep(1000) } } Function SetRoutes { #--[ Array consists of Network, Mask ]-- $RouteArray = @() $RouteArray += , @("10.0.0.0","255.0.0.0") $RouteArray += , @("172.1.0.0","255.255.0.0") $RouteArray += , @("192.168.1.0","255.255.255.0") #--[ Add more route entries here... ]-- $Index = 0 Do { $RouteNet = $ShareArray[$Index][0] $RouteMask = $ShareArray[$Index][1] iex "route delete $RouteNet" Sleep (2) iex "route add $RouteNet mask $RouteMask $IP" Sleep (2) $Index++ } While ($Index -lt $RouteArray.length) } Function SetMappings { #--[ Array consists of Drive Letter, Path, User, and Password ]-- $ShareArray = @() $ShareArray += , @("J:","\\\\192.168.1.250\\Share1","username","password") $ShareArray += , @("K:","\\\\192.168.1.250\\Share2","username","password") #--[ Add more mapping entries here... ]-- $Index = 0 Do { $MapDrive = $ShareArray[$Index][0] $MapPath = $ShareArray[$Index][1] $MapUser = $ShareArray[$Index][2] $MapPassword = $ShareArray[$Index][3] $net = $(New-Object -Com WScript.Network) if ( Exists-Drive $MapDrive){$Notify.ShowBalloonTip(2500,$ScriptName,"Drive $MapDrive is already mapped...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "Drive $MapDrive already mapped" -ForegroundColor DarkRed}}else{if (test-path $MapPath){$net.MapNetworkDrive($MapDrive, $MapPath, "False",$MapUser,$MapPassword);$Notify.ShowBalloonTip(2500,$ScriptName,"Mapping Drive $MapDrive...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "Mapping Drive $MapDrive" -ForegroundColor DarkGreen}}else{$Notify.ShowBalloonTip(2500,$ScriptName,"Cannot Map Drive $MapDrive - Target Not Found...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "Cannot Map Drive $MapDrive - Target Not Found" -ForegroundColor DarkRed}}} Sleep (2) $Index++ }While ($Index -lt $ShareArray.length) } Function Exists-Drive { param($driveletter) (New-Object System.IO.DriveInfo($driveletter)).DriveType -ne 'NoRootDirectory' } Function LoadApps { #--[ Array consists of Process Name, File Path, Arguements, Title ]-- $AppArray = @() $AppArray += , @("firefox","C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe","https://www.google.com","FireFox") #--[ Add more app entries here... ]-- #--[ Cloud Storage Provider Subsection ]-- if (!$CloudStor ){$Notify.ShowBalloonTip(2500,$ScriptName,"Cloud Providers Bypassed...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "Cloud Providers Bypassed..." -ForegroundColor Magenta;}} else { $AppArray += , @("googledrivesync","C:\\Program Files (x86)\\Google\\Drive\\googledrivesync.exe","/autostart","GoogleDrive") #--[ Add more cloud entries here... ]-- } $AppArray += , @("taskmgr","C:\\Windows\\System32\\taskmgr.exe"," ","Task Manager") #--[ Add more app entries here... ]-- $Index = 0 Do { $AppProcess = $AppArray[$Index][0] $AppExe = $AppArray[$Index][1] $AppArgs = $AppArray[$Index][2] $AppName = $AppArray[$Index][3] If((get-process -Name $AppProcess -ea SilentlyContinue) -eq $Null){start-process -FilePath $AppExe -ArgumentList $AppArgs ;$Notify.ShowBalloonTip(2500,$ScriptName,"$AppName is loading...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "Loading" $AppName "..." -ForegroundColor DarkGreen}}else{$Notify.ShowBalloonTip(2500,$ScriptName,"$AppName is already running...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "$AppName Already Running..." -ForegroundColor DarkRed } } Sleep (2) $Index++ } While ($Index -lt $AppArray.length) } <# function SendMail { #param($strTo, $strFrom, $strSubject, $strBody, $smtpServer) param($To, $From, $Subject, $Body, $smtpServer) $msg = new-object Net.Mail.MailMessage $smtp = new-object Net.Mail.SmtpClient($smtpServer) $msg.From = $From $msg.To.Add($To) $msg.Subject = $Subject $msg.IsBodyHtml = 1 $msg.Body = $Body $smtp.Send($msg) } #> Function IdentifyNics { $Domain1 = "LabDomain.com" $Domain2 = "OfficeDomain.com" #--[ Detect Network Adapters ]-- $Wired = get-wmiobject -class "Win32_NetworkAdapterConfiguration" | where {$_.IPAddress -like "192.168.1.*" } #--[ Alternate detection methods]-- #$Wired = get-wmiobject -class "Win32_NetworkAdapterConfiguration" | where {$_.IPAddress -like "192.168.1.*" } | where {$_.DNSDomainSuffixSearchOrder -match $Domain2} #$Wired = get-wmiobject -class "Win32_NetworkAdapterConfiguration" | where {$_.Description -like "Marvell Yukon 88E8056 PCI-E Gigabit Ethernet Controller" } $WiredIP = ([string]$Wired.IPAddress).split(" ") $WiredDesc = $Wired.Description if ($debug){ write-host "Name: " $Wired.Description`n"DNS Domain: " $Wired.DNSDomainSuffixSearchOrder`n"IPv4: " $WiredIP[0]`n"IPv6: " $WiredIP[1]`n"" if ($WiredIP[0]){$Notify.ShowBalloonTip(2500,$ScriptName,"Detected $WiredDesc",[system.windows.forms.tooltipicon]::Info)}else{$Notify.ShowBalloonTip(2500,$ScriptName,"Hardline not detected",[system.windows.forms.tooltipicon]::Info)} } sleep (2) $WiFi = get-wmiobject -class "Win32_NetworkAdapterConfiguration" | where {$_.Description -like "Intel(R) Centrino(R) Advanced-N 6250 AGN" } $WiFiIP = ([string]$WiFi.IPAddress).split(" ") $WiFiDesc = $WiFi.Description write-host "Name: " $WiFi.Description`n"DNS Domain: " $WiFi.DNSDomainSuffixSearchOrder`n"IPv4: " $WiFiIP[0]`n"IPv6: " $WiFiIP[1] if ($WiFiIP[0]){$Notify.ShowBalloonTip(2500,$ScriptName,"Detected $WiFiDesc",[system.windows.forms.tooltipicon]::Info)}else{$Notify.ShowBalloonTip(2500,$ScriptName,"WiFi not detected",[system.windows.forms.tooltipicon]::Info)} sleep (2) #--[ Set Routes ]-- if ($WiredIP[0]) { #--[ The hardline is connected. Favor the hardline if both connected ]-- $IP = $WiredIP[0] if ($Wired.DNSDomainSuffixSearchOrder -like $Domain1 -or $Wired.DNSDomainSuffixSearchOrder -like $Domain2) { #--[ the hardline is connected ]-- write-host ""`n"Setting routes for hardline"`n"" $Notify.ShowBalloonTip(2500,$ScriptName,"Setting routes for hardline...",[system.windows.forms.tooltipicon]::Info) #SetRoutes $IP } } else { if ($WiFiIP[0]) { if ($WiFi.DNSDomainSuffixSearchOrder -like $Domain2) { #--[ The wifi is connected --] $IP = $WiFiIP[0] write-host ""`n"Setting routes for wifi"`n"" $Notify.ShowBalloonTip(2500,$ScriptName,"Setting routes for wifi...",[system.windows.forms.tooltipicon]::Info) #SetRoutes $IP } } } } #Write-Host $IP #IdentifyNics #SetMappings #Pause-Host LoadApps If ($debug){write-host "Completed All Operations..." -ForegroundColor DarkCyan}
PowerShellCorpus/PoshCode/Logoff all users_2.ps1
Logoff all users_2.ps1
function RemoveSpace([string]$text) { $private:array = $text.Split(" ", ` [StringSplitOptions]::RemoveEmptyEntries) [string]::Join(" ", $array) } $quser = quser foreach ($sessionString in $quser) { $sessionString = RemoveSpace($sessionString) $session = $sessionString.split() if ($session[0].Equals(">nistuke")) { continue } if ($session[0].Equals("USERNAME")) { continue } # Use [1] because if the user is disconnected there will be no session ID. $result = logoff $session[1] }
PowerShellCorpus/PoshCode/Call WSPBuilder.ps1
Call WSPBuilder.ps1
function Run-DosCommand($program, [string[]]$programArgs) { write-host "Running command: $program"; write-host " Args:" 0..($programArgs.Count-1) | foreach { Write-Host " $($programArgs[$_])" } & $program $programArgs } #Get-FullPath function defined elsewhere, refers to a "base directory" which allows me to make #all path references RELATIVE to this base directory. Feel free to hardcode the path instead. $wspbuilder = Get-FullPath("tools\\WSPBuilder.exe") function Run-WspBuilder($rootDirectory) { pushd cd $rootDirectory Run-DosCommand -program $WSPBuilder -programArgs @("-BuildWSP", "true", "-OutputPath", (Get-FullPath 'deployment'), "-ExcludePaths", (Join-Path -path (Get-FirstDirectoryUnderneathSrc).fullname -childPath "bin\\Debug")) popd }
PowerShellCorpus/PoshCode/ESX host NTP Settings.ps1
ESX host NTP Settings.ps1
<#====================================================================================== File Name : ESX-NTP.ps1 Original Author : Kenneth C. Mazie : Description : This is a VMware PowerCLI script for synchronizing NTP settings across : all ESX hosts in a Virtual Center instance. It grabs all ESX hosts and : cycles through them setting the same NTP settings on each. It then : starts the service and sets it to start automatically. : : The individual commands were found on a blog post from Anders Mikkelson. : I simply combined them into a functioning script so credit goes to him. : See http://www.amikkelsen.com/?p=458 for the original posting. : : Tested on ESXi 5.1 and 5.0 : : Be sure to edit all sections to suit your needs before executing. : : As written the script will prompt for a Virtual Center instance to process : and a user/password to connect as. It also prompts for the ESX host user ID. : Hard code these if the prompts become annoying. : Notes : Requires VMware PowerShell PowerCLI extentions. : Warnings : : : Last Update by : Kenneth C. Mazie (kcmjr AT kcmjr.com to report issues) Version History : v1.0 - 03-13-12 - Original Change History : v2.0 - 00-00-00 - : =======================================================================================#> clear-host $out = Get-PSSnapin | Where-Object {$_.Name -like "vmware.vimautomation.core"};if ($out -eq $null) {Add-PSSnapin vmware.vimautomation.core} Disconnect-VIServer -confim:$false $vSphere = read-host "Process Which vSphere Instance?" $vUser = read-host "vSphere User ID?" $vPass = "" $eUser = read-host "ESX User ID?" $ePass = "password" $NTPServers = ("time.nist.gov","time-nw.nist.gov","us.pool.ntp.org") #--[ Change these to whatever NTP servers you use ]-- if ($vSphere = $null){break} Connect-VIServer -Server $vSphere -User $vUser #-Password $vPass $ESXhosts = get-vmhost foreach ($ESX in $ESXHosts) { Write-Host "Target = $ESX" Connect-VIServer -Server $ESX -User $eUser #-Password $ePass $NTPList = Get-VMHostNtpServer -VMHost $ESX Remove-VMHostNtpServer -VMHost $ESX -NtpServer $NTPList -Confirm:$false Add-VMHostNtpServer -VMHost $ESX -NtpServer $NTPServers -Confirm:$false Set-VMHostService -HostService (Get-VMHostservice -VMHost (Get-VMHost $ESXhost) | Where-Object {$_.key -eq "ntpd"}) -Policy "Automatic" Get-VmhostFirewallException -VMHost $ESX -Name "NTP Client" | Set-VMHostFirewallException -enabled:$true $ntpd = Get-VMHostService -VMHost $ESX | where {$_.Key -eq 'ntpd'} Restart-VMHostService $ntpd -Confirm:$false Disconnect-viserver -server $ESX -confim:$false } Write-Host "--- COMPLETED ---"
PowerShellCorpus/PoshCode/ModuleWriteError_1.psm1.ps1
ModuleWriteError_1.psm1.ps1
################################################################################ ## Script Name: Module Write Error ## Created On: 1/7/2010 ## Author: Thell Fowler ## Tribute: Joel 'Jaykul' Bennet ## File: ModuleWriteError.psm1 ## Usage: import-module \\Path\\to\\module\\ModuleWriteError.psm1 ## Version: 1.0.0 ## ## Purpose: Provides a New-ModuleError functions for the creation of an ## error record that is populated and formatted with an ## imported module's advanced function information. ## ## Reasoning: Informational error messages generated from 'Write-Error' do ## not truly represent the current function in some cases and ## do not inform the user of Module specific details. ## Usage of $PSCmdlet.WriteError an error record from ## New-ModuleError can resolve that. ## ## Requirements: PowerShell Version 2 ## ModuleWriteError.psd1 ## FunctionInfo.types.ps1xml ## Last Updated: 01/13/2010 ## History: ## 1.0.1 01/13/2010 - Removed nested prompt call remaining from testing. ## 1.0.0 01/13/2010 - Initial version. ## ## ################################################################################ #requires -version 2.0 Set-StrictMode -Version 2 function New-ModuleExceptionClass{ [CmdletBinding()] param([string]$exceptionType) # Generic Default Exception Class for use with WriteError output. $GenericModuleExceptionSource = @" using System; public class $($exceptionType) : System.ApplicationException { public $($exceptionType)() { } public $($exceptionType)(string message) : base(message) { } public $($exceptionType)(string message, Exception innerException) : base(message, innerException) { } } "@ # Suppresses warning: Generated type defines no public methods of it's own. Add-Type -TypeDefinition $GenericModuleExceptionSource -IgnoreWarnings -warningaction silentlycontinue } function New-ModuleError { <# .SYNOPSIS Create an error record that is populated and formatted to provide data that is contextual to an imported module's advanced functions. .DESCRIPTION Informational error messages generated from 'Write-Error' do not truly represent the current function in some cases and do not inform the user of Module specific details. When using $PSCmdlet.WriteError though that data can be populated into the error record. .EXAMPLE $PSCmdlet.WriteError(( New-ModuleError ` "Cannot get `'$Name`' because it does not exist." )) .OUTPUTS [ErrorRecord] #> [CmdletBinding()] param( [Parameter(Position=0, Mandatory=$true)] [string]$message, [string]$identifierText = $("ErrorNotSpecified"), [System.Management.Automation.ErrorCategory]$ErrorCategory = $("NotSpecified"), [PSObject]$targetObject, [string]$exceptionType = $($null), [Exception]$innerException ) Begin { # These are used in building the error record. $MyCommandCaller = ((get-pscallstack)[1].InvocationInfo.MyCommand) $MyCallersModule = ($MyCommandCaller.ModuleName) if ( $exceptionType.Length -eq 0 ) { $exceptionType = "$($MyCallersModule)ModuleException" } elseif ( ( "$($exceptionType)" -as [type] -eq $null ) -and ( $exceptionType -ne "$($MyCallersModule)ModuleException" ) ) { $exceptionType = [AppDomain]::CurrentDomain.GetAssemblies() | %{$_.GetExportedTypes()} | ?{ $_.Name -eq "$($exceptionType)" -and $_.IsSubclassOf( [System.Exception] ) } if ( $exceptionType -as [type] -eq $null ) { $exceptionType = "$($MyCallersModule)ModuleException" } } if ( ( $exceptionType -eq "$($MyCallersModule)ModuleException" ) -and ( "$($exceptionType)" -as [type] -eq $null) ) { New-ModuleExceptionClass "$($MyCallersModule)ModuleException" } } Process { if ($innerException) { $MyErrorRecord = (new-object System.Management.Automation.ErrorRecord( (new-object $exceptionType("$($message)", $innerException)), "$($identifierText), Module : $($MyCommandCaller.ModuleName)\\$($MyCommandCaller.InternalName)", $ErrorCategory, $targetObject) ) } else { $MyException = new-object $exceptionType $message $MyErrorRecord = (new-object System.Management.Automation.ErrorRecord( $MyException, "$($identifierText), Module : $($MyCommandCaller.ModuleName)\\$($MyCommandCaller.InternalName)", $ErrorCategory, $targetObject) ) } $MyErrorRecord.CategoryInfo.Activity = "$($MyCommandCaller.Name)" Write-Output $MyErrorRecord } End { } } Export-ModuleMember New-ModuleError
PowerShellCorpus/PoshCode/LibraryChart_1.ps1
LibraryChart_1.ps1
# --------------------------------------------------------------------------- ### <Script> ### <Author> ### Chad Miller ### </Author> ### <Description> ### Defines functions for wokring with Microsoft Chart Control for .NET 3.5 Framework ### Pipe output of Powershell command to Out-Chart function and specify chart type ### Chart will display in form or save to image file ### Real-time charts are supported by passing in a script block ### My thanks to Richard MacDonald for his wonderful post on Charting with PowerShell ### http://blogs.technet.com/richard_macdonald/archive/2009/04/28/3231887.aspx ### Note: Requires NET Framework 3.5 and Microsoft Chart Controls for Microsoft .NET Framework 3.5 ### </Description> ### <Usage> ### . ./LibraryChart.ps1 ### -------------------------- EXAMPLE 1 -------------------------- ### Get-Process | Sort-Object -Property WS | Select-Object Name,WS -Last 5 | out-chart -xField 'name' -yField 'WS' ### ### This command will produce a default column chart ### ### -------------------------- EXAMPLE 2 -------------------------- ### Get-Process | Sort-Object -Property WS | Select-Object Name,WS -Last 5 | out-chart -xField 'name' -yField 'WS' -filename 'c:\\users\\u00\\documents\\process.png' ### This command will output the chart to a file ### ### -------------------------- EXAMPLE 3 -------------------------- ### Get-Process | Sort-Object -Property WS | Select-Object Name,WS -Last 5 | out-chart -xField 'name' -yField 'WS' -chartType 'Pie' ### ### This command will produce a pie chart ### ### -------------------------- EXAMPLE 4 -------------------------- ### out-chart -xField 'name' -yField 'WS' -scriptBlock {Get-Process | Sort-Object -Property WS | Select-Object Name,WS -Last 1} -chartType 'line' ### ### This command will produce a real-time line chart ### ### </Usage> ### </Script> # -------------------------------------------------------------------------- [void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") [void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms.DataVisualization") ####################### function New-Chart { param ([int]$width,[int]$height,[int]$left,[int]$top,$chartTitle) # create chart object $global:Chart = New-object System.Windows.Forms.DataVisualization.Charting.Chart $global:Chart.Width = $width $global:Chart.Height = $height $global:Chart.Left = $left $global:Chart.Top = $top # create a chartarea to draw on and add to chart $chartArea = New-Object System.Windows.Forms.DataVisualization.Charting.ChartArea $global:chart.ChartAreas.Add($chartArea) [void]$global:Chart.Titles.Add($chartTitle) # change chart area colour $global:Chart.BackColor = [System.Drawing.Color]::Transparent } #New-Chart ####################### function New-BarColumnChart { param ([hashtable]$ht, $chartType='Column', $chartTitle,$xTitle,$yTitle, [int]$width,[int]$height,[int]$left,[int]$top,[bool]$asc) New-Chart -width $width -height $height -left $left -top $top -chartTile $chartTitle $chart.ChartAreas[0].AxisX.Title = $xTitle $chart.ChartAreas[0].AxisY.Title = $yTitle [void]$global:Chart.Series.Add("Data") $global:Chart.Series["Data"].Points.DataBindXY($ht.Keys, $ht.Values) $global:Chart.Series["Data"].ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::$chartType if ($asc) { $global:Chart.Series["Data"].Sort([System.Windows.Forms.DataVisualization.Charting.PointSortOrder]::Ascending, "Y") } else { $global:Chart.Series["Data"].Sort([System.Windows.Forms.DataVisualization.Charting.PointSortOrder]::Descending, "Y") } $global:Chart.Series["Data"]["DrawingStyle"] = "Cylinder" $global:chart.Series["Data"].IsValueShownAsLabel = $true $global:chart.Series["Data"]["LabelStyle"] = "Top" } #New-BarColumnChart ####################### function New-LineChart { param ([hashtable]$ht,$chartTitle, [int]$width,[int]$height,[int]$left,[int]$top) New-Chart -width $width -height $height -left $left -top $top -chartTile $chartTitle [void]$global:Chart.Series.Add("Data") # $global:Chart.Series["Data"].Points.AddXY($(get-date), $($ht.Values)) $global:Chart.Series["Data"].Points.DataBindXY($ht.Keys,$ht.Values) #$global:Chart.Series["Data"].XValueType = [System.Windows.Forms.DataVisualization.Charting.ChartValueType]::Time #$global:Chart.chartAreas[0].AxisX.LabelStyle.Format = "hh:mm:ss" #$global:Chart.chartAreas[0].AxisX.LabelStyle.Interval = 1 #$global:Chart.chartAreas[0].AxisX.LabelStyle.IntervalType = [System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType]::Seconds $global:Chart.Series["Data"].ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::Line #$global:chart.Series["Data"].IsValueShownAsLabel = $false } #New-LineChart ####################### function New-PieChart { param ([hashtable]$ht,$chartTitle, [int]$width,[int]$height,[int]$left,[int]$top) New-Chart -width $width -height $height -left $left -top $top -chartTile $chartTitle [void]$global:Chart.Series.Add("Data") $global:Chart.Series["Data"].Points.DataBindXY($ht.Keys, $ht.Values) $global:Chart.Series["Data"].ChartType = [System.Windows.Forms.DataVisualization.Charting.SeriesChartType]::Pie $global:Chart.Series["Data"]["PieLabelStyle"] = "Outside" $global:Chart.Series["Data"]["PieLineColor"] = "Black" #$global:chart.Series["Data"].IsValueShownAsLabel = $true #$global:chart.series["Data"].Label = "#PERCENT{P1}" #$legend = New-object System.Windows.Forms.DataVisualization.Charting.Legend #$global:Chart.Legends.Add($legend) #$Legend.Name = "Default" } #New-PieChart ####################### function Remove-Points { param($name='Data',[int]$maxPoints=200) while ( $global:chart.Series["$name"].Points.Count > $maxPoints ) { $global:chart.Series["$name"].Points.RemoveAT(0) } } #Add-Series ####################### function Out-Form { param($interval,$scriptBlock,$xField,$yField) # display the chart on a form $global:Chart.Anchor = [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Right -bor [System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Left $Form = New-Object Windows.Forms.Form $Form.Text = 'PowerCharts' $Form.Width = 600 $Form.Height = 600 $Form.controls.add($global:Chart) if ($scriptBlock -is [ScriptBlock]) { if (!($xField -or $yField)) { throw 'xField and yField required with scriptBlock parameter.' } $timer = New-Object System.Windows.Forms.Timer $timer.Interval = $interval $timer.add_Tick({ $ht = &$scriptBlock | ConvertTo-HashTable $xField $yField if ($global:Chart.Series["Data"].ChartTypeName -eq 'Line') { Remove-Points $ht | foreach { $global:Chart.Series["Data"].Points.AddXY($($_.Keys), $($_.Values)) } } else { $global:Chart.Series["Data"].Points.DataBindXY($ht.Keys, $ht.Values) } $global:chart.ResetAutoValues() $global:chart.Invalidate() }) $timer.Enabled = $true $timer.Start() } $Form.Add_Shown({$Form.Activate()}) $Form.ShowDialog() } #Out-Form ####################### function Out-ImageFile { param($fileName,$fileformat) $global:Chart.SaveImage($fileName,$fileformat) } ####################### ### ConvertTo-Hashtable function based on code by Jeffery Snover ### http://blogs.msdn.com/powershell/archive/2008/11/23/poshboard-and-convertto-hashtable.aspx ####################### function ConvertTo-Hashtable { param([string]$key, $value) Begin { $hash = @{} } Process { $thisKey = $_.$Key $hash.$thisKey = $_.$Value } End { Write-Output $hash } } #ConvertTo-Hashtable ####################### function Out-Chart { param( $xField=$(throw 'Out-Chart:xField is required'), $yField=$(throw 'Out-Chart:yField is required'), $chartType='Column',$chartTitle, [int]$width=500, [int]$height=400, [int]$left=40, [int]$top=30, $filename, $fileformat='png', [int]$interval=1000, $scriptBlock, [switch]$asc ) Begin { $ht = @{} } Process { if ($_) { $thisKey = $_.$xField $ht.$thisKey = $_.$yField } } End { if ($scriptBlock) { $ht = &$scriptBlock | ConvertTo-HashTable $xField $yField } switch ($chartType) { 'Bar' {New-BarColumnChart -ht $ht -chartType $chartType -chartTitle $chartTitle -width $width -height $height -left $left -top $top -asc $($asc.IsPresent)} 'Column' {New-BarColumnChart -ht $ht -chartType $chartType -chartTitle $chartTitle -width $width -height $height -left $left -top $top -asc $($asc.IsPresent)} 'Pie' {New-PieChart -chartType -ht $ht -chartTitle $chartTitle -width $width -height $height -left $left -top $top } 'Line' {New-LineChart -chartType -ht $ht -chartTitle $chartTitle -width $width -height $height -left $left -top $top } } if ($filename) { Out-ImageFile $filename $fileformat } elseif ($scriptBlock ) { Out-Form $interval $scriptBlock $xField $yField } else { Out-Form } } } #Out-Chart
PowerShellCorpus/PoshCode/Get-HttpResponseUri.ps1
Get-HttpResponseUri.ps1
function Get-HttpResponseUri { #.Synopsis # Fetch the HEAD for a url and return the ResponseUri. #.Description # Does a HEAD request for a URL, and returns the ResponseUri. This is useful for resolving (in a service-independent way) shortened urls. #.Parameter ShortUrl # A (possibly) shortened URL to be resolved to its redirect location. PARAM( [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)] [Alias("Uri","Url")] [string]$ShortUrl ) $req = [System.Net.HttpWebRequest]::Create($ShortUrl) $req.Method = "HEAD" $response = $req.GetResponse() Write-Output $response.ResponseUri $response.Close() # clean up like a good boy }
PowerShellCorpus/PoshCode/8097adfd-db82-4ae1-8996-c504851508d5.ps1
8097adfd-db82-4ae1-8996-c504851508d5.ps1
#========================================================================== # NAME: getunknownsids.ps1 # # AUTHOR: Stephen Wheet # Version: 4.0 # Date: 6/11/10 # # COMMENT: # This script was created to find unknown SIDs or old domain permissions # on folders. It ignores folders where inheirtance is turned on. # # This works on NETAPPS and WINDOWS servers. You will need the DLL's # # Version 2: completely changed the query method and ACL removal # Version 3: Added ability to query AD for servers, and handles getting # getting shares automatically from: # NETAPP FILERS # Windows servers # Version 4: Cleaned up folder checking and added checking for local # account checking so we could ignore. # #========================================================================== Function checkshare { Param($PassedShareName) Process { $path = "\\\\$serverFQDN\\$PassedShareName" $filename = $path.Replace("\\","-") + ".csv" #Place Headers on out-put file $list = "Task,Path,Access Entity," $list | format-table | Out-File "c:\\reports\\unknownsids\\$filename" #Populate Folders Array Write-Host "Writing results to : $filename" $date = Get-Date Write-Host $date Write-Host "Getting Folders in: $Path" #PSIscontainer means folders only [Array] $folders = Get-ChildItem -path $path -recurse | ? {$_.PSIsContainer} #Process data in array ForEach ($folder in [Array] $folders) { #Check to see if there are any folders If ($folder.pspath){ #Convert Powershell Provider Folder Path to standard folder path $PSPath = (Convert-Path $folder.pspath) Write-Host "Checking Dir: $PSPath" #Check to make sure valid If ($PSPath){ #Get the ACL's from each folder $error.clear() $acl = Get-Acl -Path $PSPath #Write log if no access if (!$?) { $errmsg = "Error,$PSPath,ACCESS DENIED" $errmsg | format-table | Out-File -append "$filename" } #end IF $ACL.Access | ?{!$_.IsInherited} | ?{ $_.IdentityReference -like $unknownsid -or $_.IdentityReference -like $olddomain } | % {$value = $_.IdentityReference.Value #Check for Local account $localsid = 0 If ($value -like $unknownsid){ $checkforlocal = $value.split("-") $total =$checkforlocal.count -1 if ($checkforlocal[$total] -match "^100.$" -or $checkforlocal[$total] -match "^500"){ $localsid = 1 # You can uncomment the below if you want to report on local accounts. #$list = ("Local,$PSPath,$value") #$list | format-table | Out-File -append "$filename" } #end IF } #end IF If (!$localsid){ Write-host "Found - $PSPath - $value" $list = ("Found,$PSPath,$value") $list | format-table | Out-File -append "$filename" #Remove Bad SID if ($removeacl) { $ACL.RemoveAccessRuleSpecific($_) Write-host "Deleting - $PSPath - $value" $list = ("Deleting,$PSPath,$value") $list | format-table | Out-File -append "$filename" }#end IF if ($removeacl -and $value) { $date = Get-Date Write-Host $date Write-host "Setting - $PSPath" $list = ("Setting,$PSPath") $list | format-table | Out-File -append "$filename" Set-ACL $PSpath $ACL $value = "" } #end IF } #end if } #end foreachobj } #end if } #end if } #end ForEach }#end Process } #end function get-pssnapin -registered | add-pssnapin -passthru [void][Reflection.Assembly]::LoadFile('C:\\reports\\ManageOntap.dll') #Need this DLL from netapp 3.5SDK $ReqVersion = [version]"1.2.2.1254" $QadVersion = (Get-PSSnapin Quest.ActiveRoles.ADManagement).Version #Need Quest plugins installed if($QadVersion -lt $ReqVersion) { throw "Quest AD cmdlets version '$ReqVersion' is required. Please download the latest version" } #end If #Set variables $value = "" $unknownsid = "*S-1-5-21-*" #Broken SID Verify the Broken SID number on your system and replace $olddomain = "Domain.local*" #Old w2k/nt4 domain $ErrorActionPreference = "SilentlyContinue" $removeacl = 0 #change to 1 if you want to remove the SID, 0 for only logging $localsid = 0 #Get all the servers from the specified OU $Servers = get-QADComputer -SearchRoot 'domain.local/ou/Server' # change the container. Foreach ($server in $Servers ) { $serverFQDN = $server.dnsname write-host $serverFQDN #Test ping server to make sure it's up before querying it $ping = new-object System.Net.NetworkInformation.Ping $Reply = $ping.Send($serverFQDN) if ($Reply.status -eq "Success"){ Write-Host "Online" #Check for Netapp .. if found get the shares differently If ($serverFQDN -like "*netapp*"){ $server = new-object netapp.manage.naserver($serverFQDN,1,0) #pass authentication $server.Style = "RPC" # Issue command to get the shares $NaElement = New-Object NetApp.Manage.NaElement("system-cli") $arg = New-Object NetApp.Manage.NaElement("args") $arg.AddNewChild('arg','cifs') $arg.AddNewChild('arg','shares') $NaElement.AddChildElement($arg) $CifsString = $server.InvokeElem($NaElement).GetChildContent("cli-output") # Split the returned txt up .. the $null makes it skip a line $null,$null,$Lines = $CifsString.Split("`n") Foreach ($line in $Lines ) { # Had to trick it so skip the line with permissions, then exclude ETC$ adn c$ if (!$line.startswith(" ") -and $line -notlike "*Etc$*" -and $line -notlike "*C$*"){ $l= $line.Split(" ") checkshare -PassedShareName $l[0] #Pass share to function } #end if } #end foreach } #end if Else{ #Else if a Windows server query via WMI Get-WMIObject Win32_Share -Computer $serverFQDN | where {$_.Name -like "*$*" -and $_.Name -notlike "*ADMIN*" -and $_.Name -notlike "*IPC*" -and $_.Name -notlike "*lib*"} | %{ #Set path $sharename = $_.name checkshare -PassedShareName $sharename #Pass share to function } #end ForEachObj } #End Else } #End If } #end ForEach
PowerShellCorpus/PoshCode/Easy Migration Tool v_2.1.ps1
Easy Migration Tool v_2.1.ps1
#Generated Form Function function GenerateForm { ######################################################################## # Code Generated By: Richard Yaw # Generated On: 07/12/2011 # # Easy Migration Script for VMware (Version 2.0) # - Added a "Reload Tasks" feature. # - Fixed issue with the Undo feature for SVMotions. # - Added snapshot check before doing SVMotions. # - Added ability to VMotion VMs between clusters. # # Easy Migration Script for VMware (Version 3.0) # - Added ability to run multiple migrations concurrently. # - The UI is no longer locked during a migration. # # Easy Migration Script for VMware (Version 3.1) # - Changed GUI to make it bigger on the screen. # - When doing a Host to Host migration, you can now drill down a host to list the VMs on it. ############################################################################################# #region Import the Assemblies [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null #endregion #region Generated Form Objects $MigrationForm = New-Object System.Windows.Forms.Form $Header = new-object System.Windows.Forms.Label $MigrateButton = New-Object System.Windows.Forms.Button $ClusterComboBox = New-Object System.Windows.Forms.ComboBox $SourceHostListBox = New-Object System.Windows.Forms.ListBox $SourceDBListBox = New-Object System.Windows.Forms.CheckedListBox $SourceVMListBox = New-Object System.Windows.Forms.CheckedListBox $DestinationListBox = New-Object System.Windows.Forms.ListBox $vCenterLabel = New-Object System.Windows.Forms.Label $VCComboBox = New-Object System.Windows.Forms.ComboBox $LoginButton = New-Object System.Windows.Forms.Button $ClearMsgButton = New-Object System.Windows.Forms.Button $UndoButton = New-Object System.Windows.Forms.Button $UndoALLButton = New-Object System.Windows.Forms.Button $ReloadTaskButton = New-Object System.Windows.Forms.Button $SaveTaskButton = New-Object System.Windows.Forms.Button $ClusterLabel = New-Object System.Windows.Forms.Label $HostToHostButton = New-Object System.Windows.Forms.Button $VMToHostButton = New-Object System.Windows.Forms.Button $DBtoDBButton = New-Object System.Windows.Forms.Button $VMtoDBButton = New-Object System.Windows.Forms.Button $AllClustersCheckbox = New-Object System.Windows.Forms.CheckBox $SourceButton = New-Object System.Windows.Forms.Button $DestinationButton = New-Object System.Windows.Forms.Button $FindVMLabel = New-Object System.Windows.Forms.Label $FindVMTxtBox = New-Object System.Windows.Forms.TextBox $FindVMBtn = New-Object System.Windows.Forms.Button $ResetFindVMBtn = New-Object System.Windows.Forms.Button $ResetButton = New-Object System.Windows.Forms.Button $ChangeVCButton = New-Object System.Windows.Forms.Button $CloseButton = New-Object System.Windows.Forms.Button $MessagesLabel = New-Object System.Windows.Forms.Label $MessagesListBox = New-Object System.Windows.Forms.ListBox $TaskLabel = New-Object System.Windows.Forms.Label $TaskListBox = New-Object System.Windows.Forms.ListBox $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState #endregion Generated Form Objects #---------------------------------------------- #Generated Event Script Blocks #---------------------------------------------- #Provide Custom Code for events specified in PrimalForms. $LoginButton_Click= { #TODO: Place custom script here If ((Get-PSSnapin "VMware.VimAutomation.Core" -ErrorAction SilentlyContinue) -eq $null) { Add-PSSnapin "VMware.VimAutomation.Core" } If($VCComboBox.SelectedItem -eq $null) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show("Please select a vCenter Server.") } Else { #Connect to vCenter $vCenterName = $VCComboBox.SelectedItem.ToString() Connect-VIServer $vCenterName -ErrorAction SilentlyContinue If (!$?) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show($($error[0])) } Else { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show("You are now connected to $vCenterName. Please select a cluster from the drop-down box.") $ClusterComboBox.Enabled = $true #Get Cluster $ClusterNames = Get-View -ViewType ClusterComputeResource | %{$_.Name} foreach($ClusterName in $ClusterNames) { $ClusterComboBox.Items.add($ClusterName) } $LoginButton.Enabled = $false $VCComboBox.Enabled = $false $HostToHostButton.Enabled = $true $VMToHostButton.Enabled = $true $DBtoDBButton.Enabled = $true $VMtoDBButton.Enabled = $true $ResetButton.Enabled = $true $ChangeVCButton.Enabled = $true $ReloadTaskButton.Enabled = $true $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $MigrationForm.WindowState = $InitialFormWindowState } } } } $HostToHostButton_Click= { #TODO: Place custom script here $ClusterName = $ClusterComboBox.SelectedItem If ($ClusterName -eq $null) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('Please Select a Cluster.') } Else { $SourceHostListBox.Enabled = $true $SourceHostListBox.Items.Clear() #Get Hostnames in a Cluster Get-Cluster -Name $ClusterName | Get-VMHost | % { [void]$SourceHostListBox.items.add($_.Name) } $ClusterComboBox.Enabled = $false $HostToHostButton.Enabled = $false $VMToHostButton.Enabled = $false $DBtoDBButton.Enabled = $false $VMtoDBButton.Enabled = $false $SourceButton.Text = 'Source - Select One Host' $DestinationButton.Text = 'Destination Host' $SourceButton.Enabled = $true $HostToHostButton.BackColor = [System.Drawing.Color]::lightblue $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $MigrationForm.WindowState = $InitialFormWindowState } } } $VMToHostButton_Click= { #TODO: Place custom script here $ClusterName = $ClusterComboBox.SelectedItem If ($ClusterName -eq $null) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('Please Select a Cluster.') } Else { $MigrationForm.Controls.Remove($SourceHostListBox) $MigrationForm.Controls.Add($SourceVMListBox) $SourceVMListBox.Enabled = $true $SourceVMListBox.Items.Clear() #Get VMs in a Cluster Get-Cluster -Name $ClusterName | Get-VM | % { [void]$SourceVMListBox.items.add($_.Name) } $ClusterComboBox.Enabled = $false $HostToHostButton.Enabled = $false $VMToHostButton.Enabled = $false $DBtoDBButton.Enabled = $false $VMtoDBButton.Enabled = $false $SourceButton.Text = 'Source - Select VMs' $DestinationButton.Text = 'Destination Host' $SourceButton.Enabled = $true $FindVMTxtBox.Enabled = $true $FindVMBtn.Enabled = $true $ResetFindVMBtn.Enabled = $true $VMToHostButton.BackColor = [System.Drawing.Color]::lightblue $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $MigrationForm.WindowState = $InitialFormWindowState } } } $DBtoDBButton_Click= { #TODO: Place custom script here $ClusterName = $ClusterComboBox.SelectedItem If ($ClusterName -eq $null) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('Please Select a Cluster.') } Else { $MigrationForm.Controls.Remove($SourceHostListBox) $MigrationForm.Controls.Add($SourceDBListBox) $SourceDBListBox.Enabled = $true $SourceDBListBox.Items.Clear() #Get Datastores in a Cluster Get-Cluster -Name $ClusterName | Get-VMHost | Get-Datastore | Where-Object {$_.Name -notlike "*SCR01"} | Where-Object {$_.Name -notlike "DAS*"} | % { [void]$SourceDBListBox.items.add($_.Name) } $ClusterComboBox.Enabled = $false $HostToHostButton.Enabled = $false $VMToHostButton.Enabled = $false $DBtoDBButton.Enabled = $false $VMtoDBButton.Enabled = $false $SourceButton.Text = 'Source - Select a Datastore' $DestinationButton.Text = 'Destination Datastore' $SourceButton.Enabled = $true $DBtoDBButton.BackColor = [System.Drawing.Color]::lightblue $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $MigrationForm.WindowState = $InitialFormWindowState } } } $VMToDBButton_Click= { #TODO: Place custom script here $ClusterName = $ClusterComboBox.SelectedItem If ($ClusterName -eq $null) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('Please Select a Cluster.') } Else { $MigrationForm.Controls.Remove($SourceHostListBox) $MigrationForm.Controls.Add($SourceVMListBox) $SourceVMListBox.Enabled = $true $SourceVMListBox.Items.Clear() #Get VMs in a Cluster Get-Cluster -Name $ClusterName | Get-VM | % { [void]$SourceVMListBox.items.add($_.Name) } $ClusterComboBox.Enabled = $false $HostToHostButton.Enabled = $false $VMToHostButton.Enabled = $false $DBtoDBButton.Enabled = $false $VMtoDBButton.Enabled = $false $SourceButton.Text = 'Source - Select VMs' $DestinationButton.Text = 'Destination Datastore' $SourceButton.Enabled = $true $FindVMTxtBox.Enabled = $true $FindVMBtn.Enabled = $true $ResetFindVMBtn.Enabled = $true $VMtoDBButton.BackColor = [System.Drawing.Color]::lightblue $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $MigrationForm.WindowState = $InitialFormWindowState } } } $SourceHostListBox_MouseDoubleClick= { #TODO: Place custom script here $SourceHostname = $SourceHostListBox.SelectedItem If ($SourceHostname -ne $null) { $MigrationForm.Controls.Remove($SourceHostListBox) $MigrationForm.Controls.Add($SourceVMListBox) $SourceVMListBox.Enabled = $true $SourceVMListBox.Items.Clear() Get-VMHost -name $SourceHostname | Get-VM | % { [void]$SourceVMListBox.items.add($_.Name) } $SourceButton.Text = 'Source - Select VMs' $DestinationButton.Text = 'Destination Host' $FindVMTxtBox.Enabled = $true $FindVMBtn.Enabled = $true $ResetFindVMBtn.Enabled = $true $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $MigrationForm.WindowState = $InitialFormWindowState } } } $SourceButton_OnClick= { #TODO: Place custom script here $ClusterName = $ClusterComboBox.SelectedItem If ($SourceButton.Text -eq "Source - Select One Host") { $SourceHostname = $SourceHostListBox.SelectedItem If ($SourceHostname -eq $null) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('Please Select a Source Host.') } Else { #Get Hostnames in a Cluster Get-Cluster -Name $ClusterName | Get-VMHost | Where-Object {$_.Name -notlike "$SourceHostname"} | % { [void]$DestinationListBox.items.add($_.Name) } $SourceHostListBox.Enabled = $false $SourceButton.Enabled = $false $AllClustersCheckbox.Enabled = $true $DestinationListBox.Enabled = $true $DestinationButton.Enabled = $true $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $MigrationForm.WindowState = $InitialFormWindowState } } } If ($SourceButton.Text -eq "Source - Select VMs") { $SourceVMname = $SourceVMListBox.SelectedItem If ($SourceVMname -eq $null) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('Please Select One or More VMs.') } Else { if ($DestinationButton.Text -like "Destination Host") { #Get Hostnames in a Cluster Get-Cluster -Name $ClusterName | Get-VMHost | % { [void]$DestinationListBox.items.add($_.Name) } } Else { #Get Datastores in a Cluster Get-Cluster -Name $ClusterName | Get-VMHost | Get-Datastore | Where-Object {$_.Name -notlike "*SCR01"} | Where-Object {$_.Name -notlike "DAS*"} | % { [void]$DestinationListBox.items.add($_.Name) } } $DestinationListBox.Enabled = $true $SourceVMListBox.Enabled = $false $SourceButton.Enabled = $false $AllClustersCheckbox.Enabled = $true $DestinationButton.Enabled = $true $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $MigrationForm.WindowState = $InitialFormWindowState } } } If ($SourceButton.Text -like "Source - Select a Datastore") { $SourceDBname = $SourceDBListBox.SelectedItem If ($SourceDBname -eq $null) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('Please Select One Datastore.') } Else { #Get Datastores in a Cluster Get-Cluster -Name $ClusterName | Get-VMHost | Get-Datastore | Where-Object {$_.Name -notlike "*SCR01"} | Where-Object {$_.Name -notlike "DAS*"} | Where-Object {$_.Name -notlike "$SourceDBname"} | % { [void]$DestinationListBox.items.add($_.Name) } $SourceDBListBox.Enabled = $false $SourceButton.Enabled = $false $DestinationListBox.Enabled = $true $DestinationButton.Enabled = $true $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $MigrationForm.WindowState = $InitialFormWindowState } } } } $AllClustersCheckbox_Click= { #TODO: Place custom script here $DestinationListBox.Items.Clear() #List the hosts in all the clusters Get-VMHost | % { [void]$DestinationListBox.items.add($_.Name) } $AllClustersCheckbox.Enabled = $False } $DestinationButton_OnClick= { #TODO: Place custom script here $DestinationName = $DestinationListBox.SelectedItem If ($DestinationName -eq $null) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('Please Select a Destination.') } Else { $AllClustersCheckbox.Enabled = $False $DestinationListBox.Enabled = $False $DestinationButton.Enabled = $False $MigrateButton.Enabled = $True $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $MigrationForm.WindowState = $InitialFormWindowState } } } $FindVMBtn_OnClick= { #TODO: Place custom script here If($FindVMTxtBox.Text -ne "") { If($SourceVMListBox.CheckedItems.Count -eq 0) { $SourceVMListBox.Items.Clear() } Else { $CheckedVMs = @() Foreach($VM in $SourceVMListBox.CheckedItems) { $CheckedVMs += $VM } $SourceVMListBox.Items.Clear() Foreach($CheckedVM in $CheckedVMs) { [void]$SourceVMListBox.items.add($CheckedVM) $SourceVMListBox.SetItemChecked($SourceVMListBox.items.IndexOf($CheckedVM),$true) } } $BeforeCount = $SourceVMListBox.Items.Count If($HostToHostButton.BackColor -eq [System.Drawing.Color]::lightblue) { Get-VMHost -Name $SourceHostname | Get-VM -Name $FindVMTxtBox.Text -ErrorAction SilentlyContinue | % { [void]$SourceVMListBox.items.add($_.Name) } } Else { Get-Cluster -Name $ClusterName | Get-VM -Name $FindVMTxtBox.Text -ErrorAction SilentlyContinue | % { [void]$SourceVMListBox.items.add($_.Name) } } } $AfterCount = $SourceVMListBox.Items.Count If($AfterCount -eq $BeforeCount) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('No results found.') } } $ResetFindVMBtn_OnClick= { #TODO: Place custom script here $SourceVMListBox.Items.Clear() $FindVMTxtBox.Text = "" If($HostToHostButton.BackColor -eq [System.Drawing.Color]::lightblue) { Get-VMHost -Name $SourceHostname | Get-VM | % { [void]$SourceVMListBox.items.add($_.Name) } } Else { Get-Cluster -Name $ClusterName | Get-VM | % { [void]$SourceVMListBox.items.add($_.Name) } } } $MigrateButton_OnClick= { #TODO: Place custom script here If ($SourceButton.Text -eq "Source - Select One Host") { $SourceHostname = $SourceHostListBox.SelectedItem $DestinationName = $DestinationListBox.SelectedItem $VMs = Get-VMHost $SourceHostname | Get-VM foreach($VM in $VMs) { Get-VM -Name $VM | Move-VM -Destination (Get-VMHost -Name $DestinationName) -RunAsync -ErrorAction SilentlyContinue If (!$?) { $d = Get-Date $MsgLine = "$d - Cannot migrate $VM because an exception occurred. Check the vCenter console for more details." [void]$MessagesListBox.items.add($MsgLine) } Else { $d = Get-Date $TaskLine = "$d - $VM migrated successfully from $SourceHostName to $DestinationName" [void]$TaskListBox.items.add($TaskLine) } } $SourceVMListBox.enabled = $true $SourceButton.enabled = $true $MigrateButton.Enabled = $false $AllClustersCheckbox.Checked = $false $DestinationListBox.Items.Clear() $ClearMsgButton.Enabled = $true $UndoButton.Enabled = $true $UndoALLButton.Enabled = $true $SaveTaskButton.Enabled = $true } If ($SourceButton.Text -eq "Source - Select VMs") { $DestinationName = $DestinationListBox.SelectedItem If($DestinationButton.Text -eq "Destination Host") { foreach($VM in $SourceVMListBox.CheckedItems) { $SourceName = Get-VM -Name $VM | Get-VMHost | % {$_.name} If($SourceName -ne $DestinationName) { Get-VM -Name $VM | Move-VM -Destination (Get-VMHost -Name $DestinationName) -RunAsync -ErrorAction SilentlyContinue If (!$?) { $d = Get-Date $MsgLine = "$d - Cannot migrate $VM because an exception occurred. Check the vCenter console for more details." [void]$MessagesListBox.items.add($MsgLine) } Else { $d = Get-Date $line = "$d - $VM migrated successfully from $SourceName to $DestinationName." [void]$TaskListBox.items.add($line) } } Else { $d = Get-Date $MsgLine = "$d - Cannot migrate $VM because the source host and the destination host are the same." [void]$MessagesListBox.items.add($MsgLine) } } } Else { foreach($VM in $SourceVMListBox.CheckedItems) { $VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024 $DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB} $DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2} $DBAvailableSpace = $DBFreeSpace - $DBReserved $SnapshotCount = (Get-VM -Name $VM | Get-Snapshot | Measure-Object).Count If ($VMsize -gt $DBAvailableSpace) { $VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024) $DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024) $DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024) $d = Get-Date $MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)." [void]$MessagesListBox.items.add($MsgLine) } ElseIf ($SnapshotCount -gt 0) { $d = Get-Date $MsgLine = "$d - Cannot migrate $VM because it has one or more snapshots." [void]$MessagesListBox.items.add($MsgLine) } Else { $SourceName = Get-VM -Name $VM | Get-Datastore | % {$_.name} If($SourceName -ne $DestinationName) { Get-VM -Name $VM | Move-VM -Datastore ($DestinationName) -RunAsync -ErrorAction SilentlyContinue If (!$?) { $d = Get-Date $MsgLine = "$d - Cannot migrate $VM because an exception occurred. Check the vCenter console for more details." [void]$MessagesListBox.items.add($MsgLine) } Else { $d = Get-Date $TaskLine = "$d - $VM migrated successfully from $SourceName to $DestinationName" [void]$TaskListBox.items.add($TaskLine) } } Else { $d = Get-Date $MsgLine = "$d - Cannot migrate $VM because the source datastore and the destination datastore are the same." [void]$MessagesListBox.items.add($MsgLine) } } } } $SourceVMListBox.enabled = $true $SourceButton.enabled = $true $MigrateButton.Enabled = $false $AllClustersCheckbox.Checked = $false $DestinationListBox.Items.Clear() $ClearMsgButton.Enabled = $true $UndoButton.Enabled = $true $UndoALLButton.Enabled = $true $SaveTaskButton.Enabled = $true } If ($SourceButton.Text -eq "Source - Select a Datastore") { $SourceDBname = $SourceDBListBox.SelectedItem $DestinationName = $DestinationListBox.SelectedItem $VMs = Get-Datastore -Name $SourceDBname | Get-VM If($VMs.count -gt 0) { foreach($VM in $VMs) { $VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024 $DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB} $DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2} $DBAvailableSpace = $DBFreeSpace - $DBReserved $SnapshotCount = (Get-VM -Name $VM | Get-Snapshot | Measure-Object).Count If ($VMsize -gt $DBFreeSpace) { $VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024) $DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024) $DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024) $d = Get-Date $MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)." [void]$MessagesListBox.items.add($MsgLine) } ElseIf ($SnapshotCount -gt 0) { $d = Get-Date $MsgLine = "$d - Cannot migrate $VM because it has one or more snapshots." [void]$MessagesListBox.items.add($MsgLine) } Else { Get-VM -Name $VM | Move-VM -Datastore ($DestinationName) -RunAsync -ErrorAction SilentlyContinue If (!$?) { $d = Get-Date $MsgLine = "$d - Cannot migrate $VM because an exception occurred. Check the vCenter console for more details." [void]$MessagesListBox.items.add($MsgLine) } Else { $d = Get-Date $line = "$d - $VM migrated successfully from $SourceDBName to $DestinationName" [void]$TaskListBox.items.add($line) } } } } Else { $d = Get-Date $MsgLine = "$d - No VM is present on the source datastore $SourceDBname." [void]$MessagesListBox.items.add($MsgLine) } $SourceDBListBox.enabled = $true $SourceButton.enabled = $true $AllClustersCheckbox.Checked = $false $DestinationListBox.Items.Clear() $MigrateButton.Enabled = $false $ClearMsgButton.Enabled = $true $UndoButton.Enabled = $true $UndoALLButton.Enabled = $true $SaveTaskButton.Enabled = $true } } $RESETButton_OnClick= { #TODO: Place custom script here $ClusterComboBox.Enabled = $true $HostToHostButton.Enabled = $true $VMToHostButton.Enabled = $true $DBtoDBButton.Enabled = $true $VMtoDBButton.Enabled = $true $SourceHostListBox.Items.Clear() $SourceDBListBox.Items.Clear() $SourceVMListBox.Items.Clear() $SourceButton.Enabled = $false $SourceButton.Text = 'Source' $AllClustersCheckbox.Checked = $false $DestinationListBox.Items.Clear() $DestinationButton.Enabled = $false $DestinationButton.Text = 'Destination' $FindVMTxtBox.Enabled = $false $FindVMTxtBox.Text = "" $FindVMBtn.Enabled = $false $ResetFindVMBtn.Enabled = $false $MigrateButton.Enabled = $false $MigrationForm.Controls.Remove($SourceHostListBox) $MigrationForm.Controls.Remove($SourceVMListBox) $MigrationForm.Controls.Remove($SourceDBListBox) $MigrationForm.Controls.Add($SourceHostListBox) $HostToHostButton.BackColor = [System.Drawing.Color]::Transparent $VMToHostButton.BackColor = [System.Drawing.Color]::Transparent $DBtoDBButton.BackColor = [System.Drawing.Color]::Transparent $VMtoDBButton.BackColor = [System.Drawing.Color]::Transparent } $ChangeVCButton_OnClick= { #TODO: Place custom script here $VCComboBox.Text = "" $VCComboBox.Enabled = $true $LoginButton.Enabled = $true $ClusterComboBox.Items.Clear() $ClusterComboBox.Enabled = $false $HostToHostButton.Enabled = $false $VMToHostButton.Enabled = $false $DBtoDBButton.Enabled = $false $VMtoDBButton.Enabled = $false $SourceHostListBox.Items.Clear() $SourceDBListBox.Items.Clear() $SourceVMListBox.Items.Clear() $SourceButton.Enabled = $false $SourceButton.Text = 'Source' $AllClustersCheckbox.Checked = $false $DestinationListBox.Items.Clear() $DestinationButton.Enabled = $false $DestinationButton.Text = 'Destination' $MigrateButton.Enabled = $false $ResetButton.Enabled = $false $ChangeVCButton.Enabled = $false $MessagesListBox.Items.Clear() $TaskListBox.Items.Clear() $MigrationForm.Controls.Remove($SourceHostListBox) $MigrationForm.Controls.Remove($SourceVMListBox) $MigrationForm.Controls.Remove($SourceDBListBox) $MigrationForm.Controls.Add($SourceHostListBox) $HostToHostButton.BackColor = [System.Drawing.Color]::Transparent $VMToHostButton.BackColor = [System.Drawing.Color]::Transparent $DBtoDBButton.BackColor = [System.Drawing.Color]::Transparent $VMtoDBButton.BackColor = [System.Drawing.Color]::Transparent #Disconnect from vCenter server Disconnect-VIServer -Confirm:$false } $CloseButton_OnClick= { #TODO: Place custom script here If ($VCComboBox.Text -ne "") { #Disconnect from vCenter server Disconnect-VIServer -Confirm:$false } #Close Form $MigrationForm.close() } $ClearMsgButton_Click= { #TODO: Place custom script here If($MessagesListBox.items.count -eq 0) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('No messages to clear.') } Else { $MessagesListBox.items.clear() } } $UndoButton_Click= { #TODO: Place custom script here If ($TaskListBox.Items.Count -eq 0) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('The task list is empty.') } Else { If ($TaskListBox.SelectedItems.Count -eq 0) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('Please select one or more tasks.') } Else { foreach($Task in $TaskListBox.SelectedItems) { $Task = $Task.split(" ") $VM = $Task[3] $DestinationName = $Task[7] $a = $DestinationName.indexof("SAN") If ($a -lt 0) #If Destination is NOT a datastore { #Perform VMotion $SourceName = Get-VM -name $VM | Get-VMHost | %{$_.name} If($SourceName -ne $DestinationName) { Get-VM -Name $VM | Move-VM -Destination (Get-VMHost $DestinationName) -RunAsync } Else { $d = Get-Date $MsgLine = "$d - Cannot migrate $VM because the source host and the destination host are the same." [void]$MessagesListBox.items.add($MsgLine) } } Else { #Perform SVMotion $VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024 $DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB} $DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2} $DBAvailableSpace = $DBFreeSpace - $DBReserved $SnapshotCount = (Get-VM -Name $VM | Get-Snapshot | Measure-Object).Count If ($VMsize -gt $DBAvailableSpace) { $VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024) $DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024) $DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024) $d = Get-Date $MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)." [void]$MessagesListBox.items.add($MsgLine) } ElseIf ($SnapshotCount -gt 0) { $d = Get-Date $MsgLine = "$d - Cannot migrate $VM because it has one or more snapshots." [void]$MessagesListBox.items.add($MsgLine) } Else { $SourceName = Get-VM -Name $VM | Get-Datastore | % {$_.name} If($SourceName -ne $DestinationName) { Get-VM -Name $VM | Move-VM -Datastore ($DestinationName) -RunAsync } Else { $d = Get-Date $MsgLine = "$d - Cannot migrate $VM because the source datastore and the destination datastore are the same." [void]$MessagesListBox.items.add($MsgLine) } } } } While($TaskListBox.SelectedItems.Count -gt 0) { $TaskListBox.Items.Remove($TaskListBox.SelectedItems[0]) } } } } $UndoALLButton_Click= { #TODO: Place custom script here If ($TaskListBox.Items.Count -eq 0) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('The task list is empty.') } Else { foreach($Task in $TaskListBox.Items) { $Task = $Task.split(" ") $VM = $Task[3] $DestinationName = $Task[7] $a = $DestinationName.indexof("SAN") If ($a -lt 0) #If Destination is NOT a datastore { #Perform VMotion $SourceName = Get-VM -name $VM | Get-VMHost | %{$_.name} If($SourceName -ne $DestinationName) { Get-VM -Name $VM | Move-VM -Destination (Get-VMHost $DestinationName) -RunAsync } Else { $d = Get-Date $MsgLine = "$d - Cannot migrate $VM because the source host and the destination host are the same." [void]$MessagesListBox.items.add($MsgLine) } } Else { #Perform SVMotion $VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024 $DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB} $DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2} $DBAvailableSpace = $DBFreeSpace - $DBReserved $SnapshotCount = (Get-VM -Name $VM | Get-Snapshot | Measure-Object).Count If ($VMsize -gt $DBAvailableSpace) { $VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024) $DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024) $DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024) $d = Get-Date $MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)." [void]$MessagesListBox.items.add($MsgLine) } ElseIf ($SnapshotCount -gt 0) { $d = Get-Date $MsgLine = "$d - Cannot migrate $VM because it has one or more snapshots." [void]$MessagesListBox.items.add($MsgLine) } Else { $SourceName = Get-VM -Name $VM | Get-Datastore | % {$_.name} If($SourceName -ne $DestinationName) { Get-VM -Name $VM | Move-VM -Datastore ($DestinationName) -RunAsync } Else { $d = Get-Date $MsgLine = "$d - Cannot migrate $VM because the source datastore and the destination datastore are the same." [void]$MessagesListBox.items.add($MsgLine) } } } } $TaskListBox.Items.Clear() } } $SaveTaskButton_Click= { #TODO: Place custom script here If ($TaskListBox.items.count -eq 0) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('Nothing to save to log file.') } Else { $SaveFileD = new-object System.Windows.Forms.SaveFileDialog $SaveFileD.Filter = "Log Files (*.log)|*.log"; $SaveFileD.Title = "Save to a log file"; $SaveFileD.FilterIndex = 2; $SaveFileD.RestoreDirectory = $true; if ($SaveFileD.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { $FileName = $SaveFileD.FileName $Tasks = $TaskListBox.items $logheader = "Easy Migration Tool v3.0 - Log generated on " + (Get-Date) #Save a log file for this session to a location selected by the user Out-File -InputObject $logheader -FilePath $Filename Out-File -InputObject "" -Append -FilePath $FileName Out-File -InputObject $Tasks -Append -FilePath $FileName } } } $ReloadTaskButton_Click= { #TODO: Place custom script here $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog #$OpenFileDialog.initialDirectory = $initialDirectory $OpenFileDialog.filter = "Log Files (*.log)|*.log" if ($OpenFileDialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { $FileName = $OpenFileDialog.FileName $LinesCount = (Get-Content $FileName).Count $LogLines = Get-Content $FileName | Select -Last ($LinesCount - 2) $TaskListBox.Items.Clear() foreach ($LogLine in $LogLines) { [void]$TaskListBox.items.add($LogLine) } $ClearMsgButton.Enabled = $true $UndoButton.Enabled = $true $UndoALLButton.Enabled = $true $SaveTaskButton.Enabled = $true } } #---------------------------------------------- #region Generated Form Code # Start Main Form $MigrationForm.Text = 'Easy Migration Tool v3.0' $MigrationForm.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold) $MigrationForm.Name = 'EasyMigrationForm' $MigrationForm.StartPosition = "CenterScreen" $MigrationForm.FormBorderStyle = "FixedDialog" $MigrationForm.MaximizeBox = $false $MigrationForm.MinimizeBox = $false $MigrationForm.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 1024 $System_Drawing_Size.Height = 768 $MigrationForm.ClientSize = $System_Drawing_Size # End Main Form #Start Easy_Migration Header $Header.Font = new-object System.Drawing.Font("Tahoma",10,[System.Drawing.FontStyle]::Bold) $Header.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft $Header.Text = 'Easy Migration Tool v3.0' $Header.Location = new-object System.Drawing.Point(150,15) $Header.Size = new-object System.Drawing.Size(230, 20) $MigrationForm.Controls.Add($Header) #End Easy_Migration Header # Start vCenter Server Label $vCenterLabel.TabIndex = 2 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 95 $System_Drawing_Size.Height = 20 $vCenterLabel.Size = $System_Drawing_Size $vCenterLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold) $vCenterLabel.Text = 'vCenter Server:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 30 $System_Drawing_Point.Y = 50 $vCenterLabel.Location = $System_Drawing_Point $vCenterLabel.DataBindings.DefaultDataSourceUpdateMode = 0 $vCenterLabel.Name = 'vCenterLabel' $MigrationForm.Controls.Add($vCenterLabel) # End vCenter Server Label # Start vCenter ComboBox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 120 $System_Drawing_Size.Height = 20 $VCComboBox.Size = $System_Drawing_Size $VCComboBox.Font = new-object System.Drawing.Font("Tahoma",8) $VCComboBox.DataBindings.DefaultDataSourceUpdateMode = 0 $VCComboBox.Name = 'VCComboBox' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 125 $System_Drawing_Point.Y = 50 $VCComboBox.Location = $System_Drawing_Point $VCComboBox.TabIndex = 0 $VCNames = @('vcserver01','vcserver02') foreach($VCName in $VCNames) { $VCComboBox.Items.add($VCName) } $MigrationForm.Controls.Add($VCComboBox) # End vCenter ComboBox # Start Login Button $LoginButton.TabIndex = 0 $LoginButton.Name = 'LoginButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 80 $System_Drawing_Size.Height = 22 $LoginButton.Size = $System_Drawing_Size $LoginButton.Font = new-object System.Drawing.Font("Tahoma",8) $LoginButton.UseVisualStyleBackColor = $True $LoginButton.Text = 'Login' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 250 $System_Drawing_Point.Y = 50 $LoginButton.Location = $System_Drawing_Point $LoginButton.DataBindings.DefaultDataSourceUpdateMode = 0 $LoginButton.add_Click($LoginButton_Click) $MigrationForm.Controls.Add($LoginButton) # End Login Button # Start Change VC Button $ChangeVCButton.TabIndex = 19 $ChangeVCButton.Name = 'ChangeVCButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 90 $System_Drawing_Size.Height = 22 $ChangeVCButton.Size = $System_Drawing_Size $ChangeVCButton.Font = new-object System.Drawing.Font("Tahoma",8) $ChangeVCButton.UseVisualStyleBackColor = $True $ChangeVCButton.Text = 'Change vCenter' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 335 $System_Drawing_Point.Y = 50 $ChangeVCButton.Location = $System_Drawing_Point $ChangeVCButton.DataBindings.DefaultDataSourceUpdateMode = 0 $ChangeVCButton.add_Click($ChangeVCButton_OnClick) $ChangeVCButton.Enabled = $false $MigrationForm.Controls.Add($ChangeVCButton) # End Change VC Button # Start Cluster Combobox $ClusterLabel.TabIndex = 5 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 85 $System_Drawing_Size.Height = 20 $ClusterLabel.Size = $System_Drawing_Size $ClusterLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold) $ClusterLabel.Text = 'Select Cluster:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 40 $System_Drawing_Point.Y = 90 $ClusterLabel.Location = $System_Drawing_Point $ClusterLabel.DataBindings.DefaultDataSourceUpdateMode = 0 $ClusterLabel.Name = 'ClusterLabel' $MigrationForm.Controls.Add($ClusterLabel) $ClusterComboBox.FormattingEnabled = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 120 $System_Drawing_Size.Height = 100 $ClusterComboBox.Size = $System_Drawing_Size $ClusterComboBox.Font = new-object System.Drawing.Font("Tahoma",8) $ClusterComboBox.DataBindings.DefaultDataSourceUpdateMode = 0 $ClusterComboBox.Name = 'ClusterComboBox' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 125 $System_Drawing_Point.Y = 90 $ClusterComboBox.Location = $System_Drawing_Point $ClusterComboBox.TabIndex = 5 $ClusterComboBox.Enabled = $False $MigrationForm.Controls.Add($ClusterComboBox) # End Cluster Listbox # Start Host to Host Button $HostToHostButton.TabIndex = 3 $HostToHostButton.Name = 'HostToHostButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 85 $System_Drawing_Size.Height = 20 $HostToHostButton.Size = $System_Drawing_Size $HostToHostButton.Font = new-object System.Drawing.Font("Tahoma",8) $HostToHostButton.UseVisualStyleBackColor = $True $HostToHostButton.Text = 'Host to Host' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 30 $System_Drawing_Point.Y = 130 $HostToHostButton.Location = $System_Drawing_Point $HostToHostButton.DataBindings.DefaultDataSourceUpdateMode = 0 $HostToHostButton.add_Click($HostToHostButton_Click) $HostToHostButton.Enabled = $False $MigrationForm.Controls.Add($HostToHostButton) # End Host to Host Button # Start VM to Host Button $VMToHostButton.TabIndex = 3 $VMToHostButton.Name = 'VMToHostButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 90 $System_Drawing_Size.Height = 20 $VMToHostButton.Size = $System_Drawing_Size $VMToHostButton.Font = new-object System.Drawing.Font("Tahoma",8) $VMToHostButton.UseVisualStyleBackColor = $True $VMToHostButton.Text = 'VM to Host' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 120 $System_Drawing_Point.Y = 130 $VMToHostButton.Location = $System_Drawing_Point $VMToHostButton.DataBindings.DefaultDataSourceUpdateMode = 0 $VMToHostButton.add_Click($VMToHostButton_Click) $VMToHostButton.Enabled = $false $MigrationForm.Controls.Add($VMToHostButton) # End VM to Host Button # Start Datastore to Datastore Button $DBtoDBButton.TabIndex = 3 $DBtoDBButton.Name = 'DBtoDBButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 130 $System_Drawing_Size.Height = 20 $DBtoDBButton.Size = $System_Drawing_Size $DBtoDBButton.Font = new-object System.Drawing.Font("Tahoma",8) $DBtoDBButton.UseVisualStyleBackColor = $True $DBtoDBButton.Text = 'Datastore to Datastore' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 215 $System_Drawing_Point.Y = 130 $DBtoDBButton.Location = $System_Drawing_Point $DBtoDBButton.DataBindings.DefaultDataSourceUpdateMode = 0 $DBtoDBButton.add_Click($DBtoDBButton_Click) $DBtoDBButton.Enabled = $false $MigrationForm.Controls.Add($DBtoDBButton) # End Datastore to Datastore Button # Start VM to Datastore Button $VMtoDBButton.TabIndex = 3 $VMtoDBButton.Name = 'VMtoDBButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 20 $VMtoDBButton.Size = $System_Drawing_Size $VMtoDBButton.Font = new-object System.Drawing.Font("Tahoma",8) $VMtoDBButton.UseVisualStyleBackColor = $True $VMtoDBButton.Text = 'VM to Datastore' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 350 $System_Drawing_Point.Y = 130 $VMtoDBButton.Location = $System_Drawing_Point $VMtoDBButton.DataBindings.DefaultDataSourceUpdateMode = 0 $VMtoDBButton.add_Click($VMtoDBButton_Click) $VMtoDBButton.Enabled = $false $MigrationForm.Controls.Add($VMtoDBButton) # End VM to Datastore Button # Start Source Host List Box $SourceHostListBox.FormattingEnabled = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 200 $System_Drawing_Size.Height = 415 $SourceHostListBox.Size = $System_Drawing_Size $SourceHostListBox.Font = new-object System.Drawing.Font("Tahoma",8) $SourceHostListBox.DataBindings.DefaultDataSourceUpdateMode = 0 $SourceHostListBox.Name = 'SourceHostListBox' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 30 $System_Drawing_Point.Y = 180 $SourceHostListBox.Location = $System_Drawing_Point $SourceHostListBox.MultiColumn = $false $SourceHostListBox.TabIndex = 5 $SourceHostListBox.Sorted = $True $SourceHostListBox.HorizontalScrollbar = $true $SourceHostListBox.add_MouseDoubleClick($SourceHostListBox_MouseDoubleClick) $MigrationForm.Controls.Add($SourceHostListBox) # End Source Host List Box # Start Source Datastore List Box $SourceDBListBox.FormattingEnabled = $True $SourceDBListBox.CheckOnClick = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 200 $System_Drawing_Size.Height = 415 $SourceDBListBox.Size = $System_Drawing_Size $SourceDBListBox.Font = new-object System.Drawing.Font("Tahoma",8) $SourceDBListBox.DataBindings.DefaultDataSourceUpdateMode = 0 $SourceDBListBox.Name = 'SourceDBListBox' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 30 $System_Drawing_Point.Y = 180 $SourceDBListBox.Location = $System_Drawing_Point $SourceDBListBox.MultiColumn = $false $SourceDBListBox.HorizontalScrollBar = $true $SourceDBListBox.TabIndex = 5 $SourceDBListBox.Sorted = $True $SourceDBListBox.HorizontalScrollbar = $true # End Source Datastore List Box # Start Source VM List Box $SourceVMListBox.FormattingEnabled = $True $SourceVMListBox.CheckOnClick = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 200 $System_Drawing_Size.Height = 415 $SourceVMListBox.Size = $System_Drawing_Size $SourceVMListBox.Font = new-object System.Drawing.Font("Tahoma",8) $SourceVMListBox.DataBindings.DefaultDataSourceUpdateMode = 0 $SourceVMListBox.Name = 'SourceVMListBox' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 30 $System_Drawing_Point.Y = 180 $SourceVMListBox.Location = $System_Drawing_Point $SourceVMListBox.MultiColumn = $false $SourceVMListBox.TabIndex = 5 $SourceVMListBox.Sorted = $True $SourceVMListBox.HorizontalScrollbar = $True # End Source VM List Box # Start Source Button $SourceButton.TabIndex = 7 $SourceButton.Name = 'Source Button' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 200 $System_Drawing_Size.Height = 20 $SourceButton.Size = $System_Drawing_Size $SourceButton.Font = new-object System.Drawing.Font("Tahoma",8) $SourceButton.UseVisualStyleBackColor = $True $SourceButton.Text = 'Source' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 30 $System_Drawing_Point.Y = 600 $SourceButton.Location = $System_Drawing_Point $SourceButton.DataBindings.DefaultDataSourceUpdateMode = 0 $SourceButton.add_Click($SourceButton_OnClick) $SourceButton.Enabled = $false $MigrationForm.Controls.Add($SourceButton) # End Source Button # Start All Clusters Checkbox $AllClustersCheckbox.TabIndex = 4 $AllClustersCheckbox.Name = 'AllClustersCheckbox' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 150 $System_Drawing_Size.Height = 20 $AllClustersCheckbox.Size = $System_Drawing_Size $AllClustersCheckbox.Font = new-object System.Drawing.Font("Tahoma",8) $AllClustersCheckbox.UseVisualStyleBackColor = $True $AllClustersCheckbox.Text = 'Show Hosts in All Clusters' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 250 $System_Drawing_Point.Y = 160 $AllClustersCheckbox.Location = $System_Drawing_Point $AllClustersCheckbox.DataBindings.DefaultDataSourceUpdateMode = 0 $AllClustersCheckbox.add_Click($AllClustersCheckbox_Click) $AllClustersCheckbox.Enabled = $False $MigrationForm.Controls.Add($AllClustersCheckbox) # End All Clusters Checkbox # Start Destination List Box $DestinationListBox.FormattingEnabled = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 200 $System_Drawing_Size.Height = 415 $DestinationListBox.Size = $System_Drawing_Size $DestinationListBox.Font = new-object System.Drawing.Font("Tahoma",8) $DestinationListBox.DataBindings.DefaultDataSourceUpdateMode = 0 $DestinationListBox.Name = 'DestinationListBox' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 250 $System_Drawing_Point.Y = 180 $DestinationListBox.Location = $System_Drawing_Point $DestinationListBox.HorizontalScrollBar = $true $DestinationListBox.MultiColumn = $false $DestinationListBox.TabIndex = 5 $DestinationListBox.Sorted = $True $DestinationListBox.HorizontalScrollbar = $True $MigrationForm.Controls.Add($DestinationListBox) # End Destination List Box # Start Destination Button $DestinationButton.TabIndex = 7 $DestinationButton.Name = 'Destination Button' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 200 $System_Drawing_Size.Height = 20 $DestinationButton.Size = $System_Drawing_Size $DestinationButton.Font = new-object System.Drawing.Font("Tahoma",8) $DestinationButton.UseVisualStyleBackColor = $True $DestinationButton.Text = 'Destination' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 250 $System_Drawing_Point.Y = 600 $DestinationButton.Location = $System_Drawing_Point $DestinationButton.DataBindings.DefaultDataSourceUpdateMode = 0 $DestinationButton.add_Click($DestinationButton_OnClick) $DestinationButton.Enabled = $false $MigrationForm.Controls.Add($DestinationButton) # End Destination Button # Start FindVM Label $FindVMLabel.TabIndex = 2 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 60 $System_Drawing_Size.Height = 20 $FindVMLabel.Size = $System_Drawing_Size $FindVMLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold) $FindVMLabel.Text = 'Find VM:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 30 $System_Drawing_Point.Y = 650 $FindVMLabel.Location = $System_Drawing_Point $FindVMLabel.DataBindings.DefaultDataSourceUpdateMode = 0 $FindVMLabel.Name = 'FindVMLabel' $MigrationForm.Controls.Add($FindVMLabel) # End FindVM Label # Start FindVM Textbox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 20 $FindVMTxtBox.Size = $System_Drawing_Size $FindVMTxtBox.Font = new-object System.Drawing.Font("Tahoma",8) $FindVMTxtBox.DataBindings.DefaultDataSourceUpdateMode = 0 $FindVMTxtBox.Name = 'FindVMTxtBox' $FindVMTxtBox.TabIndex = 6 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 90 $System_Drawing_Point.Y = 650 $FindVMTxtBox.Location = $System_Drawing_Point $FindVMTxtBox.Enabled = $false $MigrationForm.Controls.Add($FindVMTxtBox) # End FindVM Textbox #Start FindVM Button $MigrationForm.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 250 $System_Drawing_Point.Y = 650 $FindVMBtn.Location = $System_Drawing_Point $FindVMBtn.Name = "FindVMBtn" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 50 $FindVMBtn.Size = $System_Drawing_Size $FindVMBtn.TabIndex = 4 $FindVMBtn.Text = "Go" $FindVMBtn.Font = new-object System.Drawing.Font("Tahoma",8) $FindVMBtn.UseVisualStyleBackColor = $True $FindVMBtn.add_Click($FindVMBtn_OnClick) $FindVMBtn.Enabled = $false $MigrationForm.Controls.Add($FindVMBtn) #End FindVM Button #Start Reset FindVM Button $MigrationForm.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 305 $System_Drawing_Point.Y = 650 $ResetFindVMBtn.Location = $System_Drawing_Point $ResetFindVMBtn.Name = "ResetFindVMBtn" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Height = 20 $System_Drawing_Size.Width = 50 $ResetFindVMBtn.Size = $System_Drawing_Size $ResetFindVMBtn.TabIndex = 5 $ResetFindVMBtn.Font = new-object System.Drawing.Font("Tahoma",8) $ResetFindVMBtn.Text = "Reset" $ResetFindVMBtn.UseVisualStyleBackColor = $True $ResetFindVMBtn.add_Click($ResetFindVMBtn_OnClick) $ResetFindVMBtn.Enabled = $false $MigrationForm.Controls.Add($ResetFindVMBtn) #End Reset FindVM Button # Start Migrate Button $MigrateButton.TabIndex = 7 $MigrateButton.Name = 'MigrateButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 130 $System_Drawing_Size.Height = 25 $MigrateButton.Size = $System_Drawing_Size $MigrateButton.Font = new-object System.Drawing.Font("Tahoma",8) $MigrateButton.UseVisualStyleBackColor = $True $MigrateButton.Text = 'Migrate' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 30 $System_Drawing_Point.Y = 720 $MigrateButton.Location = $System_Drawing_Point $MigrateButton.DataBindings.DefaultDataSourceUpdateMode = 0 $MigrateButton.add_Click($MigrateButton_OnClick) $MigrateButton.Enabled = $false $MigrationForm.Controls.Add($MigrateButton) # End Migrate Button # Start RESET Button $ResetButton.TabIndex = 19 $ResetButton.Name = 'ResetButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 25 $ResetButton.Size = $System_Drawing_Size $ResetButton.Font = new-object System.Drawing.Font("Tahoma",8) $ResetButton.UseVisualStyleBackColor = $True $ResetButton.Text = 'Reset' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 170 $System_Drawing_Point.Y = 720 $ResetButton.Location = $System_Drawing_Point $ResetButton.DataBindings.DefaultDataSourceUpdateMode = 0 $ResetButton.add_Click($ResetButton_OnClick) $ResetButton.Enabled = $false $MigrationForm.Controls.Add($ResetButton) # End RESET Button # Start CLOSE Button $CloseButton.TabIndex = 19 $CloseButton.Name = 'CloseButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 130 $System_Drawing_Size.Height = 25 $CloseButton.Size = $System_Drawing_Size $CloseButton.Font = new-object System.Drawing.Font("Tahoma",8) $CloseButton.UseVisualStyleBackColor = $True $CloseButton.Text = 'Close' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 320 $System_Drawing_Point.Y = 720 $CloseButton.Location = $System_Drawing_Point $CloseButton.DataBindings.DefaultDataSourceUpdateMode = 0 $CloseButton.add_Click($CloseButton_OnClick) $MigrationForm.Controls.Add($CloseButton) # End CLOSE Button # Start Messages ListBox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 80 $System_Drawing_Size.Height = 20 $MessagesLabel.Size = $System_Drawing_Size $MessagesLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold) $MessagesLabel.Text = 'Messages' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 480 $System_Drawing_Point.Y = 50 $MessagesLabel.Location = $System_Drawing_Point $MessagesLabel.DataBindings.DefaultDataSourceUpdateMode = 0 $MessagesLabel.Name = 'MessagesLabel' $MigrationForm.Controls.Add($MessagesLabel) $MessagesListBox.FormattingEnabled = $True $MessagesListBox.SelectionMode = "None" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 525 $System_Drawing_Size.Height = 285 $MessagesListBox.Size = $System_Drawing_Size $MessagesListBox.Font = new-object System.Drawing.Font("Tahoma",8) $MessagesListBox.DataBindings.DefaultDataSourceUpdateMode = 0 $MessagesListBox.Name = 'MessagesListBox' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 480 $System_Drawing_Point.Y = 70 $MessagesListBox.Location = $System_Drawing_Point $MessagesListBox.MultiColumn = $false $MessagesListBox.HorizontalScrollbar = $true $MigrationForm.Controls.Add($MessagesListBox) # End Messages ListBox # Start Task ListBox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 80 $System_Drawing_Size.Height = 20 $TaskLabel.Size = $System_Drawing_Size $TaskLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold) $TaskLabel.Text = 'Recent Tasks' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 480 $System_Drawing_Point.Y = 380 $TaskLabel.Location = $System_Drawing_Point $TaskLabel.DataBindings.DefaultDataSourceUpdateMode = 0 $TaskLabel.Name = 'TaskLabel' $MigrationForm.Controls.Add($TaskLabel) $TaskListBox.FormattingEnabled = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 525 $System_Drawing_Size.Height = 285 $TaskListBox.Size = $System_Drawing_Size $TaskListBox.Font = new-object System.Drawing.Font("Tahoma",8) $TaskListBox.DataBindings.DefaultDataSourceUpdateMode = 0 $TaskListBox.Name = 'TaskListBox' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 480 $System_Drawing_Point.Y = 400 $TaskListBox.Location = $System_Drawing_Point $TaskListBox.MultiColumn = $false $TaskListBox.HorizontalScrollbar = $true $TaskListBox.SelectionMode = "MultiExtended" $MigrationForm.Controls.Add($TaskListBox) # End Task ListBox # Start Clear Messages Button $ClearMsgButton.TabIndex = 0 $ClearMsgButton.Name = 'ClearMsgButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 93 $System_Drawing_Size.Height = 25 $ClearMsgButton.Size = $System_Drawing_Size $ClearMsgButton.Font = new-object System.Drawing.Font("Tahoma",8) $ClearMsgButton.UseVisualStyleBackColor = $True $ClearMsgButton.Enabled = $false $ClearMsgButton.Text = 'Clear Messages' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 480 $System_Drawing_Point.Y = 720 $ClearMsgButton.Location = $System_Drawing_Point $ClearMsgButton.DataBindings.DefaultDataSourceUpdateMode = 0 $ClearMsgButton.add_Click($ClearMsgButton_Click) $MigrationForm.Controls.Add($ClearMsgButton) # End Clear Messages Button # Start Undo Button $UndoButton.TabIndex = 0 $UndoButton.Name = 'UndoButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 93 $System_Drawing_Size.Height = 25 $UndoButton.Size = $System_Drawing_Size $UndoButton.Font = new-object System.Drawing.Font("Tahoma",8) $UndoButton.UseVisualStyleBackColor = $True $UndoButton.Enabled = $false $UndoButton.Text = 'Undo' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 588 $System_Drawing_Point.Y = 720 $UndoButton.Location = $System_Drawing_Point $UndoButton.DataBindings.DefaultDataSourceUpdateMode = 0 $UndoButton.add_Click($UndoButton_Click) $MigrationForm.Controls.Add($UndoButton) # End Undo Button # Start UndoALL Button $UndoALLButton.TabIndex = 0 $UndoALLButton.Name = 'UndoALLButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 93 $System_Drawing_Size.Height = 25 $UndoALLButton.Size = $System_Drawing_Size $UndoALLButton.Font = new-object System.Drawing.Font("Tahoma",8) $UndoALLButton.UseVisualStyleBackColor = $True $UndoALLButton.Enabled = $false $UndoALLButton.Text = 'Undo ALL' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 696 $System_Drawing_Point.Y = 720 $UndoALLButton.Location = $System_Drawing_Point $UndoALLButton.DataBindings.DefaultDataSourceUpdateMode = 0 $UndoALLButton.add_Click($UndoALLButton_Click) $MigrationForm.Controls.Add($UndoALLButton) # End UndoALL Button # Start Save Task Button $SaveTaskButton.TabIndex = 0 $SaveTaskButton.Name = 'SaveTaskButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 93 $System_Drawing_Size.Height = 25 $SaveTaskButton.Size = $System_Drawing_Size $SaveTaskButton.Font = new-object System.Drawing.Font("Tahoma",8) $SaveTaskButton.UseVisualStyleBackColor = $True $SaveTaskButton.Enabled = $false $SaveTaskButton.Text = 'Save Tasks' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 804 $System_Drawing_Point.Y = 720 $SaveTaskButton.Location = $System_Drawing_Point $SaveTaskButton.DataBindings.DefaultDataSourceUpdateMode = 0 $SaveTaskButton.add_Click($SaveTaskButton_Click) $MigrationForm.Controls.Add($SaveTaskButton) # End Save Task Button # Start Load Task Button $ReloadTaskButton.TabIndex = 0 $ReloadTaskButton.Name = 'ReloadTaskButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 93 $System_Drawing_Size.Height = 25 $ReloadTaskButton.Size = $System_Drawing_Size $ReloadTaskButton.Font = new-object System.Drawing.Font("Tahoma",8) $ReloadTaskButton.UseVisualStyleBackColor = $True $ReloadTaskButton.Enabled = $false $ReloadTaskButton.Text = 'Reload Tasks' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 912 $System_Drawing_Point.Y = 720 $ReloadTaskButton.Location = $System_Drawing_Point $ReloadTaskButton.DataBindings.DefaultDataSourceUpdateMode = 0 $ReloadTaskButton.add_Click($ReloadTaskButton_Click) $MigrationForm.Controls.Add($ReloadTaskButton) # End Load Task Button #endregion Generated Form Code #Save the initial state of the form $InitialFormWindowState = $MigrationForm.WindowState #Init the OnLoad event to correct the initial state of the form $MigrationForm.add_Load($OnLoadForm_StateCorrection) #Show the Form $MigrationForm.ShowDialog()| Out-Null } #End Function #Call the Function GenerateForm
PowerShellCorpus/PoshCode/Deleted-Objects.ps1
Deleted-Objects.ps1
param ( $Computer, [String[]]$ObjectsDeleted ) $Info = $null $Disks = $null trap {Write-Host "Error WmiObject $Computer";Continue} $Disks += Get-WmiObject win32_logicaldisk -ComputerName $Computer | Where-Object {$_.Size -ne $null} foreach ($Disk in $Disks){ if ($Disk.Name -like "*:*") { $Disk = $Disk.Name.Replace(":","$") } trap {Write-Host "Error ChildItem $Computer";Continue} $Info += Get-ChildItem "\\\\$Computer\\$Disk\\*" -Recurse -ErrorAction SilentlyContinue if ($Info){ foreach ($Object in $ObjectsDeleted){ $Info | Where-Object {$_.Name -like $Object} | % {remove-item $_.fullname -Recurse -Force -ErrorAction SilentlyContinue} } } }
PowerShellCorpus/PoshCode/New-AdUser.ps1
New-AdUser.ps1
function New-AdUser { param ( [string] $Username = $(throw "Parameter -Username [System.String] is required."), [string] $Password = $(throw "Parameter -Password [System.String] is required."), [string] $OrganizationalUnit = "Users", [string] $DisplayName, [string] $FirstName, [string] $LastName, [string] $Initials, [string] $Description, [switch] $CannotChangePassword, [switch] $PasswordNeverExpires, [switch] $Disabled ) try { $currentDomain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() $dn = $currentDomain.GetDirectoryEntry().distinguishedName $ou = [ADSI] "LDAP://CN=$OrganizationalUnit,$dn" $userAccount = $ou.Create("user", "cn=$Username") $userAccount.SetInfo() $userAccount.userAccountControl = ($userAccount.userAccountControl.Item(0) -bxor 0x0002) #Enable the account $userAccount.SetInfo() # Properties $userAccount.sAMAccountName = $Username $userAccount.SetInfo() $userAccount.userPrincipalName = ("{0}@{1}" -f $Username, $currentDomain.Name) if ($DisplayName) { $userAccount.displayName = $DisplayName } if ($Description) { $userAccount.description = $Description } if ($FirstName) { $userAccount.givenname = $FirstName } if ($LastName) { $userAccount.sn = $LastName } if ($Initials) { $userAccount.initials = $Initials } $userAccount.SetInfo() $userAccount.SetPassword($Password) # Password if ($PasswordNeverExpires) { $userAccount.userAccountControl = ($userAccount.userAccountControl.Item(0) -bxor 0x10000) } if ($CannotChangePassword) { $everyOne = [System.Security.Principal.SecurityIdentifier]'S-1-1-0' $EveryoneDeny = new-object System.DirectoryServices.ActiveDirectoryAccessRule ($Everyone,'ExtendedRight','Deny', [System.Guid]'ab721a53-1e2f-11d0-9819-00aa0040529b') $self = [System.Security.Principal.SecurityIdentifier]'S-1-5-10' $SelfDeny = new-object System.DirectoryServices.ActiveDirectoryAccessRule ($self,'ExtendedRight','Deny', [System.Guid]'ab721a53-1e2f-11d0-9819-00aa0040529b') $userAccount.get_ObjectSecurity().AddAccessRule($selfDeny) $userAccount.get_ObjectSecurity().AddAccessRule($EveryoneDeny) $userAccount.CommitChanges() } $userAccount.SetInfo() if ($Disabled) { $userAccount.userAccountControl = ($userAccount.userAccountControl.Item(0) -bxor 0x0002) } $userAccount.SetInfo() } catch { Write-Error $_ #$ou.Delete("user", "cn=$Username") return $false } return $true } New-AdUser -Username bob -Password 'B0bsP4$$W0rD!@#$%' -Description "Bob's account" -FirstName Bob -LastName Doe -DisplayName "Bob Doe" -Initials R -PasswordNeverExpires -CannotChangePassword -Disabled
PowerShellCorpus/PoshCode/Reverse filename sequenc_4.ps1
Reverse filename sequenc_4.ps1
# Reverse filename sequence v 0.9 # Author: Sean Wendt # # This script will rename a sequenced set of files in a directory. # For example, you have foobar01.jpg, foobar02.jpg, foobar03.jpg # -- it will reverse the order, so the last file is now 01, the second to last 02, etc.. # # Limitations: -You cannot use the same filename prefix, i.e. foobar must change to foobars. # -It's hardcoded to only support 5 digit numbers right now. # -Similarly, it will only support a file sequence with up to 5 digits. # This is the first script I've written, I know it's not great! ;) # Help to make it better would be appreciated. Thanks. # $file_extension = Read-Host "Enter file extension, i.e. .jpg or .txt" $file_prefix = Read-Host "Enter file prefix, i.e. entering foobar will rename files to foobar001.ext, foobar002.ext, etc.." $files = Get-ChildItem | ?{ $_.PSIsContainer -ne "True"} # Creates array of files in current directory, ignores folders $idx = 0 # Sets index value (0 = filenames start at foobar00000.jpg, modify to 1 to start at foobar00001.jpg) for ($ctr=$files.count; $ctr -gt 0 ; --$ctr) { if (($idx -ge 0) -and ($idx -le 9)) { Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '00000' + $idx++ + $file_extension) } elseif (($idx -ge 10) -and ($idx -le 99)) { Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '0000' + $idx++ + $file_extension) } elseif (($idx -ge 100) -and ($idx -le 999)) { Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '000' + $idx++ + $file_extension) } elseif (($idx -ge 1000) -and ($idx -le 9999)) { Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '00' + $idx++ + $file_extension) } elseif (($idx -ge 10000) -and ($idx -le 99999)) { Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '0' + $idx++ + $file_extension) } $idx #prints the index # it just completed }
PowerShellCorpus/PoshCode/LDAPLogging.ps1
LDAPLogging.ps1
\nfunction Private:Configure-Logging {\n Use one of the following aliases:\n Get-LDAPLogging\n View current LDAP logging settings\n Enable-LDAPLogging\n Enables LDAP logging. Logging is set to log every single LDAP query and stores it in directory services log.\n Disable-LDAPLogging\n Disables LDAP logging. Logging is set to its default values.\n PS C:\\> Get-LDAPLogging\n PS C:\\> Enable-LDAPLogging DC1\n Author: Patrick Sczepanski \n Version: 1.0\n Email: patrick -at- sczepanski -dot- com\n patrick -dot- redtoo -at- redtoo -dot- com\n Blog: http://redtoo.com/blog\n Copyright: 2012\n Enable-LDAPLogging\n Disable-LDAPLogging\n Get-LDAPEventLog\n Param (\n [string]\n $HostName = $env:COMPUTERNAME\n )\n [System.Nullable``1[[System.Int32]]]$EnableLogging = $null\n switch ( $MyInvocation.InvocationName ) {\n [System.Nullable``1[[System.Int32]]]$EnableLogging = $true\n [bool]$ReadWrite = $true\n [int]$Threshold = 1\n [int]$FieldEngDef = 5\n break\n }\n [System.Nullable``1[[System.Int32]]]$EnableLogging = $false\n [bool]$ReadWrite = $true\n [int]$Threshold = 0\n [int]$FieldEngDef = 0\n break\n }\n Default { \n [System.Nullable``1[[System.Int32]]]$EnableLogging = $null\n [bool]$ReadWrite = $false\n }\n }\n if ( -not (Test-Connection $HostName -Quiet -Count 1) ) {\n continue\n }\n if ( -not ( \n -ComputerName $HostName -ErrorAction SilentlyContinue) ) {\n continue\n }\n $baseKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey( "LocalMachine", $HostName )\n try {\n $key = $baseKey.OpenSubKey($NTDSParams,$ReadWrite)\n if ( $EnableLogging -eq $true ) { \n $key.SetValue( $ExpThre, 1, [Microsoft.Win32.RegistryValueKind]::DWord )\n $key.SetValue( $IneThre, 1, [Microsoft.Win32.RegistryValueKind]::DWord )\n } elseif ( $EnableLogging -eq $false ) {\n $key.DeleteValue( $ExpThre )\n $key.DeleteValue( $IneThre )\n }\n $ExpThreValue = $key.GetValue($ExpThre)\n $IneThreValue = $key.GetValue($IneThre)\n $key.Close()\n }\n catch {\n }\n try {\n $key = $baseKey.OpenSubKey($NTDSDiag,$ReadWrite)\n if ( $EnableLogging -ne $null ) { \n $key.SetValue( $FieldEng, $FieldEngDef )\n } \n $FieldEngValue = $key.GetValue($FieldEng)\n $key.Close()\n }\n catch {\n }\n $baseKey.Close()\n New-Object PSObject -Property @{\n }\n}\nNew-Alias Get-LDAPLogging Configure-Logging -Force\nNew-Alias Enable-LDAPLogging Configure-Logging -Force\nNew-Alias Disable-LDAPLogging Configure-Logging -Force\nFunction Global:Get-LDAPEventLog {\n PS C:\\> Get-LDAPEventLog\n [string],[int]\n [LDAPLookups]\n Author: Patrick Sczepanski \n Version: 1.0\n Email: patrick -at- sczepanski -dot- com\n patrick -dot- redtoo -at- redtoo -dot- com\n Blog: http://redtoo.com/blog\n Copyright: 2012\n Enable-LDAPLogging\n Disable-LDAPLogging\nParam (\n [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Position=0)]\n [string]\n $DNSHostName = $env:COMPUTERNAME,\n [int]\n $LookupMinutes = 60\n )\n Begin {\n $Script:AlreadyLookedUp = @{}\nAdd-Type @'\nusing System;\n public class LDAPLookups {\n public string DNSHostName;\n public string ClientIP;\n public string ClientName;\n public string StartNode;\n public string Filter;\n public string SearchScope;\n public string Attributes;\n public string ServerControls;\n public string Date;\n public string Time;\n }\n'@ \n(?msx)\n # Option m = multi-line e.g. ^=start of line and $=end of line \n # Option s = single-line e.g. . includes end-of-line \n # Option x = spaces and comments are allowed in the pattern \nClient:\\r\\n\n (?<Client>.*)\\:(?<Port>.*)\\r\\n?\nStarting\\snode\\:\\r\\n\n (?<StartNode>.*?)\\r\\n\nFilter:\\r\\n\n (?<Filter>.*?)\\r\\n\nSearch\\sscope:\\r\\n\n (?<SearchScope>.*?)\\r\\n\nAttribute\\sselection:\\r\\n\n (?<Attributes>.*?)\\r\\n\nServer\\scontrols:\\r\\n\n (?<ServerControls>.*?)\\r\\n\nVisited\\sentries:\\r\\n\n (?<VisitedEntries>.*?)\\r\\n\nReturned\\sentries:\\r\\n\n (?<ReturnedEntries>.*)\n }\n Process {\n Get-WinEvent -ComputerName $DNSHostName -FilterHashtable @{ "LogName"="Directory Service" ; "ID"=1644; StartTime= [datetime]::Now.AddMinutes( -$LookupMinutes ) } |\n Foreach-Object { \n if ( $_.Message -match $RegEx ) { \n New-Object LDAPLookups -Property @{\n try {\n if( -not $AlreadyLookedUp.contains( $ClientIP ) ){\n $AlreadyLookedUp.$ClientIP = ( [System.Net.Dns]::GetHostByAddress( $ClientIP ).HostName )\n }\n }\n catch {\n $AlreadyLookedUp.$ClientIP = $ClientIP\n }\n $AlreadyLookedUp.$ClientIP\n )\n "Time" = $_.TimeCreated.ToString( "HH:mm:ss" )\n }\n }\n } \n } \n End {\n Remove-Variable -Scope Script -Name AlreadyLookedUp\n }\n}
PowerShellCorpus/PoshCode/num.ps1
num.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 ) { if ( $c.ContainsKey($svno.ToString().SubString(0,1).ToUpper()) ) { write-host $svno -Fore $c.Get_Item($svno.ToString().SubString(0,1).ToUpper()).ToString() } else { write-host $svno } } }
PowerShellCorpus/PoshCode/e0d5c1ac-138e-4921-8f14-f59a45084096.ps1
e0d5c1ac-138e-4921-8f14-f59a45084096.ps1
[string]$entry = $args[0] if ($entry -eq $null) { [string]$entry = Read-Host -Prompt "Enter Computer Name" } $Computers = Get-QADComputer $entry $Computers | ForEach-Object {Get-WmiObject Win32_Registry -ComputerName $_.Name | Select-Object @{Name="Name";Expression={$_.__SERVER}},CurrentSize,MaximumSize,Caption}
PowerShellCorpus/PoshCode/WSUS Admin Module_1.ps1
WSUS Admin Module_1.ps1
Write-Host "`n" Write-Host "`t`tWSUS Administrator Module 1.0" Write-Host "`n" Write-Host -nonewline "Make initial connection to WSUS Server:`t" Write-Host -fore Yellow "Connect-WSUSServer" Write-Host -nonewline "Disconnect from WSUS Server:`t`t" Write-Host -fore Yellow "Disconnect-WSUSServer" Write-Host -nonewline "List all available commands:`t`t" Write-Host -fore Yellow "Get-WSUSCommands" Write-Host "`n" function Get-WSUSCommands { <# .SYNOPSIS Lists all WSUS functions available from this module. .DESCRIPTION Lists all WSUS functions available from this module. .NOTES Name: Get-WSUSCommand Author: Boe Prox DateCreated: 18Oct2010 .LINK https://boeprox.wordpress.org .EXAMPLE Get-WSUSCommands Description ----------- This command lists all of the available WSUS commands in the module. #> [cmdletbinding()] Param () #List all WSUS functions available Get-Command *WSUS* -CommandType Function | Sort-Object Name } function Connect-WSUSServer { <# .SYNOPSIS Retrieves the last check-in times of clients on WSUS. .DESCRIPTION Retrieves the last check-in times of clients on WSUS. You will need to run this on a machine that has the WSUS Administrator console installed. .PARAMETER WsusServer Name of WSUS server to query against. .PARAMETER Secure Determines if a secure connection will be used to connect to the WSUS server. If not used, then a non-secure connection will be used. .NOTES Name: Get-LastCheckIn Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Connect-WSUSServer -wsusserver "server1" Description ----------- This command will make the connection to the WSUS using an unsecure port (Default:80). .EXAMPLE Connect-WSUSServer -wsusserver "server1" -secure Description ----------- This command will make a secure connection (Default: 443) to a WSUS server. #> [cmdletbinding( DefaultParameterSetName = 'wsus', ConfirmImpact = 'low' )] Param( [Parameter( Mandatory = $True, Position = 0, ParameterSetName = 'wsus', ValueFromPipeline = $True)] [string]$WsusServer, [Parameter( Mandatory = $False, Position = 1, ParameterSetName = 'wsus', ValueFromPipeline = $False)] [switch]$Secure ) #Load required assemblies [void][reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration") #Make connection to WSUS server Write-Host -ForegroundColor Yellow "Attempting connection to WSUS Server: $($wsusserver)" $ErrorActionPreference = 'stop' Try { If ($secure) { $Global:wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer($wsusserver,$True) $Wsus | FT Name, Version,PortNumber } Else { $Global:wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer($wsusserver,$False) $Wsus | FT Name, Version,PortNumber } } Catch { Write-Error "Unable to connect to $($wsusserver)!`n$($error[0])" } } function Disconnect-WSUSServer { <# .SYNOPSIS Disconnects session against WSUS server. .DESCRIPTION Disconnects session against WSUS server. .NOTES Name: Disconnect-WSUSServer Author: Boe Prox DateCreated: 27Oct2010 .LINK https://boeprox.wordpress.org .EXAMPLE Disconnect-WSUSServer Description ----------- This command will disconnect the session to the WSUS server. #> [cmdletbinding()] Param () #Disconnect WSUS session by removing the variable Remove-Variable -Name wsus -Force } function Get-WSUSClients { <# .SYNOPSIS Retrieves a list of all of the clients in WSUS. .DESCRIPTION Retrieves a list of all of the clients in WSUS. .NOTES Name: Get-WSUSClients Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Get-WSUSClients Description ----------- This command will list every client in WSUS. #> [cmdletbinding()] Param () #Gather all computers in WSUS $wsus.GetComputerTargets() } function Start-WSUSSync { <# .SYNOPSIS Start synchronization on WSUS server. .DESCRIPTION Start synchronization on WSUS server. .PARAMETER Monitor Starts a synchronization and runs a background job to monitor currently running content download and notifies user when completed. .NOTES Name: Start-WSUSSync Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Start-WSUSSync Description ----------- This command will begin a manual sychronization on WSUS with the defined update source. .EXAMPLE Start-WSUSSync -monitor Description ----------- This command will begin a manual synchronization on WSUS and will begin a background job that will notifiy via pop-up message when the synchronization has completed. #> [cmdletbinding( DefaultParameterSetName = 'monitor', ConfirmImpact = 'low', SupportsShouldProcess = $True )] Param ( [Parameter( Mandatory = $False, Position = 0, ParameterSetName = 'monitor', ValueFromPipeline = $False)] [switch]$Monitor ) $sub = $wsus.GetSubscription() $sync = $sub.GetSynchronizationProgress() If ($monitor) { #Stop and remove any jobs for SyncMonitoring $jobs = Get-Job | ? {$_.Name -eq "WSUSSyncProgressMonitor"} If ($jobs) { $jobs | Stop-Job $jobs | Remove-Job } #Start WSUS synchronization If ($pscmdlet.ShouldProcess($($wsus.name))) { $sub.StartSynchronization() "Synchronization have been started." Start-Sleep -Seconds 3 Start-Job -Name "WSUSSyncProgressMonitor" -ArgumentList $sync -ScriptBlock { Param ( $sync ) #Load required assemblies for message window [void] [System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”) While ($sync.Phase -ne "NotProcessing") { $null } [System.Windows.Forms.MessageBox]::Show("Synchronization has been completed on WSUS",”Information”) } | Out-Null } } Else { #Start WSUS synchronization If ($pscmdlet.ShouldProcess($($wsus.name))) { $sub.StartSynchronization() "Synchronization have been started." } } } function Stop-WSUSSync { <# .SYNOPSIS Stops a currently running WSUS sync. .DESCRIPTION Stops a currently running WSUS sync. .NOTES Name: Stop-WSUSSync Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Stop-WSUSSync Description ----------- This command will stop a currently running WSUS synchronization. #> [cmdletbinding( DefaultParameterSetName = 'update', ConfirmImpact = 'low', SupportsShouldProcess = $True )] Param() $sub = $wsus.GetSubscription() #Cancel synchronization running on WSUS If ($pscmdlet.ShouldProcess($($wsus.name))) { $sub.StopSynchronization() "Synchronization have been cancelled." } } function Get-WSUSSyncHistory { <# .SYNOPSIS Retrieves the synchronization history of the WSUS server. .DESCRIPTION Retrieves the synchronization history of the WSUS server. .NOTES Name: Get-WSUSSyncHistory Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Get-WSUSSyncHistory Description ----------- This command will list out the entire synchronization history of the WSUS server. #> [cmdletbinding()] Param () $sub = $wsus.GetSubscription() $sub.GetSynchronizationHistory() } function Get-WSUSSyncProgress { <# .SYNOPSIS Displays the current progress of a WSUS synchronization. .DESCRIPTION Displays the current progress of a WSUS synchronization. .PARAMETER Monitor Runs a background job to monitor currently running synchonization and notifies user when completed. .NOTES Name: Get-WSUSSyncProgress Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Get-WSUSSyncProgress Description ----------- This command will show you the current status of the WSUS sync. .EXAMPLE Get-WSUSSyncProgress -monitor Description ----------- This command will begin a background job that will notify you when the WSUS synchronization has been completed. #> [cmdletbinding()] Param ( [Parameter( Mandatory = $False, Position = 0, ParameterSetName = 'monitor', ValueFromPipeline = $False)] [switch]$Monitor ) $sub = $wsus.GetSubscription() If ($monitor) { $job = Get-Job If ($job) { $job = Get-Job -Name "WSUSSyncProgressMonitor" } If ($job) { Get-Job -Name "WSUSSyncProgressMonitor" | Stop-Job Get-Job -Name "WSUSSyncProgressMonitor" | Remove-Job } Start-Job -Name "WSUSSyncProgressMonitor" -ArgumentList $sub -ScriptBlock { Param ( $sub ) #Load required assemblies for message window [void] [System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”) While (($sub.GetSynchronizationProgress()).Phase -ne "NotProcessing") { $null } [System.Windows.Forms.MessageBox]::Show("Synchronization has been completed on WSUS",”Information”) } | Out-Null } Else { #Gather all child servers in WSUS $sub.GetSynchronizationProgress() } } function Get-WSUSEvents { <# .SYNOPSIS Retrieves all WSUS events. .DESCRIPTION Retrieves all WSUS events from the WSUS server. .NOTES Name: Get-WSUSEvents Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Get-WSUSEvents Description ----------- This command will show you all of the WSUS events. #> [cmdletbinding()] Param () $sub = $wsus.GetSubscription() $sub.GetEventHistory() } function Get-WSUSGroups { <# .SYNOPSIS Retrieves all of the WSUS Target Groups. .DESCRIPTION Retrieves all of the WSUS Target Groups. .NOTES Name: Get-WSUSGroups Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Get-WSUSGroups Description ----------- This command will list out all of the WSUS Target groups and their respective IDs. #> [cmdletbinding()] Param () $wsus.GetComputerTargetGroups() } function Get-WSUSServer { <# .SYNOPSIS Retrieves connection and configuration information from the WSUS server. .DESCRIPTION Retrieves connection and configuration information from the WSUS server. .PARAMETER Configuration Lists more configuration information from WSUS Server .NOTES Name: Get-WSUSServer Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Get-WSUSServer Description ----------- This command will display basic information regarding the WSUS server. .EXAMPLE Get-WSUSServer -configuration Description ----------- This command will list out more detailed information regarding the configuration of the WSUS server. #> [cmdletbinding( DefaultParameterSetName = 'wsus', ConfirmImpact = 'low' )] Param( [Parameter( Mandatory = $False, Position = 0, ParameterSetName = 'wsus', ValueFromPipeline = $False)] [switch]$Configuration ) If ($configuration) { $wsus.GetConfiguration() } Else { $wsus } } function Get-WSUSUpdates { <# .SYNOPSIS Retrieves all of the updates from a WSUS server. .DESCRIPTION Retrieves all of the updates from a WSUS server. .NOTES Name: Get-WSUSUpdates Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Get-WSUSUpdates Description ----------- This command will list out every update that is in WSUS's database whether it has been approved or not. #> [cmdletbinding()] Param () $wsus.GetUpdates() } function Get-WSUSEmailConfig { <# .SYNOPSIS Retrieves the email notification configuration from WSUS. .DESCRIPTION Retrieves the email notification configuration from WSUS. .PARAMETER SendTestEmail Optional switch that will send a test email to the configured email addresses .NOTES Name: Get-WSUSEmailConfig Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Get-WSUSEmailConfig Description ----------- This command will display the configuration of the email notifications. .EXAMPLE Get-WSUSEmailConfig -SendTestEmail Description ----------- This command will send a test email to the address or addresses in the To field. #> [cmdletbinding( DefaultParameterSetName = 'wsus', ConfirmImpact = 'low' )] Param( [Parameter( Mandatory = $False, Position = 0, ParameterSetName = 'wsus', ValueFromPipeline = $False)] [switch]$SendTestEmail ) $email = $wsus.GetEmailNotificationConfiguration() If ($SendTestEmail) { $email.SendTestEmail() Write-Host -fore Green "Test email sent." } Else { $email } } function Get-WSUSUpdateCategories { <# .SYNOPSIS Retrieves the list of Update categories available from WSUS. .DESCRIPTION Retrieves the list of Update categories available from WSUS. .NOTES Name: Get-WSUSUpdateCategories Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Get-WSUSUpdateCategories Description ----------- This command will list all of the categories for updates in WSUS. #> [cmdletbinding()] Param () $wsus.GetUpdateCategories() } function Get-WSUSStatus { <# .SYNOPSIS Retrieves a list of all updates and their statuses along with computer statuses. .DESCRIPTION Retrieves a list of all updates and their statuses along with computer statuses. .NOTES Name: Get-WSUSStatus Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Get-WSUSStatus Description ----------- This command will display the status of the WSUS server along with update statuses. #> [cmdletbinding()] Param () $wsus.getstatus() } function Set-WSUSEmailConfig { <# .SYNOPSIS Configures the email notifications on a WSUS server. .DESCRIPTION Configures the email notifications on a WSUS server. It is important to note that the email address to send the emails to is Read-Only and can only be configured from the WSUS Admin Console. After the settings have been changed, the new configuration will be displayed. .PARAMETER EmailLanguage What type of language to send the email in. .PARAMETER SenderDisplayName The friendly name of where the email is coming from. .PARAMETER SenderEmailAddress The senders email address .PARAMETER SendStatusNotification Determines if an email will be sent for a status notification .PARAMETER SendSyncnotification Determines if an email will be sent after a sync by WSUS .PARAMETER SMTPHostname Server name of the smtp server to send email from .PARAMETER SMTPPort Port number to be used to connect to smtp server to send email .PARAMETER SmtpServerRequiresAuthentication Used if smtp server requires authentication .PARAMETER SmtpUserName Username to submit if required by smtp server .PARAMETER StatusNotificationFrequency Frequency (Daily or Weekly) to send notifications .PARAMETER StatusNotificationTimeOfDay Date/Time to send notifications .PARAMETER UpdateServer Name of the WSUS update server .PARAMETER SmtpPassword Password to user for smtp server connection. .NOTES Name: Set-WSUSEmailConfig Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Set-WSUSEmailConfig -SenderDisplayName "WSUSAdmin" -SenderEmailAddress "wsusadmin@domain.com" Description ----------- This command will change the sender name and email address for email notifications and then display the new settings. #> [cmdletbinding( DefaultParameterSetName = 'wsus', ConfirmImpact = 'low' )] Param( [Parameter( Mandatory = $False, Position = 0, ParameterSetName = '', ValueFromPipeline = $False)] [string]$EmailLanguage, [Parameter( Mandatory = $False, Position = 1, ParameterSetName = '', ValueFromPipeline = $False)] [string]$SenderDisplayName, [Parameter( Mandatory = $False, Position = 2, ParameterSetName = '', ValueFromPipeline = $False)] [string]$SenderEmailAddress, [Parameter( Mandatory = $False, Position = 3, ParameterSetName = '', ValueFromPipeline = $False)] [string][ValidateSet("True","False")]$SendStatusNotification, [Parameter( Mandatory = $False, Position = 4, ParameterSetName = '',ValueFromPipeline = $False)] [string][ValidateSet("True","False")]$SendSyncnotification, [Parameter( Mandatory = $False, Position = 5, ParameterSetName = '', ValueFromPipeline = $False)] [string]$SMTPHostname, [Parameter( Mandatory = $False, Position = 6, ParameterSetName = '', ValueFromPipeline = $False)] [int]$SMTPPort, [Parameter( Mandatory = $False, Position = 7, ParameterSetName = '', ValueFromPipeline = $False)] [string][ValidateSet("True","False")]$SmtpServerRequiresAuthentication, [Parameter( Mandatory = $False, Position = 8, ParameterSetName = 'account', ValueFromPipeline = $False)] [string]$SmtpUserName, [Parameter( Mandatory = $False, Position = 9, ParameterSetName = '', ValueFromPipeline = $False)] [string][ValidateSet("Daily","Weekly")]$StatusNotificationFrequency, [Parameter( Mandatory = $False, Position = 10, ParameterSetName = '', ValueFromPipeline = $False)] [string]$StatusNotificationTimeOfDay, [Parameter( Mandatory = $False,Position = 11, ParameterSetName = '',ValueFromPipeline = $False)] [string]$UpdateServer, [Parameter( Mandatory = $False,Position = 12, ParameterSetName = 'account',ValueFromPipeline = $False)] [string]$SmtpPassword ) #Configure Email Notifications $email = $wsus.GetEmailNotificationConfiguration() $ErrorActionPreference = 'stop' Try { If ($StatusNotificationTimeOfDay) { #Validate Notification Time of Day Parameter If (!([regex]::ismatch($StatusNotificationTimeOfDay,"^\\d{2}:\\d{2}$"))) { Write-Error "$($StatusNotificationTimeOfDay) is not a valid time to use!`nMust be 'NN:NN'" } Else { $email.StatusNotificationTimeOfDay = $StatusNotificationTimeOfDay } } If ($UpdateServer) {$email.UpdateServer = $UpdateServer} If ($EmailLanguage) {$email.EmailLanguage = $EmailLanguage} If ($SenderDisplayName) {$email.SenderDisplayName = $SenderDisplayName} If ($SenderEmailAddress) { #Validate Email Address Parameter If (!([regex]::ismatch($SenderEmailAddress,"^\\w+@\\w+\\.com|mil|org|net$"))) { Write-Error "$($SenderEmailAddress) is not a valid email address!`nMust be 'xxxx@xxxxx.xxx'" } Else { $email.SenderEmailAddress = $SenderEmailAddress } } If ($SMTPHostname) {$email.SMTPHostname = $SMTPHostname} If ($SMTPPort) {$email.SMTPPort = $SMTPPort} If ($SmtpServerRequiresAuthentication) {$email.SmtpServerRequiresAuthentication = $SmtpServerRequiresAuthentication} If ($SmtpUserName) {$email.SmtpUserName = $SmtpUserName} If ($SmtpPassword) {$mail.SetSmtpUserPassword($SmtpPassword)} Switch ($StatusNotificationFrequency) { "Daily" {$email.StatusNotificationFrequency = [Microsoft.UpdateServices.Administration.EmailStatusNotificationFrequency]::Daily} "Weekly" {$email.StatusNotificationFrequency = [Microsoft.UpdateServices.Administration.EmailStatusNotificationFrequency]::Weekly} Default {$Null} } Switch ($SendStatusNotification) { "True" {$email.SendStatusNotification = 1} "False" {$email.SendStatusNotification = 0} Default {$Null} } Switch ($SendSyncNotification) { "True" {$email.SendSyncNotification = 1} "False" {$email.SendSyncNotification = 0} Default {$Null} } } Catch { Write-Error "$($error[0])" } #Save Configuration Changes Try { $email.Save() Write-Host -fore Green "Email settings changed" $email } Catch { Write-Error "$($error[0])" } } function Convert-WSUSTargetGroup { <# .SYNOPSIS Converts the WSUS group from ID to Name or Name to ID. .DESCRIPTION Converts the WSUS group from ID to Name or Name to ID. .PARAMETER Id GUID of the group to be converted to friendly name .PARAMETER Name Name of the group to be converted to a guid .NOTES Name: Convert-WSUSTargetGroup Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Convert-WSUSTargetGroup -name "Domain Servers" Description ----------- This command will convert the group name "Domain Servers" into the GUID format. .EXAMPLE Convert-WSUSTargetGroup -ID "b73ca6ed-5727-47f3-84de-015e03f6a88a" Description ----------- This command will convert the given GUID into a friendly name. #> [cmdletbinding( DefaultParameterSetName = 'name', ConfirmImpact = 'low' )] Param( [Parameter( Mandatory = $False, Position = 2, ParameterSetName = 'id', ValueFromPipeline = $False)] [string]$Id, [Parameter( Mandatory = $False, Position = 3, ParameterSetName = 'name', ValueFromPipeline = $False)] [string]$Name ) If ($name) { Try { $group = $wsus.GetComputerTargetGroups() | ? {$_.Name -eq $name} $group | Select -ExpandProperty ID } Catch { Write-Error "Unable to locate $($name)." } } If ($id) { Try { $group = $wsus.GetComputerTargetGroups() | ? {$_.ID -eq $id} $group | Select -ExpandProperty Name } Catch { Write-Error "Unable to locate $($id)." } } } function Get-WSUSClientsInGroup { <# .SYNOPSIS Retrieves a list of clients that are members of a group. .DESCRIPTION Retrieves a list of clients that are members of a group. .PARAMETER Id Retrieves list of clients in group by group guid. .PARAMETER Name Retrieves list of clients in group by group name. .NOTES Name: Get-WSUSClientsInGroup Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Get-WSUSClientsInGroup -name "Domain Servers" Description ----------- This command will list all clients that are members of the specified group via group name. .EXAMPLE Get-WSUSClientsInGroup -ID "b73ca6ed-5727-47f3-84de-015e03f6a88a" Description ----------- This command will list all clients that are members of the specified group via the group guid. #> [cmdletbinding( DefaultParameterSetName = 'name', ConfirmImpact = 'low' )] Param( [Parameter( Mandatory = $False, Position = 2, ParameterSetName = 'name', ValueFromPipeline = $False)] [string]$Name, [Parameter( Mandatory = $False, Position = 3, ParameterSetName = 'id', ValueFromPipeline = $False)] [string]$Id ) If ($id) { ($wsus.GetComputerTargetGroups() | ? {$_.Id -eq $id}).GetComputerTargets() } If ($name) { ($wsus.GetComputerTargetGroups() | ? {$_.name -eq $name}).GetComputerTargets() } } function Get-WSUSClient { <# .SYNOPSIS Retrieves information about a WSUS client. .DESCRIPTION Retrieves information about a WSUS client. .PARAMETER Computer Name of the client to search for. Accepts a partial name. .NOTES Name: Get-WSUSClient Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Get-WSUSClient -computer "server1" Description ----------- This command will search for and display all computers matching the given input. #> [cmdletbinding( DefaultParameterSetName = 'wsus', ConfirmImpact = 'low' )] Param( [Parameter( Mandatory = $True, Position = 0, ParameterSetName = 'wsus', ValueFromPipeline = $True)] [string]$Computer ) $ErrorActionPreference = 'stop' #Retrieve computer in WSUS Try { $wsus.SearchComputerTargets($computer) } Catch { Write-Error "Unable to retrieve $($computer) from database." } } function New-WSUSGroup { <# .SYNOPSIS Creates a new WSUS Target group. .DESCRIPTION Creates a new WSUS Target group. .PARAMETER Group Name of group being created. .PARAMETER ParentGroupName Name of group being created. .PARAMETER ParentGroupId Name of group being created. .NOTES Name: New-WSUSGroup Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE New-WSUSGroup -name "TestGroup" Description ----------- This command will create a new Target group called 'TestGroup' .EXAMPLE New-WSUSGroup -name "TestGroup" -parentgroupname "Domain Servers" Description ----------- This command will create a new Target group called 'TestGroup' under the parent group 'Domain Servers' #> [cmdletbinding( DefaultParameterSetName = 'group', ConfirmImpact = 'low', SupportsShouldProcess = $True )] Param( [Parameter( Mandatory = $True, Position = 0, ParameterSetName = '', ValueFromPipeline = $True)] [string]$Group, [Parameter( Mandatory = $False, Position = 1, ParameterSetName = 'parentgroup', ValueFromPipeline = $True)] [string]$ParentGroupName, [Parameter( Mandatory = $False, Position = 2, ParameterSetName = 'parentgroup', ValueFromPipeline = $True)] [string]$ParentGroupId ) Process { #Determine action based on Parameter Set Name Switch ($pscmdlet.ParameterSetName) { "group" { Write-Verbose "Creating computer group" If ($pscmdlet.ShouldProcess($group)) { #Create the computer target group $wsus.CreateComputerTargetGroup($group) "$($group) has been created." } } "parentgroup" { If ($parentgroupname) { #Retrieve group based off of name Write-Verbose "Querying for parent group" $parentgroup = Get-WSUSGroups | ? {$_.name -eq $parentgroupname} If (!$parentgroup) { Write-Error "Parent Group name `'$parentgroupname`' does not exist in WSUS!" Break } } If ($parentgroupid) { #Retrieve group based off of guid Write-Verbose "Querying for parent group" $parentgroup = Get-WSUSGroups | ? {$_.id -eq $parentgroupid} If (!$parentgroup) { Write-Error "Parent Group id `'$parentgroupid`' does not exist in WSUS!" Break } } Write-Verbose "Creating computer group" If ($pscmdlet.ShouldProcess($group)) { #Create the computer target group $wsus.CreateComputerTargetGroup($group,$parentgroup) "$($group) has been created under $($parentgroup.Name)." } } } } } function Get-WSUSUpdate { <# .SYNOPSIS Retrieves information from a wsus update. .DESCRIPTION Retrieves information from a wsus update. Depending on how the information is presented in the search, more than one update may be returned. .PARAMETER Update String to search for. This can be any string for the update to include KB article numbers, name of update, category, etc... Use of wildcards (*,%) not allowed in search! .NOTES Name: Get-WSUSUpdate Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Get-WSUSUpdate -update "Exchange" Description ----------- This command will list every update that has 'Exchange' in it. .EXAMPLE Get-WSUSUpdate -update "925474" Description ----------- This command will list every update that has '925474' in it. #> [cmdletbinding( DefaultParameterSetName = 'wsus', ConfirmImpact = 'low' )] Param( [Parameter( Mandatory = $True, Position = 0, ParameterSetName = 'wsus', ValueFromPipeline = $True)] [string]$Update ) $ErrorActionPreference = 'stop' #Retrieve computer in WSUS Try { $wsus.SearchUpdates($update) } Catch { Write-Error "Unable to retrieve $($update) from database." } } function Remove-WSUSGroup { <# .SYNOPSIS Creates a new WSUS Target group. .DESCRIPTION Creates a new WSUS Target group. .PARAMETER Name Name of group being deleted. .PARAMETER Id Id of group being deleted. .NOTES Name: Remove-WSUSGroup Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Remove-WSUSGroup -name "Domain Servers" Description ----------- This command will remove the Domain Servers WSUS Target group. .EXAMPLE Remove-WSUSGroup -id "fc93e74e-ba59-4593-9ff7-690af1be695f" Description ----------- This command will remove the Target group with ID 'fc93e74e-ba59-4593-9ff7-690af1be695f' from WSUS. #> [cmdletbinding( DefaultParameterSetName = 'name', ConfirmImpact = 'low', SupportsShouldProcess = $True )] Param( [Parameter( Mandatory = $False, Position = 0, ParameterSetName = 'name', ValueFromPipeline = $True)] [string]$Name, [Parameter( Mandatory = $False, Position = 1, ParameterSetName = 'id', ValueFromPipeline = $True)] [string]$Id ) Process { #Determine action based on Parameter Set Name Switch ($pscmdlet.ParameterSetName) { "name" { Write-Verbose "Querying for computer group" $group = Get-WSUSGroup -name $name If (!$group) { Write-Error "Group $name does not exist in WSUS!" Break } Else { If ($pscmdlet.ShouldProcess($name)) { #Create the computer target group $group.Delete() "$($name) has been deleted from WSUS." } } } "id" { Write-Verbose "Querying for computer group" $group = Get-WSUSGroup -id $id If (!$group) { Write-Error "Group $id does not exist in WSUS!" Break } If ($pscmdlet.ShouldProcess($id)) { #Create the computer target group $group.Delete() "$($id) has been deleted from WSUS." } } } } } function Add-WSUSClientToGroup { <# .SYNOPSIS Adds a computer client to an existing WSUS group. .DESCRIPTION Adds a computer client to an existing WSUS group. .PARAMETER Group Name of group to add client to. .PARAMETER Computer Name of computer being added to group. .NOTES Name: Add-WSUSClientToGroup Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Add-WSUSClientToGroup -group "Domain Servers" -computer "server1" Description ----------- This command will add the client "server1" to the WSUS target group "Domain Servers". #> [cmdletbinding( DefaultParameterSetName = 'group', ConfirmImpact = 'low', SupportsShouldProcess = $True )] Param( [Parameter( Mandatory = $True, Position = 0, ParameterSetName = 'group', ValueFromPipeline = $True)] [string]$Group, [Parameter( Mandatory = $False, Position = 1, ParameterSetName = 'group', ValueFromPipeline = $True)] [string]$Computer ) #Verify Computer is in WSUS Write-Verbose "Validating client in WSUS" $client = Get-WSUSClient -computer $computer If ($client) { #Get group object Write-Verbose "Retrieving group" $targetgroup = Get-WSUSGroup -name $group If (!$targetgroup) { Write-Error "Group $group does not exist in WSUS!" Break } #Add client to group Write-Verbose "Adding client to group" If ($pscmdlet.ShouldProcess($($client.fulldomainname))) { $targetgroup.AddComputerTarget($client) "$($client.FullDomainName) has been added to $($group)" } } Else { Write-Error "Computer: $computer is not in WSUS!" } } function Remove-WSUSClientFromGroup { <# .SYNOPSIS Removes a computer client to an existing WSUS group. .DESCRIPTION Removes a computer client to an existing WSUS group. .PARAMETER Group Name of group to remove client from. .PARAMETER Computer Name of computer being removed from group. .NOTES Name: Remove-WSUSClientToGroup Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Remove-WSUSClientFromGroup -group "Domain Servers" -computer "server1" Description ----------- This command will remove the client "server1" from the WSUS target group "Domain Servers". #> [cmdletbinding( DefaultParameterSetName = 'group', ConfirmImpact = 'low', SupportsShouldProcess = $True )] Param( [Parameter( Mandatory = $True, Position = 0, ParameterSetName = 'group', ValueFromPipeline = $True)] [string]$Group, [Parameter( Mandatory = $False, Position = 1, ParameterSetName = 'group', ValueFromPipeline = $True)] [string]$Computer ) #Verify Computer is in WSUS $client = Get-WSUSClient -computer $computer If ($client) { #Get group object Write-Verbose "Retrieving group" $targetgroup = Get-WSUSGroup -name $group If (!$targetgroup) { Write-Error "Group $group does not exist in WSUS!" Break } #Remove client from group Write-Verbose "Removing client to group" If ($pscmdlet.ShouldProcess($($client.fulldomainname))) { $targetgroup.RemoveComputerTarget($client) "$($client.fulldomainname) has been removed from $($group)" } } Else { Write-Error "Computer: $computer is not in WSUS!" } } function Get-WSUSDatabaseConfig { <# .SYNOPSIS Displays the current WSUS database configuration. .DESCRIPTION Displays the current WSUS database configuration. .NOTES Name: Get-WSUSDatabaseConfig Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Get-WSUSDatabaseConfig Description ----------- This command will display the configuration information for the WSUS connection to a database. #> [cmdletbinding()] Param () $wsus.GetDatabaseConfiguration() } function Get-WSUSSubscription { <# .SYNOPSIS Displays WSUS subscription information. .DESCRIPTION Displays WSUS subscription information. You can view the next synchronization time, who last modified the schedule, etc... .NOTES Name: Get-WSUSSubscription Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Get-WSUSSubscription Description ----------- This command will list out the various subscription information on the WSUS server. #> [cmdletbinding()] Param () $wsus.GetSubscription() } function Deny-WSUSUpdate { <# .SYNOPSIS Declines an update on WSUS. .DESCRIPTION Declines an update on WSUS. Use of the -whatif is advised to be sure you are declining the right patch or patches. .PARAMETER InputObject Collection of update/s being declined. This must be an object, otherwise it will fail. .PARAMETER Update Name of update/s being declined. .NOTES Name: Deny-WSUSUpdate Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Get-WSUSUpdate -update "Exchange 2010" | Deny-WSUSUpdate Description ----------- This command will decline all updates with 'Exchange 2010' in its metadata. .EXAMPLE Deny-WSUSUpdate -Update "Exchange 2010" Description ----------- This command will decline all updates with 'Exchange 2010' in its metadata. .EXAMPLE $updates = Get-WSUSUpdate -update "Exchange 2010" Deny-WSUSUpdate -InputObject $updates Description ----------- This command will decline all updates with 'Exchange 2010' in its metadata. .EXAMPLE Get-WSUSUpdate -update "Exchange 2010" | Deny-WSUSUpdate Description ----------- This command will decline all updates with 'Exchange 2010' in its metadata via the pipeline. #> [cmdletbinding( DefaultParameterSetName = 'collection', ConfirmImpact = 'low', SupportsShouldProcess = $True )] Param( [Parameter( Mandatory = $True, Position = 0, ParameterSetName = 'collection', ValueFromPipeline = $True)] [system.object]$InputObject, [Parameter( Mandatory = $False, Position = 1, ParameterSetName = 'string', ValueFromPipeline = $False)] [string]$Update ) Process { Switch ($pscmdlet.ParameterSetName) { "Collection" { Write-Verbose "Using 'Collection' set name" #Change the collection to patches for use in loop $patches = $inputobject } "String" { Write-Verbose "Using 'String' set name" #Gather all updates from given information Write-Verbose "Searching for updates" $patches = Get-WSUSUpdate -update $update } } ForEach ($patch in $patches) { #Decline the update Write-Verbose "Declining update" If ($pscmdlet.ShouldProcess($($patch.title))) { $patch.Decline($True) | out-null #Print out report of what was declined New-Object PSObject -Property @{ Patch = $patch.title ApprovalAction = "Declined" } } } } } function Approve-WSUSUpdate { <# .SYNOPSIS Approves a WSUS update for a specific group with an optional deadline. .DESCRIPTION Approves a WSUS update for a specific group with an optional deadline. .PARAMETER InputObject Update object that is being approved. .PARAMETER Update Name of update being approved. .PARAMETER Group Name of group which will receive the update. .PARAMETER Deadline Optional deadline for client to install patch. .PARAMETER Action Type of approval action to take on update. Accepted values are Install, Approve, Uninstall and NotApproved .NOTES Name: Approve-WSUSUpdate Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Approve-WSUSUpdate -update "KB979906" -Group "Domain Servers" -Action Install Description ----------- This command will approve all updates with the KnowledgeBase number of KB979906 for the 'Domain Servers' group and the action command of 'Install'. .EXAMPLE Approve-WSUSUpdate -update "KB979906" -Group "Domain Servers" -Action Install -Deadline (get-Date).AddDays(3) Description ----------- This command will approve all updates with the KnowledgeBase number of KB979906 for the 'Domain Servers' group and the action command of 'Install' and sets a deadline for 3 days from when this command is run. .EXAMPLE Get-WSUSUpdate -Update "KB979906" | Approve-WSUSUpdate -Group "Domain Servers" -Action Install Description ----------- This command will take the collection of objects from the Get-WSUSUpdate command and then approve all updates for the 'Domain Servers' group and the action command of 'Install'. #> [cmdletbinding( DefaultParameterSetName = 'string', ConfirmImpact = 'low', SupportsShouldProcess = $True )] Param( [Parameter( Mandatory = $True, Position = 0, ParameterSetName = 'collection', ValueFromPipeline = $True)] [system.object] [ValidateNotNullOrEmpty()] $InputObject, [Parameter( Mandatory = $True, Position = 0, ParameterSetName = 'string', ValueFromPipeline = $False)] [string]$Update, [Parameter( Mandatory = $True, Position = 1, ParameterSetName = '', ValueFromPipeline = $False)] [string] [ValidateSet("Install", "All", "NotApproved","Uninstall")] $Action, [Parameter( Mandatory = $True, Position = 2, ParameterSetName = '', ValueFromPipeline = $False)] [string]$Group, [Parameter( Mandatory = $False, Position = 3, ParameterSetName = '', ValueFromPipeline = $False)] [datetime]$Deadline ) Begin { #Define the actions available Write-Verbose "Defining available approval actions" $Install = [Microsoft.UpdateServices.Administration.UpdateApprovalAction]::Install $All = [Microsoft.UpdateServices.Administration.UpdateApprovalAction]::All $NotApproved = [Microsoft.UpdateServices.Administration.UpdateApprovalAction]::NotApproved $Uninstall = [Microsoft.UpdateServices.Administration.UpdateApprovalAction]::Uninstall #Search for group specified Write-Verbose "Searching for group" $targetgroup = Get-WSUSGroup -name $group If (!$targetgroup) { Write-Error "Group $group does not exist in WSUS!" Break } } Process { #Perform appropriate action based on Parameter set name Switch ($pscmdlet.ParameterSetName) { "collection" { Write-Verbose "Using 'Collection' set name" #Change the variable that will hold the objects $patches = $inputobject } "string" { Write-Verbose "Using 'String' set name" #Search for updates Write-Verbose "Searching for update/s" $patches = Get-WSUSUpdate -update $update If (!$patches) { Write-Error "Update $update could not be found in WSUS!" Break } } } ForEach ($patch in $patches) { #Determine if Deadline is required If ($deadline) { Write-Verbose "Approving update with a deadline." If ($pscmdlet.ShouldProcess($($patch.title))) { #Create the computer target group $patch.Approve($action,$targetgroup,$deadline) | out-null #Print out report of what was approved New-Object PSObject -Property @{ Patch = $patch.title TargetGroup = $group ApprovalAction = $action Deadline = "$($deadline)" } } } Else { #Approve the patch Write-Verbose "Approving update without a deadline." If ($pscmdlet.ShouldProcess($($patch.title))) { #Create the computer target group $patch.Approve($action,$targetgroup) | out-null #Print out report of what was approved New-Object PSObject -Property @{ Patch = $patch.title TargetGroup = $group ApprovalAction = $action } } } } } } function Get-WSUSGroup { <# .SYNOPSIS Retrieves specific WSUS target group. .DESCRIPTION Retrieves specific WSUS target group. .PARAMETER Name Name of group to search for. No wildcards allowed. .PARAMETER Id GUID of group to search for. No wildcards allowed. .NOTES Name: Get-WSUSGroups Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Get-WSUSGroup -name "Domain Servers" Description ----------- This command will search for the group and display the information for Domain Servers" .EXAMPLE Get-WSUSGroup -ID "0b5ba818-021e-4238-8098-7245b0f90557" Description ----------- This command will search for the group and display the information for the WSUS group guid 0b5ba818-021e-4238-8098-7245b0f90557" #> [cmdletbinding( DefaultParameterSetName = 'name', ConfirmImpact = 'low', SupportsShouldProcess = $True )] Param( [Parameter( Mandatory = $True, Position = 0, ParameterSetName = 'name', ValueFromPipeline = $False)] [string]$Name, [Parameter( Mandatory = $True, Position = 0, ParameterSetName = 'id', ValueFromPipeline = $False)] [string]$Id ) Switch ($pscmdlet.ParameterSetName) { "name" {$wsus.GetComputerTargetGroups() | ? {$_.name -eq $name}} "id" {$wsus.GetComputerTargetGroups() | ? {$_.id -eq $id}} } } function Remove-WSUSUpdate { <# .SYNOPSIS Removes an update on WSUS. .DESCRIPTION Removes an update on WSUS. Use of the -whatif is advised to be sure you are declining the right patch or patches. .PARAMETER Update Name of update being removed. .NOTES Name: Remove-WSUSUpdate Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Remove-WSUSUpdate -update "KB986569" Description ----------- This command will remove all instances of KB986569 from WSUS. #> [cmdletbinding( DefaultParameterSetName = 'update', ConfirmImpact = 'low', SupportsShouldProcess = $True )] Param( [Parameter( Mandatory = $True, Position = 0, ParameterSetName = 'update', ValueFromPipeline = $True)] [string]$Update ) Begin { #Gather all updates from given information Write-Verbose "Searching for updates" $patches = Get-WSUSUpdate -update $update } Process { ForEach ($patch in $patches) { #Storing update guid $guid = ($patch.id).updateid If ($pscmdlet.ShouldProcess($($patch.title))) { $wsus.DeleteUpdate($id,$True) "$($patch.title) has been deleted from WSUS" } } } } function Stop-WSUSDownloads { <# .SYNOPSIS Cancels all current WSUS downloads. .DESCRIPTION Cancels all current WSUS downloads. .NOTES Name: Stop-WSUSDownloads Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Stop-WSUSDownloads Description ----------- This command will stop all updates being downloaded to the WSUS server. #> [cmdletbinding( DefaultParameterSetName = 'update', ConfirmImpact = 'low', SupportsShouldProcess = $True )] Param() #Cancel all downloads running on WSUS If ($pscmdlet.ShouldProcess($($wsus.name))) { $wsus.CancelAllDownloads() "Downloads have been cancelled." } } function Resume-WSUSDownloads { <# .SYNOPSIS Resumes all current WSUS downloads. .DESCRIPTION Resumes all current WSUS downloads that had been cancelled. .NOTES Name: Resume-WSUSDownloads Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Resume-WSUSDownloads Description ----------- This command will resume the downloading of updates to the WSUS server. #> [cmdletbinding( DefaultParameterSetName = 'update', ConfirmImpact = 'low', SupportsShouldProcess = $True )] Param() #Cancel all downloads running on WSUS If ($pscmdlet.ShouldProcess($($wsus.name))) { $wsus.ResumeAllDownloads() "Downloads have been resumed." } } function Stop-WSUSUpdateDownload { <# .SYNOPSIS Stops update download after approval. .DESCRIPTION Stops update download after approval. .PARAMETER update Name of update to cancel download. .NOTES Name: Stop-WSUSUpdateDownload Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Stop-WSUSUpdateDownload -update "KB965896" Description ----------- This command will cancel the download of update KB956896. #> [cmdletbinding( DefaultParameterSetName = 'update', ConfirmImpact = 'low', SupportsShouldProcess = $True )] Param( [Parameter( Mandatory = $True, Position = 0, ParameterSetName = 'update', ValueFromPipeline = $True)] [string]$update ) Begin { #Gather all updates from given information Write-Verbose "Searching for updates" $patches = Get-WSUSUpdate -update $update } Process { If ($patches) { ForEach ($patch in $patches) { Write-Verbose "Cancelling update download" If ($pscmdlet.ShouldProcess($($patch.title))) { $patch.CancelDownload() "$($patch.title) download has been cancelled." } } } Else { Write-Warning "No patches found that need downloading cancelled." } } } function Resume-WSUSUpdateDownload { <# .SYNOPSIS Resumes previously cancelled update download after approval. .DESCRIPTION Resumes previously cancelled update download after approval. .PARAMETER Update Name of cancelled update download to resume download. .NOTES Name: Resume-WSUSUpdateDownload Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Resume-WSUSUpdateDownload -update "KB965896" Description ----------- This command will resume the download of update KB956896 that was previously cancelled. #> [cmdletbinding( DefaultParameterSetName = 'update', ConfirmImpact = 'low', SupportsShouldProcess = $True )] Param( [Parameter( Mandatory = $True, Position = 0, ParameterSetName = 'update', ValueFromPipeline = $True)] [string]$Update ) Begin { #Gather all updates from given information Write-Verbose "Searching for updates" $patches = Get-WSUSUpdate -update $update } Process { If ($patches) { ForEach ($patch in $patches) { Write-Verbose "Resuming update download" If ($pscmdlet.ShouldProcess($($patch.title))) { $patch.ResumeDownload() "$($patch.title) download has been resumed." } } } Else { Write-Warning "No patches found needing to resume download!" } } } function Start-WSUSCleanup { <# .SYNOPSIS Performs a cleanup on WSUS based on user inputs. .DESCRIPTION Performs a cleanup on WSUS based on user inputs. .PARAMETER DeclineSupersededUpdates Declined Superseded Updates will be removed. .PARAMETER DeclineExpiredUpdates Expired updates should be declined. .PARAMETER CleanupObsoleteUpdates Delete obsolete updates from the database. .PARAMETER CompressUpdates Obsolete revisions to updates should be deleted from the database. .PARAMETER CleanupObsoleteComputers Delete obsolete computers from the database. .PARAMETER CleanupUnneededContentFiles Delete unneeded update files. .NOTES Name: Start-WSUSCleanup Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Start-WSUSCleanup -CompressUpdates -CleanupObsoleteComputers Description ----------- This command will run the WSUS cleanup wizard and delete obsolete computers from the database and delete obsolete update revisions from the database. .EXAMPLE Start-WSUSCleanup -CompressUpdates -CleanupObsoleteComputers -DeclineExpiredUpdates -CleanupObsoleteUpdates -CleanupUnneededContentFiles Description ----------- This command performs a full WSUS cleanup against the database. #> [cmdletbinding( DefaultParameterSetName = 'cleanup', ConfirmImpact = 'low', SupportsShouldProcess = $True )] Param( [Parameter( Mandatory = $False, Position = 0, ParameterSetName = 'cleanup', ValueFromPipeline = $False)] [switch]$DeclineSupersededUpdates, [Parameter( Mandatory = $False, Position = 1, ParameterSetName = 'cleanup', ValueFromPipeline = $False)] [switch]$DeclineExpiredUpdates, [Parameter( Mandatory = $False, Position = 2, ParameterSetName = 'cleanup', ValueFromPipeline = $False)] [switch]$CleanupObsoleteUpdates, [Parameter( Mandatory = $False, Position = 3, ParameterSetName = 'cleanup', ValueFromPipeline = $False)] [switch]$CompressUpdates, [Parameter( Mandatory = $False, Position = 4, ParameterSetName = 'cleanup', ValueFromPipeline = $False)] [switch]$CleanupObsoleteComputers, [Parameter( Mandatory = $False, Position = 5, ParameterSetName = 'cleanup', ValueFromPipeline = $False)] [switch]$CleanupUnneededContentFiles ) Begin { #Create cleanup scope $cleanScope = new-object Microsoft.UpdateServices.Administration.CleanupScope #Create cleanup manager object $cleanup = $wsus.GetCleanupManager() #Determine what will be in the scope If ($DeclineSupersededUpdates) { $cleanScope.DeclineSupersededUpdates = $True } If ($DeclineExpiredUpdates) { $cleanScope.DeclineExpiredUpdates = $True } If ($CleanupObsoleteUpdates) { $cleanScope.CleanupObsoleteUpdates = $True } If ($CompressUpdates) { $cleanScope.CompressUpdates = $True } If ($CleanupObsoleteComputers) { $cleanScope.CleanupObsoleteComputers = $True } If ($CleanupUnneededContentFiles) { $cleanScope.CleanupUnneededContentFiles = $True } } Process { Write-Host "Beginning cleanup" If ($pscmdlet.ShouldProcess($($wsus.name))) { $cleanup.PerformCleanup($cleanScope) } } } function Get-WSUSChildServers { <# .SYNOPSIS Retrieves all WSUS child servers. .DESCRIPTION Retrieves all WSUS child servers. .NOTES Name: Get-WSUSChildServers Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Get-WSUSChildServers Description ----------- This command will display all of the Child WSUS servers. #> [cmdletbinding()] Param () #Gather all child servers in WSUS $wsus.GetChildServers() } function Get-WSUSDownstreamServers { <# .SYNOPSIS Retrieves all WSUS downstream servers. .DESCRIPTION Retrieves all WSUS downstream servers. .NOTES Name: Get-WSUSDownstreamServers Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Get-WSUSDownstreamServers Description ----------- This command will display a list of all of the downstream WSUS servers. #> [cmdletbinding()] Param () #Gather all child servers in WSUS $wsus.GetDownstreamServers() } function Get-WSUSContentDownloadProgress { <# .SYNOPSIS Retrieves the progress of currently downloading updates. Displayed in bytes downloaded. .DESCRIPTION Retrieves the progress of currently downloading updates. Displayed in bytes downloaded. .PARAMETER Monitor Runs a background job to monitor currently running content download and notifies user when completed. .NOTES Name: Get-WSUSContentDownloadProgress Author: Boe Prox DateCreated: 24SEPT2010 .LINK https://boeprox.wordpress.org .EXAMPLE Get-WSUSContentDownloadProgress Description ----------- This command will display the current progress of the content download. .EXAMPLE Get-WSUSContentDownloadProgress -monitor Description ----------- This command will create a background job that will monitor the progress and alert the user via pop-up message that the download has been completed. #> [cmdletbinding()] Param ( [Parameter( Mandatory = $False, Position = 0, ParameterSetName = 'monitor', ValueFromPipeline = $False)] [switch]$Monitor ) If ($monitor) { #Stop and remove same jobs if existing $job = Get-Jo
PowerShellCorpus/PoshCode/Get-ChildItemColor_1.ps1
Get-ChildItemColor_1.ps1
function Get-ChildItemColor { <# .Synopsis Returns childitems with colors by type. .Description This function wraps Get-ChildItem and tries to output the results color-coded by type: Compressed - Yellow Directories - Dark Cyan Executables - Green Text Files - Cyan Others - Default .ReturnValue All objects returned by Get-ChildItem are passed down the pipeline unmodified. .Notes NAME: Get-ChildItemColor AUTHOR: Tojo2000 <tojo2000@tojo2000.com> #> $regex_opts = ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase ` -bor [System.Text.RegularExpressions.RegexOptions]::Compiled) $fore = $Host.UI.RawUI.ForegroundColor $compressed = New-Object System.Text.RegularExpressions.Regex( '\\.(zip|tar|gz|rar)$', $regex_opts) $executable = New-Object System.Text.RegularExpressions.Regex( '\\.(exe|bat|cmd|py|pl|ps1|psm1|vbs|rb|reg)$', $regex_opts) $text_files = New-Object System.Text.RegularExpressions.Regex( '\\.(txt|cfg|conf|ini|csv|log)$', $regex_opts) Invoke-Expression ("Get-ChildItem $args") | %{ if ($_.GetType().Name -eq 'DirectoryInfo') { $Host.UI.RawUI.ForegroundColor = 'DarkCyan' echo $_ $Host.UI.RawUI.ForegroundColor = $fore } elseif ($compressed.IsMatch($_.Name)) { $Host.UI.RawUI.ForegroundColor = 'Yellow' echo $_ $Host.UI.RawUI.ForegroundColor = $fore } elseif ($executable.IsMatch($_.Name)) { $Host.UI.RawUI.ForegroundColor = 'Green' echo $_ $Host.UI.RawUI.ForegroundColor = $fore } elseif ($text_files.IsMatch($_.Name)) { $Host.UI.RawUI.ForegroundColor = 'Cyan' echo $_ $Host.UI.RawUI.ForegroundColor = $fore } else { echo $_ } } }
PowerShellCorpus/PoshCode/Asp_1.net-Using httpConext.ps1
Asp_1.net-Using httpConext.ps1
Default.aspx ---------------- Partial Class _Default Inherits System.Web.UI.Page Dim var1 As String Dim var2 As String Protected Sub lnk_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnk.Click Context.Items("Nome") = var1 Context.Items("Email") = var2 Server.Transfer("pagina3.aspx") End Sub Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load var1 = "20091005" var2 = "20091106" End Sub End Class pagina3.aspx -------------------------- Partial Class pagina3 Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim context As HttpContext = HttpContext.Current Label1.Text = CStr(context.Items("Nome")) Label2.Text = CStr(context.Items("Email")) End Sub End Class
PowerShellCorpus/PoshCode/Get-InstalledProgram_v4.ps1
Get-InstalledProgram_v4.ps1
param ( [String[]]$Computer, $User ) ############################################################################################# if ($User) {$Connection = Get-Credential -Credential $User} ############################################################################################# if (!$Connection){ foreach ($Comp in $Computer){ $Install_soft = gwmi win32_product -ComputerName $Comp | where {$_.vendor -notlike "*Microsoft*" -and $_.vendor -notlike "*PGP*" -and $_.vendor -notlike "*Intel*" -and $_.vendor -notlike "*Corel*" -and $_.vendor -notlike "*Adobe*" -and $_.vendor -notlike "*ABBYY*" -and $_.vendor -notlike "*Sun*" -and $_.vendor -ne "SAP" -and $_.vendor -ne "Marvell" -and $_.vendor -ne "Hewlett-Packard"} | Format-List __SERVER,Name,Version,InstallDate $Install_soft } } else { foreach ($Comp in $Computer){ $Install_soft = gwmi win32_product -ComputerName $Comp -Credential $Connection | where {$_.vendor -notlike "*Microsoft*" -and $_.vendor -notlike "*PGP*" -and $_.vendor -notlike "*Intel*" -and $_.vendor -notlike "*Corel*" -and $_.vendor -notlike "*Adobe*" -and $_.vendor -notlike "*ABBYY*" -and $_.vendor -notlike "*Sun*" -and $_.vendor -ne "SAP" -and $_.vendor -ne "Marvell" -and $_.vendor -ne "Hewlett-Packard"} | Format-List __SERVER,Name,Version,InstallDate $Install_soft } }
PowerShellCorpus/PoshCode/hex2dec.ps1
hex2dec.ps1
@echo off ::unequal symbols for %%i in ("!", "x") do if "%1" equ "%%~i" goto:error ::display help information args for %%i in ("-h", "/h", "-help", "/help") do ( if "%1" equ "%%~i" goto:help ) if "%1" equ "-?" goto:help if "%1" equ "/?" goto:help ::interactive mode if "%1" equ "" ( if not defined run goto:interactive goto:error ) ::parsing input data setlocal enabledelayedexpansion ::checking is arg hex or dec 2>nul set /a "res=%1" if "%1" equ "%res%" goto:dec2hex ::patterns echo "%1" | findstr /r \\x > nul set e1=%errorlevel% echo "%1" | findstr /r [0-9a-f] > nul set e2=%errorlevel% echo "%1" | findstr /r [g-wyz] > nul set e3=%errorlevel% ::parsing error codes if %e1% equ 0 if %e2% equ 0 if %e3% equ 1 set "k=%1" & goto:hex2dec if %e1% equ 1 if %e2% equ 0 if %e3% equ 1 set "k=0x%1" & goto:hex2dec goto:error :dec2hex 2>nul set /a "num=%1" set "map=0123456789ABCDEF" for /l %%i in (1, 1, 8) do ( set /a "res=num & 15, num >>=4" for %%j in (!res!) do set "hex=!map:~%%j,1!!hex!" ) for /f "tokens=* delims=0" %%i in ("!hex!") do set "hex=0x%%i" echo %1 = !hex! & goto:eof :hex2dec set "num=%k%" if "%num:~0,1%" equ "x" goto:error 2>nul set /a "res=%k%" for /f "tokens=2,3" %%i in ('findstr "# " "%~dpnx0"') do set "num=!num:%%i=%%j!" if "%res%" neq "" (echo !num! = !res!) else goto:error endlocal exit /b :error if defined run echo =^>err & goto:eof echo Invalid data. exit /b 1 :help ::Hex2dec v1.10 - converts hex to decimal and vice versa ::Copyright (C) 2012 Greg Zakharov ::forum.script-coding.com :: ::Usage: hex2dec [decimal | hexadecimal] :: ::Example 1: :: C:\\>hex2dec 0x017a :: 0x017A = 378 :: ::Example 2: :: C:\\>hex2dec 13550 :: 13550 = 0x34EE :: ::Example 3: :: C:\\>hex2dec 23f :: 0x23F = 575 for /f "tokens=* delims=:" %%i in ('findstr "^::" "%~dpnx0"') do echo.%%i exit /b 0 rem :: Upper case chart :: # a A # b B # c C # d D # e E # f F rem :: End of chart :: :interactive ::interactive mode on echo Hex2dec v1.10 - converts hex to decimal and vice versa echo. setlocal ::marker - already launched set run=true :begin set /p "ask=>>> " cmd /c "%~dpnx0" %ask% if "%ask%" equ "clear" cls if "%ask%" equ "exit" cls & goto:eof echo. goto:begin endlocal exit /b
PowerShellCorpus/PoshCode/PowerBot _1.0.ps1
PowerBot _1.0.ps1
## This script requires ...\\WindowsPowerShell\\Libraries\\Meebey.SmartIrc4net.dll ## You can get Meebey.SmartIrc4net.dll from ## http://voxel.dl.sourceforge.net/sourceforge/smartirc4net/SmartIrc4net-0.4.0.bin.tar.bz2 ## And the docs are at http://smartirc4net.meebey.net/docs/0.4.0/html/ ############################################################################################ ## Configure with a .psd1 file for the module, with Private data like: ## FunctionsToExport = 'Start-PowerBot', 'Resume-PowerBot', 'Stop-PowerBot' ## RequiredAssemblies = 'Meebey.SmartIrc4net.dll', 'Starksoft.Net.Proxy.dll' ## PrivateData = @{ ## Nick = @('ABot', 'PowershellBot') ## RealName = 'Jaykul''s PowerShell Bot' ## Pass = 'bot' ## Server = "irc.freenode.net" ## Port = 8001 ## Channels = @('#PowerShell') ## # ProxyServer = "www.proxy.com" ## # ProxyPort = "8000" ## } ############################################################################################ ## Add-Type -path $ProfileDir\\Libraries\\Meebey.SmartIrc4net.dll ## $null = [Reflection.Assembly]::LoadFrom("$ProfileDir\\Libraries\\Meebey.SmartIrc4net.dll") function Start-PowerBot { [CmdletBinding()] PARAM( [Parameter(Position=0)] [string[]]$channels = $ExecutionContext.SessionState.Module.PrivateData.Channels , [Parameter(Position=1)] [string[]]$nick = $ExecutionContext.SessionState.Module.PrivateData.Nick , [Parameter(Position=2)] [string]$password = $ExecutionContext.SessionState.Module.PrivateData.Password , [Parameter(Position=5)] [string]$server = $ExecutionContext.SessionState.Module.PrivateData.Server , [Parameter(Position=6)] [int]$port = $ExecutionContext.SessionState.Module.PrivateData.Port , [Parameter(Position=10)] [string]$realname = $ExecutionContext.SessionState.Module.PrivateData.RealName , [Parameter(Position=5)] [string]$ProxyServer= $ExecutionContext.SessionState.Module.PrivateData.ProxyServer , [Parameter(Position=6)] [int]$ProxyPort = $ExecutionContext.SessionState.Module.PrivateData.ProxyPort ) Write-Host "Private Data:`n`n$( $ExecutionContext.SessionState.Module.PrivateData | Out-String )" -Fore Cyan Write-Host "Proxy Server: $ProxyServer, $ProxyPort" -Fore Yellow if(!$global:irc) { $global:irc = New-Object Meebey.SmartIrc4net.IrcClient if($ProxyServer) { $global:proxy = New-Object Starksoft.Net.Proxy.HttpProxyClient $ProxyServer, $ProxyPort Write-Host "Creating Proxy: ${global:proxy}" $global:irc.Proxy = $global:proxy } # $irc.Encoding = [Text.Encoding]::UTF8 # $irc will track channels for us $irc.ActiveChannelSyncing = $true $irc.Add_OnError( {Write-Error $_.ErrorMessage} ) $irc.Add_OnQueryMessage( {OnQueryMessage_ProcessCommands} ) $irc.Add_OnChannelMessage( {OnChannelMessage_ProcessCommands} ) $irc.Add_OnChannelMessage( {OnChannelMessage_ResolveUrls} ) } $irc.Connect($server, $port) $irc.SendDelay = 300 $irc.Login($nick, $realname, 0, $nick[0], $password) ## $channels | % { $irc.RfcJoin( $_ ) } foreach($channel in $channels) { $irc.RfcJoin( $channel ) } $global:PBC = Get-BotCommands Resume-PowerBot # Shortcut so starting this thing up only takes one command } ## Note that PowerBot stops listening if you press a key ... ## You'll have to re-run Resume-Powerbot to get him to listen again function Resume-PowerBot { while(!$Host.UI.RawUI.KeyAvailable) { $irc.Listen($false) } } function Stop-PowerBot { [CmdletBinding()] PARAM( [Parameter(Position=0)] [string]$QuitMessage = "If people listened to themselves more often, they would talk less." ) $irc.RfcQuit($QuitMessage) sleep 2 $irc.Disconnect() } function Resolve-Parameters { Param($command) $Tokens = [System.Management.Automation.PSParser]::Tokenize($command,[ref]$null) for($t = $Tokens.Count; $t -ge 0; $t--) { # DEBUG $token | fl * | out-host if($Tokens[$t].Type -eq "CommandParameter") { $token = $Tokens[$t] for($c = $t; $c -ge 0; $c--) { if( $Tokens[$c].Type -eq "Command" ) { $cmd = which $Tokens[$c].Content # if($cmd.CommandType -eq "Alias") { # $cmd = @(which $cmd.Definition)[0] # } $short = $token.Content -replace "^-?","^" Write-Debug "Parameter $short" $parameters = $cmd.ParameterSets | Select -expand Parameters $param = @($parameters | Where-Object { $_.Name -match $short -or $_.Aliases -match $short} | Select -Expand Name -Unique) if("Verbose","Debug","WarningAction","WarningVariable","ErrorAction","ErrorVariable","OutVariable","OutBuffer","WhatIf","Confirm" -contains $param ) { $command = $command.Remove( $token.Start, $token.Length ) } elseif($param.Count -eq 1) { $command = $command.Remove( $token.Start, $token.Length ).Insert( $token.Start, "-$($param[0])" ) } break } } } } return $command } function Bind-Parameters { Param([string[]]$params) $bound = @{} $unbound = @() while($params) { Write-Host "$params" [string]$name, [string]$value, $params = @($params) if($name.StartsWith("-")) { $name = $name.trim("-"," ") if($value.StartsWith("-")) { $bound[$name.trim("-"," ")] = New-Object System.Management.Automation.SwitchParameter $true $params = @($value) + $params } else { $bound[$name] = $value } } else { $unbound += "$name" if($value) { $params = @($value) + $params } } } $bound, $unbound } #################################################################################################### ## Event Handlers #################################################################################################### ## Event handlers in powershell have TWO automatic variables: $This and $_ ## In the case of SmartIrc4Net: ## $This - usually the connection, and such ... ## $_ - the IrcEventArgs, which just has the Data member: ## function OnQueryMessage_ProcessCommands { $Data = $_.Data Write-Verbose $Data.From # Write-Verbose $Data.Message Write-Debug $( $Data | Out-String ) # Write-Debug $( $Data | Get-Member | Out-String ) $command, $params = $Data.MessageArray Write-Verbose "`nCommand: $command `nParams: $params" if($PBC.ContainsKey($command)) { $Command, $Params = (Resolve-Parameters $((@($command) + @($Params)) -join " ")) -split " +" $bound, $unbound = Bind-Parameters @($params) trap { Write-Error "Error in ProcessCommands:`n$($_|out-string)"; Continue } Write-Debug "$Data | `&$($PBC[$command]) $bound $unbound" $Data | &$PBC[$command] @bound @unbound | Out-String -width (510 - $Data.From.Length - $nick.Length - 3) | % { $_.Trim().Split("`n") | %{ $irc.SendMessage("Message", $Data.Nick, $_.Trim() ) }} } } function OnChannelMessage_ProcessCommands { $Data = $_.Data Write-Verbose $Data.From # Write-Verbose $Data.Channel # Write-Verbose $Data.Message Write-Debug $($Data | Out-String) # Write-Debug $($Data | Get-Member | Out-String) [string]$command, [string[]]$params = $Data.MessageArray if($PBC.ContainsKey($command)) { $Command, $Params = (Resolve-Parameters $((@($command) + @($Params)) -join " ")) -split " +" $bound, $unbound = Bind-Parameters @params trap { Write-Error "Error in ProcessCommands:`n$($_|out-string)"; Continue } Write-Debug "$Data | `&$($PBC[$command]) $bound $unbound" $Data | &$PBC[$command] @bound @unbound | Out-String -width (510 - $Data.Channel.Length - $nick.Length - 3) | % { $_.Trim().Split("`n") | %{ $irc.SendMessage("Message", $Data.Channel, $_.Trim() ) }} } } function OnChannelMessage_ResolveUrls { $c = $_.Data.Channel $n = $_.Data.Nick $m = $_.Data.Message Resolve-URL $m | % { $irc.SendMessage("Message", $c, "<$($n)> $_" ) } } Import-Module "$PSScriptRoot\\PowerBotCommands.psm1" -Force
PowerShellCorpus/PoshCode/Format-String.ps1
Format-String.ps1
##############################################################################\n##\n## Format-String\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\nReplaces text in a string based on named replacement tags\n\n.EXAMPLE\n\nFormat-String "Hello {NAME}" @{ NAME = 'PowerShell' }\nHello PowerShell\n\n.EXAMPLE\n\nFormat-String "Your score is {SCORE:P}" @{ SCORE = 0.85 }\nYour score is 85.00 %\n\n#>\n\nparam(\n ## The string to format. Any portions in the form of {NAME}\n ## will be automatically replaced by the corresponding value\n ## from the supplied hashtable.\n $String,\n\n ## The named replacements to use in the string\n [hashtable] $Replacements\n)\n\nSet-StrictMode -Version Latest\n\n$currentIndex = 0\n$replacementList = @()\n\n## Go through each key in the hashtable\nforeach($key in $replacements.Keys)\n{\n ## Convert the key into a number, so that it can be used by\n ## String.Format\n $inputPattern = '{(.*)' + $key + '(.*)}'\n $replacementPattern = '{${1}' + $currentIndex + '${2}}'\n $string = $string -replace $inputPattern,$replacementPattern\n $replacementList += $replacements[$key]\n\n $currentIndex++\n}\n\n## Now use String.Format to replace the numbers in the\n## format string.\n$string -f $replacementList
PowerShellCorpus/PoshCode/Test-TCPPort_1.ps1
Test-TCPPort_1.ps1
function Test-TCPPort { param ( [parameter(Mandatory=$true)] [string] $ComputerName, [parameter(Mandatory=$true)] [string] $Port ) try { $TimeOut = 5000 $IsConnected = $false $Addresses = [System.Net.Dns]::GetHostAddresses($ComputerName) | ? {$_.AddressFamily -eq 'InterNetwork'} $Address = [System.Net.IPAddress]::Parse($Addresses) $Socket = New-Object System.Net.Sockets.TCPClient $Connect = $Socket.BeginConnect($Address, $Port, $null, $null) $Wait = $Connect.AsyncWaitHandle.WaitOne($TimeOut, $false) if ( $Socket.Connected ) { $IsConnected = $true } else { $IsConnected = $false } } catch { Write-Warning $_ $IsConnected = $false } finally { $Socket.Close() return $IsConnected } }
PowerShellCorpus/PoshCode/Create SP2010 Farm V_2.ps1
Create SP2010 Farm V_2.ps1
############################################################################ ## Create-SPFarm ## V 0.3 ## Jos.Verlinde ############################################################################ Param ( [String] $Farm = "SP2010", [String] $SQLServer = $env:COMPUTERNAME, [String] $Passphrase = "pass@word1", [int] $CAPort = 26101 , [switch] $Force = $false ) # Disable the Loopback Check on stand alone demo servers. # This setting usually kicks out a 401 error when you try to navigate to sites that resolve to a loopback address e.g. 127.0.0.1 New-ItemProperty HKLM:\\System\\CurrentControlSet\\Control\\Lsa -Name "DisableLoopbackCheck" -value "1" -PropertyType dword #region Process Input Parameters $SecPhrase=ConvertTo-SecureString $Passphrase –AsPlaintext –Force $Passphrase = $null ## get Farm Account $cred_farm = $host.ui.PromptForCredential("FARM Setup", "SP Farm Account (SP_farm)", "contoso\\sp_farm", "NetBiosUserName" ) #Endregion # Create a new farm New-SPConfigurationDatabase –DatabaseName “$FARM-Config” –DatabaseServer $SQLServer –AdministrationContentDatabaseName “$FARM-Admin-Content” –Passphrase $SecPhrase –FarmCredentials $Cred_Farm # Create Central Admin New-SPCentralAdministration -Port $CAPort -WindowsAuthProvider "NTLM" #Install Help Files Install-SPApplicationContent #Secure resources Initialize-SPResourceSecurity #Install (all) features If ( $Force ) { $Features = Install-SPFeature –AllExistingFeatures -force } else { $Features = Install-SPFeature –AllExistingFeatures } ## Report features installed $Features # Provision all Services works only on stand alone servers (ie one-click-install ) # Install-SPService -Provision ## Todo : Check for Errors in the evenlog ## ## Start Central Admin Start-Process "http://$($env:COMPUTERNAME):$CAPort" ## Run Farm configuration Wizard Start-Process "http://$($env:COMPUTERNAME):$CAPort/_admin/adminconfigintro.aspx?scenarioid=adminconfig&welcomestringid=farmconfigurationwizard_welcome" ##@@ Todo - Run Farm Wizard or better yet create required service applications (minimal - normal - all template)
PowerShellCorpus/PoshCode/Pause-Script & Out-More.ps1
Pause-Script & Out-More.ps1
# Pause-Script # # Pauses execution until a key is pressed. function Pause-Script { param([string]$message = 'Press any key to continue...') Write-Host -NoNewLine $message $null = $Host.UI.RawUI.ReadKey("NoEcho, IncludeKeyDown") Write-Host "" } # Out-More # # Displays one window's worth of data at a time. # # Args: # $window_size: The number of lines to display # # Returns: # Each object in the input pipeline. function Out-More { param ([int]$window_size = ($Host.UI.RawUI.WindowSize.Height - 1)) $i = 0 foreach ($line in $input) { Write-Output $line $i += 1 if ($i -eq $window_size) { Pause-Script $i = 0 } } }
PowerShellCorpus/PoshCode/Logger.psm1 0.5.ps1
Logger.psm1 0.5.ps1
<# Name : Universal NLog Logging Module (NLog.psm1) Version : 0.5 Author : Joel Bennett (MVP) Site : http://www.HuddledMasses.org/ Version History: 0.5 - Port to NLog from Log4Net ( http://nlog-project.org ) Include support for Growl plugin for NLog, but left out the rotating log files stuff (I'll get to that later). http://ryanfarley.com/blog/archive/2010/05/06/announcing-the-growl-for-windows-target-for-nlog.aspx 0.4 - Bugfix, Viewer and Documentation release. Fixed a few typo-bugs Added documentation (man page) comments for Get-Logger. Changed a few parameter names (sorry) to make the default parameters more unique (so you have to type less on the command-line) Changed the default logger to use the logger module's folder as a backup (Some people might not have the Profile path -- this module could be installed anywhere and loaded by file name) Fixed up the xml output with a nice stylesheet http`://poshcode.org/1750 that formats and makes the page refresh. 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 NLog 2.0 : http://nlog-project.org Documentation : http://nlog-project.org/documentation.html 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\\NLog.dll function Get-RelativePath { <# .SYNOPSIS Get a path to a file (or folder) relative to another folder .DESCRIPTION Converts the FilePath to a relative path rooted in the specified Folder .PARAMETER Folder The folder to build a relative path from .PARAMETER FilePath The File (or folder) to build a relative path TO .PARAMETER Resolve If true, the file and folder paths must exist .Example Get-RelativePath ~\\Documents\\WindowsPowerShell\\Logs\\ ~\\Documents\\WindowsPowershell\\Modules\\Logger\\log4net.xslt ..\\Modules\\Logger\\log4net.xslt Returns a path to log4net.xslt relative to the Logs folder #> [CmdletBinding()] param( [Parameter(Mandatory=$true, Position=0)] [string]$Folder , [Parameter(Mandatory=$true, Position=1, ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [string]$FilePath , [switch]$Resolve ) process { $from = $Folder = split-path $Folder -NoQualifier -Resolve:$Resolve $to = $filePath = split-path $filePath -NoQualifier -Resolve:$Resolve while($from -and $to -and ($from -ne $to)) { if($from.Length -gt $to.Length) { $from = split-path $from } else { $to = split-path $to } } $filepath = $filepath -replace "^"+[regex]::Escape($to)+"\\\\" $from = $Folder while($from -and $to -and $from -gt $to ) { $from = split-path $from $filepath = join-path ".." $filepath } Write-Output $filepath } } function Get-Logger { <# .SYNOPSIS Get an existing Logger by name, or create a new logger .DESCRIPTION Returns a logger matching the name (wildcards allowed) provided. If the logger already exists, it is returned with it's settings as-is, unless the -Force switch is specified, in which case the new settings are used If only one logger matches the name, that logger becomes the new default logger. .PARAMETER Name The name of the logger to find or create. If no name is specified, all existing loggers are returned. .PARAMETER Level The level at which to log in this new logger. Defaults to "DEBUG" Possible levels are as follows (each level includes all levels above it): FATAL ERROR WARN (aka WARNING) INFO (aka VERBOSE, HOST) DEBUG .PARAMETER MessagePattern The pattern for loggers which use patterns (mostly the file loggers). Defaults to: ' ${longdate} ${level:uppercase=true} ${logger} [${ndc}] [${ndc}] - ${message}${newline}' For a complete list of possible pattern names, see: http://nlog-project.org/layoutrenderers.html .PARAMETER Growl Outputs log messages to growl For reference see: http://ryanfarley.com/blog/archive/2010/05/06/announcing-the-growl-for-windows-target-for-nlog.aspx .PARAMETER Folder The folder where log files are kept. Defaults to your Documents\\WindowsPowerShell folder. NOTE: if the specified folder does not exist, the fallback is your Documents\\WindowsPowerShell folder, but if that doesn't exist, the folder where this file is stored is used. .PARAMETER EmailTo An email address to send WARNING or above messages to. REQUIRES that your $PSEmailServer variable be set .PARAMETER Console Creates a colored console logger .PARAMETER EventLog Creates an EventLog logger .PARAMETER TraceLog Creates a .Net Trace logger .PARAMETER DebugLog Creates a .Net Debug logger .PARAMETER FileLog Creates a file logger. Note the LogLock parameter! .PARAMETER RollingFileLog Creates a rolling file logger with a max size of 250KB. Note the LogLock parameter! .PARAMETER XmlLog Creates an Xml-formatted file logger. Note the LogLock parameter! Note: the XmlLog will output an XML Header and will add a footer when the logger is closed. This results in a log file which is readable in xml viewers like IE, particularly if you have a copy of the XSLT stylesheet for Log4Net (http://poshcode.org/1750) named log4net.xslt in the same folder with the log file. WARNING: Because of this, it does not APPEND to the file, but overwrites it each time you create the logger. .PARAMETER RollingXmlLog Creates a rolling file Xml logger with a max size of 500KB. Note the LogLock parameter! Note: the rolling xml logger cannot create "valid" xml because it appends to the end of the file (and therefore can't guarantee the file is well-formed XML). In order to get a valid Xml file, you can use a "*View.xml" file with contents like this (which this script will create): <?xml version="1.0" ?> <?xml-stylesheet type="text/xsl" href="log4net.xslt"?> <!DOCTYPE events [<!ENTITY data SYSTEM "PowerShellLogger.xml">]> <log4net:events version="1.2" xmlns:log4net="http://logging.apache.org/log4net/schemas/log4net-events-1.2"> &data; </log4net:events> .PARAMETER LogLock Determines the type of file locking used (defaults to SHARED): SHARED is the "MinimalLocking" model which opens the file once for each AcquireLock/ReleaseLock cycle, thus holding the lock for the minimal amount of time. This method of locking is considerably slower than... EXCLUSIVE is the "ExclusiveLocking" model which opens the file once for writing and holds it open until the logger is closed, maintaining an exclusive lock on the file the whole time.. .PARAMETER UdpSend Creates an UdpAppender which sends messages to the localmachine port 8080 We'll probably tweak this in a future release, but for now if you need to change that you need to edit the script .PARAMETER ChainsawSend Like UdpSend, creates an UdpAppender which sends messages to the localmachine port 8080. This logger uses the log4j xml formatter which is somewhat different than the default, and uses their namespace. .PARAMETER Force Force resetting the logger switches even if the logger already exists #> param( [Parameter(Mandatory=$false, Position=0)] [string]$Name = "*" , [Parameter(Mandatory=$false)] # Actual Values: Trace, Debug, Info, Warn, Error, Fatal [ValidateSet("Verbose","Trace","Debug","Info","Host","Warn","Warning","Error","Fatal")] [string]$Level = "Trace" , [Parameter(Mandatory=$false)] #" %date %-5level %logger [%property{NDC}] - %message%newline" $MessagePattern = ' ${longdate} ${level:uppercase=true} ${logger} - ${message}${newline}' , [Parameter(Mandatory=$false)] [string]$Folder = $(Split-Path $Profile.CurrentUserAllHosts) , [String]$EmailTo , [Switch]$Force , [Switch]$ConsoleLog , [Switch]$EventLog , [Switch]$TraceLog , [Switch]$DebugLog , [Switch]$FileLog #, [Switch]$RollingFileLog , [Switch]$XmlLog #, [Switch]$RollingXmlLog , [Switch]$UdpSend , [Switch]$ChainsawSend , [Switch]$Growl # , # [Parameter(Mandatory=$false, Position=99)] # [ValidateSet("Shared","Exclusive")] # [String]$LogLock = "Shared" ) ## Make sure the folder exists if(!(Test-Path $Folder)) { $Folder = Split-Path $Profile.CurrentUserAllHosts if(!(Test-Path $Folder)) { $Folder = $PSScriptRoot } } $Script:NLogLoggersCollection | Where-Object { $_.Name -Like $Name } | Tee -var LoggerOutputBuffer if((!(test-path Variable:LoggerOutputBuffer) -or $Force) -and !$Name.Contains('*')) { if($Level -eq "VERBOSE") { $Level = "Trace" } if($Level -eq "HOST") { $Level = "Info" } if($Level -eq "WARNING") { $Level = "Warn" } $Targets = @() if(test-path Variable:Email) { if(!$PSEmailServer) { throw "You need to specify your SMTP mail server by setting the global $PSEmailServer variable" } $Targets += "Mail" $Null,$Domain = $email -split "@",2 } else { $Domain = "no.com" } # if($LogLock -eq "Shared") { # $LockMode = "MinimalLock" # } else { # $LockMode = "ExclusiveLock" # } $xslt = "" if(Test-Path $PSScriptRoot\\log4net.xslt) { $xslt = @" <?xml-stylesheet type="text/xsl" href="$(Get-RelativePath $Folder $PSScriptRoot\\NLog.xslt)"?> "@ } Set-Content "${Folder}\\${Name}View.Xml" @" <?xml version="1.0" ?> $xslt <!DOCTYPE events [<!ENTITY data SYSTEM "$Name.xml">]> <events version="1.2" xmlns:log4net="http`://logging.apache.org/log4net/schemas/log4net-events-1.2"> <logname>$Name</logname> &data; </events> "@ if($EventLog) { $Targets += "EventLog" } if($TraceLog) { $Targets += "Trace" } if($DebugLog) { $Targets += "Debug" } if($FileLog) { $Targets += "File" } # if($RollingFileLog) { $Targets += "<appender-ref ref=""RollingFileAppender"" />`n" } if($UdpSend) { $Targets += "Udp" } if($Growl) { $Targets += "Growl" } if($ChainsawSend) { $Targets += "Chainsaw" } if($XmlLog) { $Targets += "Xml" } # if($RollingXmlLog) { $Targets += "<appender-ref ref=""RollingXmlAppender"" />`n" if($VerbosePreference -gt "SilentlyContinue") { "Created XML viewer for you at: ${Folder}\\${Name}View.Xml" } $xslt = $xslt -replace "<","&lt;" -replace ">","&gt;" -replace '"',"'" if($ConsoleLog -or ($Targets.Count -eq 0)) { $Targets += "Console" } $extensions = "" if($Growl -and (Test-Path $PSScriptRoot\\NLog.Targets.GrowlNotify.dll)){ $extensions = @" <extensions> <add assembly="NLog.Targets.GrowlNotify" /> </extensions> "@ } $OFS = "," [xml]$config = @" <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> $extensions <targets> <target name="Console" xsi:type="ColoredConsole" layout="$MessagePattern"/> <target name="File" xsi:type="File" fileName="$Folder\\$Name.log" layout="$MessagePattern"/> <target name="Xml" xsi:type="File" fileName="$Folder\\$Name.xml" layout="`${log4jxmlevent}"/> <target name="EventLog" xsi:type="EventLog" log="Application" source="$Name" layout="$MessagePattern"/> <target name="Trace" xsi:type="Trace" layout="$MessagePattern"/> <target name="Debug" xsi:type="Debugger" layout="$MessagePattern"/> <target name="Udp" xsi:type="Network" address="udp://localhost:8080" layout="$MessagePattern"/> <target name="Chainsaw" xsi:type="Chainsaw" address="udp://localhost:8080" /> $(if($Growl){ '<target name="Growl" xsi:type="GrowlNotify" layout="$MessagePattern"/>' }) <target name="Mail" xsi:type="FilteringWrapper" condition="level > LogLevel.Debug or contains(message,'email')" > <target xsi:type="Mail" addNewLines="True" smtpServer="$PSEmailServer" layout="$MessagePattern" from="PoshLogger@$Domain" to="$EmailTo" subject="PowerShell Logger Message" /> </target> </targets> <rules> <logger name="$Name" minlevel="$Level" writeTo="$Targets"/> </rules> </nlog> "@ $config.Save("${PSScriptRoot}\\NLog.config") [NLog.LogManager]::Configuration = New-Object 'NLog.Config.XmlLoggingConfiguration' $config.nlog, $PSScriptRoot\\NLog.config $Script:NLogLoggersCollection += $Script:Logger = [NLog.LogManager]::GetLogger($Name) write-output $Script:Logger } elseif($NLogLoggersCollection.Count -eq 1) { $script:Logger = $NLogLoggersCollection[0] write-output $Script:Logger } } function Set-Logger { param( [Parameter(Mandatory=$true, ValueFromPipeline=$true)] [NLog.Logger]$Logger ) $script:Logger = $Logger } function Push-LogContext { param( [Parameter(Mandatory=$true)] [string]$Name ) [NLog.Contexts.NestedDiagnosticsContext]::Push($Name) } function Pop-LogContext { [NLog.Contexts.NestedDiagnosticsContext]::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.Trace($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.ErrorException($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 * $NLogLoggersCollection = @() $script:Logger = Get-Logger "PowerShellLogger" -File # -Console -Growl ## THIS IS THE DEFAULT LOGGER. CONFIGURE AS YOU SEE FIT
PowerShellCorpus/PoshCode/5f5f41e1-5b7f-46e6-a165-083c18a8ea02.ps1
5f5f41e1-5b7f-46e6-a165-083c18a8ea02.ps1
function Run-Query($siteUrl, $queryText) { [reflection.assembly]::loadwithpartialname("microsoft.sharePOint") | out-null [reflection.assembly]::loadwithpartialname("microsoft.office.server") | out-null [reflection.assembly]::loadwithpartialname("microsoft.office.server.search") | out-null $s = [microsoft.sharepoint.spsite]$siteUrl $q = new-object microsoft.office.server.search.query.fulltextsqlquery -arg $s $q.querytext = $queryText $q.RowLimit = 100 $q.ResultTypes = "RelevantResults" $dt = $q.Execute() $r = $dt["RelevantResults"] $output = @() while ($r.Read()) { $o = new-object PSObject 0..($r.FieldCount-1) | foreach { add-member -inputObject $o -memberType "NoteProperty" -name $r.GetName($_) -value $r[$_].ToString() } $output += $o } return $output } @@#Sample usage: @@#Run-Query -siteUrl "http://dev/" -queryText "SELECT PreferredName, WorkPhone FROM S"
PowerShellCorpus/PoshCode/ConvertFrom-CliXml_1.ps1
ConvertFrom-CliXml_1.ps1
function ConvertFrom-CliXml { param( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String[]]$InputObject ) begin { $OFS = "`n" [String]$xmlString = "" } process { $xmlString += $InputObject } end { $type = [type]::gettype("System.Management.Automation.Deserializer") $ctor = $type.getconstructor("instance,nonpublic", $null, @([xml.xmlreader]), $null) $sr = new-object System.IO.StringReader $xmlString $xr = new-object System.Xml.XmlTextReader $sr $deserializer = $ctor.invoke($xr) $method = @($type.getmethods("nonpublic,instance") | where-object {$_.name -like "Deserialize"})[1] $done = $type.getmethod("Done", [System.Reflection.BindingFlags]"nonpublic,instance") while (!$done.invoke($deserializer, @())) { try { $method.invoke($deserializer, "") } catch { write-warning "Could not deserialize $string: $_" } } $xr.Close() $sr.Dispose() } }
PowerShellCorpus/PoshCode/Create SP2010 Farm V_1.ps1
Create SP2010 Farm V_1.ps1
############################################################################ ## Create-SPFarm ## V 0.3 ## Jos.Verlinde ############################################################################ Param ( [String] $Farm = "SP2010", [String] $SQLServer = $env:COMPUTERNAME, [String] $Passphrase = "pass@word1", [int] $CAPort = 26101 , [switch] $Force = $false ) # Disable the Loopback Check on stand alone demo servers. # This setting usually kicks out a 401 error when you try to navigate to sites that resolve to a loopback address e.g. 127.0.0.1 New-ItemProperty HKLM:\\System\\CurrentControlSet\\Control\\Lsa -Name "DisableLoopbackCheck" -value "1" -PropertyType dword #region Process Input Parameters $SecPhrase=ConvertTo-SecureString $Passphrase –AsPlaintext –Force $Passphrase = $null ## get Farm Account $cred_farm = $host.ui.PromptForCredential("FARM Setup", "SP Farm Account (SP_farm)", "contoso\\sp_farm", "NetBiosUserName" ) #Endregion # Create a new farm New-SPConfigurationDatabase –DatabaseName “$FARM-Config” –DatabaseServer $SQLServer –AdministrationContentDatabaseName “$FARM-Admin-Content” –Passphrase $SecPhrase –FarmCredentials $Cred_Farm # Create Central Admin New-SPCentralAdministration -Port $CAPort -WindowsAuthProvider "NTLM" #Install Help Files Install-SPApplicationContent #Secure resources Initialize-SPResourceSecurity #Install (all) features If ( $Force ) { $Features = Install-SPFeature –AllExistingFeatures -force } else { $Features = Install-SPFeature –AllExistingFeatures } ## Report features installed $Features # Provision all Services works only on stand alone servers (ie one-click-install ) # Install-SPService -Provision ## Todo : Check for Errors in the evenlog ## ## Start Central Admin Start-Process "http://$($env:COMPUTERNAME):$CAPort" ## Run Farm configuration Wizard Start-Process "http://$($env:COMPUTERNAME):$CAPort/_admin/adminconfigintro.aspx?scenarioid=adminconfig&welcomestringid=farmconfigurationwizard_welcome" ##@@ Todo - Run Farm Wizard or better yet create required service applications (minimal - normal - all template)
PowerShellCorpus/PoshCode/Get-WootDeal.ps1
Get-WootDeal.ps1
<# .Synopsis Gets the daily woot deal from woot.com. .Description Gets product description and price of the daily woot deal from the woot.com website. .Outputs Custom object containing two (2) NoteProperties: Product and Price. .Parameter URL The URL to load and search for pricing. Don't get funky, this HAS to be the woot website url, as the code won't work with anything else, because it screen scrapes for information. .Notes This script uses the Webrequest class to load a webpage (woot.com), then does a regex search of the html code to find some specific information (also known as 'screen scraping'). This was a learning exercise I inflicted upon myself with the goal of using xml parsers (such as the xmldocument class) to reliably extract information from xhtml-compliant websites (of which woot.com purports to be, at least according to their page headers :)) It was a nightmare. I ran into all kinds of compliance issues with the xml classes, and so after much frustration, achieved the goal using a completely different method. #> param( [Parameter(Position=0, Mandatory=$false)] [string] $URL = "http://www.woot.com" ) [string]$WorkingDir = Split-Path $MyInvocation.MyCommand.Path -Parent $Request = [System.Net.Webrequest]::Create($URL) $Response = $Request.GetResponse() $RawStream = $Response.GetResponseStream() $Encoding = [System.Text.Encoding]::GetEncoding("utf-8") ## better safe than sorry $EncodedStream = New-Object System.IO.StreamReader($RawStream, $Encoding) $Data = $EncodedStream.ReadToEnd() $Product = [regex]::Match($Data,"(?<=<h2\\sclass=`"fn`">).+(?=</h2>)").Value $Price = [regex]::Match($Data,"(?<=<span\\sclass=`"amount`">)[0-9\\.]+(?=</span>)").Value $Output = New-Object Object | Add-Member NoteProperty -Name Product -Value $Product -PassThru | Add-Member NoteProperty -Name Price -Value $Price -PassThru Write-Output $Output Send-MailMessage -To "<INSERT YOUR EMAIL HERE>" ` -From "dailydeal@woot.com" ` -Subject "Daily Woot! Deal" ` -Body ($Output | Format-Table -AutoSize | Out-String) ` -SmtpServer "<INSERT YOUR SMTP SERVER HERE>" $EncodedStream.Close() $Response.Close() break #experimental stuff Set-Content -Value $Data -Path "$WorkingDir\\Get-Webpage_Data.xhtml" -Force try { } catch { Write-Host $_ } finally { $XmlReader.Close() }
PowerShellCorpus/PoshCode/FTP Upload Dir Tree.ps1
FTP Upload Dir Tree.ps1
function upload-directory { param( [string] $server = $( Throw "You must specify an FTP server to logon to."), [string] $dir = $( Throw "You must specify a local directory to upload (ie, C:\\Testing\\FTPTest\\)"), [switch] $overwrite = $false, [System.Management.Automation.PSCredential] $cred = $( Throw "You must provide credentials with which to logon to the FTP server.") ) $files = (get-childitem $dir -r) foreach ($file in $files) { $remfilename = $file.FullName.Replace($dir, "") $remfilename = $remfilename.Replace("\\", "/") if ($file.Attributes.ToString().IndexOf("Directory") -ge 0) { try { send-ftp -server $server -cred $cred -create $remfilename -overwrite:$overwrite } catch {} #if the directory already exists, ignore the error } else { send-ftp -server $server -cred $cred -localfile $file.FullName -remotefile $remfilename -overwrite:$overwrite } #end ifelse } #end foreach }
PowerShellCorpus/PoshCode/Shift Operators.ps1
Shift Operators.ps1
#requires -version 2.0 ## for v1 you need to change Add-Type to "New-Type":http://poshcode.org/720 Add-Type @" public class Shift { public static int Left(int x, int count) { return x >> count; } public static uint Left(uint x, int count) { return x >> count; } public static long Left(long x, int count) { return x >> count; } public static ulong Left(ulong x, int count) { return x >> count; } public static int Right(int x, int count) { return x << count; } public static uint Right(uint x, int count) { return x << count; } public static long Right(long x, int count) { return x << count; } public static ulong Right(ulong x, int count) { return x << count; } } "@ #.Example # ShiftLeft 16 1 ## returns 8 #.Example # 8,16 |Shift-Left ## returns 4,8 function Shift-Left { PARAM( $x=1, $y ) BEGIN { if($y) { [Shift]::Left( $x, $y ) } } PROCESS { if($_){ [Shift]::Left($_, $x) } } } #.Example # ShiftRight 8 1 ## returns 16 #.Example # 2,4,8 |Shift-Right 2 ## returns 8,16,32 function Shift-Right { PARAM( $x=1, $y ) BEGIN { if($y) { [Shift]::Right( $x, $y ) } } PROCESS { if($_){ [Shift]::Right($_, $x) } } }
PowerShellCorpus/PoshCode/Get-Constructor.ps1
Get-Constructor.ps1
# Eg: Get-Constructor System.IO.StreamReader function Get-Constructor { Param([Type]$type) $OFS = ", " $Type.GetConstructors("Public,Instance,Static") | ForEach-Object { "{0}( {1} )" -f $_.DeclaringType, "$($_.GetParameters() | %{ $_.ParameterType })" } }
PowerShellCorpus/PoshCode/chkhash_22.ps1
chkhash_22.ps1
# calculate SHA512 of file. function Get-SHA512([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]')) { $stream = $null; $cryptoServiceProvider = [System.Security.Cryptography.SHA512CryptoServiceProvider]; $hashAlgorithm = new-object $cryptoServiceProvider $stream = $file.OpenRead(); $hashByteArray = $hashAlgorithm.ComputeHash($stream); $stream.Close(); ## We have to be sure that we close the file stream if any exceptions are thrown. trap { if ($stream -ne $null) { $stream.Close(); } break; } foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }} return [string]$result; } function noequal ( $first, $second) { if (!($second) -or $second -eq "") {return $true} $first=join-path $first "\\" foreach($s in $second) { if ($first.tolower().startswith($s.tolower())) {return $false} } return $true } function WriteFileNameEnd ( ) { if ($global:oldctop -eq $null) {return} [console]::cursortop=$global:oldctop [console]::cursorleft=0 write-host "" } function WriteFileName ( [string]$writestr ) # this function prints multiline messages on top of each other, good for iterating through filenames without filling { # the console with a huge wall of text. Call this function to print each of the filename messages, then call writefilenameend when done # before printing anything else, so that you are not printing into a long file name with extra characters from it visible. if ($global:lastlen -eq $null) {$global:lastlen=0} $ctop=[console]::cursortop [console]::cursorleft=0 $oldwritestrlen=$writestr.length if ($global:lastlen -gt $writestr.length) { $writestr = $writestr + (" " * ($global:lastlen-$writestr.length)) } $writelines = [math]::divrem($writestr.length, [console]::bufferwidth, [ref]$null) $cwe = ($writelines-([console]::bufferheight-$ctop))+1 # don't ask. if ($cwe -gt 0) {$ctop-=($cwe)} write-host "$writestr" -nonewline $global:lastlen = $oldwritestrlen $global:oldctop=([console]::cursortop) [console]::cursortop=$ctop [console]::cursorleft=0 } # 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, minus directories and minus files in excluded paths 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 | %{WriteFileName "SHA-512 Hashing: `"$($_.fullname)`" ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru} WriteFileNameEnd $files |export-clixml $hashespath "Created $hashespath" "$($files.count) file hash(es) saved. Exiting." exit } write-host "Loading file hashes from $hashespath..." -nonewline $xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database if ($xfiles.count -eq 0) {"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 -literalpath $f.fullname) -eq $null) {continue} # skip if file no longer exists. $n=($hash.($f.fullname)) if ($n -eq $null) { $nu++ # increment needs/needed updating count if ($upd -eq $false) {WriteFileNameEnd; "Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue WriteFileName "SHA-512 Hashing `"$($f.fullname)`" ..." # Create SHA512 hash of file $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force} $xfiles+=@($f) # then add file + hash to list continue } WriteFileName "SHA-512 Hashing and checking: `"$($f.fullname)`" ..." $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 WriteFileNameEnd if ($upd -eq $true) { $xfiles[$n]=$f; "Updated `"$($f.fullname)`"";continue} "Bad SHA-512 found: `"$($f.fullname)`"" } WriteFileNameEnd # restore cursor position after last write string 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/ConvertTo-Icon.ps1
ConvertTo-Icon.ps1
[Reflection.Assembly]::LoadWithPartialName("System.Drawing") | Out-Null #Version History #v1.0 - Chad Miller - Initial release #Converts Image Files to icon files #Adapted from WinForm C# code by Haresh Ambaliya #http://code.msdn.microsoft.com/Convert-Image-file-to-Icon-c927d9f7 function ConvertTo-Icon { [cmdletbinding()] param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] $Path) process{ if ($Path -is [string]) { $Path = get-childitem $Path } $Path | foreach { $image = [System.Drawing.Image]::FromFile($($_.FullName)) $FilePath = "{0}\\{1}.ico" -f $($_.DirectoryName), $($_.BaseName) $stream = [System.IO.File]::OpenWrite($FilePath) $bitmap = new-object System.Drawing.Bitmap $image $bitmap.SetResolution(72,72) $icon = [System.Drawing.Icon]::FromHandle($bitmap.GetHicon()) $icon.Save($stream) $stream.Close() } } }
PowerShellCorpus/PoshCode/Get-Parameter_2.ps1
Get-Parameter_2.ps1
param($Cmdlet) foreach ($paramset in (Get-Command $Cmdlet).ParameterSets) { $Output = @() foreach ($param in $paramset.Parameters) { $process = "" | Select-Object Name, ParameterSet, Aliases, IsMandatory, CommonParameter $process.Name = $param.Name if ( $paramset.name -eq "__AllParameterSets" ) { $process.ParameterSet = "Default" } else { $process.ParameterSet = $paramset.Name } $process.Aliases = $param.aliases $process.IsMandatory = $param.IsMandatory if ($param.aliases -match "vb|db|ea|wa|ev|wv|ov|ob") { $process.CommonParameter = $TRUE } else { $process.CommonParameter = $FALSE } $output += $process } Write-Output $Output #Write-Host "`n" }
PowerShellCorpus/PoshCode/ExportSQLDeadlockGraphs.ps1
ExportSQLDeadlockGraphs.ps1
<# ALZDBA SQLServer_Export_DeadlockGraphs_SMO.ps1 Export top n Deadlock graphs for all databases of a given SQLServer (SQL2008+) Instance results in a number of .XDL files and one overview file *AllDbDeadlockGraphs.csv. Double clicking an .XDL file will open the graphical representation of the deadlock info in SQLServer Management Studio ( You'll need SSMS 2012 to overcome the XML-schema changes they did during the SQL2008 lifetime ) #> #requires -version 2 #SQLServer instance $SQLInstance = 'Yourserver\\yourinstance' #What number of plans to export per db ? [int]$nTop = 50 trap { # Handle all errors not handled by try\\catch $err = $_.Exception write-verbose "Trapped error: $err.Message" while( $err.InnerException ) { $err = $err.InnerException write-host $err.Message -ForegroundColor Black -BackgroundColor Red }; # End the script. break } $ALLDbResults = $null Clear-Host if (!($ALLDbResults) ) { # databases of which we do not want sqlplans [string[]]$ExcludedDb = 'master', 'model', 'msdb', 'DDBAserverPing' #recipient #$ALLDbResults = $null $SampleTime = Get-Date -Format 'yyyyMMdd_HHmm' #Load SQLServer SMO libraries [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null $serverInstance = New-Object ("Microsoft.SqlServer.Management.Smo.Server") $SQLInstance #Oh please put some application info in your connection metadata ! $serverInstance.ConnectionContext.ApplicationName = "DBA_Export_DeadlockGraphs" $serverInstance.ConnectionContext.WorkstationId = $env:COMPUTERNAME # connecting should take less than 5 seconds ! $serverInstance.ConnectionContext.ConnectTimeout = 5 #connect before processing $serverInstance.ConnectionContext.Connect() #region DeadlockInfoQuery $Query = '' if ( $serverInstance.VersionMajor -lt 10 ) { write-host $('{0} is of a Non-supported SQLServer version [{1}].' -f $SQLInstance, $serverInstance.VersionString) -ForegroundColor Black -BackgroundColor Red # End the script. break } elseif ( $serverInstance.VersionMajor -eq 10 -and $serverInstance.VersionMinor -lt 50 ) { # SQL2008 write-host $('{0} is of a Non-supported SQLServer version [{1}].' -f $SQLInstance, $serverInstance.VersionString) -ForegroundColor Black -BackgroundColor Red # End the script. break } else { # SQL2008R2 and up $Query = $( 'Set QUOTED_IDENTIFIER ON; /* Fetch the Health Session data into a temporary table */ if object_id(''tempdb..#SystemHealthSessionData'') is null begin Create table #SystemHealthSessionData ( PK int not null primary key clustered, XMLDATA xml not null ) insert INTO #SystemHealthSessionData SELECT cast( 1 as int ) as PK, CAST(xet.target_data AS XML) AS XMLDATA FROM sys.dm_xe_session_targets xet INNER JOIN sys.dm_xe_sessions xe ON ( xe.address = xet.event_session_address ) WHERE xe.name = ''system_health''; CREATE PRIMARY XML INDEX PXML_SystemHealthSessionData ON #SystemHealthSessionData (XMLDATA); end ; ; with cteDeadLocks as ( SELECT top ( 50 ) x.y.value(''(@timestamp)[1]'', ''datetime'') [timestampUTC] , CAST(x.y.value(''data(.//data/value)[1]'', ''VARCHAR(MAX)'') AS XML).value(''deadlock[1]/victim-list[1]/victimProcess[1]/@id[1]'' , ''VARCHAR(128)'') [victim] , CAST(x.y.value(''data(.//data/value)[1]'', ''VARCHAR(MAX)'') AS XML).query(''deadlock/process-list/*'') [ProcessList] , CAST(x.y.value(''data(.//data/value)[1]'', ''VARCHAR(MAX)'') AS XML).query(''deadlock/resource-list/*'') [ResourceList] , CAST(x.y.value(''data(.)[1]'', ''VARCHAR(MAX)'') AS XML).query(''*'') as DeadlockGraph FROM #SystemHealthSessionData [deadlock] CROSS APPLY [XMLDATA].nodes(''/RingBufferTarget/event'') AS x ( y ) WHERE x.y.query(''.'').exist(''/event[@name="xml_deadlock_report"]'') = 1 and x.y.value(''(@timestamp)[1]'', ''datetime'') > DATEADD(dd, datediff(dd, 0, getUTCdate()) - 2 , 0) and CAST(x.y.value(''data(.//data/value)[1]'', ''VARCHAR(MAX)'') AS XML).query(''deadlock/resource-list/*'').value(''(//@dbid)[1]'', ''integer'') = db_id() Order by [timestampUTC] desc ) Select convert(varchar(25),SERVERPROPERTY(''ServerName'')) as ServerName , * /* process block 1 */ , [ResourceList].value(''(//@dbid)[1]'', ''integer'') [DbId1] , DB_NAME( [ResourceList].value(''(//@dbid)[1]'', ''integer'')) [DbName1] , [ProcessList].value(''(//@id)[1]'', ''nvarchar(128)'') [Id1] , [ProcessList].value(''(//@status)[1]'', ''nvarchar(128)'') [Status1] , [ProcessList].value(''(//@waitresource)[1]'', ''nvarchar(128)'') [waitresource1] , [ProcessList].value(''(//@waittime)[1]'', ''integer'') [waittime1] , [ProcessList].value(''(//@transactionname)[1]'', ''nvarchar(128)'') [transactionname1] , [ProcessList].value(''(//@clientapp)[1]'', ''nvarchar(256)'') [ApplicationName1] , [ProcessList].value(''(//@hostname)[1]'', ''nvarchar(256)'') [hostname1] , [ProcessList].value(''(//@loginname)[1]'', ''nvarchar(256)'') [loginname1] , [ProcessList].value(''(//@isolationlevel)[1]'', ''nvarchar(256)'') [isolationlevel1] , [ProcessList].value(''(//@currentdb)[1]'', ''integer'') [ConnectionCurrentDb1] , DB_NAME( [ProcessList].value(''(//@currentdb)[1]'', ''integer'')) [ConnectionCurrentDbName1] , [ProcessList].value(''(//@lasttranstarted)[1]'', ''datetime'') [lasttranstarted1] , [ProcessList].value(''(//@lastbatchstarted)[1]'', ''datetime'') [lastbatchstarted1] /* process block 2 */ , [ResourceList].value(''(//@dbid)[2]'', ''integer'') [DbId2] , DB_NAME( [ResourceList].value(''(//@dbid)[2]'', ''integer'')) [DbName2] , [ProcessList].value(''(//@id)[2]'', ''nvarchar(128)'') [Id2] , [ProcessList].value(''(//@status)[2]'', ''nvarchar(128)'') [Status2] , [ProcessList].value(''(//@waitresource)[2]'', ''nvarchar(128)'') [waitresource2] , [ProcessList].value(''(//@waittime)[2]'', ''integer'') [waittime2] , [ProcessList].value(''(//@transactionname)[2]'', ''nvarchar(128)'') [transactionname2] , [ProcessList].value(''(//@clientapp)[2]'', ''nvarchar(256)'') [ApplicationName2] , [ProcessList].value(''(//@hostname)[2]'', ''nvarchar(256)'') [hostname2] , [ProcessList].value(''(//@loginname)[2]'', ''nvarchar(256)'') [loginname2] , [ProcessList].value(''(//@isolationlevel)[2]'', ''nvarchar(256)'') [isolationlevel2] , [ProcessList].value(''(//@currentdb)[2]'', ''integer'') [ConnectionCurrentDb2] , DB_NAME( [ProcessList].value(''(//@currentdb)[2]'', ''integer'')) [ConnectionCurrentDbName2] , [ProcessList].value(''(//@lasttranstarted)[2]'', ''datetime'') [lasttranstarted2] , [ProcessList].value(''(//@lastbatchstarted)[2]'', ''datetime'') [lastbatchstarted2] /* process block 3 */ , [ResourceList].value(''(//@dbid)[3]'', ''integer'') [DbId3] , DB_NAME( [ResourceList].value(''(//@dbid)[3]'', ''integer'')) [DbName3] , [ProcessList].value(''(//@id)[3]'', ''nvarchar(128)'') [Id3] , [ProcessList].value(''(//@status)[3]'', ''nvarchar(128)'') [Status3] , [ProcessList].value(''(//@waitresource)[3]'', ''nvarchar(128)'') [waitresource3] , [ProcessList].value(''(//@waittime)[3]'', ''integer'') [waittime3] , [ProcessList].value(''(//@transactionname)[3]'', ''nvarchar(128)'') [transactionname3] , [ProcessList].value(''(//@clientapp)[3]'', ''nvarchar(256)'') [ApplicationName3] , [ProcessList].value(''(//@hostname)[3]'', ''nvarchar(256)'') [hostname3] , [ProcessList].value(''(//@loginname)[3]'', ''nvarchar(256)'') [loginname3] , [ProcessList].value(''(//@isolationlevel)[3]'', ''nvarchar(256)'') [isolationlevel3] , [ProcessList].value(''(//@currentdb)[3]'', ''integer'') [ConnectionCurrentDb3] , DB_NAME( [ProcessList].value(''(//@currentdb)[3]'', ''integer'')) [ConnectionCurrentDbName3] , [ProcessList].value(''(//@lasttranstarted)[3]'', ''datetime'') [lasttranstarted3] , [ProcessList].value(''(//@lastbatchstarted)[3]'', ''datetime'') [lastbatchstarted3] /* process block 4 */ , [ResourceList].value(''(//@dbid)[4]'', ''integer'') [DbId4] , DB_NAME( [ResourceList].value(''(//@dbid)[4]'', ''integer'')) [DbName4] , [ProcessList].value(''(//@id)[4]'', ''nvarchar(128)'') [Id4] , [ProcessList].value(''(//@status)[4]'', ''nvarchar(128)'') [Status4] , [ProcessList].value(''(//@waitresource)[4]'', ''nvarchar(128)'') [waitresource4] , [ProcessList].value(''(//@waittime)[4]'', ''integer'') [waittime4] , [ProcessList].value(''(//@transactionname)[4]'', ''nvarchar(128)'') [transactionname4] , [ProcessList].value(''(//@clientapp)[4]'', ''nvarchar(256)'') [ApplicationName4] , [ProcessList].value(''(//@hostname)[4]'', ''nvarchar(256)'') [hostname4] , [ProcessList].value(''(//@loginname)[4]'', ''nvarchar(256)'') [loginname4] , [ProcessList].value(''(//@isolationlevel)[4]'', ''nvarchar(256)'') [isolationlevel4] , [ProcessList].value(''(//@currentdb)[4]'', ''integer'') [ConnectionCurrentDb4] , DB_NAME( [ProcessList].value(''(//@currentdb)[4]'', ''integer'')) [ConnectionCurrentDbName4] , [ProcessList].value(''(//@lasttranstarted)[4]'', ''datetime'') [lasttranstarted4] , [ProcessList].value(''(//@lastbatchstarted)[4]'', ''datetime'') [lastbatchstarted4] from cteDeadLocks DL order by [timestampUTC] desc ; ' -f $nTop ) } #endregion DeadlockInfoQuery $i = 0 foreach($db in $serverInstance.Databases){ if ( $ExcludedDb -notcontains $db.Name ) { $i += 1 $pct = 100 * $i / $serverInstance.Databases.Count Write-progress -Status "Processing DBs - $($db.Name)" -Activity "Collection DeadlockGraphs $SQLInstance" -PercentComplete $pct try { $DbResults = $db.ExecuteWithResults("$Query").Tables[0] ; if ( !( $ALLDbResults )) { $ALLDbResults = $DbResults.clone() } if ( $DbResults.rows.count -gt 0 ) { $ALLDbResults += $DbResults } } catch { #just neglect this error Write-host $_.Exception.Message -BackgroundColor Red -ForegroundColor Black } } else { Write-Verbose "Excluded Db $db.name" } } #Take control: do it yourself ! $serverInstance.ConnectionContext.Disconnect() } if ( $ALLDbResults -and $ALLDbResults.Count -gt 0 ) { $TargetPath = "$env:TEMP\\Powershell" if ( !(Test-Path $TargetPath) ) { md $TargetPath | Out-Null } Write-progress -Status "Exporting Consumption Data" -Activity "Exporting Deadlock Graphs $SQLInstance" -PercentComplete 15 $TargetFile = $('{0}-{1}_AllDbDeadlockGraphs.csv' -f $SampleTime, $($SQLInstance -replace '\\\\', '_') ) #$ALLDbResults | Select Db_Name, Row_Number, Schema, Object_Name, avg_elapsed_time, total_elapsed_time, execution_count, Calls_Per_Second, Avg_Worker_Time, Total_Worker_Time, Missing_Indexes, cached_time, Time_In_Cache_SS | sort Db_Name, Row_Number | Export-Csv -Path $( Join-Path -Path $TargetPath -ChildPath $TargetFile ) -Delimiter ';' -NoTypeInformation $ALLDbResults | SELECT ServerName, timestampUTC, victim, processlist, resourcelist, DbId1, DbName1, Id1, Status1, waitresource1, waittime1, transactionname1, ApplicationName1, hostname1, loginname1, isolationlevel1, ConnectionCurrentDb1, ConnectionCurrentDbName1, lasttranstarted1, lastbatchstarted1, DbId2, DbName2, Id2, Status2, waitresource2, waittime2, transactionname2, ApplicationName2, hostname2, loginname2, isolationlevel2, ConnectionCurrentDb2, ConnectionCurrentDbName2, lasttranstarted2, lastbatchstarted2, DbId3, DbName3, Id3, Status3, waitresource3, waittime3, transactionname3, ApplicationName3, hostname3, loginname3, isolationlevel3, ConnectionCurrentDb3, ConnectionCurrentDbName3, lasttranstarted3, lastbatchstarted3, DbId4, DbName4, Id4, Status4, waitresource4, waittime4, transactionname4, ApplicationName4, hostname4, loginname4, isolationlevel4, ConnectionCurrentDb4, ConnectionCurrentDbName4, lasttranstarted4, lastbatchstarted4 | sort TimestampUTC -desc | Export-Csv -Path $( Join-Path -Path $TargetPath -ChildPath $TargetFile ) -Delimiter ';' -NoTypeInformation $i = 0 foreach ( $p in $ALLDbResults ) { $i += 1 $pct = 100 * $i / $ALLDbResults.Count Write-progress -Status "Exporting DeadlockGraphs - $($p.timestampUTC)" -Activity "Exporting Deadlock Graphs $SQLInstance" -PercentComplete $pct [datetime]$TimestampUTC = $p.timestampUTC $TimestampUTCfmt = Get-Date -Date $TimestampUTC -format 'yyyyMMdd_hhmmss_fff' $TargetFileName = $('DeadLockGraph-{0}-{1}-{2}.XDL' -f $($p.ServerName.Replace('\\','_')), $p.DbName1, $TimestampUTCfmt ) Write-verbose $TargetFileName Out-File -FilePath $( Join-Path -Path $TargetPath -ChildPath $TargetFileName ) -InputObject $p.DeadlockGraph } #open explorer at target path Invoke-Item "$TargetPath" } else { Write-Host "No DeadlockGraphs to be exported ! " -ForegroundColor Black -BackgroundColor Yellow } Write-Host 'The end.'
PowerShellCorpus/PoshCode/192.168.1.1.ps1
192.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/Copy Files Log to Excel.ps1
Copy Files Log to Excel.ps1
# Get User/Pass $Cred = Get-Credential # Add Quest CMDLETS Add-PSSnapin Quest.ActiveRoles.ADManagement -WarningAction SilentlyContinue -ErrorAction SilentlyContinue # Get Computer's from AD $Computers = Get-QADComputer -SearchRoot "OU=Workstations,DC=Domain,DC=com" -Credential $Cred # Import BITS for the file transfers Import-Module BitsTransfer # Let's Copy the files! Function Deploy { Clear-Host $Computers | ForEach-Object { # Format Computer Name $Computer = $_.name $FileToCopy = "C:\\Users\\Public\\File.Here" # Check to see if the computer is online $Online = Test-Connection -Quiet -ComputerName $Computer IF ($Online -eq $true) { # If Online discover if system is 32 or 64 bit $WMI = Get-WmiObject -Credential $Cred -Class Win32_OperatingSystem -ComputerName $Computer $OSArch = $WMI.OSArchitecture IF ($OSArch -eq '64-bit') { # 64 bit systems Start-BitsTransfer -Source $FileToCopy -Credential $cred -Description "$Computer - Patch" -Destination "\\\\$Computer\\C$\\Program Files (x86)\\APPFOLDER\\SubFolder\\File.Here" } ELSE { # 32 bit systems Start-BitsTransfer -Source $FileToCopy -Credential $cred -Description "$Computer - Patch" -Destination "\\\\$Computer\\C$\\Program Files\\APPFOLDER\\SubFolder\\File.Here" } } } } <# For finding MD5 hash of files Taken from: author:fuhj(powershell@live.cn ,http://txj.shell.tor.hu) In hind sight I guess I could have used get-sha1 from powershell powerpack. #> 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;} return [string]$hashByteArray; } # Let's check the versions! # This is called in the logging function Function GetFileInfo { # Check's to see if the system is online $Online = Test-Connection -Quiet -ComputerName $Computer IF ($Online -eq $true) { # If Online discover if system is 32 or 64 bit $WMI = Get-WmiObject -Credential $Cred -Class Win32_OperatingSystem -ComputerName $Computer $OSArch = $WMI.OSArchitecture IF ($OSArch -eq '64-bit') { # 64 bit systems $File = "\\\\$Computer\\C$\\Program Files (x86)\\APPHERE\\SubFolder\\File.here" IF ((Test-Path $file) -eq $true) { $MD5 = Get-MD5 $File IF ($MD5 -eq "71 138 251 146 147 253 178 99 136 67 73 107 206 247 60 235"){ $c.Cells.Item($intRow,2) = "PATCHED"} ELSE {$c.Cells.Item($intRow,2) = "NOT PATCHED"} } ELSE {$c.Cells.Item($intRow,2) = "FILE MISSING OR ACCESS DENIED"} } ELSE { # 32 bit systems $File = "\\\\$Computer\\C$\\Program Files\\APPHERE\\SubFolder\\File.here" IF ((Test-Path $file) -eq $true) { $MD5 = Get-MD5 $File IF ($MD5 -eq "71 138 251 146 147 253 178 99 136 67 73 107 206 247 60 235"){ $c.Cells.Item($intRow,2) = "PATCHED"} ELSE {$c.Cells.Item($intRow,2) = "NOT PATCHED"} } ELSE {$c.Cells.Item($intRow,2) = "FILE MISSING OR ACCESS DENIED"} } } # If Offline mark as such ELSE {$c.Cells.Item($intRow,2) = "OFFLINE"} } # Let's log this with... EXCEL! Function LogIT { # Generate Excel Document $a = New-Object -comobject Excel.Application # Let's the document be seen otherwise it would run the the background $a.visible = $True # Adds the workbook $b = $a.Workbooks.Add() # Sets up the Sheet $c = $b.Worksheets.Item(1) # Make the Headers $c.Cells.Item(1,1) = "Machine Name" $c.Cells.Item(1,2) = "Version" $c.Cells.Item(1,3) = "Report Time Stamp" # Set Font & Color $d = $c.UsedRange $d.Interior.ColorIndex = 19 $d.Font.ColorIndex = 11 # I like my headers to be bold. $d.Font.Bold = $True # Starts writing in the next row $intRow = 2 # Get the data $Computers | ForEach-Object { # Format the computer Name $Computer = $_.name # Input the computer name $c.Cells.Item($intRow,1) = $Computer # Get the file info GetFileInfo # Put's in the date $c.Cells.Item($intRow,3) = Get-date # Got to the next row $intRow = $intRow + 1 } # Formats the data $d.EntireColumn.AutoFit() } # Oh Crap, bad things are happening! Need to backout of this NOW! Function DangerWillRobinson { $Computers | ForEach-Object { # Format Computer Name $Computer = $_.name # Check to see if the computer is online $Online = Test-Connection -Quiet -ComputerName $Computer IF ($Online -eq $true) { # If Online discover if system is 32 or 64 bit $WMI = Get-WmiObject -Credential $Cred -Class Win32_OperatingSystem -ComputerName $Computer $OSArch = $WMI.OSArchitecture IF ($OSArch -eq '64-bit') { # 64 bit systems $FILE = Get-WMIObject -computer $Computer -Credential $Cred -query "Select * From CIM_DataFile Where Name ='C:\\\\Program Files (x86)\\\\YOUAPP\\\\APPSSUBFOLDER\\\\FILE.HERE'" $FILE.Delete() } ELSE { # 32 bit systems $FILE = Get-WMIObject -computer $Computer -Credential $Cred -query "Select * From CIM_DataFile Where Name ='C:\\\\Program Files\\\\YOUAPP\\\\APPSSUBFOLDER\\\\FILE.HERE'" $FILE.Delete() } } } } Deploy LogIT
PowerShellCorpus/PoshCode/Update VM Tools_2.ps1
Update VM Tools_2.ps1
######################################################## # Created by Brian English # for Charlotte County Government # No warranty suggested or implied ######################################################## ######################################################## #connect to VirtualCenter server (i.e. virtual-center-1) if ($args[0] -eq $null) {$hostName = Read-Host "What host do you want to connect to?"} else {$hostName = $args[0]} #connect to selected Virtualcenter or host server Connect-VIServer $hostName ######################################################## #get all vms listed in virtualcenter $vms = get-vm ######################################################## #check power state on each vm #if 'On' update tools Foreach ($i in $vms) { #if virtualcenter is virtualized skip it # a system restart would stop this script if ((get-vm -name $i).Name -eq $hostname) {"Skipping " + $hostname} #if primary DC or DNS is virtualized skip it too #elseif ((get-vm -name $i).Name -eq "DNS/DC/DHCP") #{"Skipping DNS/DC/DHCP server name"} else { if ((get-vm -name $i).PowerState -eq "PoweredOn") { $i Get-Date -format "hh:mm:ss" @@ update-tools -guest (get-vmguest -vm (get-vm -name $i)) Get-Date -format "hh:mm:ss" }#if #}#if }#foreach
PowerShellCorpus/PoshCode/MetroApps Module.ps1
MetroApps Module.ps1
<# Created by: Tome Tanasovski Version: 1.0 Date: 11/2/2012 This module provides two functions: Get-MetroApp - This cmdlet reads the registry for the keys that have the launcher id and the entry point (interesting for xaml apps, but not so much for html5 apps) Start-MetroApp - This cmdlet uses one of the ids returned by Get-metroapp to launch an app in the win8 metro interface Apologies for the lack of get-help documentation, but I'll be doing a blog post about this shortly: http://powertoe.wordpress.com Original C# code modified slightly from here - also the registry info is on this page too: http://stackoverflow.com/questions/12925748/iapplicationactivationmanageractivateapplication-in-c #> $code = @" using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Win8 { public enum ActivateOptions { None = 0x00000000, // No flags set DesignMode = 0x00000001, // The application is being activated for design mode, and thus will not be able to // to create an immersive window. Window creation must be done by design tools which // load the necessary components by communicating with a designer-specified service on // the site chain established on the activation manager. The splash screen normally // shown when an application is activated will also not appear. Most activations // will not use this flag. NoErrorUI = 0x00000002, // Do not show an error dialog if the app fails to activate. NoSplashScreen = 0x00000004, // Do not show the splash screen when activating the app. } [ComImport, Guid("2e941141-7f97-4756-ba1d-9decde894a3d"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IApplicationActivationManager { // Activates the specified immersive application for the "Launch" contract, passing the provided arguments // string into the application. Callers can obtain the process Id of the application instance fulfilling this contract. IntPtr ActivateApplication([In] String appUserModelId, [In] String arguments, [In] ActivateOptions options, [Out] out UInt32 processId); IntPtr ActivateForFile([In] String appUserModelId, [In] IntPtr /*IShellItemArray* */ itemArray, [In] String verb, [Out] out UInt32 processId); IntPtr ActivateForProtocol([In] String appUserModelId, [In] IntPtr /* IShellItemArray* */itemArray, [Out] out UInt32 processId); } [ComImport, Guid("45BA127D-10A8-46EA-8AB7-56EA9078943C")]//Application Activation Manager public class ApplicationActivationManager : IApplicationActivationManager { [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)/*, PreserveSig*/] public extern IntPtr ActivateApplication([In] String appUserModelId, [In] String arguments, [In] ActivateOptions options, [Out] out UInt32 processId); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] public extern IntPtr ActivateForFile([In] String appUserModelId, [In] IntPtr /*IShellItemArray* */ itemArray, [In] String verb, [Out] out UInt32 processId); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] public extern IntPtr ActivateForProtocol([In] String appUserModelId, [In] IntPtr /* IShellItemArray* */itemArray, [Out] out UInt32 processId); } } "@ add-type -TypeDefinition $code $appman = new-object Win8.ApplicationActivationManager function Get-MetroApp { $entry = 'HKCU:\\Software\\Classes\\ActivatableClasses\\Package' foreach ($appkey in (dir $entry |select -ExpandProperty pspath)) { #$id = ((dir (join-path $appkey 'Server')) |Get-ItemProperty).appusermodelid $id = (dir (Join-Path $appkey server) |?{$_.pspath -notmatch 'BackgroundTransferHost.1'} |Get-ItemProperty).appusermodelid if ($id) { $possibleclassidkeys = dir (join-path $appkey 'ActivatableClassID') |select -ExpandProperty pspath # we look for the app key first, then app.wwa, and then any other key if neither returns an entrypoint $key = $possibleclassidkeys |?{$_ -match 'app$'} $entrypoint=$null if ($key) { if (Test-Path (join-path $key CustomAttributes)) { $entrypoint = (Get-ItemProperty (join-path $key CustomAttributes)).('appobject.entrypoint') } } if (!$entrypoint) { $key = $possibleclassidkeys |?{$_ -match 'app.wwa$'} if ($key) { if (Test-Path (join-path $key CustomAttributes)) { $entrypoint = (Get-ItemProperty (join-path $key CustomAttributes)).('appobject.entrypoint') } } } if (!$entrypoint) { foreach ($key in $possibleclassidkeys) { if (Test-Path (join-path $key CustomAttributes)) { $entrypoint = (Get-ItemProperty (join-path $key CustomAttributes)).('appobject.entrypoint') break } } } new-object psobject -Property ([ordered] @{ EntryPoint = $entrypoint ID = $id }) } } } function Start-MetroApp { param( [Parameter(Mandatory=$true, Position=0, ValueFromPipelineByPropertyName=$true)] [string] $ID ) $appman.ActivateApplication($ID,$null,[Win8.ActivateOptions]::None,[ref]0) }
PowerShellCorpus/PoshCode/New-XVM_1.ps1
New-XVM_1.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/Get-RecurseMember_2.ps1
Get-RecurseMember_2.ps1
function Get-RecurseMember { <# .Synopsis Does a recursive search for unique users that are members of an AD group. .Description Recursively gets a list of unique users that are members of the specified group, expanding any groups that are members out into their member users. Note: Requires the Quest AD Cmdlets http://www.quest.com/powershell/activeroles-server.aspx .Parameter group The name of the group. .Example PS> Get-RecurseMember 'My Domain Group' .Notes NAME: Get-RecurseMember AUTHOR: tojo2000 #Requires -Version 2.0 #> param([Parameter(Position = 0, Mandatory = $true]) [string]$group) $users = @{} try { $members = Get-QADGroupMember $group } catch [ArgumentException] { Write-Host "`n`n'$group' not found!`n" return $null } foreach ($member in $members) { if ($member.Type -eq 'user') { $users.$($member.Name.ToLower()) = $member } elseif ($member.Type -eq 'group') { foreach ($user in (Get-RecurseMember $member.Name)) { $users.$($user.Name.ToLower()) = $user } } } foreach ($user in $users.Keys | sort) { Write-Output $users.$user } }
PowerShellCorpus/PoshCode/Snippet Compiler_1.ps1
Snippet Compiler_1.ps1
#Require 2.0 $def = [Environment]::CurrentDirectory ################################################################################################## $mnuOpen_Click= { (New-Object Windows.Forms.OpenFileDialog) | % { $_.FileName = "source" $_.Filter = "C# (*.cs)|*.cs" $_.InitialDirectory = $def if ($_.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) { $sr = New-Object IO.StreamReader $_.FileName $txtEdit.Text = $sr.ReadToEnd() $sr.Close() } } } $mnuFont_Click= { (New-Object Windows.Forms.FontDialog) | % { $_.Font = "Lucida Console" $_.MinSize = 10 $_.MaxSize = 12 $_.ShowEffects = $false if ($_.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) { $txtEdit.Font = $_.Font } } } $mnuOpaF_Click= { $frmMain.Opacity = 1 $cur.Checked = $false $mnuOpaF.Checked = $true $cur = $mnuOpaF } $mnuWrap_Click= { $toggle =! $mnuWrap.Checked $mnuWrap.Checked = $toggle $txtEdit.WordWrap = $toggle } $tbTools_ButtonClick= { switch ($_.Button.Tag) { "Atom" { Invoke-Atom; break } "Progress" { Show-Panel $mnuToS1 $scSplt1; break } "Params" { Show-Panel $mnuToS2 $scSplt2; break } "Build" { Invoke-Builder; break } "BuildEx" { Start-AfterBuilding; break } "Exit" { $frmMain.Close(); break } } } $cboPlat_SelectedIndexChanged= { switch ($cboPlat.SelectedIndex) { "0" { $lboRefs.Items.Remove("`"System.Core.dll`""); break } "1" { $lboRefs.Items.Add("`"System.Core.dll`""); break } } } $chkExec_Click= { switch ($chkExec.Checked) { $true { $txtIOut.Text = $def + '\\app.exe' $chkWApp.Enabled = $true $chkIMem.Enabled = $false $mnuBnRA.Enabled = $true $btnBnRA.Enabled = $true break } $false { $txtIOut.Text = $def + '\\lib.dll' $chkWApp.Enabled = $false $chkIMem.Enabled = $true $mnuBnRA.Enabled = $false $btnBnRA.Enabled = $false break } } } $chkWApp_Click= { switch ($chkWApp.Checked) { $true { $lboRefs.Items.AddRange(@("`"System.Drawing.dll`"", "`"System.Windows.Forms.dll`"")) break } $false { $lboRefs.Items.Remove("`"System.Windows.Forms.dll`"") $lboRefs.Items.Remove("`"System.Drawing.dll`"") break } } } $mnuICnM_Click= { $script:buff = $lboRefs.SelectedItem $lboRefs.Items.Remove($lboRefs.SelectedItem) } $mnuIIns_Click= { (New-Object Windows.Forms.OpenFileDialog) | % { $_.Filter = "PE File (*.dll)|*.dll" $_.InitialDirectory = [Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory() if ($_.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) { $lboRefs.Items.Add('"' + (Split-Path -leaf $_.FileName) + '"') } } } $frmMain_Load= { $txtIOut.Text = $def + '\\app.exe' $sbPnl_2.Text = "Str: 1, Col: 0" $lboRefs.Items.Add("`"System.dll`"") } ################################################################################################## function frmMain_Show { Add-Type -AssemblyName System.Windows.Forms [Windows.Forms.Application]::EnableVisualStyles() $ico = [Drawing.Icon]::ExtractAssociatedIcon($($PSHome + '\\powershell_ise.exe')) $cdcp = New-Object CodeDom.Compiler.CompilerParameters $dict = New-Object "Collections.Generic.Dictionary[String, String]" $dict.Add("CompilerVersion", "v3.5") $frmMain = New-Object Windows.Forms.Form $mnuMain = New-Object Windows.Forms.MainMenu $mnuFile = New-Object Windows.Forms.MenuItem $mnuAtom = New-Object Windows.Forms.MenuItem $mnuOpen = New-Object Windows.Forms.MenuItem $mnuEmp1 = New-Object Windows.Forms.MenuItem $mnuExit = New-Object Windows.Forms.MenuItem $mnuEdit = New-Object Windows.Forms.MenuItem $mnuUndo = New-Object Windows.Forms.MenuItem $mnuEmp2 = New-Object Windows.Forms.MenuItem $mnuCopy = New-Object Windows.Forms.MenuItem $mnuPast = New-Object Windows.Forms.MenuItem $mnuICut = New-Object Windows.Forms.MenuItem $mnuEmp3 = New-Object Windows.Forms.MenuItem $mnuSAll = New-Object Windows.Forms.MenuItem $mnuView = New-Object Windows.Forms.MenuItem $mnuFont = New-Object Windows.Forms.MenuItem $mnuEmp4 = New-Object Windows.Forms.MenuItem $mnuOpac = New-Object Windows.Forms.MenuItem $mnuOp50 = New-Object Windows.Forms.MenuItem $mnuOp60 = New-Object Windows.Forms.MenuItem $mnuOp70 = New-Object Windows.Forms.MenuItem $mnuOp80 = New-Object Windows.Forms.MenuItem $mnuOp90 = New-Object Windows.Forms.MenuItem $mnuOpaF = New-Object Windows.Forms.MenuItem $mnuTgls = New-Object Windows.Forms.MenuItem $mnuWrap = New-Object Windows.Forms.MenuItem $mnuToS1 = New-Object Windows.Forms.MenuItem $mnuToS2 = New-Object Windows.Forms.MenuItem $mnuMake = New-Object Windows.Forms.MenuItem $mnuBAsm = New-Object Windows.Forms.MenuItem $mnuBnRA = New-Object Windows.Forms.MenuItem $mnuHelp = New-Object Windows.Forms.MenuItem $mnuInfo = New-Object Windows.Forms.MenuItem $tbTools = New-Object Windows.Forms.ToolBar $btnAtom = New-Object Windows.Forms.ToolBarButton $btnToS1 = New-Object Windows.Forms.ToolBarButton $btnMake = New-Object Windows.Forms.ToolBarButton $btnBAsm = New-Object Windows.Forms.ToolBarButton $btnBnRA = New-Object Windows.Forms.ToolBarButton $btnExit = New-Object Windows.Forms.ToolBarButton $scSplt1 = New-Object Windows.Forms.SplitContainer $scSplt2 = New-Object Windows.Forms.SplitContainer $lstView = New-Object Windows.Forms.ListView $chPoint = New-Object Windows.Forms.ColumnHeader $chError = New-Object Windows.Forms.ColumnHeader $chCause = New-Object Windows.Forms.ColumnHeader $txtEdit = New-Object Windows.Forms.RichTextBox $gboMake = New-Object Windows.Forms.GroupBox $lblLab1 = New-Object Windows.Forms.Label $cboPlat = New-Object Windows.Forms.ComboBox $chkExec = New-Object Windows.Forms.CheckBox $chkWApp = New-Object Windows.Forms.CheckBox $chkIDbg = New-Object Windows.Forms.CheckBox $chkIMem = New-Object Windows.Forms.CheckBox $lblLab2 = New-Object Windows.Forms.Label $txtIOut = New-Object Windows.Forms.TextBox $lblLab3 = New-Object Windows.Forms.Label $lboRefs = New-Object Windows.Forms.ListBox $sbPanel = New-Object Windows.Forms.StatusBar $sbPnl_1 = New-Object Windows.Forms.StatusBarPanel $sbPnl_2 = New-Object Windows.Forms.StatusBarPanel $imgList = New-Object Windows.Forms.ImageList $mnuRefs = New-Object Windows.Forms.ContextMenu $mnuIMov = New-Object Windows.Forms.MenuItem $mnuICnM = New-Object Windows.Forms.MenuItem $mnuIBuf = New-Object Windows.Forms.MenuItem $mnuIIns = New-Object Windows.Forms.MenuItem # #mnuMain # $mnuMain.MenuItems.AddRange(@($mnuFile, $mnuEdit, $mnuView, $mnuMake, $mnuHelp)) # #mnuFile # $mnuFile.MenuItems.AddRange(@($mnuAtom, $mnuOpen, $mnuEmp1, $mnuExit)) $mnuFile.Text = "&File" # #mnuAtom # $mnuAtom.Shortcut = "F3" $mnuAtom.Text = "Nu&Clear..." $mnuAtom.Add_Click({Invoke-Atom}) # #mnuOpen # $mnuOpen.Shortcut = "CtrlO" $mnuOpen.Text = "&Open" $mnuOpen.Add_Click($mnuOpen_Click) # #mnuEmp1 # $mnuEmp1.Text = "-" # #mnuExit # $mnuExit.Shortcut = "CtrlX" $mnuExit.Text = "E&xit" $mnuExit.Add_Click({$frmMain.Close()}) # #mnuEdit # $mnuEdit.menuItems.AddRange(@($mnuUndo, $mnuEmp2, $mnuCopy, $mnuPast, $mnuICut, ` $mnuEmp3, $mnuSAll)) $mnuEdit.Text = "&Edit" # #mnuUndo # $mnuUndo.Shortcut = "CtrlZ" $mnuUndo.Text = "&Undo" $mnuUndo.Add_Click({$txtEdit.Undo()}) # #mnuEmp2 # $mnuEmp2.Text = "-" # #mnuCopy # $mnuCopy.Shortcut = "CtrlC" $mnuCopy.Text = "&Copy" $mnuCopy.Add_Click({if ($txtEdit.SelectionLength -ge 0) {$txtEdit.Copy()}}) # #mnuPast # $mnuPast.Shortcut = "CtrlV" $mnuPast.Text = "&Paste" $mnuPast.Add_Click({$txtEdit.Paste()}) # #mnuICut # $mnuICut.Shortcut = "Del" $mnuICut.Text = "Cut &Item" $mnuICut.Add_Click({if ($txtEdit.SelectionLength -ge 0) {$txtEdit.Cut()}}) # #mnuEmp3 # $mnuEmp3.Text = "-" # #mnuSAll # $mnuSAll.Shortcut = "CtrlA" $mnuSAll.Text = "Select &All" $mnuSAll.Add_Click({$txtEdit.SelectAll()}) # #mnuView # $mnuView.MenuItems.AddRange(@($mnuFont, $mnuEmp4, $mnuOpac, $mnuTgls)) $mnuView.Text = "&View" # #mnuFont # $mnuFont.Text = "&Font..." $mnuFont.Add_Click($mnuFont_Click) # #mnuEmp4 # $mnuEmp4.Text = "-" # #mnuOpac # $mnuOpac.MenuItems.AddRange(@($mnuOp50, $mnuOp60, $mnuOp70, $mnuOp80, $mnuOp90, $mnuOpaF)) $mnuOpac.Text = "&Opacity" # #mnuOp50 # $mnuOp50.Text = "50%" $mnuOp50.Add_Click({Set-Opacity $mnuOp50; $cur = $mnuOp50}) # #mnuOp60 # $mnuOp60.Text = "60%" $mnuOp60.Add_Click({Set-Opacity $mnuOp60; $cur = $mnuOp60}) # #mnuOp70 # $mnuOp70.Text = "70%" $mnuOp70.Add_Click({Set-Opacity $mnuOp70; $cur = $mnuOp70}) # #mnuOp80 # $mnuOp80.Text = "80%" $mnuOp80.Add_Click({Set-Opacity $mnuOp80; $cur = $mnuOp80}) # #mnuOp90 # $mnuOp90.Text = "90%" $mnuOp90.Add_Click({Set-Opacity $mnuOp90; $cur = $mnuOp90}) # #mnuOpaF # $cur = $mnuOpaF #checked item by default $mnuOpaF.Checked = $true $mnuOpaF.Text = "Opaque" $mnuOpaF.Add_Click($mnuOpaF_Click) # #mnuTgls # $mnuTgls.MenuItems.AddRange(@($mnuWrap, $mnuToS1, $mnuToS2)) $mnuTgls.Text = "&Toggles" # #mnuWrap # $mnuWrap.Checked = $true $mnuWrap.Shortcut = "CtrlW" $mnuWrap.Text = "&Wrap Mode" $mnuWrap.Add_Click($mnuWrap_Click) # #mnuToS1 # $mnuToS1.Checked = $true $mnuToS1.Text = "Building &Progress" $mnuToS1.Add_Click({Show-Panel $mnuToS1 $scSplt1}) # #mnuToS2 # $mnuToS2.Checked = $true $mnuToS2.Shortcut = "F12" $mnuToS2.Text = "Building P&roperties" $mnuToS2.Add_Click({Show-Panel $mnuToS2 $scSplt2}) # #mnuMake # $mnuMake.MenuItems.AddRange(@($mnuBAsm, $mnuBnRA)) $mnuMake.Text = "&Build" # #mnuBAsm # $mnuBAsm.Shortcut = "F5" $mnuBAsm.Text = "&Compile" $mnuBAsm.Add_Click({Invoke-Builder}) # #mnuBnRA # $mnuBnRA.Shortcut = "F9" $mnuBnRA.Text = "Compile And &Run" $mnuBnRA.Add_Click({Start-AfterBuilding}) # #mnuHelp # $mnuHelp.MenuItems.AddRange(@($mnuInfo)) $mnuHelp.Text = "&Help" # #mnuInfo # $mnuInfo.Text = "About..." $mnuInfo.Add_Click({frmInfo_Show}) # #tbTools # $tbTools.Buttons.AddRange(@($btnAtom, $btnToS1, $btnMake, $btnBAsm, $btnBnRA, $btnExit)) $tbTools.ImageList = $imgList $tbTools.Add_ButtonClick($tbTools_ButtonClick) # #btnAtom # $btnAtom.ImageIndex = 0 $btnAtom.Tag = "Atom" $btnAtom.ToolTipText = "NuClear (F3)" # #btnToS1 # $btnToS1.ImageIndex = 1 $btnToS1.Tag = "Progress" $btnToS1.ToolTipText = "Building Progress Panel" # #btnMake # $btnMake.ImageIndex = 2 $btnMake.Tag = "Params" $btnMake.ToolTipText = "Building Properties (F12)" # #btnBAsm # $btnBAsm.ImageIndex = 3 $btnBAsm.Tag = "Build" $btnBAsm.ToolTipText = "Compile (F5)" # #btnBnRA # $btnBnRA.ImageIndex = 4 $btnBnRA.Tag = "BuildEx" $btnBnRA.ToolTipText = "Compile And Run (F9)" # #btnExit # $btnExit.ImageIndex = 5 $btnExit.Tag = "Exit" $btnExit.ToolTipText = "Exit (Ctrl+X)" # #scSplt1 # $scSplt1.Anchor = "Left, Top, Right, Bottom" $scSplt1.Location = New-Object Drawing.Point(0, 28) $scSplt1.Orientation = "Horizontal" $scSplt1.Panel1.Controls.Add($scSplt2) $scSplt1.Panel2.Controls.Add($lstView) $scSplt1.Size = New-Object Drawing.Size(790, 500) $scSplt1.SplitterDistance = 410 $scSplt1.SplitterWidth = 1 # #scSplt2 # $scSplt2.Dock = "Fill" $scSplt2.Panel1.Controls.Add($txtEdit) $scSplt2.Panel2.Controls.Add($gboMake) $scSplt2.SplitterDistance = 510 $scSplt2.SplitterWidth = 1 # #lstView # $lstView.Columns.AddRange(@($chPoint, $chError, $chCause)) $lstView.Dock = "Fill" $lstView.FullRowSelect = $true $lstView.GridLines = $true $lstView.MultiSelect = $false $lstView.ShowItemToolTips = $true $lstView.SmallImageList = $imgList $lstView.View = "Details" # #chPoint # $chPoint.Text = "Line" $chPoint.Width = 50 # #chError # $chError.Text = "Error" $chError.TextAlign = "Right" $chError.Width = 65 # #chCause # $chCause.Text = "Description" $chCause.Width = 650 # #txtEdit # $txtEdit.AcceptsTab = $true $txtEdit.Dock = "Fill" $txtEdit.Font = New-Object Drawing.Font("Courier New", 10) $txtEdit.ScrollBars = "Both" $txtEdit.Add_Click({Write-CursorPoint}) $txtEdit.Add_KeyUp({Write-CursorPoint}) $txtEdit.Add_TextChanged({Write-CursorPoint}) # #gboMake # $gboMake.Controls.AddRange(@($lblLab1, $cboPlat, $chkExec, $chkWApp, $chkIDbg, ` $chkIMem, $lblLab2, $txtIOut, $lblLab3, $lboRefs)) $gboMake.Dock = "Fill" $gboMake.Text = "Building Parameters" # #lblLab1 # $lblLab1.Location = New-Object Drawing.Point(21, 33) $lblLab1.Text = "Platform:" $lblLab1.Width = 50 # #cboPlat # $cboPlat.Anchor = "Left, Top, Right" $cboPlat.Items.AddRange(@(".NET Framework 2.0", ".NET Framework 3.5")) $cboPlat.Location = New-Object Drawing.Point(71, 30) $cboPlat.SelectedItem = ".NET Framework 2.0" $cboPlat.Width = 180 $cboPlat.Add_SelectedIndexChanged($cboPlat_SelectedIndexChanged) # #chkExec # $chkExec.Checked = $true $chkExec.Location = New-Object Drawing.Point(23, 63) $chkExec.Text = "Create Executable" $chkExec.Width = 120 $chkExec.Add_Click($chkExec_Click) # #chkWApp # $chkWApp.Location = New-Object Drawing.Point(43, 83) $chkWApp.Text = "Windows Application" $chkWApp.Width = 130 $chkWApp.Add_Click($chkWApp_Click) # #chkIDbg # $chkIDbg.Checked = $true $chkIDbg.Location = New-Object Drawing.Point(23, 103) $chkIDbg.Text = "Include Debug Information" $chkIDbg.Width = 157 # #chkIMem # $chkIMem.Enabled = $false $chkIMem.Location = New-Object Drawing.Point(23, 123) $chkIMem.Text = "Building In Memory" $chkIMem.Width = 130 # #lblLab2 # $lblLab2.Location = New-Object Drawing.Point(23, 163) $lblLab2.Text = "Output:" $lblLab2.Width = 45 # #txtIOut # $txtIOut.Anchor = "Left, Top, Right" $txtIOut.Location = New-Object Drawing.Point(71, 160) $txtIOut.Width = 180 # #lblLab3 # $lblLab3.Location = New-Object Drawing.Point(23, 203) $lblLab3.Size = New-Object Drawing.Size(70, 17) $lblLab3.Text = "References:" # #lboRefs # $lboRefs.Anchor = "Left, Top, Right, Bottom" $lboRefs.ContextMenu = $mnuRefs $lboRefs.Location = New-Object Drawing.Point(23, 223) $lboRefs.SelectionMode = "One" $lboRefs.Size = New-Object Drawing.Size(229, 157) # #sbPanle # $sbPanel.Panels.AddRange(@($sbPnl_1, $sbPnl_2)) $sbPanel.ShowPanels = $true $sbPanel.SizingGrip = $false # #sbPnl_1 # $sbPnl_1.AutoSize = "Spring" # #sbPnl_2 # $sbPnl_2.Alignment = "Center" $sbPnl_2.AutoSize = "Contents" # #imgList # $i_1, $i_2, $i_3, $i_4, $i_5, $i_6, $i_7, $i_8 | % { $imgList.Images.Add((Get-Image $_)) } # #mnuRefs # $mnuRefs.MenuItems.AddRange(@($mnuIMov, $mnuICnM, $mnuIBuf, $mnuIIns)) # #mnuIMov # $mnuIMov.Shortcut = "Del" $mnuIMov.Text = "Remove Item" $mnuIMov.Add_Click({$lboRefs.Items.Remove($lboRefs.SelectedItem)}) # #mnuICnM # $mnuICnM.Shortcut = "CtrlM" $mnuICnM.Text = "Copy And Remove" $mnuICnM.Add_Click($mnuICnM_Click) # #mnuIBuf # $mnuIBuf.Text = "Insert Copied..." $mnuIBuf.Add_Click({if ($script:buff -ne $null) {$lboRefs.Items.Add($script:buff)}}) # #mnuIIns # $mnuIIns.Shortcut = "CtrlR" $mnuIIns.Text = "Add Reference" $mnuIIns.Add_Click($mnuIIns_Click) # #frmMain # $frmMain.ClientSize = New-Object Drawing.Size(790, 550) $frmMain.Controls.AddRange(@($tbTools, $scSplt1, $sbPanel)) $frmMain.FormBorderStyle = "FixedSingle" $frmMain.Icon = $ico $frmMain.Menu = $mnuMain $frmMain.StartPosition = "CenterScreen" $frmMain.Text = "Snippet Compiler" $frmMain.Add_Load($frmMain_Load) [void]$frmMain.ShowDialog() } ################################################################################################## function frmInfo_Show { $frmInfo = New-Object Windows.Forms.Form $pbImage = New-Object Windows.Forms.PictureBox $lblName = New-Object Windows.Forms.Label $lblCopy = New-Object Windows.Forms.Label $btnExit = New-Object Windows.Forms.Button # #pbImage # $pbImage.Location = New-Object Drawing.Point(16, 16) $pbImage.Size = New-Object Drawing.Size(32, 32) $pbImage.SizeMode = "StretchImage" # #lblName # $lblName.Font = New-Object Drawing.Font("Microsoft Sans Serif", 8, [Drawing.FontStyle]::Bold) $lblName.Location = New-Object Drawing.Point(53, 19) $lblName.Size = New-Object Drawing.Size(360, 18) $lblName.Text = "Snippet Compiler v2.53" # #lblCopy # $lblCopy.Location = New-Object Drawing.Point(67, 37) $lblCopy.Size = New-Object Drawing.Size(360, 23) $lblCopy.Text = "(C) 2012-2013 greg zakharov gregzakh@gmail.com" # #btnExit # $btnExit.Location = New-Object Drawing.Point(135, 67) $btnExit.Text = "OK" # #frmInfo # $frmInfo.AcceptButton = $btnExit $frmInfo.CancelButton = $btnExit $frmInfo.ClientSize = New-Object Drawing.Size(350, 110) $frmInfo.ControlBox = $false $frmInfo.Controls.AddRange(@($pbImage, $lblName, $lblCopy, $btnExit)) $frmInfo.ShowInTaskBar = $false $frmInfo.StartPosition = "CenterScreen" $frmInfo.Text = "About..." $frmInfo.Add_Load({$pbImage.Image = $ico.ToBitmap()}) [void]$frmInfo.ShowDialog() } ################################################################################################## function Invoke-Atom { if ($txtEdit.Text -ne "") { $res = [Windows.Forms.MessageBox]::Show("Do you want to save data before?", ` $frmMain.Text, [Windows.Forms.MessageBoxButtons]::YesNoCancel, ` [Windows.Forms.MessageBoxIcon]::Question) switch ($res) { 'Yes' { (New-Object Windows.Forms.SaveFileDialog) | % { $_.FileName = "source" $_.Filter = "C# (*.cs)|*.cs" $_.InitialDirectory = $def if ($_.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) { Out-File $_.FileName -enc UTF8 -input $txtEdit.Text } } break } 'No' { $txtEdit.Clear(); break } 'Cancel' { return } } }#if } function Set-Opacity($obj) { $cur.Checked = $false $frmMain.Opacity = [float]('.' + $($obj.Text)[0]) $obj.Checked = $true } function Show-Panel($obj1, $obj2) { switch ($obj1.Checked) { $true {$obj1.Checked = $false; $obj2.Panel2Collapsed = $true; break } $false {$obj1.Checked = $true; $obj2.Panel2Collapsed = $false; break } } } function Get-CursorPoint { $z = $txtEdit.SelectionStart $y = $txtEdit.GetLineFromCharIndex($z) + 1 $x = $z - $txtEdit.GetFirstCharIndexOfCurrentLine() return (New-Object Drawing.Point($x, $y)) } function Write-CursorPoint { $sbPnl_2.Text = 'Str: ' + (Get-CursorPoint).Y.ToString() + ', Col: ' + ` (Get-CursorPoint).X.ToString() } function Invoke-Builder { $lstView.Items.Clear() if ($txtEdit.Text -ne "") { switch ($cboPlat.SelectedIndex) { "0" { $cscp = New-Object Microsoft.CSharp.CSharpCodeProvider; break } "1" { $cscp = New-Object Microsoft.CSharp.CSharpCodeProvider($dict); break} } $cdcp.GenerateExecutable = $chkExec.Checked if ($chkWApp.Checked) { $cdcp.CompilerOptions = "/t:winexe" } $cdcp.IncludeDebugInformation = $chkIDbg.Checked $cdcp.GenerateInMemory = $chkIMem.Checked if ($lboRefs.Items.Count -ne 0) { for ($i = 0; $i -lt $lboRefs.Items.Count; $i++) { $cdcp.ReferencedAssemblies.Add($lboRefs.Items[$i].ToString()) } } $cdcp.WarningLevel = 3 $cdcp.OutputAssembly = $txtIOut.Text $script:make = $cscp.CompileAssemblyFromSource($cdcp, $txtEdit.Text) $make.Errors | % { if ($_.Line -ne 0 -and $_.Column -ne 0) { $err = $_.Line.ToString() + ', ' + ($_.Column - 1).ToString() } elseif ($_.Line -ne 0 -and $_.Column -eq 0) { $err = $_.Line.ToString() + ', 0' } elseif ($_.Line -eq 0 -and $_.Column -eq 0) { $err = '*' } if (!($_.IsWarning)) { $lstView.ForeColor = [Drawing.Color]::Crimson $itm = $lstView.Items.Add($err, 6) } else { $lstView.ForeColor = [Drawing.Color]::Gray $itm = $lstView.Items.Add($err, 7) } $itm.SubItems.Add($_.ErrorNumber) $itm.SubItems.Add($_.ErrorText) } }#if } function Start-AfterBuilding { Invoke-Builder if ($script:make.Errors.Count -eq 0) { Invoke-Item $txtIOut.Text } } function Get-Image($img) { [Drawing.Image]::FromStream((New-Object IO.MemoryStream(($$ = ` [Convert]::FromBase64String($img)), 0, $$.Length))) } ################################################################################################## # #do not modify or remove this because these are images for toolbar and lower panel # $i_1 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAARCAIAAACNaGH2AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + ` "AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAVFJREFUOE91kTGOgzAQRc2ZOA" + ` "s9lU+Uxj1lak7hMtJKVCjalSIZkpiEVbSN980Y2GijjEaDgTff3+PiNs/GmJQKKk+txuhboR9TsX7kCd22rXP" + ` "eeU/d7/eydr5pGuput6NO8yx5n810/4Z7vMT1kUjrCJod9G2h3XvaOp8ScqW1St8iTt5qW1dVVV3XpXXxHoVm" + ` "r3+0ejCDhveiTYPQcYqcbKN/wof+ddCkXyLhJE5XodFGjAaffIaeE21aVjqODCvTWYzd+75nXcqroATu4zSaG" + ` "Ee0IWjw3mbHzEE75UtusJwS+hIHxgkkB1KIPBwOyHddt/aIk8s1LDQc9KtpvWIJJij0+XzievOkqHi11ujdO7" + ` "Q336J9PgnNfW2j5ffz4NYJim+hx/EL7U0Dx8veG7hOcBw+heaU2GIvar7kvNYqiTATFDqE418Ox6A55AySz8A" + ` "v1EEhBG84RKcAAAAASUVORK5CYII=" $i_2 = "iVBORw0KGgoAAAANSUhEUgAAABIAAAARCAIAAABfOGuuAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + ` "AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAOVJREFUOE+VkUEOgyAQRfFMnM" + ` "NrzJ3Yu3TtKTiEaVOTFgICXXQ3nQG1xjapkOEzII8vQ5OeSQiB1IVoysBZGZY5Yp4vi7QNBWFKoVJ6U8g5Kaw" + ` "qQUuFrMCaUlwxjeoQfBbBHFtCZxEWV0wDMd8mbMj71iiGGYvRE/A63SRAiI6xYRiIwnNNyoxRL27nKPpPCCFj" + ` "1W6MzabOTcIcDGN93+dX+h9aa7obY94/6iopwfs7Y13XVZRkwdxUdzcA527Cu6nWjTFrr3VuEqy9MEZuVB96R" + ` "9ZfSdu2n3XImDHjFtaM+9h/OuRvranSBDuoeeYAAAAASUVORK5CYII=" $i_3 = "iVBORw0KGgoAAAANSUhEUgAAABIAAAAQCAIAAACUZLgLAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + ` "AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAWJJREFUOE+FkTFywjAQRcUROI" + ` "sqWnpKeirVHIFD0OwdqDnFnsANZiZFEguwncad8tYCm2Bmovksa3nffq08a38aN13psTXLyeM5/7MJ9kdtoyK" + ` "qBFbY7/fE3W4nIRyPR1EJGsxpiqUk2+02pWDSe1QNEjwtIA1r2muvS1ZZljQGoGJgLFGP2PTiKTPMOgiFmg9H" + ` "UWYWi0UPBFWv4pO4EaubyCyiSTUxTeL0wXOkzWaD53K5BOjlcPJIPIjjhw8M09MYhi5E8tVqxcG8d/P5nLher" + ` "/vXhri6/sKk67oYIzdBJKcNRZgAYEtBXX8iEh8MGTGqn9fhcOBURVHQCNuMAWS52816vDA81l0C0GQz40zZs0" + ` "bMvqYoQE6Yl0gO7EN4xa7Xj6lbtjI3bjglDkmZ6XKXG7DBLZsMhpBvsBjPb93G2Xq3SzyjGEtTdXZg3DsvmJv" + ` "4nOTHvF6xqjr9r+9TlfUo/gXNq15sSG6qYQAAAABJRU5ErkJggg==" $i_4 = "iVBORw0KGgoAAAANSUhEUgAAABQAAAARCAIAAABSJhvpAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + ` "AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAARRJREFUOE9tklFuxCAMROH+J9" + ` "jTNU1VabUQAmT/qc3AwNJYoyQEPzwYbH5fthRTo1iLN4a26LD0oYyRhFkNga8rQ/JdlR8PUzSMfEA1M6kkrUt" + ` "+yaDRzKuw8sDmGJWuPGBWa1uoldXmPwvNpsL5zDmIWA01p2ezQF8pB2jAUmR2C8NYAlMIkgqndMQURFgY+8ST" + ` "/LLtqMghYINnz51p3eIW2PkBx+hifLFb7DDOic7nY0vpJRLKANavGkhiKrq92B7weT6p5WB6WWXZsI98Dmbny" + ` "zktV20UC+H3rGLP6B+GedXYf0EgQ1j4eW+8WMuGSSrs/c/h90W3Bb3fq7679ntY1loKyp8b2LltkXfbrGn2y7" + ` "lZ2x9XMW8UGH69+AAAAABJRU5ErkJggg==" $i_5 = "iVBORw0KGgoAAAANSUhEUgAAABIAAAAQCAIAAACUZLgLAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + ` "AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAhNJREFUOE9jfPPyBgMZAKgNju" + ` "o2nlWtXqVVtQpOAhnIKGDqbohiBmQ9fXuv77rzbsOdtxC08dY7NLTu0tvgaXtQtOk3rQcq7Tv5BEheePFx4rm" + ` "X7SefQ1DrcRC7+9TLxVdfuEzdiaIN6IAZpx/V7r0F1Pbr77/7H382HH9eeugpEBXvA6GmA89699/OX3ISRVve" + ` "irNAPambrhXvubPzwXugznOvvmYffJq0/SEQxa+/V7ntYeHasyh+q1x3unLzhYTV53wWnw1afSVpx929jz8Bd" + ` "a66+8Fu8W3TKZd0u85FzbvqO20fijagC4Ha3OccNZ9+zGTOOasll6P2PHjx9fenn39MZ1xTaTqjUnEideYls9" + ` "aNKNqAoQx0pFbHTo2+Q0BtufsfPv3yC+i92A13gfYA9egWHMxfchFdm23Xlri5B4DarOadAAYX0HnAgHFdegP" + ` "oPL3mM5oVx8zKjhStuARUg2Jb1Kx9QTP3WE/bBwx6oMMaD98LX3sdEmnAuAIit8ZjQOd0br+I0Na27ULB4iPu" + ` "E7YA42T5hYdBi0+Y9O/3n3fmwL13Jx992nH9HRAFdZ0On30YnjZAqQRodeXyg5b1yzTKFwERMHEBkXbtLuPmg" + ` "0BkUHkE6DFgeAA9gqINmF6m7blQtfJQ/sL9+YsPAW0GxikYXYSg0mVXJ+6+DQw2FG1ADlAnWqpF40KSIro2ZC" + ` "Fi2ACR3EDpQ7cspgAAAABJRU5ErkJggg==" $i_6 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAANCAIAAAD5fKMWAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + ` "AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAJxJREFUKFONjEEOwyAMBMn/P5" + ` "lD1FSCENt5QLpgcA1tpaI52LtjFrk42LvvMi59r9uwwn4jJOAqwAS2llAoMCegHUsq9LWFVVAG22odADm12hS" + ` "JGyb1s8ioICgcBxudP8A620RPz/T91IZPG4m/8UI4z92AVOcH8AeaoPppfzvYQ86bgs/ysQ3U0ED1l91+hJ3i" + ` "mlLjiCsoidJzG15Z2J4gUYDWoQAAAABJRU5ErkJggg==" $i_7 = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + ` "AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAsZJREFUOE9FkmtIk1EYx9/nvH" + ` "u3V+dUyltIIaI5DAsiyy5SlphmCprpirnp8MWaoEikXwzayrQgzTLtQ0hN0UIssyQv1AcnQnMaXlIzTDOsvG7" + ` "OnG7qTmdq+vBwLpzf/znP4fwBY0z9D6O+k6qpdlha5lOwsri4zDI2eSqz/4DQyWmLoYiAhNlg+JsQjzkOFxXh" + ` "ykpcUYELCnBGBo6Onj1xfH5iYgOzV9+gLafDcGoqVqlwYSHOzcUKBU5JsWd8PA4NnQvY211fty2Yi47CERE2i" + ` "eRDerotONjm7W1xdV11d1/192+NicFBQSaxWO/jM/Fz3H7DtE5nDgzEISHNKtXIzExTVtYUwC+A3wBPpFL96K" + ` "g2O9vg5TXg6VkadtIuGEpKMPj62vz8Rjhu1mIxLi015+aOATy7cvWP0UiIaaXyh0jU6eKicXXt7+ulevcFjnl" + ` "4kBqTLNsnkxms1sWVlX6t1mQ2E3qc477weH1CYZujY4ODw7VMJdW+c0ePs/N3F5dhgaAfoFuWvGyzEXQN428K" + ` "hQ5AzzA6gaCVz28QCKRxsVSrl6eWZT+zbA+f3wVQl5NjXSMwJqI2tbodoJ2mP/J4r2i6imEuno+img4famSYN" + ` "ob5hFCJXD41P0/oSY1mBeMFq/VldnYLQANCGoTu03RSQhzVVVJcw+O9BXisVE6uv7KP494BdHCcaXXVZLHU5+" + ` "VVkVOaTqbp/PyblMlorBYKNQCNEgmp2p2W9hrgDUJkbJHLib41MfEBwD2EgtzchgYH7D/dUV5WjlAZQK1Y/By" + ` "gmiRClQBPAaoCAu4C5CMUSdPy5Eub1iDTe7W6mHQJUAJQShoAeAhAtvkAKoBYhI4dPTK/3vCm+ciq/lHJDZHo" + ` "DkK3AW6tcyQzETrIspFnw41Gw7aXtpw4/HXwuuyyNFB8YZfXOU+PkD27w8+cqq19sbBg2mL+AY/qjcgixtNMA" + ` "AAAAElFTkSuQmCC" $i_8 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAIAAAC0tAIdAAAABGdBTUEAALGPC/xhBQAAAglJREFUKFN1jktoE" + ` "1EUhufMTCbJNNNFS01xZ9GFCCIYhBYUF1XR7nygSxvRVSS6kbQoEoklYggUiuJj300NkRpsXdqNZhHRpp1ETW" + ` "LSdJJ08piZmFGbx3EmDdoUvfxc/vvf/3wcArtPsXir2bBUq+bZ2Vc7vrQnsT1S1ZKYB0Rbq8F5vSM8n9wx0NU" + ` "uCK6axCCy2ByURMbhmPlvW1XLxQy5keu96aAWFqxYZ+65j6XT69sH/rILmQlVNLjdrBn2HRiyYbO/+M3k8wX+" + ` "0VZrlQ2exp/c00cMRx4ZGz6E2NeSmTuu0UpF+TPQYeeTt6spAypsOgZDg+efePejQuMPq7DM+v3BrrZak3IRQ" + ` "73QgwKJMowcvLwU6kcBUB1orFOuGyclqYPX2YWEW4pSKFowDViGC2eGy3FK9zlTq9SXCfdMT7/cwhP6xmFjY4" + ` "3DFI0JwAyEnlkxC7r/Cvh9dzNJTzpPyW08kefvKhEasxzGAD+DEqPck8Z3QbNejQOmTCjuyi6x/jaeyL811WM" + ` "s8hSuAPLwYIKxGPeeOHwa10BPooD5gUaUctrHZFkhsm/gV4Ta/EBqqn8kl+eNo7aj4cDVehQ64Se69p5afL5n" + ` "5vFr4st878ocuToHW4oHQFiERBBWX3QSLcyESNe142fPTRGKrDiv++zjnivj93XZNeNp35pvJ7o8Fy89LJWk3" + ` "9PM0i5eafwSAAAAAElFTkSuQmCC" ################################################################################################## frmMain_Show
PowerShellCorpus/PoshCode/Invoke-NamedParameter_1.ps1
Invoke-NamedParameter_1.ps1
Function Invoke-NamedParameter { <# .SYNOPSIS Invokes a method using named parameters. .DESCRIPTION A function that simplifies calling methods with named parameters to make it easier to deal with long signatures and optional parameters. This is particularly helpful for COM objects. .PARAMETER Object The object that has the method. .PARAMETER Method The name of the method. .PARAMETER Parameter A hashtable with the names and values of parameters to use in the method call. .PARAMETER Argument An array of arguments without names to use in the method call. .NOTES Name: Invoke-NamedParameter Author: Jason Archer DateCreated: 2011-04-06 1.0 - 2011-04-06 - Jason Archer Initial release. .EXAMPLE $shell = New-Object -ComObject Shell.Application Invoke-NamedParameter $Shell "Explore" @{"vDir"="$pwd"} Description ----------- Invokes a method named "Explore" with the named parameter "vDir." #> [CmdletBinding(DefaultParameterSetName = "Named")] param( [Parameter(ParameterSetName = "Named", Position = 0, Mandatory = $true)] [Parameter(ParameterSetName = "Positional", Position = 0, Mandatory = $true)] [ValidateNotNull()] [System.Object]$Object , [Parameter(ParameterSetName = "Named", Position = 1, Mandatory = $true)] [Parameter(ParameterSetName = "Positional", Position = 1, Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$Method , [Parameter(ParameterSetName = "Named", Position = 2, Mandatory = $true)] [ValidateNotNull()] [Hashtable]$Parameter , [Parameter(ParameterSetName = "Positional")] [Object[]]$Argument ) end { ## Just being explicit that this does not support pipelines if ($PSCmdlet.ParameterSetName -eq "Named") { ## Invoke method with parameter names ## Note: It is ok to use a hashtable here because the keys (parameter names) and values (args) ## will be output in the same order. We don't need to worry about the order so long as ## all parameters have names $Object.GetType().InvokeMember($Method, [System.Reflection.BindingFlags]::InvokeMethod, $null, ## Binder $Object, ## Target ([Object[]]($Parameter.Values)), ## Args $null, ## Modifiers $null, ## Culture ([String[]]($Parameter.Keys)) ## NamedParameters ) } else { ## Invoke method without parameter names $Object.GetType().InvokeMember($Method, [System.Reflection.BindingFlags]::InvokeMethod, $null, ## Binder $Object, ## Target $Argument, ## Args $null, ## Modifiers $null, ## Culture $null ## NamedParameters ) } } } <# Examples Calling a method with named parameters. $shell = New-Object -ComObject Shell.Application Invoke-NamedParameters $Shell "Explore" @{"vDir"="$pwd"} The syntax for more than one would be @{"First"="foo";"Second"="bar"} Calling a method that takes no parameters (you can also use -Argument with $null). $shell = New-Object -ComObject Shell.Application Invoke-NamedParameters $Shell "MinimizeAll" @{} #>
PowerShellCorpus/PoshCode/FuncionInfo_2.types.ps1xml.ps1
FuncionInfo_2.types.ps1xml.ps1
<?xml version="1.0" encoding="utf-8" ?> <Types> <Type> <Name>System.Management.Automation.FunctionInfo</Name> <Members> <ScriptProperty> <Name>Verb</Name> <GetScriptBlock> if ($this.Name.Contains("-")) { $this.Name.Substring(0,$this.Name.Indexof("-")) } else { $null } </GetScriptBlock> </ScriptProperty> <ScriptProperty> <Name>Noun</Name> <GetScriptBlock> if ($this.Name.Contains("-")){ $this.Name.Substring(($this.Name.Indexof("-")+1),($this.Name.length - ($this.Name.Indexof("-")+1))) } else { $this.Name } </GetScriptBlock> </ScriptProperty> <ScriptProperty> <Name>Prefix</Name> <GetScriptBlock> $prefix_val = $((gmo $this.Module).ExportedFunctions.Values + (gcm -mo $this.ModuleName -CommandType "Function") | where { $_.Verb -eq $this.Verb } | group { $_.Definition } | % { $names = $_.Group | Select -Expand Name; $ofs = "-"; $verb,[string]$noun = @($names)[0] -split "-"; foreach($name in $names){ if ( $name.contains("-") ) { $name.substring($name.IndexOf("-") + 1, $name.LastIndexOf($noun) - $name.IndexOf("-") - 1 ) } } } | where {$_} | select -unique | foreach { $_ | where {$this.Noun -match $_ } }) if ( $prefix_val ) { $prefix_val } else { $null } </GetScriptBlock> </ScriptProperty> <ScriptProperty> <Name>InternalName</Name> <GetScriptBlock> $prefix = $this.Prefix if ($prefix) { "$($this.Verb)-$($this.Noun.Replace($prefix, $null))" } else { "$($this.Name)" } </GetScriptBlock> </ScriptProperty> </Members> </Type> </Types>
PowerShellCorpus/PoshCode/Get-MachineStartupShutdo.ps1
Get-MachineStartupShutdo.ps1
##############################################################################\n##\n## Get-MachineStartupShutdownScript\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\nGet the startup or shutdown scripts assigned to a machine\n\n.EXAMPLE\n\nGet-MachineStartupShutdownScript -ScriptType Startup\nGets startup scripts for the machine\n\n#>\n\nparam(\n ## The type of script to search for: Startup, or Shutdown.\n [Parameter(Mandatory = $true)]\n [ValidateSet("Startup","Shutdown")]\n $ScriptType\n)\n\nSet-StrictMode -Version Latest\n\n## Store the location of the group policy scripts for the machine\n$registryKey = "HKLM:\\SOFTWARE\\Policies\\Microsoft\\Windows\\System\\Scripts"\n\n## There may be no scripts defined\nif(-not (Test-Path $registryKey))\n{\n return\n}\n\n## Go through each of the policies in the specified key\nforeach($policy in Get-ChildItem $registryKey\\$scriptType)\n{\n ## For each of the scripts in that policy, get its script name\n ## and parameters\n foreach($script in Get-ChildItem $policy.PsPath)\n {\n Get-ItemProperty $script.PsPath | Select Script,Parameters\n }\n}
PowerShellCorpus/PoshCode/Get-MySqlDataSet.ps1
Get-MySqlDataSet.ps1
# Get-MySQLDataSet - Query a MySQL server & return the result to a PoSh variable # Created: 11/29/07 Modified: 11/29/07 # Written by: Matt Wilson (Kemis / Matt at ClearChoiceIT dot com) with MAJOR help from # Joel Bennett (Jaykul): http://powershellcentral.com/scripts/57 # Andrew Dashin: http://andrewdashin.com/powershell-mysql.aspx # Robbie Foust (rfoust): http://posh.jaykul.com/p/588 # And many, many more in the #Powershell freenode IRC channel! ################################################################################## # Input variables - Adjust to taste param ( $server = "server" # Server name/IP address of database host , $username = "user" # User ID to database (not necessarily Linux login) , $password = "password" # User ID's password , $database = "dbname" # Database name you'd like to query , $global:Query = 'SELECT `user_index`,`user_login`,`user_fname`,`user_lname`,`user_passwd` FROM `dbname` WHERE 1' # What would you like to get? ) # We require the full path to the MySQL.Data.dll # Modify according to your own path to this library # Need the library? Get it from: http://dev.mysql.com/downloads/connector/net/5.0.html [void][system.reflection.Assembly]::LoadFrom("C:\\Program Files\\MySQL\\MySQL Connector Net 5.0.8.1\\Binaries\\.NET 2.0\\MySQL.Data.dll") # Connection string derived from the above variables function global:Set-SqlConnection ( $server = $(Read-Host "SQL Server Name"), $username = $(Read-Host "Username"), $password = $(Read-Host "Password"), $database = $(Read-Host "Default Database") ) { $SqlConnection.ConnectionString = "server=$server;user id=$username;password=$password;database=$database;pooling=false" } # A function to allow the user to perform a query that returns a table full of data function global:Get-SqlDataTable( $Query = $(if (-not ($Query -gt $null)) {Read-Host "Query to run"}) ) { # Open the DB connection if it's not already # Typically, leave the opening & closing up to this function if (-not ($SqlConnection.State -like "Open")) { $SqlConnection.Open() } # Create the SQL command object & pre-supply the query & connection string properties $SqlCmd = New-Object MySql.Data.MySqlClient.MySqlCommand $Query, $SqlConnection # I still have no clue what a SQL Data Adapter is, but create it & supply the command object $SqlAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter $SqlAdapter.SelectCommand = $SqlCmd # Create a new dataset object to hold our query results $DataSet = New-Object System.Data.DataSet # Using the adapter, we fill the DataSet with our results # NOTE: out-null to prevent # of rows returned from appearing in the resulting array $SqlAdapter.Fill($DataSet) | Out-Null # Close the database connection & return the results $SqlConnection.Close() return $DataSet.Tables[0] } # Global variable to store MySQL connection info so it can be used anytime # This variable is used by the help functions above Set-Variable SqlConnection (New-Object MySql.Data.MySqlClient.MySqlConnection) -Scope Global -Option AllScope -Description "Personal variable for Sql Query functions" # Establish & open the database connection Set-SqlConnection $server $username $password $database # Run the query to actually get the table & do what you'd like with it in PoSh! # $global:dbusers = Get-SqlDataTable $Query
PowerShellCorpus/PoshCode/Fisher-Yates shuffle.ps1
Fisher-Yates shuffle.ps1
function Shuffle { param([Array] $a) $rnd=(new-object System.Random) for($i=0;$i -lt $a.Length;$i+=1){ $newpos=$i + $rnd.Next($a.Length - $i); $tmp=$a[$i]; $a[$i]=$a[$newpos]; $a[$newpos]=$tmp } return $a }
PowerShellCorpus/PoshCode/Alias latest msbuild.ps1
Alias latest msbuild.ps1
## Because of Split-Path, I get the "Framework" folder path (one level above the versioned folders) $rtr = Split-Path $([System.Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()) ## Then I loop through them in ascending (numerical, but really ascii) order ## each time I find installutil or mdbuild, I update the alias to point at the newer version foreach($rtd in get-childitem $rtr -filt v* | sort Name) { if( Test-Path (join-path $rtd.FullName installutil.exe) ) { set-alias installutil (resolve-path (join-path $rtd.FullName installutil.exe)) } if( Test-Path (join-path $rtd.FullName msbuild.exe) ) { set-alias msbuild (resolve-path (join-path $rtd.FullName msbuild.exe)) } }
PowerShellCorpus/PoshCode/GPRS Online log.ps1
GPRS Online log.ps1
################################################################################ # Get-GprsTime.ps1(V 1008) # Check the total connect time of any GPRS devices from a specified date. # Use the -Verbose switch for some extra information if desired. A default value # can be set with the -Monthly switch but can be temporarily overridden with any # -Start value and deleted by entering an invalid date. Now uses .NET Parse to # use any culture date input. Switches -M and -S cannot be used together. # A Balloon prompt will be issued in the Notification area for the 5 days # before the nominal month end, and a suitable Icon (exclamation.ico) file needs # to be available in the $PWD directory for this to work. # NOTE: this can effectively be suppressed by using a value higher than the SIM # card term, ie something like -Account 90 for a 30 day card which will override # the default setting. Use -Today to check only today's usage. # Use 'Set-Alias Get-GprsTime -Account 30' to set value permanently to 30 days. # Examples: # .\\Get-GprsTime.ps1 -Monthly 4/8/2009 # .\\Get-GprsTime.ps1 -Start 12/07/2009 -Account 100 -Verbose # .\\Get-GprsTime.ps1 -m 5/9/2009 # .\\Get-GprsTime.ps1 10/4/2009 -v # .\\Get-GprsTime.ps1 -v # .\\Get-GprsTime.ps1 -Today # .\\Get-GprsTime.ps1 # # The author can be contacted at www.SeaStarDevelopment.Bravehost.com and the # 'exclamation.ico' file is included in the Gprs100x.zip download there. ################################################################################ Param ([String] $start, [String] $monthly, [Int] $account = 0, #Start warning prompt 5 days before month end. [Switch] $today, [Switch] $verbose, [Switch] $debug) Trap [System.Management.Automation.MethodInvocationException] { [Int]$line = $error[0].InvocationInfo.ScriptLineNumber [System.Media.SystemSounds]::Hand.Play() If ($line -eq 165) { Write-Warning "[$name] Current GPRS variable has been deleted." $monthly = "" [Environment]::SetEnvironmentVariable("GPRS",$monthly,"User") } Else { Write-Warning "[$name] Date is missing or invalid $SCRIPT:form" } Exit 1 } $name = $myInvocation.MyCommand $newLine = "[$name] The switches -Start and -Monthly can only be used separately." If ($debug) { $DebugPreference = 'Continue' } If ($start -and $monthly) { [System.Media.SystemSounds]::Hand.Play() Write-Warning "$newLine" Exit 1 } $SCRIPT:form = "" #In certain cases Culture & UICulture can be different and have been known to # return conflicting results regarding '-is [DateTime]' queries, etc. If ($Host.CurrentCulture -eq $Host.CurrentUICulture) { $SCRIPT:form = '-Use format mm/dd/year' [Int]$culture = "{0:%d}" -f [DateTime] "6/5/2009" #Returns local day. If ($culture -eq 6) { $SCRIPT:form = '-Use format dd/mm/year' } } $ErrorActionPreference = 'SilentlyContinue' $VerbosePreference = 'SilentlyContinue' $WarningPreference = 'Continue' $conn = $disc = $default = $print = $null $timeNow = [DateTime]::Now $total = $timeNow - $timeNow #Set initial value to 00:00:00. $insert = "since" If ($verbose) { $VerbosePreference = 'Continue' } Function CreditMsg ($value, $value2) { $value = [Math]::Abs($value) $prefix = "CURRENT" [DateTime] $creditDT = $value2 $creditDT = $creditDT.AddDays($value) #Add the -Account days. $thisDay = "{0:M/d/yyyy}" -f [DateTime]::Now #Force US format. #If we use '$number = $creditDT - (Get-Date)' instead of the line below we #can sometimes get a value of 1 returned instead 2, hence the above lines. $number = $creditDT - [DateTime] $thisDay [String] $credit = $creditDT $credit = $credit.Replace('00:00:00','') #Remove any trailing time. $credit = "{0:d}" -f [DateTime]$credit Switch($number.Days) { 1 {$prefix = "($value days) will expire tomorrow"; break} 0 {$prefix = "($value days) will expire today"; break} -1 {$prefix = "($value days) expired yesterday"; break} {($_ -lt 0)} {$prefix = "($value days) expired on $credit"; break} {($_ -le 5)} {$prefix = "($value days) will expire on $credit"} Default {$prefix = "CURRENT"} #Only come here if over 5 days. } Return $prefix } Function Interval ([String] $value) { Switch($value) { { $_ -match '^00:00:\\d+(.*)$' } {$suffix = "seconds"; break} { $_ -match '^00:\\d+:\\d+(.*)$'} {$suffix = "minutes"; break} Default {$suffix = " hours"} } Return $suffix } Function CheckSetting ($value) { If ($value) { $print = $default.ToShortDateString() #Correct for local culture. } Else { $print = "(Value not set)" } Return $print } #The Script effectively starts here............................................. $getGprs = [Environment]::GetEnvironmentVariable("GPRS","User") #First check for GPRS variable and change from US date format to current locale. If ([DateTime]::TryParse($getGprs, [Ref]$timeNow)) { #No error as date is valid. $default = "{0:d}" -f [datetime]$getGprs $default = [DateTime]::Parse($default) $checkYear = "{0:yyyy}" -f $default $checkMonth = "{0:%M}" -f $default $dayCount = [DateTime]::DaysInMonth($checkYear,$checkMonth) #Range 28-31. If($account -eq 0) { $account = $dayCount $summary = "$($dayCount.ToString()) days" } Else { $summary = "$($account.Tostring()) days" } $text = CreditMsg $account $getGprs #Check if within 5 days of expiry date. If (($text -ne "CURRENT") -and (Test-Path "$pwd\\exclamation.ico") ) { [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") $objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon $objNotifyIcon.Icon = "$pwd\\exclamation.ico" $objNotifyIcon.BalloonTipIcon = "Info" $objNotifyIcon.BalloonTipTitle = "GPRS online account" $objNotifyIcon.BalloonTipText = "Credit $text" $objNotifyIcon.Visible = $True $objNotifyIcon.ShowBalloonTip(10000) } } Else { $summary = "(Days not set)" If ((!$today) -and (!$monthly) -and (!$start)) { [System.Media.SystemSounds]::Hand.Play() Write-Warning("Monthly date is either invalid or not set.") Exit 1 } } If ($start) { $start = [DateTime]::Parse($start) #Trigger TRAP if invalid! [DateTime]$limit = $start $convert = "{0:D}" -f $limit $print = CheckSetting $default } If ($monthly) { $start = [DateTime]::Parse($monthly) #Trigger TRAP if invalid! Write-Output "Setting GPRS (monthly) environment variable to: $monthly" $gprs = [String]$start.Replace('00:00:00','') [Environment]::SetEnvironmentVariable("GPRS",$gprs,"User") [DateTime] $limit = $start #Change to required US date format. $convert = "{0:D}" -f $limit $print = $limit.ToShortDateString() $summary = "(Days undetermined)" #Will show next time around. } If ($today) { $verBosePreference = 'Continue' #Show VERBOSE by default. [DateTime] $limit = (Get-Date) $convert = "{0:D}" -f $limit $limit = $limit.Date #Override any start date if using -Today input. $insert = "for today" $print = CheckSetting $default } If ((!$today) -and (!$monthly) -and (!$start)) { If ($default) { $monthly = $default [DateTime] $limit = $monthly $convert = "{0:D}" -f $limit $print = CheckSetting $default } } Write-Verbose "All records $($insert.Replace('for ','')) - $convert" Write-Verbose "Script activation - User [$($env:UserName)] Computer [$($env:ComputerName)]" Write-Output "" Write-Output "Calculating total connect time of all GPRS modem devices..." #We cannot proceed beyond here without a valid $limit value. Write-Debug "Using - [Search date] $($limit.ToShortDateString()) [Account] $summary [GPRS Monthly] $print" $lines = Get-EventLog system | Where-Object {($_.TimeGenerated -ge $limit) -and ` ($_.EventID -eq 20159 -or $_.EventID -eq 20158)} If ($lines) { Write-Verbose "A total of $([Math]::Truncate($lines.Count/2)) online sessions extracted from the System Event Log." } Else { Write-Output "(There are no events indicated in the System Event Log)" } $lines | ForEach-Object { $source = $_.Source If ($_.EventID -eq 20159) { #Event 20159 is Disconnect. $disc = $_.TimeGenerated } Else { #Event 20158 is Connect. $conn = $_.TimeGenerated } #We are only interested in matching pairs of DISC/CONN... If ($disc -ne $null -and $conn -ne $null -and $disc -gt $conn) { $diff = $disc - $conn $total += $diff $convDisc = "{0:G}" -f $disc $convConn = "{0:G}" -f $conn $period = Interval $diff Write-Verbose "Disconnect at $convDisc. Online - $diff $period" Write-Verbose " Connect at $convConn." } } #End ForEach If (!$source) { $source = '(Undetermined)' } Write-Verbose "Using local event source - System Event Log [$source]" $period = Interval $total Write-Output "Total online usage $insert $convert is $total $($period.Trim())." Write-Output ""
PowerShellCorpus/PoshCode/ConvertFrom-FahrenheitWi_2.ps1
ConvertFrom-FahrenheitWi_2.ps1
## From Windows PowerShell Cookbook (O'Reilly) ## by Lee Holmes (http://www.leeholmes.com/guide) param([double] $Fahrenheit) Set-StrictMode -Version Latest ## Convert Fahrenheit to Celsius function ConvertFahrenheitToCelsius([double] $fahrenheit) { $celsius = $fahrenheit - 32 $celsius = $celsius / 1.8 $celsius } $celsius = ConvertFahrenheitToCelsius $fahrenheit ## Output the answer "$fahrenheit degrees Fahrenheit is $celsius degrees Celsius."
PowerShellCorpus/PoshCode/New-TestDataSet.ps1
New-TestDataSet.ps1
## Generate a dummy dataset for testing Param( $path = $pwd, $files = $(ls $path) ) $global:dt = New-Object system.data.datatable "datatable" $global:ds = New-Object system.data.dataset "dataset" $null = $ds.Tables.Add( $dt ) $global:cols = ls | where {!$_.PsIsContainer} | Get-Member -type Properties "Name", "Length", "CreationTime", "LastAccessTime", "LastWriteTime", "Extension", "Mode", "FullName" foreach($c in $cols){ $null = $dt.Columns.Add( $c.Name, $($c.Definition -split " ")[0] ) } foreach($f in ls|?{!$_.PsIsContainer}){ $null = $dt.LoadDataRow( @($cols | % { $f.$($_.Name) }), $null ) } return $ds
PowerShellCorpus/PoshCode/finddupe_16.ps1
finddupe_16.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; } $starttime=[datetime]::now write-host "Usage: finddupe.ps1 <directory/file #1> <directory/file #2> ... <directory/file #N> [-delete] [-noprompt]" $matches = 0 # initialize number of matches for summary. $filesdeleted = 0 # number of files deleted. $bytesrec = 0 # Number of bytes recovered. $files=@() $del = $false # delete duplicates $noprompt = $false # delete without prompting toggle $currentdir = $true # work on current directory by default $args | ?{$_ -eq "-delete"} |%{$del=$true} $args | ?{$_ -eq "-noprompt"} | %{$noprompt=$true} $files=@(dir -ea 0 -recurse ($args | ?{$_ -ne "-delete" -and $_ -ne "-noprompt"})|?{$_.psiscontainer -ne $true} ) if ($files.count -eq 0) {"No files found.`a";exit} for ($i=0;$i -ne $files.count; $i++) # Cycle thru all files { if ($files[$i] -eq $null) {continue} $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 ($filecheck.md5 -eq $null) { $md5 = (get-md5 $filecheck.fullname) $filecheck = $filecheck | %{add-member -inputobject $_ -name MD5 -membertype noteproperty -value $md5 -passthru} } if ($files[$c].md5 -eq $null) { $md5 = (get-md5 $files[$c].fullname) $files[$c] = $files[$c] | %{add-member -inputobject $_ -name MD5 -membertype noteproperty -value $md5 -passthru} } if ($filecheck.md5 -eq $files[$c].md5) { write-host "Size and MD5 match: " -fore red -nonewline write-host "`"$($filecheck.fullname)`"" -nonewline write-host " and " -nonewline write-host "`"$($files[$c].fullname)`"" $matches++ if ($del -eq $true) { if ($noprompt -eq $true) { del $files[$c].fullname write-host "Deleted duplicate: " -f red -nonewline write-host "$($files[$c].fullname)." } else { del $files[$c].fullname -confirm } if ((get-item -ea 0 $files[$c].fullname) -eq $null) { $filesdeleted += 1 $bytesrec += $files[$c].length } } $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 duplicates found: $matches." Write-host "Number of duplicates deleted: $filesdeleted." # Display number of duplicate files deleted and bytes recovered. write-host "$bytesrec bytes recovered." write-host "" write-host "Time to run: $(([datetime]::now)-$starttime|select hours, minutes, seconds, milliseconds)" write-host ""
PowerShellCorpus/PoshCode/validate an IP address.ps1
validate an IP address.ps1
# validate given IP address in $ip1 variable $ip1 = "192.168.22.455" ($ip1.split(".") | where-object { $_ -ge 1 -and $_ -le 255 } | Where-Object { $_ -match "\\d{1,3}"} | Measure-Object).count -eq 4
PowerShellCorpus/PoshCode/HP_Plink_ISO.ps1
HP_Plink_ISO.ps1
$plink = plink -ssh Administrator@$ILOIP -pw $PSWD -auto_store_key_in_cache "set /map1/oemhp_vm1/cddr1 oemhp_image=http://IPADDRESS/ISO.iso" $plink = plink -ssh Administrator@$ILOIP -pw $PSWD -auto_store_key_in_cache "set /map1/oemhp_vm1/cddr1 oemhp_boot=connect" $plink = plink -ssh Administrator@$ILOIP -pw $PSWD -auto_store_key_in_cache "set /map1/oemhp_vm1/cddr1 oemhp_boot=once"
PowerShellCorpus/PoshCode/Get Twitter RSS Feed_9.ps1
Get Twitter RSS Feed_9.ps1
param ([String] $ScreenName) $client = New-Object System.Net.WebClient $idUrl = "https://api.twitter.com/1/users/show.json?screen_name=$ScreenName" $data = $client.DownloadString($idUrl) $start = 0 $findStr = '"id":' do { $start = $data.IndexOf($findStr, $start + 1) if ($start -gt 0) { $start += $findStr.Length $end = $data.IndexOf(',', $start) $userId = $data.SubString($start, $end-$start) } } while ($start -le $data.Length -and $start -gt 0) $feed = "http://twitter.com/statuses/user_timeline/$userId.rss" $feed
PowerShellCorpus/PoshCode/Convert-CBZ2CBR.ps1
Convert-CBZ2CBR.ps1
########################################################################### # # NAME: Convert-CBZ2CBR.ps1 # # AUTHOR: Neiljmorrow # EMAIL: Neiljmorrow@gmail.com # # NOTE: Written to use command line version of 7zip (http://7zip.com) # from the default install location. Please modify the path below # if necessary. # # COMMENT: # # You have a royalty-free right to use, modify, reproduce, and # distribute this script file in any way you find useful, provided that # you agree that the creator, owner above has no warranty, obligations, # or liability for such use. # # VERSION HISTORY: # 1.0 1/24/2009 - Initial release # ########################################################################### #set alias to command line version of 7zip set-alias cbrzip "c:\\program files\\7-zip\\7z.exe" #find all files in the immediate directory dir "*.cbz" | foreach-object{ #Make a copy and rename as zip copy-item $_.name ($_.basename + ".zip") #unzip the file to a "temp" directory cbrzip -oTemp x ($_.basename + ".zip") #remove the zip file remove-item ($_.basename + ".zip") #rar the contents of the "temp" directory cbrzip a ($_.basename + ".rar") "temp" #remove the "temp" directory remove-item -r "temp" #rename the rar file to cbr rename-item ($_.basename + ".rar") ($_.basename + ".cbr") } #remove 7zip alias remove-item alias:cbrzip
PowerShellCorpus/PoshCode/Search-Registry.ps1
Search-Registry.ps1
##############################################################################\n##\n## Search-Registry\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\nSearch the registry for keys or properties that match a specific value.\n\n.EXAMPLE\n\nPS >Set-Location HKCU:\\Software\\Microsoft\\\nPS >Search-Registry Run\n\n#>\n\nparam(\n ## The text to search for\n [Parameter(Mandatory = $true)]\n [string] $Pattern\n)\n\nSet-StrictMode -Off\n\n## Helper function to create a new object that represents\n## a registry match from this script\nfunction New-RegistryMatch\n{\n param( $matchType, $keyName, $propertyName, $line )\n\n $registryMatch = New-Object PsObject -Property @{\n MatchType = $matchType;\n KeyName = $keyName;\n PropertyName = $propertyName;\n Line = $line\n }\n\n $registryMatch\n}\n\n## Go through each item in the registry\nforeach($item in Get-ChildItem -Recurse -ErrorAction SilentlyContinue)\n{\n ## Check if the key name matches\n if($item.Name -match $pattern)\n {\n New-RegistryMatch "Key" $item.Name $null $item.Name\n }\n\n ## Check if a key property matches\n foreach($property in (Get-ItemProperty $item.PsPath).PsObject.Properties)\n {\n ## Skip the property if it was one PowerShell added\n if(($property.Name -eq "PSPath") -or\n ($property.Name -eq "PSChildName"))\n {\n continue\n }\n\n ## Search the text of the property\n $propertyText = "$($property.Name)=$($property.Value)"\n if($propertyText -match $pattern)\n {\n New-RegistryMatch "Property" $item.Name `\n property.Name $propertyText\n }\n }\n}
PowerShellCorpus/PoshCode/d9442693-acf2-4df5-8552-91dec539a96f.ps1
d9442693-acf2-4df5-8552-91dec539a96f.ps1
<# .SYNOPSIS Writes out the the words for 99 Bottle of Beer on the wall. .DESCRIPTION Writes out the the words for 99 Bottle of Beer on the wall. .PARAMETER BottlesOfBeerOnTheWall Give the starting number of how many bottles of beer that are on the wall. Valid range is 2 to 99. .PARAMETER Voice Use if you want a voice to the song. .EXAMPLE Sing-FolkSong -BottlesOfBeerOnTheWall 99 Ninety-nine bottles of beer on the wall, ninety-nine bottles of beer. Take one down pass it around, ninety-eight bottles of beer on the wall. ... One bottle of beer on the wall, one bottle of beer. Take one down pass it around, zero bottles of beer on the wall. #> [CmdletBinding()] Param( [Parameter(ValueFromPipeline=$true)] [ValidateRange(0,99)] [Alias('BottlesOfBeer')] [int]$BottlesOfBeerOnTheWall=99, [switch]$Voice ) $bob = 'bottles of beer' $wall = 'on the wall' $todpia = 'Take one down, pass it around' $tens = @(' ',' ','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety') $ones = @('zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve', ` 'thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen') function Say-Number([int]$number){ if($number-ge20){ $numberword = $tens[($number-($number%10))/10] Write-Verbose "$numberword is greater than 20" if($number%10){ $numberword += "-$($ones[$number%10])" Write-Verbose "$numberword is $number" } } else{ $numberword = $ones[$number] Write-Verbose "$numberword is less than 20" } return $numberword } function Start-Sentence ([string]$word){ return "$(([string]$word[0]).ToUpper())$($word.substring(1))" } function Read-Words ($phrase){ $VoiceBox = New-Object -ComObject SAPI.SpVoice; $VoiceBox.Speak( [string]$phrase, 1 ) | out-null; } for($i=$BottlesOfBeerOnTheWall;$i-gt2;$i--){ $bobotw = Say-Number $i Write-Host "$(Start-Sentence $bobotw) $bob $wall, $bobotw $bob." Write-Host "$todpia, $(Say-Number ($i-1)) $bob $wall." Write-Host '' if($Voice){ Read-Words "$(Start-Sentence $bobotw) $bob $wall, $bobotw $bob. $todpia, $(Say-Number ($i-1)) $bob $wall." Start-Sleep -Seconds 9 } } Write-Host "$(Start-Sentence (Say-Number 2)) $bob $wall, $(Say-Number 2) $bob." Write-Host "$todpia, $(Say-Number 1) $($bob.Replace('bottles','bottle')) $wall." Write-Host "" Write-Host "$(Start-Sentence (Say-Number 1)) $($bob.Replace('bottles','bottle')) $($wall), $(Say-Number 1) $($bob.Replace('bottles','bottle'))." Write-Host "$todpia, $(Say-Number 0) $bob $wall."
PowerShellCorpus/PoshCode/Get-Entropy.ps1
Get-Entropy.ps1
function Get-Entropy { <# .SYNOPSIS Calculate the entropy of a byte array. Author: Matthew Graeber (@mattifestation) .PARAMETER ByteArray Specifies the byte array containing the data from which entropy will be calculated. .EXAMPLE C:\\PS> $RandArray = New-Object Byte[](10000) C:\\PS> foreach ($Offset in 0..9999) { $RandArray[$Offset] = [Byte] (Get-Random -Min 0 -Max 256) } C:\\PS> $RandArray | Get-Entropy Description ----------- Calculates the entropy of a large array containing random bytes. .EXAMPLE C:\\PS> 0..255 | Get-Entropy Description ----------- Calculates the entropy of 0-255. This should equal exactly 8. .INPUTS System.Byte[] Get-Entropy accepts a byte array from the pipeline .OUTPUTS System.Double Get-Entropy outputs a double representing the entropy of the byte array. .LINK http://www.exploit-monday.com #> [CmdletBinding()] Param ( [Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)] [Byte[]] $ByteArray ) BEGIN { $FrequencyTable = @{} $ByteArrayLength = 0 } PROCESS { foreach ($Byte in $ByteArray) { $FrequencyTable[$Byte]++ $ByteArrayLength++ } } END { $Entropy = 0.0 foreach ($Byte in 0..255) { $ByteProbability = ([Double] $FrequencyTable[[Byte]$Byte]) / $ByteArrayLength if ($ByteProbability -gt 0) { $Entropy += -$ByteProbability * [Math]::Log($ByteProbability, 2) } } Write-Output $Entropy } }
PowerShellCorpus/PoshCode/Shift Operators_2.ps1
Shift Operators_2.ps1
#requires -version 2.0 Add-Type @" public class Shift { public static int Right(int x, int count) { return x >> count; } public static uint Right(uint x, int count) { return x >> count; } public static long Right(long x, int count) { return x >> count; } public static ulong Right(ulong x, int count) { return x >> count; } public static int Left(int x, int count) { return x << count; } public static uint Left(uint x, int count) { return x << count; } public static long Left(long x, int count) { return x << count; } public static ulong Left(ulong x, int count) { return x << count; } } "@ #.Example # Shift-Left 16 1 ## returns 8 #.Example # 8,16 |Shift-Left ## returns 4,8 function Shift-Left { PARAM( $x=1, $y ) BEGIN { if($y) { [Shift]::Left( $x, $y ) } } PROCESS { if($_){ [Shift]::Left($_, $x) } } } #.Example # Shift-Right 8 1 ## returns 16 #.Example # 2,4,8 |Shift-Right 2 ## returns 8,16,32 function Shift-Right { PARAM( $x=1, $y ) BEGIN { if($y) { [Shift]::Right( $x, $y ) } } PROCESS { if($_){ [Shift]::Right($_, $x) } } }