full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PoshCode/Get-VMHostSerialNumber.ps1
|
Get-VMHostSerialNumber.ps1
|
function Get-VMHostSerialNumber {
param([VMware.VimAutomation.Types.VMHost[]]$InputObject = $null)
process {
$hView = $_ | Get-View -Property Hardware
$serviceTag = $hView.Hardware.SystemInfo.OtherIdentifyingInfo | where {$_.IdentifierType.Key -eq "ServiceTag" }
$assetTag = $hView.Hardware.SystemInfo.OtherIdentifyingInfo | where {$_.IdentifierType.Key -eq "AssetTag" }
$obj = New-Object psobject
$obj | Add-Member -MemberType NoteProperty -Name VMHost -Value $_
$obj | Add-Member -MemberType NoteProperty -Name ServiceTag -Value $serviceTag.IdentifierValue
$obj | Add-Member -MemberType NoteProperty -Name AssetTag -Value $assetTag.IdentifierValue
Write-Output $obj
}
}
|
PowerShellCorpus/PoshCode/FTP ListDirectory.ps1
|
FTP ListDirectory.ps1
|
$cred = Get-Credential
[System.Net.FtpWebRequest]$request = [System.Net.WebRequest]::Create("ftp://joelbennett.net")
$request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory #Details
$request.Credentials = $cred
$response = $request.GetResponse()
$list = Receive-Stream $response.GetResponseStream()
|
PowerShellCorpus/PoshCode/Get-Parameter_6.ps1
|
Get-Parameter_6.ps1
|
function Get-Parameter ( $Cmdlet, [switch]$ShowCommon ) {
foreach ($paramset in (Get-Command $Cmdlet).ParameterSets){
$Output = @()
foreach ($param in $paramset.Parameters) {
if ( !$ShowCommon ) {
if ($param.aliases -match "vb|db|ea|wa|ev|wv|ov|ob|wi|cf") { continue }
}
$process = "" | Select-Object Name, Type, ParameterSet, Aliases, Position, IsMandatory
$process.Name = $param.Name
$process.Type = $param.ParameterType.Name
if ( $paramset.name -eq "__AllParameterSets" ) { $process.ParameterSet = "Default" }
else { $process.ParameterSet = $paramset.Name }
$process.Aliases = $param.aliases
if ( $param.Position -lt 0 ) { $process.Position = $null }
else { $process.Position = $param.Position }
$process.IsMandatory = $param.IsMandatory
$output += $process
}
Write-Output $Output
#Write-Host "`n"
}
}
|
PowerShellCorpus/PoshCode/PrinterActivity.ps1
|
PrinterActivity.ps1
|
#PrinterChecking Script By Henrik Pedersen Ċmark and Daniel Lundgren
#This script is designed to check what printers that is still in use.
#It's assumed the printer is classed as inactive if it hasnt been used in X months
#The script is reading the Systemlog on a printserver of your choice, the one you type in the hostname for,
#sorting the log on eventID 10 (successful print) and searching for entries the latest 6 months.
#When its done it gets printer ports and ques from the same server and then compare them to the messageline from the eventlog.
#And then checking if the mportname of is in the message.
#If it is, it will write the name to a file and if not it will write the name to another file.
#You will need admin rights to use the script.
$date = Get-Date -UFormat %Y%m%d
#Finding out what host to check logs from
Write-Host "What server do you want to get the eventlog from?"
$hostname = Read-Host
Write-Host "Getting eventlog from remote server "$hostname". Please wait..."
Write-Host "Please wait... (this might take a few minutes)"
#Get Eventlog from a remote host
$events = gwmi -ComputerName $hostname -query "select * from win32_ntlogevent where logfile='system' and eventcode='10' and sourcename='print'" | Select-Object EventCode, Timegenerated, Message | sort Timegenerated
#Making a variable for the printerports
$printerports = Get-WmiObject -computername $hostname Win32_Printer | Select-Object Portname, DeviceID, __server, name
#Converting newest logtimes to DateTime
$newest = [System.Management.ManagementDateTimeConverter]::ToDateTime($events[0].TimeGenerated)
Write-Host "Oldest logentry is from:" $newest
Write-Host "How many months back do you want to check?"
$months = Read-Host
#Checks is the path where the files gonna be added exists, it it dont, it creates it
if ((Test-Path -path $hostname) -ne $True)
{
New-Item -type directory -path $hostname
}
$counter = 0
while ($counter -ne ($printerports.count-1))
{
$foundprinted = 0
#Looping through each line and checking for how old the events are and if they match the current printerquename
foreach ($line in $events)
{
#Converting Timegenerated to DateTime
$current = ([System.Management.ManagementDateTimeConverter]::ToDateTime($line.TimeGenerated))
#Checking each line for beeing less then X months and has quename in the message
if ($current -gt $(Get-Date).AddMonths(-$months) -and ($line.message -match $printerports[$counter].name ))
{
$foundprinted = 1
}
}
if ($foundprinted)
{
write-host -ForegroundColor Green $printerports[$counter].name"is in use!"
#Writing to a file
add-content -path $hostname\\Validprinters_$date.txt -Value $printerports[$counter].name
}
else
{
#Writing to another file
write-host -ForegroundColor red $printerports[$counter].name "is not in use!"
add-content -path $hostname\\Invalidprinters_$date.txt -Value $printerports[$counter].name
}
#Adds 1 to the counter so the loop ends after all quenames are checked
$counter=$counter+1
}
|
PowerShellCorpus/PoshCode/Report movie lib. stats.ps1
|
Report movie lib. stats.ps1
|
function getmoviestat ($drives) {
$drives=$drives | %{if ($_.systemname -eq $env:computername) {add-member -inputobject $_ -name BRs -membertype noteproperty -value ( gci -ea 0 "$($_.name)\\media\\BR movies\\*" -include *.mkv,*.m2ts ) -passthru } else {add-member -inputobject $_ -name BRs -membertype noteproperty -value ( invoke-command -session $s -scriptblock { param ($name) gci -ea 0 "$name\\media\\BR movies\\*" -include *.mkv,*.m2ts } -argumentlist $_.name ) -passthru}}
$drives=$drives | %{if ($_.systemname -eq $env:computername) { add-member -inputobject $_ -name SDs -membertype noteproperty -value ( gci -ea 0 "$($_.name)\\media\\SD movies\\*" -include *.mkv,*.avi ) -passthru } else {add-member -inputobject $_ -name SDs -membertype noteproperty -value ( invoke-command -session $s -scriptblock { param ($name) gci -ea 0 "$name\\media\\SD movies\\*" -include *.mkv,*.avi } -argumentlist $_.name) -passthru}}
$drives=$drives | %{ add-member -inputobject $_ -name MVs -membertype scriptproperty -value { $this.SDs + $this.BRs } -passthru }
$drives=$drives | %{ add-member -inputobject $_ -name BRsize -membertype scriptproperty -value { $n=0;foreach($mv in $this.BRs){ $n+=$mv.length }; [math]::round($n/1gb,0)} -passthru }
$drives=$drives | %{ add-member -inputobject $_ -name SDsize -membertype scriptproperty -value { $n=0;foreach($mv in $this.SDs){ $n+=$mv.length }; [math]::round($n/1gb,0)} -passthru }
$drives=$drives | %{ add-member -inputobject $_ -name MVsize -membertype scriptproperty -value { $this.BRsize + $this.SDsize } -passthru }
}
function totalstats ($drives,$systemname="All") {
$drivesobject = new-object psobject -property @{
systemname=$systemname
name="All"
capacity= $drives | %{$s=0}{$s+=$_.capacity}{$s}
freespace= $drives | %{$s=0}{$s+=$_.freespace}{$s}
SDs= $drives | %{$movs=@()}{if ($_.SDs.count -ne 0 -and $_.SDs -ne $null){$movs+=$_.SDs}}{$movs}
BRs= $drives | %{$movs=@()}{if ($_.BRs.count -ne 0 -and $_.BRs -ne $null){$movs+=$_.BRs}}{$movs}
MVs= $drives | %{$movs=@()}{if ($_.MVs.count -ne 0 -and $_.MVs -ne $null){$movs+=$_.MVs}}{$movs}
SDsize= $drives | %{$s=0}{$s+=$_.SDsize}{$s}
BRsize= $drives | %{$s=0}{$s+=$_.BRsize}{$s}
MVSize= $drives | %{$s=0}{$s+=$_.MVsize}{$s}
}
return $drivesobject
}
function displaystats ($drives) {
$drives | ft -a systemname, name, @{Label="Size";Expression={[math]::round($_.capacity/1GB,0)}}, @{Label="Used"; Expression={[math]::round(($_.capacity-$_.freespace)/1GB,0)}},@{Label="free"; Expression={[math]::round($_.freespace/1GB,0)}}, @{Label="SDs";Expression={if ($_.SDs.count) {$_.SDs.count} else {0}}}, @{Label="BRs";Expression={ if ($_.BRs.count) {$_.BRs.count} else {0}}}, @{Label="Movs";Expression={ if ($_.MVs.count) {$_.MVs.count} else {0}}}, @{label="SD SZ";Expression={$_.SDsize}}, @{Label="BR SZ"; Expression={$_.BRsize}}, @{Label="Mov SZ"; Expression={$_.MVsize}}, @{Label="Other SZ"; Expression={[math]::round((($_.capacity/1GB)-($_.freespace/1GB))-$_.MVSize,0)}}, @{Label="<SDs>"; Expression={if ($_.SDs.count -ne 0 -and $_.SDs.count -ne $null) {[math]::round($_.SDsize/$_.SDs.count,0) } else {"?"}};align="right"}, @{Label="<BRs>"; Expression={if($_.BRsize -ne 0 -and $_.BRsize -ne $null){$global:BRave=[math]::round($_.BRsize/$_.BRs.count,0);$BRave } else {$global:BRave=0;"?"}};align="right"}, @{Label="<Movs>"; Expression={if ($_.MVsize -ne 0 -and $_.MVsize -ne $null) {[math]::round($_.MVsize/$_.MVs.count,0)} else {"?"}};align="right"}, @{Label="BR slots";Expression={ if ($BRAve -ne 0 -and $BRave -ne $null) {[math]::round($_.capacity/1GB/$BRAve)} else {"?"}}; Align="Right"},@{label="BRs Avail";Expression={if ($BRAve -eq 0 -or $BRave -eq $null) {"?"} else {[math]::round(($_.freespace/1gb)/$BRAve,0)}};Align="Right" }
}
$cn = "QuadBox"
if ($env:computername -eq $cn) {$cn = "SixShooter"}
$s = new-pssession -ea 0 -computername $cn -sessionOption (new-pssessionoption -noCompression)
$localdrives=@(gwmi -class win32_volume | ?{$_.filesystem -eq "ntfs"} | ?{$_.name -notlike "\\\\*"}|?{test-path "$($_.name)\\media\\BR movies"}|sort driveletter)
getmoviestat $localdrives
$remotedrives=@()
if ($s -ne $null) {$remotedrives=@(invoke-command -session $s -scriptblock {gwmi -class win32_volume | ?{$_.filesystem -eq "ntfs"} | ?{$_.name -notlike "\\\\*"}|?{test-path "$($_.name)\\media\\BR movies"}|sort driveletter}); getmoviestat $remotedrives }
$localall=totalstats $localdrives $localdrives[0].systemname
$remoteall=totalstats $remotedrives $remotedrives[0].systemname
$all=totalstats ($remotedrives+$localdrives)
displaystats ($localdrives+$localall+$remotedrives+$remoteall+$all)
if ($s -ne $null) {remove-pssession $S}
write-host "Press Any Key to continue..." -n; $host.ui.rawui.readkey() | out-null; write-host ""
|
PowerShellCorpus/PoshCode/Get-PerformanceHistory _1.ps1
|
Get-PerformanceHistory _1.ps1
|
#requires -version 2.0
## Get-PerformanceHistory.ps1
##############################################################################################################
## Lets you see the amount of time recent commands in your history have taken
## History:
## v2.5 - added "average" calculation if the first thing in your command line is a range: 1..x
## v2 - added measuring the scripts involved in the command, (uses Tokenizer)
## - adds a ton of parsing to make the output pretty
##############################################################################################################
#requires -version 2.0
param( [int]$count=1, [int]$id=((Get-History -count 1| Select Id).Id) )
$Parser = [System.Management.Automation.PsParser]
function FormatTimeSpan($ts) {
if($ts.Minutes) {
if($ts.Hours) {
if($ts.Days) {
return "{0:##}d {1:00}:{2:00}:{3:00}.{4:00000}" -f $ts.Days, $ts.Hours, $ts.Minutes, $ts.Seconds, [int](100000 * ($ts.TotalSeconds - [Math]::Floor($ts.TotalSeconds)))
}
return "{0:##}:{1:00}:{2:00}.{3:00000}" -f $ts.Hours, $ts.Minutes, $ts.Seconds, [int](100000 * ($ts.TotalSeconds - [Math]::Floor($ts.TotalSeconds)))
}
return "{0:##}:{1:00}.{2:00000}" -f $ts.Minutes, $ts.Seconds, [int](100000 * ($ts.TotalSeconds - [Math]::Floor($ts.TotalSeconds)))
}
return "{0:#0}.{1:00000}" -f $ts.Seconds, [int](100000 * ($ts.TotalSeconds - [Math]::Floor($ts.TotalSeconds)))
}
Get-History -count $count -id $id |
ForEach {
$msr = $null
$cmd = $_
# default formatting values
$avg = 7; $len = 8; $count = 1
$tok = $Parser::Tokenize( $cmd.CommandLine, [ref]$null )
if( ($tok[0].Type -eq "Number") -and
($tok[0].Content -le 1) -and
($tok[2].Type -eq "Number") -and
($tok[1].Content -eq "..") )
{
$count = ([int]$tok[2].Content) - ([int]$tok[0].Content) + 1
}
$com = @( $tok | where {$_.Type -eq "Command"} |
foreach { get-command $_.Content } |
where { $_.CommandType -eq "ExternalScript" } |
foreach { $_.Path } )
# If we actually got a script, measure it out
if($com.Count -gt 0){
$msr = Get-Content -path $com | Measure-Object -L -W -C
} else {
$msr = Measure-Object -in $cmd.CommandLine -L -W -C
}
"" | Select @{n="Id"; e={$cmd.Id}},
@{n="Duration"; e={FormatTimeSpan ($cmd.EndExecutionTime - $cmd.StartExecutionTime)}},
@{n="Average"; e={FormatTimeSpan ([TimeSpan]::FromTicks( (($cmd.EndExecutionTime - $cmd.StartExecutionTime).Ticks / $count) ))}},
@{n="Lines"; e={$msr.Lines}},
@{n="Words"; e={$msr.Words}},
@{n="Chars"; e={$msr.Characters}},
@{n="Type"; e={if($com.Count -gt 0){"Script"}else{"Command"}}},
@{n="Commmand"; e={$cmd.CommandLine}}
} |
# I have to figure out what the longest time string is to make it look its best
Foreach {
$avg = [Math]::Max($avg,$_.Average.Length);
$len = [Math]::Max($len,$_.Duration.Length);
$_ } | Sort Id |
Format-Table @{l="Duration";e={"{0,$len}" -f $_.Duration}},@{l="Average";e={"{0,$avg}" -f $_.Average}},Lines,Words,Chars,Type,Commmand -auto
|
PowerShellCorpus/PoshCode/Select-CSVString_1.ps1
|
Select-CSVString_1.ps1
|
# NAME
# Select-CSVString
#
# SYNOPSIS
# Convert CSV files to custom objects with properties
#
# SYNTAX
# Select-CSVString -pattern <string[]> -files (ls *) [-StartDate <DateTime>] [-EndDate <DateTime>]
param ([regex]$pattern,$files=("$($exinstall)TransportRoles\\Logs\\AgentLog","$($exinstall.substring(0,1)):\\Program Files (x86)\\Microsoft Forefront Protection for Exchange Server\\Data\\FSEAgentLog"|%{ls $_}|Sort-Object LastWriteTime), [string]$StartDate, [string]$EndDate)
# Check start and end dates
$local:erroractionpreference = "Stop"
If(!$StartDate -and !$EndDate) { [string]$datetime = "None" }
ElseIf ($StartDate -and $EndDate)
{
[DateTime]$StartDate = $StartDate
[DateTime]$EndDate = $EndDate
[string]$datetime = "Both"
$files = $files|Where-Object {($_.CreationTime -ge $StartDate -or $_.LastWriteTime -ge $StartDate) -and $_.CreationTime -le $EndDate}
}
ElseIf ($StartDate -and !$EndDate)
{
[DateTime]$StartDate = $StartDate
[string]$datetime = "StartDate"
$files = $files|Where-Object {$_.CreationTime -ge $StartDate -or $_.LastWriteTime -ge $StartDate}
}
ElseIf (!$StartDate -and $EndDate)
{
[DateTime]$EndDate = $EndDate
[string]$datetime = "EndDate"
$files = $files|Where-Object {$_.CreationTime -le $EndDate -or $_.LastWriteTime -le $EndDate}
}
$local:erroractionpreference = "Continue"
# Get columns
$columns = @($files)[0]|Get-Content -TotalCount 5
foreach($col in $columns)
{
$col = $col -Replace "^#Fields: ",""
If ($col -notmatch "^#")
{
$columns = $col.Split(',')
break
}
}
# Get Results
foreach($file in $files)
{
Write-Debug "File: $($file.FullName)"
trap
{
Write-Debug "File Locked"
$script:lines = $file|Get-Content|Select-String $pattern
continue
}
$lines = $file|Select-String $pattern -ErrorAction Stop
foreach($l in $lines) {
Write-Debug "Line: $($l.Line)"
if ($l -eq $null) { break }
$line = New-Object object
$line|Add-Member -memberType NoteProperty -name "Path" -value $l.Path
# ---------- Delimiter magic inside ----------
# It has been asked, why not dump select-string to a
# file and import-csv the whole thing? To get realtime
# results and avoid temporary files, thats why.
$z = [char](222)
$from = ","
$tmp = $l.Line -replace "(?:`"((?:(?:[^`"]|`"`"))+)(?:`"$from|`"`$))|(?:$from)|(?:((?:.(?!$from))*.)(?:$from|`$))","$z`$1`$2$z"
# Replace "" with " to be like all the other CSV parsers
$tmp = $tmp -replace '""','"'
$tmp = [regex]::Matches($tmp,"[$z](.*?)[$z]")
$row = @()
$tmp | foreach { $row += $_.Groups[1].Value }
# ---------- Delimiter magic inside ----------
0..($columns.Count-1)|Foreach-Object {
# Convert timestamps to datetime objects
If($columns[$_] -match "(timestamp|date-time)") {$row[$_] = [DateTime]$row[$_]}
$line|Add-Member -memberType NoteProperty -name $columns[$_] -Value $row[$_]
}
# Determine if the line meets datetime requirements
If($datetime -eq "None") {Write-Output $line}
ElseIf($datetime -eq "EndDate" -and $EndDate -ge $line.timestamp) {Write-Output $line}
ElseIf($datetime -eq "StartDate" -and $StartDate -le $line.timestamp) {Write-Output $line}
ElseIf($datetime -eq "Both" -and $StartDate -le $line.timestamp -and $EndDate -ge $line.timestamp) {Write-Output $line}
}
}
|
PowerShellCorpus/PoshCode/finddupe_2.ps1
|
finddupe_2.ps1
|
write-host "Usage: finddupe.ps1 <directory1> <directory2> ... <directoryN>"
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;
}
$matches = 0 # initialize number of matches for summary.
$files = (dir $args -recurse | ? {$_.psiscontainer -ne $true})
for ($i=0;$i -ne $files.count; $i++) # Cycle thru all files
{
if ($files[$i] -eq $null) {continue}
$md5 = $null
$filecheck = $files[$i]
$files[$i] = $null
for ($c=0;$c -ne $files.count; $c++)
{
if ($files[$c] -eq $null) {continue}
# write-host "Comparing $filecheck and $($files[$c]) `r" -nonewline
if ($filecheck.length -eq $files[$c].length)
{
#write-host "Comparing MD5 of $($filecheck.fullname) and $($files[$c].fullname) `r" -nonewline
if ($md5 -eq $null) {$md5 = (get-md5 $filecheck)}
if ($md5 -eq (get-md5 $files[$c]))
{
write-host "Size and MD5 match: " -fore red -nonewline
"{0} and {1}" -f $filecheck.fullname, $files[$c].fullname
$matches++
$files[$c] = $null
}
}
}
}
write-host ""
write-host "Number of Files checked: $($files.count)." # Display useful info; files checked and matches found.
write-host "Number of matches found: $($matches)."
write-host ""
|
PowerShellCorpus/PoshCode/Check Modules path_1..ps1
|
Check Modules path_1..ps1
|
function Update-ModulePath {
<#
.Synopsis
Command insures that path and the name of psm1 file are alike.
.Description
This function should help to troubleshoot modules. It loooks up path that should contain modules.
For each .psm1 file found it checks if parent folder containing this file has same name.
I created this function after I was banging my head for few hours why my module won't show up.
After several approaches it came out clear that it was simple TYPO in file.psm1 name...
.Example
Update-ModulePath -Fix Files
Will look all files and rename .psm1 files to match parent folder
.Example
Update-ModulePath -Fix Folder
Will look all files and rename parent folder to match file names
.Parameter Fix
Switch to decide if we prefer to name folders or files to get all matches.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[ValidateSet("Files","Folders")]
[string]$Fix
)
<# Steps to be taken:
* enumerate all .psm1 files
* check which one is misconfigured
* rename file/ folder to fix this issue
#>
ForEach ($ModuleFile in @(Get-ChildItem -Recurse @($($env:PSModulePath).Split(";")) -filter *.psm1)) {
if (($file = $ModuleFile.BaseName) -eq ($folder = $ModuleFile.Directory.ToString().Split('\\')[-1])) {
Write-Verbose "$Modulefile.Name is fine"
} else {
Write-Verbose "$ModuleFile.Name is BAD"
switch ($Fix) {
"Files" {
Write-Verbose "We rename file $file"
$OldName = $ModuleFile.FullName
$NewName = $OldName -replace "$file.psm1$", "$folder.psm1"
}
"Folders" {
Write-Verbose "We rename folder $folder"
$OldName = $ModuleFile.FullName -replace "\\\\$file.psm1", ""
$NewName = $OldName -replace "$folder$", $file
}
}
Write-Host "Renaming $OldName to $NewName"
Rename-Item -Force $OldName $NewName
}
}
}
|
PowerShellCorpus/PoshCode/Get-ScriptPerformancePro.ps1
|
Get-ScriptPerformancePro.ps1
|
#############################################################################\n##\n## Get-ScriptPerformanceProfile\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\nComputes the performance characteristics of a script, based on the transcript\nof it running at trace level 1.\n\n.DESCRIPTION\n\nTo profile a script:\n\n 1) Turn on script tracing in the window that will run the script:\n Set-PsDebug -trace 1\n 2) Turn on the transcript for the window that will run the script:\n Start-Transcript\n (Note the filename that PowerShell provides as the logging destination.)\n 3) Type in the script name, but don't actually start it.\n 4) Open another PowerShell window, and navigate to the directory holding\n this script. Type in '.\\Get-ScriptPerformanceProfile <transcript>',\n replacing <transcript> with the path given in step 2. Don't\n press <Enter> yet.\n 5) Switch to the profiled script window, and start the script.\n Switch to the window containing this script, and press <Enter>\n 6) Wait until your profiled script exits, or has run long enough to be\n representative of its work. To be statistically accurate, your script\n should run for at least ten seconds.\n 7) Switch to the window running this script, and press a key.\n 8) Switch to the window holding your profiled script, and type:\n Stop-Transcript\n 9) Delete the transcript.\n\n.NOTES\n\nYou can profile regions of code (ie: functions) rather than just lines\nby placing the following call at the start of the region:\n Write-Debug "ENTER <region_name>"\nand the following call and the end of the region:\n Write-Debug "EXIT"\nThis is implemented to account exclusively for the time spent in that\nregion, and does not include time spent in regions contained within the\nregion. For example, if FunctionA calls FunctionB, and you've surrounded\neach by region markers, the statistics for FunctionA will not include the\nstatistics for FunctionB.\n\n#>\n\nparam(\n ## The path of the transcript log file\n [Parameter(Mandatory = $true)]\n $Path\n)\n\nSet-StrictMode -Version Latest\n\nfunction Main\n{\n ## Run the actual profiling of the script. $uniqueLines gets\n ## the mapping of line number to actual script content.\n ## $samples gets a hashtable mapping line number to the number of times\n ## we observed the script running that line.\n $uniqueLines = @{}\n $samples = GetSamples $uniqueLines\n\n "Breakdown by line:"\n "----------------------------"\n\n ## Create a new hash table that flips the $samples hashtable --\n ## one that maps the number of times sampled to the line sampled.\n ## Also, figure out how many samples we got altogether.\n $counts = @{}\n $totalSamples = 0;\n foreach($item in $samples.Keys)\n {\n $counts[$samples[$item]] = $item\n $totalSamples += $samples[$item]\n }\n\n ## Go through the flipped hashtable, in descending order of number of\n ## samples. As we do so, output the number of samples as a percentage of\n ## the total samples. This gives us the percentage of the time our\n ## script spent executing that line.\n foreach($count in ($counts.Keys | Sort-Object -Descending))\n {\n $line = $counts[$count]\n $percentage = "{0:#0}" -f ($count * 100 / $totalSamples)\n "{0,3}%: Line {1,4} -{2}" -f $percentage,$line,\n $uniqueLines[$line]\n }\n\n ## Go through the transcript log to figure out which lines are part of\n ## any marked regions. This returns a hashtable that maps region names\n ## to the lines they contain.\n ""\n "Breakdown by marked regions:"\n "----------------------------"\n $functionMembers = GenerateFunctionMembers\n\n ## For each region name, cycle through the lines in the region. As we\n ## cycle through the lines, sum up the time spent on those lines and\n ## output the total.\n foreach($key in $functionMembers.Keys)\n {\n $totalTime = 0\n foreach($line in $functionMembers[$key])\n {\n $totalTime += ($samples[$line] * 100 / $totalSamples)\n }\n\n $percentage = "{0:#0}" -f $totalTime\n "{0,3}%: {1}" -f $percentage,$key\n }\n}\n\n## Run the actual profiling of the script. $uniqueLines gets\n## the mapping of line number to actual script content.\n## Return a hashtable mapping line number to the number of times\n## we observed the script running that line.\nfunction GetSamples($uniqueLines)\n{\n ## Open the log file. We use the .Net file I/O, so that we keep\n ## monitoring just the end of the file. Otherwise, we would make our\n ## timing inaccurate as we scan the entire length of the file every time.\n $logStream = [System.IO.File]::Open($Path, "Open", "Read", "ReadWrite")\n $logReader = New-Object System.IO.StreamReader $logStream\n\n $random = New-Object Random\n $samples = @{}\n\n $lastCounted = $null\n\n ## Gather statistics until the user presses a key.\n while(-not $host.UI.RawUI.KeyAvailable)\n {\n ## We sleep a slightly random amount of time. If we sleep a constant\n ## amount of time, we run the very real risk of improperly sampling\n ## scripts that exhibit periodic behaviour.\n $sleepTime = [int] ($random.NextDouble() * 100.0)\n Start-Sleep -Milliseconds $sleepTime\n\n ## Get any content produced by the transcript since our last poll.\n ## From that poll, extract the last DEBUG statement (which is the last\n ## line executed.)\n $rest = $logReader.ReadToEnd()\n $lastEntryIndex = $rest.LastIndexOf("DEBUG: ")\n\n ## If we didn't get a new line, then the script is still working on\n ## the last line that we captured.\n if($lastEntryIndex -lt 0)\n {\n if($lastCounted) { $samples[$lastCounted] ++ }\n continue;\n }\n\n ## Extract the debug line.\n $lastEntryFinish = $rest.IndexOf("\\n", $lastEntryIndex)\n if($lastEntryFinish -eq -1) { $lastEntryFinish = $rest.length }\n\n $scriptLine = $rest.Substring(\n $lastEntryIndex, ($lastEntryFinish - $lastEntryIndex)).Trim()\n if($scriptLine -match 'DEBUG:[ \\t]*([0-9]*)\\+(.*)')\n {\n ## Pull out the line number from the line\n $last = $matches[1]\n\n $lastCounted = $last\n $samples[$last] ++\n\n ## Pull out the actual script line that matches the line number\n $uniqueLines[$last] = $matches[2]\n }\n\n ## Discard anything that's buffered during this poll, and start\n ## waiting again\n $logReader.DiscardBufferedData()\n }\n\n ## Clean up\n $logStream.Close()\n $logReader.Close()\n\n $samples\n}\n\n## Go through the transcript log to figure out which lines are part of any\n## marked regions. This returns a hashtable that maps region names to\n## the lines they contain.\nfunction GenerateFunctionMembers\n{\n ## Create a stack that represents the callstack. That way, if a marked\n ## region contains another marked region, we attribute the statistics\n ## appropriately.\n $callstack = New-Object System.Collections.Stack\n $currentFunction = "Unmarked"\n $callstack.Push($currentFunction)\n\n $functionMembers = @{}\n\n ## Go through each line in the transcript file, from the beginning\n foreach($line in (Get-Content $Path))\n {\n ## Check if we're entering a monitor block\n ## If so, store that we're in that function, and push it onto\n ## the callstack.\n if($line -match 'write-debug "ENTER (.*)"')\n {\n $currentFunction = $matches[1]\n $callstack.Push($currentFunction)\n }\n ## Check if we're exiting a monitor block\n ## If so, clear the "current function" from the callstack,\n ## and store the new "current function" onto the callstack.\n elseif($line -match 'write-debug "EXIT"')\n {\n [void] $callstack.Pop()\n $currentFunction = $callstack.Peek()\n }\n ## Otherwise, this is just a line with some code.\n ## Add the line number as a member of the "current function"\n else\n {\n if($line -match 'DEBUG:[ \\t]*([0-9]*)\\+')\n {\n ## Create the arraylist if it's not initialized\n if(-not $functionMembers[$currentFunction])\n {\n $functionMembers[$currentFunction] =\n New-Object System.Collections.ArrayList\n }\n\n ## Add the current line to the ArrayList\n $hitLines = $functionMembers[$currentFunction]\n if(-not $hitLines.Contains($matches[1]))\n {\n [void] $hitLines.Add($matches[1])\n }\n }\n }\n }\n\n $functionMembers\n}\n\n. Main
|
PowerShellCorpus/PoshCode/PasswordNeverExpires.ps1
|
PasswordNeverExpires.ps1
|
# Synopsis:
# Windows Script to collect usernames and OU locations
# for User Account with Password Set to Never Expire
# and email .txt list to email address
# Author: VulcanX
# Date: 2011/10/11
# Version: 1.0
# Requirements:
# -Quest PSSnapin Installed Locally
# -SMTP Access to Relay/Exchange
# Import AD module for additionals cmdlets
Import-Module ActiveDirectory
# Add Quest Snapin for Get-Q* cmdlets
Add-PSSnapin Quest.ActiveRoles.ADManagement
# Create variable for use later in script
$currentDate = get-date -format "yyyy-MM-dd"
# Find all users with Password Set to Never Expire and Export to a txt
Get-Qaduser -PasswordNeverExpires | Out-File "C:\\Password_Exp\\Exp_$currentdate.txt"
# Create variable for logfile location + name
$attach = "C:\\Password_Exp\\Exp_$currentdate.txt"
# Send Email with .txt attachment to infosec
Send-MailMessage -From 'email1@domain.com' -to 'email2@domain.com' -Subject `
"Password Expiration - $currentDate" -Body "User Accounts whose Passwords Never Expire `n `r Please refer to the txt attachment" `
-Attachments $attach -SmtpServer 'smtp01.domain.com'
|
PowerShellCorpus/PoshCode/Bytes.ps1
|
Bytes.ps1
|
#requires -version 2.0\nAdd-Type @"\npublic class Shift {\n public static int Right(int x, int count) { return x >> count; }\n public static uint Right(uint x, int count) { return x >> count; }\n public static long Right(long x, int count) { return x >> count; }\n public static ulong Right(ulong x, int count) { return x >> count; }\n public static int Left(int x, int count) { return x << count; }\n public static uint Left(uint x, int count) { return x << count; }\n public static long Left(long x, int count) { return x << count; }\n public static ulong Left(ulong x, int count) { return x << count; }\n} \n"@\n\n\n\n#.Example \n# Shift-Left 16 1 ## returns 32\n#.Example \n# 8,16 |Shift-Left ## returns 16,32\nfunction Shift-Left {\nPARAM( $x=1, $y )\nBEGIN {\n if($y) {\n [Shift]::Left( $x, $y )\n }\n}\nPROCESS {\n if($_){\n [Shift]::Left($_, $x)\n }\n}\n}\n\n\n#.Example \n# Shift-Right 8 1 ## returns 4\n#.Example \n# 2,4,8 |Shift-Right 2 ## returns 0,1,2\nfunction Shift-Right {\nPARAM( $x=1, $y )\nBEGIN {\n if($y) {\n [Shift]::Right( $x, $y )\n }\n}\nPROCESS {\n if($_){\n [Shift]::Right($_, $x)\n }\n}\n}\n\n\nfunction Write-FileByte {\n################################################################\n#.Synopsis\n# Overwrites or creates a file with an array of raw bytes.\n#.Parameter ByteArray\n# System.Byte[] array of bytes to put into the file. If you\n# pipe this array in, you must pipe the [Ref] to the array.\n#.Parameter Path\n# Path to the file as a string or as System.IO.FileInfo object.\n# Path as a string can be relative, absolute, or a simple file\n# name if the file is in the present working directory.\n#.Example\n# write-filebyte -bytearray $bytes -path outfile.bin\n#.Example\n# [Ref] $bytes | write-filebyte -path c:\\temp\\outfile.bin\n################################################################\n[CmdletBinding()] Param (\n [Parameter(Mandatory = $True, ValueFromPipeline = $True)] [System.Byte[]] $ByteArray,\n [Parameter(Mandatory = $True)] $Path\n)\n\nif ($Path -is [System.IO.FileInfo])\n { $Path = $Path.FullName }\nelseif ($Path -notlike "*\\*") #Simple file name.\n { $Path = "$pwd" + "\\" + "$Path" }\nelseif ($Path -like ".\\*") #pwd of script\n { $Path = $Path -replace "^\\.",$pwd.Path }\nelseif ($Path -like "..\\*") #parent directory of pwd of script\n { $Path = $Path -replace "^\\.\\.",$(get-item $pwd).Parent.FullName }\nelse\n { throw "Cannot resolve path!" }\n[System.IO.File]::WriteAllBytes($Path, $ByteArray)\n}\n\n\nfunction Convert-HexStringToByteArray {\n################################################################\n#.Synopsis\n# Convert a string of hex data into a System.Byte[] array. An\n# array is always returned, even if it contains only one byte.\n#.Parameter String\n# A string containing hex data in any of a variety of formats,\n# including strings like the following, with or without extra\n# tabs, spaces, quotes or other non-hex characters:\n# 0x41,0x42,0x43,0x44\n# \\x41\\x42\\x43\\x44\n# 41-42-43-44\n# 41424344\n# The string can be piped into the function too.\n################################################################\n[CmdletBinding()]\nParam ( [Parameter(Mandatory = $True, ValueFromPipeline = $True)] [String] $String )\n\n#Clean out whitespaces and any other non-hex crud.\n$String = $String.ToLower() -replace '[^a-f0-9\\\\\\,x\\-\\:]',''\n\n#Try to put into canonical colon-delimited format.\n$String = $String -replace '0x|\\\\x|\\-|,',':'\n\n#Remove beginning and ending colons, and other detritus.\n$String = $String -replace '^:+|:+$|x|\\\\',''\n\n#Maybe there's nothing left over to convert...\nif ($String.Length -eq 0) { ,@() ; return } \n\n#Split string with or without colon delimiters.\nif ($String.Length -eq 1)\n{ ,@([System.Convert]::ToByte($String,16)) }\nelseif (($String.Length % 2 -eq 0) -and ($String.IndexOf(":") -eq -1))\n{ ,@($String -split '([a-f0-9]{2})' | foreach-object { if ($_) {[System.Convert]::ToByte($_,16)}}) }\nelseif ($String.IndexOf(":") -ne -1)\n{ ,@($String -split ':+' | foreach-object {[System.Convert]::ToByte($_,16)}) }\nelse\n{ ,@() }\n#The strange ",@(...)" syntax is needed to force the output into an\n#array even if there is only one element in the output (or none).\n}\n\n\nfunction Convert-ByteArrayToHexString {\n################################################################\n#.Synopsis\n# Returns a hex representation of a System.Byte[] array as\n# one or more strings. Hex format can be changed.\n#.Parameter ByteArray\n# System.Byte[] array of bytes to put into the file. If you\n# pipe this array in, you must pipe the [Ref] to the array.\n# Also accepts a single Byte object instead of Byte[].\n#.Parameter Width\n# Number of hex characters per line of output.\n#.Parameter Delimiter\n# How each pair of hex characters (each byte of input) will be\n# delimited from the next pair in the output. The default\n# looks like "0x41,0xFF,0xB9" but you could specify "\\x" if\n# you want the output like "\\x41\\xFF\\xB9" instead. You do\n# not have to worry about an extra comma, semicolon, colon\n# or tab appearing before each line of output. The default\n# value is ",0x".\n#.Parameter Prepend\n# An optional string you can prepend to each line of hex\n# output, perhaps like '$x += ' to paste into another\n# script, hence the single quotes.\n#.Parameter AddQuotes\n# An switch which will enclose each line in double-quotes.\n#.Example\n# [Byte[]] $x = 0x41,0x42,0x43,0x44\n# Convert-ByteArrayToHexString $x\n#\n# 0x41,0x42,0x43,0x44\n#.Example\n# [Byte[]] $x = 0x41,0x42,0x43,0x44\n# Convert-ByteArrayToHexString $x -width 2 -delimiter "\\x" -addquotes\n#\n# "\\x41\\x42"\n# "\\x43\\x44"\n################################################################\n[CmdletBinding()] Param (\n [Parameter(Mandatory = $True, ValueFromPipeline = $True)] [System.Byte[]] $ByteArray,\n [Parameter()] [Int] $Width = 10,\n [Parameter()] [String] $Delimiter = ",0x",\n [Parameter()] [String] $Prepend = "",\n [Parameter()] [Switch] $AddQuotes\n)\n\nif ($Width -lt 1) { $Width = 1 }\nif ($ByteArray.Length -eq 0) { Return }\n$FirstDelimiter = $Delimiter -Replace "^[\\,\\;\\:\\t]",""\n$From = 0\n$To = $Width - 1\nDo\n{\n $String = [System.BitConverter]::ToString($ByteArray[$From..$To])\n $String = $FirstDelimiter + ($String -replace "\\-",$Delimiter)\n if ($AddQuotes) { $String = '"' + $String + '"' }\n if ($Prepend -ne "") { $String = $Prepend + $String }\n $String\n $From += $Width\n $To += $Width\n} While ($From -lt $ByteArray.Length)\n}\n\n\nfunction Convert-ByteArrayToString {\n################################################################\n#.Synopsis\n# Returns the string representation of a System.Byte[] array.\n# ASCII string is the default, but Unicode, UTF7, UTF8 and\n# UTF32 are available too.\n#.Parameter ByteArray\n# System.Byte[] array of bytes to put into the file. If you\n# pipe this array in, you must pipe the [Ref] to the array.\n# Also accepts a single Byte object instead of Byte[].\n#.Parameter Encoding\n# Encoding of the string: ASCII, Unicode, UTF7, UTF8 or UTF32.\n# ASCII is the default.\n################################################################\n[CmdletBinding()] Param (\n [Parameter(Mandatory = $True, ValueFromPipeline = $True)] [System.Byte[]] $ByteArray,\n [Parameter()] [String] $Encoding = "ASCII"\n)\n\nswitch ( $Encoding.ToUpper() )\n{\n "ASCII" { $EncodingType = "System.Text.ASCIIEncoding" }\n "UNICODE" { $EncodingType = "System.Text.UnicodeEncoding" }\n "UTF7" { $EncodingType = "System.Text.UTF7Encoding" }\n "UTF8" { $EncodingType = "System.Text.UTF8Encoding" }\n "UTF32" { $EncodingType = "System.Text.UTF32Encoding" }\n Default { $EncodingType = "System.Text.ASCIIEncoding" }\n}\n$Encode = new-object $EncodingType\n$Encode.GetString($ByteArray)\n}\n\n\nfunction Get-FileHex {\n################################################################\n#.Synopsis\n# Display the hex dump of a file.\n#.Parameter Path\n# Path to file as a string or as a System.IO.FileInfo object;\n# object can be piped into the function, string cannot.\n#.Parameter Width\n# Number of hex bytes shown per line (default = 16).\n#.Parameter Count\n# Number of bytes in the file to process (default = all).\n#.Parameter NoOffset\n# Switch to suppress offset line numbers in output.\n#.Parameter NoText\n# Switch to suppress ASCII translation of bytes in output.\n################################################################\n[CmdletBinding()] Param (\n [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)]\n [Alias("FullName","FilePath")] $Path,\n [Parameter()] [Int] $Width = 16,\n [Parameter()] [Int] $Count = -1,\n [Parameter()] [Switch] $NoOffset,\n [Parameter()] [Switch] $NoText\n)\n\n$linecounter = 0 # Offset from beginning of file in hex.\n$placeholder = "." # What to print when byte is not a letter or digit.\n\nget-content $path -encoding byte -readcount $width -totalcount $count |\nforeach-object {\n $paddedhex = $asciitext = $null\n $bytes = $_ # Array of [Byte] objects that is $width items in length.\n\n foreach ($byte in $bytes) {\n $byteinhex = [String]::Format("{0:X}", $byte) # Convert byte to hex, e.g., "F".\n $paddedhex += $byteinhex.PadLeft(2,"0") + " " # Pad with zero to force 2-digit length, e.g., "0F ".\n } \n\n # Total bytes in file unlikely to be evenly divisible by $width, so fix last line.\n # Hex output width is '$width * 3' because of the extra spaces added around hex characters.\n if ($paddedhex.length -lt $width * 3)\n { $paddedhex = $paddedhex.PadRight($width * 3," ") }\n\n foreach ($byte in $bytes) {\n if ( [Char]::IsLetterOrDigit($byte) -or\n [Char]::IsPunctuation($byte) -or\n [Char]::IsSymbol($byte) )\n { $asciitext += [Char] $byte }\n else\n { $asciitext += $placeholder }\n }\n\n $offsettext = [String]::Format("{0:X}", $linecounter) # Linecounter in hex too.\n $offsettext = $offsettext.PadLeft(8,"0") + "h:" # Pad linecounter with left zeros.\n $linecounter += $width # Increment linecounter, each line representing $width bytes.\n\n if (-not $NoOffset) { $paddedhex = "$offsettext $paddedhex" }\n if (-not $NoText) { $paddedhex = $paddedhex + $asciitext }\n $paddedhex\n}\n}\n\n\nfunction Toggle-Endian {\n################################################################\n#.Synopsis\n# Swaps the ordering of bytes in an array where each swappable\n# unit can be one or more bytes, and, if more than one, the\n# ordering of the bytes within that unit is NOT swapped. Can\n# be used to toggle between little- and big-endian formats.\n# Cannot be used to swap nibbles or bits within a single byte.\n#.Parameter ByteArray\n# System.Byte[] array of bytes to be rearranged. If you\n# pipe this array in, you must pipe the [Ref] to the array, but\n# a new array will be returned (originally array untouched).\n#.Parameter SubWidthInBytes\n# Defaults to 1 byte. Defines the number of bytes in each unit\n# (or atomic element) which is swapped, but no swapping occurs\n# within that unit. The number of bytes in the ByteArray must\n# be evenly divisible by SubWidthInBytes.\n#.Example\n# $bytearray = toggle-endian $bytearray\n#.Example\n# [Ref] $bytearray | toggle-endian -SubWidthInBytes 2\n################################################################\n[CmdletBinding()] Param (\n [Parameter(Mandatory = $True, ValueFromPipeline = $True)] [System.Byte[]] $ByteArray,\n [Parameter()] [Int] $SubWidthInBytes = 1\n)\n\nif ($ByteArray.count -eq 1 -or $ByteArray.count -eq 0) { $ByteArray ; return } \n\nif ($SubWidthInBytes -eq 1) { [System.Array]::Reverse($ByteArray); $ByteArray ; return } \n\nif ($ByteArray.count % $SubWidthInBytes -ne 0)\n{ throw "ByteArray size must be an even multiple of SubWidthInBytes!" ; return } \n\n$newarray = new-object System.Byte[] $ByteArray.count \n\n# $i tracks ByteArray from head, $j tracks NewArray from end.\nfor ($($i = 0; $j = $newarray.count - 1) ;\n $i -lt $ByteArray.count ;\n $($i += $SubWidthInBytes; $j -= $SubWidthInBytes))\n{\n for ($k = 0 ; $k -lt $SubWidthInBytes ; $k++)\n { $newarray[$j - ($SubWidthInBytes - 1) + $k] = $ByteArray[$i + $k] }\n}\n$newarray\n}\n\n\nfunction PushToTcpPort\n{\n param ([Byte[]] $bytearray, [String] $ipaddress, [Int32] $port)\n $tcpclient = new-object System.Net.Sockets.TcpClient($ipaddress, $port) -ErrorAction "SilentlyContinue"\n trap { "Failed to connect to $ipaddress`:$port" ; return }\n $networkstream = $tcpclient.getstream()\n #write(payload,starting offset,number of bytes to send)\n $networkstream.write($bytearray,0,$bytearray.length)\n $networkstream.close(1) #Wait 1 second before closing TCP session.\n $tcpclient.close()\n}\n
|
PowerShellCorpus/PoshCode/Get-ExchangeDBSizes_2.ps1
|
Get-ExchangeDBSizes_2.ps1
|
<#
.SYNOPSIS
Get-ExchangeDBSizes - Gather data on Exchange 2007 / 2010 Mailbox Databases.
.DESCRIPTION
Gathers data from Exchange mailbox servers.
These data include:
Server\\StorageGroup\\Database (2007) or Database (2010),
Total Size (in GB) of the disk,
Size of the .edb file (in GB),
Free disk space,
Percent Disk Free,
Total Mailboxes on the database,
White Space,
Total Free disk space,
Total Percent Free disk space
.EXAMPLE
Get-ExchangeDBSizes
.LINK
http://unlockpowershell.wordpress.com/
http://poshcode.org/1902
.NOTES
File Name: Get-ExchangeDBSizes.ps1
Author: Karl Mitschke
Requires: Exchange Managemnent Shell
Requires: Powershell V2
Created: 6/14/2010
Modified: 7/28/2010 to convert .EdbFilePath to String
Modified: 7/28/2010 - Changed whitespace to a [double]
#>
Function Get-MountPointInfo($ServerName) {
$Summary = @()
$VolumeHash = @{}
$VolumeCapacityHash = @{}
$DatabaseSizeHash = @{}
$DatabaseFreeHash = @{}
$MountPoints = Get-WmiObject -Class Win32_Mountpoint -ComputerName $ServerName
$MailboxDatabases = Get-MailboxDatabase -Server $ServerName
$Volumes = Get-WmiObject -Class Win32_Volume -ComputerName $ServerName | Where-Object {$_.DriveType -eq 3}| Select-Object Name,FreeSpace,Capacity
$DatabaseLetters = $MailboxDatabases | Select-Object edbfilepath
foreach ($Volume in $Volumes) {
$VolumeHash.Add($Volume.name.TrimEnd("\\"),$Volume.FreeSpace)
$VolumeCapacityHash.Add($Volume.name.TrimEnd("\\"),$Volume.Capacity)
}
foreach ($drive in $DatabaseLetters)
{
$letter = $drive.EdbFilePath.ToString().Substring(0,$drive.EdbFilePath.ToString().LastIndexOf("\\"))
$DatabaseSizeHash.Add($letter.TrimEnd("\\"),$VolumeCapacityHash[$letter])
$DatabaseFreeHash.Add($letter.TrimEnd("\\"),$VolumeHash[$letter])
}
$VolumeHash.Clear()
$VolumeCapacityHash.Clear()
#Now I have all mailbox databases, along with the OS reported free space and capacity
foreach ($MP in $Mountpoints) {
$MP.directory = $MP.directory.replace("\\\\","\\").Split("=")[1].Replace("`"","")
if($DatabaseSizeHash[$MP.directory])
{
#This mountpoint is a database
$Record = new-Object PSObject
$OSfree = $DatabaseFreeHash[$MP.directory]
$OSCapacity = $DatabaseSizeHash[$MP.directory]
$DestFolder = "\\\\"+$ServerName + "\\" + $MP.directory
$colItems = (Get-ChildItem $destfolder.Replace(":","$") -Recurse| where{$_.length -ne $null} |Measure-Object -property length -sum)
if($colItems.sum -eq $null) {
$fsize = 0
} else {
$fsize = $colItems.sum
}
$TotFolderSize = $fsize + $OSfree
$percFree = "{0:P0}" -f ( $OSfree/$TotFolderSize)
$Record | add-Member -memberType noteProperty -name Server -Value $ServerName
$Record | add-Member -memberType noteProperty -name "Mount Point" -Value $MP.directory
$Record | add-Member -memberType noteProperty -name "Capacity" -Value ("{0:N2}" -f ($OSCapacity /1gb))
$Record | add-Member -memberType noteProperty -name "Used" -Value ("{0:N2}" -f ($fsize / 1gb))
$Record | add-Member -memberType noteProperty -name "Free" -Value ("{0:N2}" -f ($OSfree / 1gb))
$Record | add-Member -memberType noteProperty -name "Percent Free" -Value $percFree
$Summary += $Record
}
}
return $Summary
}
function Get-ExchangeWhiteSpace {
param(
$ComputerName = $(throw "ComputerName cannot be empty.")
)
# Convert Dates to WMI CIM dates
$tc = [System.Management.ManagementDateTimeconverter]
$Start =$tc::ToDmtfDateTime( (Get-Date).AddDays(-1).Date )
$End =$tc::ToDmtfDateTime( (Get-Date).Date)
$whiteSpace = @{}
# Create two claculated properties for InsertionStrings values
$DB = @{Name="DB";Expression={$_.InsertionStrings[1]}}
$FreeMB = @{Name="FreeMB";Expression={[int]$_.InsertionStrings[0]}}
$freespace = Get-WMIObject Win32_NTLogEvent -ComputerName $ComputerName -Filter "LogFile='Application' AND EventCode=1221 AND TimeWritten>='$Start' AND TimeWritten<='$End'" | Select-Object $DB,$FreeMB | Sort-Object DB –Unique –Descending
$freespace | ForEach-Object {$whiteSpace.Add($_.DB,$_.FreeMB)}
#Preceding function from Shay Levy http://blogs.microsoft.co.il/blogs/scriptfanatic/archive/2009/08/13/exchange-white-space.aspx
}
$AllServers = @()
$ServerVersion = @{}
foreach ($server in Get-MailboxServer)
{
$ServerName = $server.name
$version = Get-ExchangeServer -Identity $ServerName | Select-Object AdminDisplayVersion
if($version.admindisplayversion.major)
{
$ServerVersion.Add($ServerName,$version.admindisplayversion.major)
}
else
{
$ServerVersion.Add($ServerName,$version.admindisplayversion.Split()[1].split(".")[0])
}
}
foreach ($server in Get-MailboxServer)
{
$ServerName = $server.Name
if ([int]$ServerVersion[$ServerName] -gt 8)
{ #An Exchange 2010 server, so use Get-MailboxDatabase <database> -Status | Select-Object AvailableNewMailboxSpace
$whiteSpace = @{}
$Free = Get-MailboxDatabase -Server $ServerName -Status | Select-Object Server,Name,AvailableNewMailboxSpace
foreach ($item in $free)
{
$db = $ServerName+"\\"+$item.Name
$whiteSpace.Add($item.Name,[double]$item.AvailableNewMailboxSpace.split("(")[1].Split()[0]/1mb)
}
}
Else
{#not an Exchange 2010 server
. Get-ExchangeWhiteSpace $ServerName
}
$MountPoint = . Get-MountPointInfo $ServerName
foreach ($objItem in Get-MailboxDatabase -Server $ServerName)
{
$edbfilepath = $objItem.edbfilepath
$path = "`\\`\\" + $ServerName + "`\\" + $objItem.EdbFilePath.ToString().Split(":")[0] + "$"+ $objItem.EdbFilePath.ToString().Split(":")[1]
$dbsize = Get-ChildItem $path
$dbpath=(Split-Path $EdbFilePath.ToString().Split(":")[1] -Leaf).trimend(".edb")
if (!$MountPoint)
{
$mailboxpath = $ServerName + $EdbFilePath.ToString().Split(":")[1].trimend(".edb")
$size = get-wmiobject -computername $ServerName win32_logicaldisk |where-object {$_.deviceid -eq $objItem.EdbFilePath.ToString().Split("\\")[0]} |select-object deviceID, Freespace, Size
$freespace = ($size.freespace / 1GB)
$total = ($size.size / 1GB)
}
if ($MountPoint)
{
$mailboxpath = "$ServerName\\$dbpath"
$MPPath = $EdbFilePath.ToString().Substring(0,$EdbFilePath.ToString().LastIndexOf("\\"))
$freespace = $DatabaseFreeHash[$MPPath ] /1GB
$total = $DatabaseSizeHash[$MPPath] /1GB
}
$PercentFree = "{0:n2}" -f ($freespace / $total *100)
if (!$MountPoint)
{
$mailboxcount = Get-MailboxStatistics -database "$mailboxpath" |Where {$_.DisconnectDate -eq $null -and $_.ObjectClass -eq 'Mailbox'} |measure-object
}
if($MountPoint)
{
$mailboxcount = Get-MailboxStatistics -database $mailboxpath.Split("\\")[1] |Where {$_.DisconnectDate -eq $null -and $_.ObjectClass -eq 'Mailbox'} |measure-object
}
$ReturnedObj = New-Object PSObject
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Server\\StorageGroup\\Database" -Value $objItem.Identity
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Total Size (GB)" -Value ("{0:n2}" -f ($total))
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Used Space (GB)" -Value ("{0:n2}" -f ($dbsize.Length/1024MB))
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Free Space (GB)" -Value ("{0:n2}" -f ($freespace))
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Percent Disk Free" -Value $percentfree
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "User Mailbox Count" -Value $mailboxcount.count
if ($objitem.Identity.Split("\\").Count -eq 3){$dbasename = $objitem.Identity.Substring($objitem.Identity.IndexOf("\\")+1)}
else{$dbasename = $objitem.Identity}
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "White Space (GB)" -Value ("{0:n2}" -f ($whiteSpace[$dbasename]/1024))
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Total Free (GB)" -Value ("{0:n2}" -f ($freespace + $whiteSpace[$dbasename]/1024))
$TotalPercent = ($freespace + $whiteSpace[$dbasename]/1024) / $total *100
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Total Percent Free" -Value ("{0:n2}" -f ($TotalPercent))
$AllServers += $ReturnedObj
}
}
$AllServers |Export-Csv C:\\scripts\\MailboxDatabaseSizeReport.csv -NoTypeInformation
|
PowerShellCorpus/PoshCode/Get-SPListItem.ps1
|
Get-SPListItem.ps1
|
#.Example
# Get-SPListItem "Scrum Team Assignments"
# Gets all the items in the list with the default columns on them
#.Example
# Get-SPListItem -Name "Scrum Team Assignments" -Property "Scrum Team","Team Role","Last","First"
# Gets all the items in the list with just the specified columns as properties
#.Example
# Get-SPListItem -ListUrl "https://sharepoint.domain.org/subsite/Lists/ListName/AllItems.aspx"
# Deduces list and sharepoint service URL from the list url
function Get-SPListItem {
[CmdletBinding(DefaultParameterSetName="FromListName")]
param(
# Url of the sharepoint (sub)site where the list is. This is NOT the url to the list, but to the site root
# E.g: for https://sharepoint.domain.org/organization/site/Lists/listName/AllItems.aspx
# You should put: https://sharepoint.domain.org/organization/site/
[Parameter(Mandatory=$True, Position=0, ParameterSetName="FromListName")]
[string]$SharepointUrl,
# The name of a sharepoint list to retrieve
[Parameter(Mandatory=$True, Position=1, ParameterSetName="FromListName")]
[String]$Name,
# The full url to a sharepoint list (this only works if the URL has "/Lists/listname/" in it)...
[Parameter(Mandatory=$True,ParameterSetName="FromListUrl")]
[string]$ListUrl,
# Columns that you want to retrieve from the list, as they appear in the list (or extra column names like "Created Date" or "Modified Date")
[String[]]$Property,
# Maximum number of items to retrieve (Defaults to 1000)
[Int]$MaxCount = 1000
)
if($PSCmdlet.ParameterSetName -eq "FromListUrl") {
if(!$ListUrl.Contains("/Lists/")) {
throw "Can't deduce list name from ListUrl"
}
$i = $ListUrl.IndexOf("/Lists/")
$SharepointUrl = $ListUrl.SubString(0,$i)
$ListName = $ListUrl.SubString($i+7, $ListUrl.IndexOf("/",$i+7) - $i - 7)
if($ListName -match "%") {
Add-Type -Assembly System.Web
$ListName = [System.Web.HttpUtility]::UrlDecode($ListName)
}
}
$ServiceUrl = $SharepointUrl.Trim("/") + "/_vti_bin/Lists.asmx"
Write-Verbose "Sharepoint Service Url: $ServiceUrl"
Write-Verbose "Sharepoint List Name: $ListName"
# Must manually set the Service.Url even after you fetch the service (otherwise it points at the root site)
$Service = New-WebServiceProxy $ServiceUrl -UseDefaultCred
$Service.Url = $ServiceUrl
# Help people out (a little) by printing the ErrorString from soap exceptions
trap [System.Web.Services.Protocols.SoapException] {
Write-Error $_.Exception.Detail.errorstring."#text"
throw $_
}
# Get the list metadata from sharepoint and figure out what columns it has:
$list = $Service.GetList($ListName)
Write-Verbose "Default List View URL: $(([Uri]$SharepointUrl).GetLeftPart('authority'))$($List.DefaultViewUrl)"
$Fields = $list.Fields.Field
# A trick for debugging obstinate lists
if($DebugPreference -gt "SilentlyContinue") {
$Global:SPListFields = $Fields
Write-Debug "Global variable SPListFields set to list fields for debugging purposes"
}
# Filter the list of columns if we were given a list
if($Property.Count -gt 0) {
$Fields = $Fields | Where-Object { $Property -contains $_.DisplayName }
} else {
$Fields = $Fields | Where-Object { $_.FromBaseType -ne "TRUE" -and $_.Hidden -ne "TRUE" }
}
# Turn that list of columns into selectors for GetListItems and Select-Object
$ViewFields = @()
$ObjectProperties = @()
foreach($f in $Fields.GetEnumerator()) {
$ViewFields += $f.StaticName
$ObjectProperties += @{ Name = $f.DisplayName; Expression = [ScriptBlock]::Create("`$_.`"ows_$($f.StaticName)`"") }
}
# Generate some xml
[xml]$vf = "<ViewFields>$($ViewFields | ForEach-Object { "<FieldRef Name='$_'/>" })</ViewFields>"
Write-Verbose $vf.OuterXml
$ListItems = $service.GetListItems($listName, "", [Xml]"<Query/>", $vf, $MaxCount, [Xml]"<QueryOptions/>", "").Data.Row
# A trick for debugging obstinate lists
if($DebugPreference -gt "SilentlyContinue") {
$Global:SPObjectProperties = $ObjectProperties
Write-Debug "Global variable SPObjectProperties set to ObjectProperties for debugging purposes"
}
# A trick for debugging obstinate lists
if($DebugPreference -gt "SilentlyContinue") {
$Global:SPListItems = $ListItems
Write-Debug "Global variable SPListItems set to list items for debugging purposes"
}
$ListItems | Select-Object $ObjectProperties
}
|
PowerShellCorpus/PoshCode/Read-Choice.ps1
|
Read-Choice.ps1
|
function Read-Choice {
#.Synopsis
# Prompt the user for a choice, and return the (0-based) index of the selected item
#.Parameter Message
# The question to ask
#.Parameter Choices
# An array of strings representing the "menu" items, with optional ampersands (&) in them to mark (unique) characters to be used to select each item
#.Parameter DefaultChoice
# The (0-based) index of the menu item to select by default (defaults to zero).
#.Parameter Title
# An additional caption that can be displayed (usually above the Message) as part of the prompt
#.Example
# Read-Choice "WEBPAGE BUILDER MENU" "Create Webpage","View HTML code","Publish Webpage","Remove Webpage","E&xit"
PARAM([string]$message, [string[]]$choices, [int]$defaultChoice=0, [string]$Title=$null )
if($choices[0].IndexOf('&') -lt 0) {
$i = 0;
$choices = $choices | ForEach-Object {
if($_ -notmatch '&.') { "&$i $_" } else { $_ }
$i++
}
}
$Host.UI.PromptForChoice( $caption, $message, [Management.Automation.Host.ChoiceDescription[]]$choices, $defaultChoice )
}
|
PowerShellCorpus/PoshCode/Update-ISETabs.ps1
|
Update-ISETabs.ps1
|
foreach($tab in $psISE.PowerShellTabs) {
foreach($file in $tab.Files) {
$position = Select-Object -InputObject $file.Editor -Property CaretLine, CaretColumn
$content = Get-Content $file.FullPath -Raw
if($content -ne $file.Editor.Text) {
$file.Editor.Text = Get-Content $file.FullPath -Raw
Write-Verbose "Updated $($file.DisplayName)"
$file.Editor.SetCaretPosition( $Position.CaretLine, $Position.CaretColumn )
}
}
}
|
PowerShellCorpus/PoshCode/Kill-Process_v2.ps1
|
Kill-Process_v2.ps1
|
function Kill-Process(){
param(
[string[]]$ComputerNames,
[string[]]$ProcessNames,
$User
)
if ($ProcessNames -eq $null){Write-Error 'The parametre "ProcessNames" cannot be empty';break}
if ($User -is [String]){$Connection = Get-Credential -Credential $User}
if ($Connection -eq $null){
foreach ($int1 in $ComputerNames){
foreach ($int2 in $ProcessNames){
if ($int2 -notlike "*.exe") {$int2 = $int2 + '.exe'}
$Kill_Process = gwmi "win32_process" -ComputerName $int1 -filter "name='$int2'" |
% {$_.terminate();$count++}
$Kill_Process = "" | select @{e={$int1};n='Computer'},`
@{e={$int2};n='Process'}, @{e={$count};n='Count'}
$Kill_Process
}
}
}
else {
foreach ($int1 in $ComputerNames){
foreach ($int2 in $ProcessNames){
$Kill_Process = gwmi "win32_process" -ComputerName $int1 -filter "name='$int2'" -Credential $Connection |
% {$_.terminate();$count++}
$Kill_Process = "" | select @{e={$int1};n='Computer'},`
@{e={$int2};n='Process'}, @{e={$count};n='Count'}
$Kill_Process
}
}
}
}
|
PowerShellCorpus/PoshCode/BridgeBot 1.2.ps1
|
BridgeBot 1.2.ps1
|
## Depends on the PoshXmpp.dll from http://CodePlex.com/PoshXmpp
#requires -pssnapin PoshXmpp
##########################################################################################
# @Author: Joel Bennnett
# @Usage:
# Start-JabberMirror.ps1 User@JabberServer.com Password "groupchat@oneserver.com" "groupchat@anotherserver.com" "BridgeBot" "http://rssfeed"
##########################################################################################
param (
$JabberId = $(Read-Host "Jabber Login")
,$Password = $(Read-Host "Password")
,$IRC = "powershell%irc.freenode.net@irc.im.flosoft.biz" # $(Read-Host "First Jabber conference address")
,$JabberConf = "powershell@conference.im.flosoft.biz" # $(Read-Host "Second Jabber conference address")
,$ChatNick = "PowerBot" # $(Read-Host "The nickname you want to use")
,[string[]]$AtomFeeds = @("http://groups.google.com/group/microsoft.public.windows.powershell/feed/atom_v1_0_topics.xml")
)
## Requires System.Web for the RSS-feed option
[Reflection.Assembly]::LoadWithPartialName("System.Web") | Out-Null
function Start-PowerBot {
$global:LastNewsCheck = $([DateTime]::Now.AddHours(-5))
$global:feedReader = new-object Xml.XmlDocument
$global:PoshXmppClient = PoshXmpp\\New-Client $JabberId $Password # http://im.flosoft.biz:5280/http-poll/
PoshXmpp\\Connect-Chat $IRC $ChatNick
PoshXmpp\\Connect-Chat $JabberConf $ChatNick
PoshXmpp\\Send-Message $IRC "Starting Mirror to $('{0}@{1}' -f $JabberConf.Split(@('%','@'),3))"
PoshXmpp\\Send-Message $JabberConf "Starting Mirror to $('{0}@{1}' -f $IRC.Split(@('%','@'),3))"
PoshXmpp\\Send-Message $IRC "/msg nickserv :id Sup3rB0t"
}
function Process-Command($Chat, $Message) {
$split = $message.Body.Split(" |;")
$from = $Message.From.Bare.ToLower()
switch -regex ( $split[0] ) {
"!list" {
Write-Host "!LIST COMMAND. Send users of [$Chat] to [$($Message.From.Bare)]" -fore Magenta
$users = @($PoshXmppClient.ChatManager.GetUsers( $Chat ).Values)
PoshXmpp\\Send-Message $from ("There are $($users.Count) on $($Chat):")
PoshXmpp\\Send-Message $from ($users -join ", ")
}
"!gh|!get-help|!man" {
$help = get-help $split[1] | Select Synopsis,Syntax
$msgs = (get-help $split[1] | ... Synopsis Syntax | Out-String -w 1000 | split-string "`n" -count 4)[0,2];
PoshXmpp\\Send-Message $from $help.Synopsis;
PoshXmpp\\Send-Message $from ($help.Syntax | Out-String -w 1000 | split-string "`n" -count 4 -rem )[1]
}
}
}
# Max IRC Message Length http://www.faqs.org/rfcs/rfc1459.html
# PRIVMSG CHANNEL MSG
$IrcMaxLen = 510 - ("PRIVMSG :".Length + $IRC.Length + $JabberId.split('@')[0].Length)
function Get-Feeds([string[]]$JIDs,[string[]]$AtomFeeds) {
Write-Verbose "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) {
foreach($jid in $JIDs) {
$msg = ([System.Web.HttpUtility]::HtmlDecode($e.summary."#text") -replace "<br>", "").Trim()
$template = "{0} (Posted at {1:hh:mm} by {2}) {{0}} :: {3}" -f
$e.title."#text", [datetime]$e.updated, $e.author.name, $e.link.href
$len = [math]::Min($IrcMaxLen,($template.Length + $msg.Length)) - ($template.Length +3)
PoshXmpp\\Send-Message $jid $($template -f $msg.SubString(0,$len))
}
[Threading.Thread]::Sleep( 500 )
}
}
}
$global:LastNewsCheck = [DateTime]::Now
}
[regex]$anagram = "^Unscramble ... (.*)$"
function Bridge {
PoshXmpp\\Receive-Message -All | foreach-object {
Write-Verbose ("MESSAGE: FROM[{0}] RESOURCE[{1}] BODY[{2}]" -f $_.From.Bare, $_.From.Resource, $_.Body)
if( $_.Type -eq "Error" ) {
Write-Error $_.Error
}
if( $_.From.Resource -ne $ChatNick ) {
$Chat = $null;
if( $_.From.Bare -eq $IRC )
{
$Chat = $JabberConf;
}
elseif( $_.From.Bare -eq $JabberConf )
{
$Chat = $IRC;
}
else
{
$_
}
if($Chat){
if(![String]::IsNullOrEmpty($_.Body) -and ($_.Body[0] -eq '!')) {
PoshXmpp\\Send-Message $Chat ("<{0}> {1}" -f $_.From.Resource, $_.Body)
Process-Command $Chat $_
}
elseif(($_.From.Resource -eq "GeoBot") -and $_.Body.StartsWith("Unscramble ... "))
{
Write-Verbose "KILL ANAGRAM! $($anagram.Match($_.Body).Groups[1].value)"
$answers = Solve-Anagram $($anagram.Match($_.Body).Groups[1].value)
foreach($ans in $answers) {
Write-Verbose "ANAGRAM: $($_.From.Bare) $ans"
PoshXmpp\\Send-Message "$($_.From.Bare.ToLower())" "$ans (PowerShell Scripting FTW!)"
}
}
elseif( ![String]::IsNullOrEmpty($_.Subject) )
{
$_.To = $Chat
# Send it directly using a method on the PoshXmppClient
$PoshXmppClient.Send($_)
}
else
{
PoshXmpp\\Send-Message $Chat ("<{0}> {1}" -f $_.From.Resource, $_.Body)
}
}
}
}
}
function Start-Bridge {
"PRESS ANY KEY TO STOP"
while(!$Host.UI.RawUI.KeyAvailable) {
Bridge
Get-Feeds @($IRC,$JabberConf) $AtomFeeds
$counter = 0
Write-Verbose "PRESS ANY KEY TO STOP" # we're going to wait 3 * 60 seconds
while(!$Host.UI.RawUI.KeyAvailable -and ($counter++ -lt 1800)) {
Bridge
[Threading.Thread]::Sleep( 100 )
}
}
}
function Stop-PowerBot {
PoshXmpp\\Disconnect-Chat $IRC $ChatNick
PoshXmpp\\Disconnect-Chat $JabberConf $ChatNick
$global:PoshXmppClient.Close();
}
##
## Silly anagram spoiler
##
function Solve-Anagram($anagram) {
[xml]$form = Post-HTTP "http://www.anagramsolver.net/Default.aspx" ""
[xml]$result = Post-HTTP "http://www.anagramsolver.net/Default.aspx" (
"{0}&{1}&{2}&btnAnagram=Anagram" -f "txtAnagram=$anagram",
("__VIEWSTATE={0}" -f $($form.SelectSingleNode("//*[@id='__VIEWSTATE']").value)),
("__EVENTVALIDATION={0}" -f $($form.SelectSingleNode("//*[@id='__EVENTVALIDATION']").value)))
$result.SelectSingleNode("//*[@id='lblResult']")."#text"
}
function Post-HTTP($url,$bytes) {
$request = [System.Net.WebRequest]::Create($url)
#$bytes = [Text.Encoding]::UTF8.GetBytes( $post )
$request.ContentType = "application/x-www-form-urlencoded"
$request.ContentLength = $bytes.Length
$request.Method = "POST"
$rq = new-object IO.StreamWriter $request.GetRequestStream()
$rq.Write($bytes,0,$bytes.Length)
$rq.Close()
$response = $request.GetResponse()
$reader = new-object IO.StreamReader $response.GetResponseStream(),[Text.Encoding]::UTF8
return $reader.ReadToEnd()
}
|
PowerShellCorpus/PoshCode/Users_Contacts from CSV_2.ps1
|
Users_Contacts from CSV_2.ps1
|
#=============================================================================#
#=============================================================================#
#=============================================================================#
#
# SCRIPT : CreateOrUpdateUsersOrContacts.ps1
# LAST UPDATE : 9/18/2009
# VERSION : 1.00
#
#
# DESCRIPTION:
# PowerShell script for creating/updating mail-enabled Users or Contact objects
# in Active Directory for Exchange 2003. Uses a CSV source file.
#
#
# TO DO:
# * Logging.
# * Roll-back
# * Eliminate need to hard-code LDAP fields, use CSV header instead.
# * Confirm required LDAP fields are present and populated.
# * Incorporate command-line argument functionality
#
# (NOTE: NONE OF THESE HAVE BEEN IMPLEMENTED YET!!!)
#
# CSV input path and file name
# $File = $args[0] # -f <CSV File Name>
#
# Type of Active Directory object to target
# $ADObject = $args[1] # -a <AD Object Type>
#
# Where the Contacts should be created
# $OUPath = $args[2] # -o <Target OU Path>
#
# Which Exchange environment to create contacts in (CHI or LA)
# $Affiliate = $args[3] # -e <Exchange Environment>
#
# Test only -- Add 'what if' to New-QADObject
# $TestFlag = $args[4] # -t
#
# Domain and username of authentication credentials
# $UserName = $args[5] # -u <domain\\sAMAccountName>
#
# Password for above credentials
# $Password = $args[6] # -p <password>
#
#
# VERSION HISTORY:
# 1.00 - 8/18/2009
# * Initial Release.
#
#
# AUTHOR:
# banglogic - banglogic@gmail.com
#
#=============================================================================#
#=============================================================================#
#=============================================================================#
#=============================================================================#
#=============================================================================#
# Functions
#=============================================================================#
#=============================================================================#
#=============================================================================#
Function Set_People_Attributes {
#=============================================================================#
$Input | Set-QADObject -ObjectAttributes @{
c = ($_.c);
co = ($_.co);
countryCode = ($_.countryCode);
comment = ($_.comment);
company = ($_.company);
description = ($_.description);
division = ($_.division);
employeeID = ($_.employeeID);
employeeType = ($_.employeeType);
extensionAttribute1 = ($_.extensionAttribute1);
extensionAttribute2 = ($_.extensionAttribute2);
extensionAttribute3 = ($_.extensionAttribute3);
extensionAttribute4 = ($_.extensionAttribute4);
extensionAttribute5 = ($_.extensionAttribute5);
extensionAttribute6 = ($_.extensionAttribute6);
extensionAttribute7 = ($_.extensionAttribute7);
extensionAttribute8 = ($_.extensionAttribute8);
extensionAttribute9 = ($_.extensionAttribute9);
extensionAttribute10 = ($_.extensionAttribute10);
extensionAttribute11 = ($_.extensionAttribute11);
extensionAttribute12 = ($_.extensionAttribute12);
extensionAttribute13 = ($_.extensionAttribute13);
extensionAttribute14 = ($_.extensionAttribute14);
extensionAttribute15 = ($_.extensionAttribute15);
facsimileTelephoneNumber = ($_.facsimileTelephoneNumber);
givenName = ($_.givenName);
info = ($_.info);
initials = ($_.initials);
l = ($_.l);
# memberOf = ($_.memberOf); # Group memberships
mobile = ($_.mobile);
physicalDeliveryOfficeName = ($_.physicalDeliveryOfficeName);
postalCode = ($_.postalCode);
sn = ($_.sn);
st = ($_.st);
streetAddress = ($_.streetAddress);
telephoneNumber = ($_.telephoneNumber);
title = ($_.title)
} -Verbose
}
#=============================================================================#
Function Set_User_Attributes {
#=============================================================================#
$Input | Set-QADUser -ObjectAttributes @{
homeDirectory = ($_.homeDirectory);
homeDrive = ($_.homeDrive);
# manager = ($_.manager); # Path of user's manager
mobile = ($_.mobile);
profilePath = ($_.profilePath);
sAMAccountName = ($_.sAMAccountName);
scriptPath = ($_.scriptPath);
userPrincipalName = ($_.sAMAccountName + $Domain);
wWWHomePage = ($_.wWWHomePage)
} -Verbose
}
#=============================================================================#
Function Set_Mail_Attributes {
#=============================================================================#
$Input | Set-QADObject -ObjectAttributes @{
legacyExchangeDN = ($Root_LegacyExchangeDN + $_.mailNickname);
mail = ($_.mail);
mailNickname = ($_.mailNickname);
# msExchHideFromAddressLists = ($_.msExchHideFromAddressLists); # TRUE or FALSE
# msExchHomeServerName = ($_.msExchHomeServerName); # Only for User objects
targetAddress = ($_.targetAddress)
} -Verbose
}
#=============================================================================#
#=============================================================================#
# Script Setup
#=============================================================================#
#=============================================================================#
#=============================================================================#
# Load snap-in for Quest ActiveRoles cmdlets
#=============================================================================#
If (-not (Get-PSSnapin Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue)) {
Add-PSSnapin Quest.ActiveRoles.ADManagement -Verbose
}
#=============================================================================#
# Initialize variables
#=============================================================================#
$CSVPath = "\\\\SERVER\\SharePath\\ListOfPeople.csv"
$PeopleList = Import-Csv $CSVPath -Verbose # CSV file containing people info
$MailEnable = $false
# Set these all to null to clear from last execution.
$ObjectType = $null
$Domain = $null
$OU = $null
$Root_LegacyExchangeDN = $null
$Server = $null
$UserName = $null
#=============================================================================#
# Affiliate Number 1 attributes
#=============================================================================#
$Affiliate1_Contact_OU = "OU=Contacts,DC=affiliate1,DC=com"
$Affiliate1_User_OU = "OU=Users,DC=affiliate1,DC=com"
$Affiliate1_Root_LegacyExchangeDN = "/O=Affiliate 1/OU=AFFILIATE1/cn=Recipients/cn="
$Affiliate1_Domain = "@affiliate1.com"
$Affiliate1_Server = "domaincontroller.affiliate1.com"
#=============================================================================#
# Affiliate Number 2 attributes
#=============================================================================#
$Affiliate2_Contact_OU = "OU=Contacts,DC=affiliate2,DC=com"
$Affiliate2_User_OU = "OU=Users,DC=affiliate2,DC=com"
$Affiliate2_Root_LegacyExchangeDN = "/O=Affiliate 2/OU=AFFILIATE2/cn=Recipients/cn="
$Affiliate2_Domain = "@affiliate2.com"
$Affiliate2_Server = "domaincontroller.affiliate2.com"
#=============================================================================#
# Credentials
#=============================================================================#
$Location = Read-Host "Affiliate location: ''A1'' for Affiliate 1, ''A2'' for Affiliate 2:"
$ObjectType = Read-Host "Object type? ''Contact'' or ''User'':"
If ($Location -eq "AF1") {
If ($ObjectType -eq "User") { $OU = $Affiliate1_User_OU }
Else { $OU = $CHI_Contact_OU }
$Root_LegacyExchangeDN = $Affiliate1_Root_LegacyExchangeDN
$Domain = $Affiliate1_Domain
$Server = $Affiliate1_Server
$UserName = $Affiliate1_UserName
}
If ($Location -eq "AF2") {
If ($ObjectType -eq "User") { $OU = $Affiliate2_User_OU }
Else { $OU = $CHI_Contact_OU }
$Root_LegacyExchangeDN = $Affiliate2_Root_LegacyExchangeDN
$Domain = $Affiliate2_Domain
$Server = $Affiliate2_Server
$UserName = $Affiliate2_UserName
}
$UserName = Read-Host "Enter username for the domain you are connecting to (''DOMAIN\\username''):"
$Password = Read-Host "Enter password for"$UserName -AsSecureString
Connect-QADService -Service $Server -ConnectionAccount $UserName -ConnectionPassword $Password -Verbose
#=============================================================================#
#=============================================================================#
# Main Script
#=============================================================================#
#=============================================================================#
#=============================================================================#
# Create or update Contact or User objects from CSV records
#=============================================================================#
$PeopleList | ForEach-Object {
$Person = Get-QADObject -DisplayName $_.displayName -LdapFilter "(&(objectClass=$ObjectType))" -Verbose
If ($Person -eq $Null){
Write-Host "Creating Object for" $_.displayName -ForegroundColor Green -Verbose
If ($ObjectType -eq "Contact") {
$Person = New-QADObject -ParentContainer $OU -Name $_.cn -Type $ObjectType -DisplayName $_.displayName -Verbose
}
ElseIf ($ObjectType -eq "User") {
$Person = New-QADUser -ParentContainer $OU -Name $_.cn -DisplayName $_.displayName -SamAccountName $_.sAMAccountName -UserPrincipalName ($_.sAMAccountName+"$Domain") -Verbose
$Person | Set_User_Attributes
}
$Person | Set_People_Attributes
}
Else {
Write-Host "Updating Properties for" $_.displayName -ForegroundColor Red -Verbose
$Person | Set_People_Attributes
}
If ($MailEnable -eq $true) {
$Person | Set_Mail_Attributes
}
}
#=============================================================================#
# END SCRIPT
#=============================================================================#
|
PowerShellCorpus/PoshCode/2200e57e-b53f-4e8d-96c9-43d4360ace3e.ps1
|
2200e57e-b53f-4e8d-96c9-43d4360ace3e.ps1
|
# Environment proprties
[string]$QTDIR = "C:\\Qt\\4.8.3-msvc2008"
[string]$rootDir = "C:\\Build\\"
[string]$buildDir = "C:\\Build\\build_dir\\"
[string]$outputDir = "C:\\Build\\output_dir\\"
[string]$svnDir = "C:\\Build\\build_dir\\vacuum"
[string]$svnUrl = "http://vacuum-im.googlecode.com/svn/trunk/"
[string]$qmake = "qmake.exe"
[Environment]::SetEnvironmentVariable("QTDIR", $QTDIR, "User")
$env:Path += ";C:\\Qt\\4.8.3-msvc2008\\bin\\"
Import-VisualStudioVars -VisualStudioVersion 2008 -Architecture x86
$currentScriptDirectory = split-path -parent $MyInvocation.MyCommand.Definition
[Reflection.Assembly]::LoadFile(($currentScriptDirectory + ".\\SharpSvn\\SharpSvn.dll"))
$svnClient = New-Object SharpSvn.SvnClient
$repoUri = New-Object SharpSvn.SvnUriTarget($svnUrl)
Write-Host "Getting source code from subversion repository" $repoUri -ForegroundColor Green
$svnClient.CheckOut($repoUri, $svnDir)
$svnInfo = $null
$svnClient.GetInfo($SvnDir, ([ref]$svnInfo))
$rev = $svnInfo.LastChangeRevision
Set-Location $svnDir
Write-Host "Configuring ..." -ForegroundColor Green
& qmake.exe -r CONFIG-=debug CONFIG+=release INSTALL_PREFIX=C:/Build/output_dir
Write-Host "Building ..." -ForegroundColor Green
& nmake /NOLOGO
Write-Host "Installing ..." -ForegroundColor Green
& nmake install /NOLOGO
|
PowerShellCorpus/PoshCode/Set-IPConfigv4.ps1
|
Set-IPConfigv4.ps1
|
# script parameters
param(
[string[]] $Computers = $env:computername,
[switch] $ChangeSettings,
[switch] $EnableDHCP,
[switch] $IpRelease
)
# script variables
$nl = [Environment]::NewLine
$Domain = "domain.local"
$DNSSuffix = @("domain.local,domain.com")
$DNSServers = @("10.10.0.1", "10.10.0.2", "10.10.0.3", "10.10.0.4")
$WINSServers = @("10.10.0.5", "10.10.0.6")
$Gateway = @("10.10.255.254")
# script functions
Function ChangeIPConfig($NIC){
if ($EnableDHCP){
$NIC.EnableDHCP()
$NIC.SetDNSServerSearchOrder()
}
else{
$DNSServers = Get-random $DNSservers -Count 4
$NIC.SetDNSServerSearchOrder($DNSServers)
#$x = 0
#$IPaddress = @()
#$NetMask = @()
#$Gateway = @()
#$Metric = @()
#foreach ($IP in $NIC.IPAddress){
#$IPaddress[$x] = $NIC.IPAddress[$x]
#$NetMask[$x] = $NIC.IPSubnet[$x]
#$Gateway[$x] = $NIC.DefaultIPGateway[$x]
#$Metric[$x] = $NIC.GatewayCostMetric[$x]
#$x++
#}
#$NIC.EnableStatic($IPaddress, $NetMask)
#$NIC.SetGateways($Gateway, $Metric)
#$NIC.SetWINSServer($WINSServers)
}
$NIC.SetDynamicDNSRegistration("TRUE")
$NIC.SetDNSDomain($Domain)
# remote WMI registry method for updating DNS Suffix SearchOrder
$registry = [WMIClass]"\\\\$computer\\root\\default:StdRegProv"
$HKLM = [UInt32] "0x80000002"
$registry.SetStringValue($HKLM, "SYSTEM\\CurrentControlSet\\Services\\TCPIP\\Parameters", "SearchList", $DNSSuffix)
}
Function ShowDetails($NIC, $Computer){
Write-Output "$($nl)$(" IP settings on: ")$($Computer.ToUpper())$($nl)$($nl)$(" for") $($NIC.Description)$(":")$($nl)"
Write-Output "$("Hostname = ")$($NIC.DNSHostName)"
Write-Output "$("DNSDomain= ")$($NIC.DNSDomain)"
Write-Output "$("Domain DNS Registration Enabled = ")$($NIC.DomainDNSRegistrationEnabled)"
Write-Output "$("Full DNS Registration Enabled = ")$($NIC.FullDNSRegistrationEnabled)"
Write-Output "$("DNS Domain Suffix Search Order = ")$($NIC.DNSDomainSuffixSearchOrder)"
Write-Output "$("MAC address = ")$($NIC.MACAddress)"
Write-Output "$("DHCP enabled = ")$($NIC.DHCPEnabled)"
# show all IP adresses on this NIC
$x = 0
foreach ($IP in $NIC.IPAddress){
Write-Output "$("IP address $x =")$($NIC.IPAddress[$x])$("/")$($NIC.IPSubnet[$x])"
$x++
}
Write-Output "$("Default IP Gateway = ")$($NIC.DefaultIPGateway)"
Write-Output "$("DNS Server Search Order = ")$($NIC.DNSServerSearchOrder)"
}
# actual script execution
foreach ($Computer in $Computers){
If (Test-connection $Computer -quiet -count 1){
Try {
[array]$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration -Computername $Computer -EA Stop | where{$_.IPEnabled -eq "TRUE"}
}
Catch {
Write-Warning "$($error[0])"
Write-Output "$("INACCESIBLE: ")$($nl)$($Computer.ToUpper())"
Write-Host $nl
continue
}
# Generate selection menu
$NICindex = $NICs.count
Write-Host "$nl Selection for "$Computer.ToUpper() ": $nl"
For ($i=0;$i -lt $NICindex; $i++) {
Write-Host -ForegroundColor Green "$i --> $($NICs[$i].Description)"
Write-Output $(ShowDetails $NICs[$i] $Computer)
}
$nl
Write-Host -ForegroundColor Green "q --> Quit" $nl
# Wait for user selection input
Do {
$SelectIndex = Read-Host "Select connection by number or 'q' (=default) to quit"
Switch -regex ($SelectIndex){
"^q.*"{$SelectIndex="quit"; $kip = $true}
"\\d"{$SelectIndex = $SelectIndex -as [int]}
"^\\s*$"{$SelectIndex="quit"; $kip = $true}
}
}
Until (($SelectIndex -lt $NICindex) -OR $SelectIndex -like "q*")
$nl
Write-Host "You selected: $SelectIndex"
#skip current $computer if $true
If ($kip) {continue}
# Change settings for selected network card if option is true and show updated values
If ($ChangeSettings){
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")){
Write-Warning "You need Administrator rights to run this script!"
Break
}
If ($IpRelease){
#$NICs[$SelectIndex].ReleaseDHCPLease
$NICs[$SelectIndex].RenewDHCPLease
}
Else{
ChangeIPConfig $NICs[$SelectIndex]
}
start-sleep -s 2
Write-Host $nl " ====NEW SETTINGS====" $nl
$UpdatedNIC = Get-WMIObject Win32_NetworkAdapterConfiguration -Computername $Computer | where{$_.Index -eq $NICs[$SelectIndex].Index}
Write-Output $(ShowDetails $UpdatedNIC $Computer)$($nl)
}
Else{
If ($SelectIndex -notlike "q*"){
$nl
Write-Warning "For changing settings add -ChangeSettings as parameter, if not this script is output only"
$nl
}
}
}
}
|
PowerShellCorpus/PoshCode/Set-Encoding.ps1
|
Set-Encoding.ps1
|
function Set-Encoding{
<#
.Synopsis
Takes a Script file or any other text file into memory
and Re-Encodes it in the format specified.
.Parameter FilePath
The path to the file to be re-encoded.
.Parameter Unicode
Outputs the file in Unicode format.
.Parameter UTF7
Outputs the file in UTF7 format.
.Parameter UTF8
Outputs the file in UTF8 format.
.Parameter UTF32
Outputs the file in UTF32 format.
.Parameter ASCII
Outputs the file in ASCII format.
.Parameter BigEndianUnicode
Outputs the file in BigEndianUnicode format.
.Parameter Default
Uses the encoding of the system's current ANSI code page.
.Parameter OEM
Uses the current original equipment manufacturer code page
identifier for the operating system.
.Example
ls *.ps1 | Set-Encoding -ASCII
.Description
Written to provide an easy method to perform easy batch
encoding, calls on the command Out-File with the -Encoding
parameter and the -Force switch. Primarily to fix UnknownError
status received when trying to sign non-ascii format files with
digital signatures. Don't use on your MP3's or other non-text
files :)
#>
[CmdletBinding()]
PARAM(
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)]
[ValidateScript({
if((resolve-path $_).Provider.Name -ne "FileSystem") {
throw "Specified Path is not in the FileSystem: '$_'"
}
return $true
})]
[Alias("Fullname","Path")]
[string]$FilePath,
[switch]$Unicode,
[switch]$UTF7,
[switch]$UTF8,
[switch]$UTF32,
[switch]$ASCII,
[switch]$BigEndianUnicode,
[switch]$Default,
[switch]$OEM
)
BEGIN{
$Encoding = ""
switch(
$Unicode,
$UTF7,
$UTF8,
$UTF32,
$ASCII,
$BigEndianUnicode,
$Default,
$OEM
){
$Unicode{$Encoding = "Unicode"}
$UTF7{$Encoding = "UTF7"}
$UTF8{$Encoding = "UTF8"}
$UTF32{$Encoding = "UTF32"}
$ASCII{$Encoding = "ASCII"}
$BigEndianUnicode{$Encoding = "BigEndianUnicode"}
$Default{$Encoding = "Default"}
$OEM{$Encoding = "OEM"}
}
}
PROCESS{
(Get-Content $FilePath) | Out-File -FilePath $FilePath -Encoding $Encoding -Force
}
}
|
PowerShellCorpus/PoshCode/finddupe_15.ps1
|
finddupe_15.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 -eq $null) {"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/Get-ProcedureCallTree.ps1
|
Get-ProcedureCallTree.ps1
|
#requires -version 2
#Uses SQLParser.ps1 script http://poshcode.org/1445 to return Stored Procedure Call Tree
#Chad Miller
#http://chadwickmiller.spaces.live.com/
param ($procedure, $server, $database, $schema='dbo')
add-type -AssemblyName Microsoft.SqlServer.Smo
#Only create the dynamic SQLParser type if it hasn't been created
if (!($global:__SQLParser))
{
$global:__SQLParser = ./SQLParser.ps1
}
#######################
function Invoke-Coalesce
{
param ($expression1, $expression2)
if ($expression1)
{ $expression1 }
else
{ $expression2 }
} #Invoke-Coalesce
#######################
filter Get-StatementByType
{
param ($statementType)
if ($_)
{ $statement = $_ }
#If the statement of specify type is found send to output
if ($statement | Get-Member -Type Property $statementType)
{ $_.$statementType }
else
{
#If the statement type is StatementList (a collection of statements) recursively call filter Get-StatementByType
$property = $statement | Get-Member | where {$_.Definition -like "Microsoft.Data.Schema.ScriptDom.Sql.StatementList*"}
if ($property)
{ $property | foreach {$statement.$($_.Name)} | foreach {$_.Statements} | Get-StatementByType $statementType }
}
}
#######################
function Get-ProcedureReference
{
param ($procedure, $procedureText, $server, $database, $schema)
$srv = new-object ("Microsoft.SqlServer.Management.Smo.Server") $server
#The sqlparser class needs the SQL version information to in order to use version specific parser
#8 is 2000, 9 is 2005 and 10 is 2008.
$sqlparser = switch ($srv.Version.Major)
{
8 { new-object SQLParser Sql80,$false,$procedureText }
9 { new-object SQLParser Sql90,$false,$procedureText }
10 { new-object SQLParser Sql100,$false,$procedureText }
default { new-object SQLParser Sql100,$false,$procedureText }
}
#Fragements => Batches => Statements. The statements will be one of many different types. In this case we are looking for
#a statement type of ExecutableEntity i.e. an EXECUTE statement. Once the statement type if found output the specified properties
$sqlparser.Fragment.Batches | foreach {$_.Statements} | Get-StatementByType 'ExecutableEntity' | foreach {$_.ProcedureReference.Name} |
select @{n='Server';e={Invoke-Coalesce $_.ServerIdentifier.Value $server}}, `
@{n='Database';e={Invoke-Coalesce $_.DatabaseIdentifier.Value $database}}, `
@{n='Schema';e={Invoke-Coalesce $_.SchemaIdentifier.Value $schema}}, @{n='Procedure';e={$_.BaseIdentifier.Value}} |
select *, @{n='Source';e={"{0}.{1}.{2}.{3}" -f $server,$database,$schema,$procedure}}, `
@{n='Target';e={"{0}.{1}.{2}.{3}" -f $_.Server,$_.Database,$_.Schema,$_.Procedure}}
} #Get-ProcedureReference
#######################
function Get-ProcedureText
{
param($server, $database, $schema, $procedure)
#Use SMO to get a reference to server, database and procedure, then call SMO script method
$srv = new-object ("Microsoft.SqlServer.Management.Smo.Server") $server
$db= $srv.Databases[$database]
$proc = $db.StoredProcedures | where {$_.Schema -eq $schema -and $_.Name -eq $procedure}
$proc.Script()
} #Get-ProcedureText
#######################
# MAIN
#######################
$procedureText = Get-ProcedureText $server $database $schema $procedure
#SMO Script method returns a string collection, the first to elements [0] and [1] contain set statements
#There is bug in SMO Script method where the statements are not terminated i.e. no ; or GO statement
#Note: When script method is used with file output scripting option the statements are terminated.
#In our case we don't need the SET statements, just the procedure text, which is element [2]
$procedureReference = Get-ProcedureReference $procedure $procedureText[2] $server $database $schema
$procedureReference
#If a procedureReference object is returned recursively call the PowerShel script
if ($procedureReference)
{ $procedureReference | foreach {./Get-ProcedureCallTree.ps1 $_.Procedure $_.Server $_.Database $_.Schema} }
|
PowerShellCorpus/PoshCode/Get-NestedGroups v_2.ps1
|
Get-NestedGroups v_2.ps1
|
Function Global:Get-NestedGroups {
<#
.SYNOPSIS
Enumerate all AD group memberships of an account (including nested membership).
.DESCRIPTION
This script will return the AD group objects for each group the user is a member of.
.PARAMETER UserName
The username whose group memberships to find.
.EXAMPLE
Get-NestedGroups johndoe | Out-GridView
Get-NestedGroups johndoe, janedoe | % { $_ | Out-GridView }
Get-ADUser -Filter "cn -like 'john*'" | % { Get-NestedGroups $_ | Sort-Object Name | Out-GridView -Title "Groupmembership for $($_)" }
"johndoe","janedoe" | % { Get-NestedGroups $_ | Sort-Object Name | Export-CSV Groupmembership-$($_.Name).csv -Delimiter ";" }
"johndoe","janedoe" | Get-NestedGroups | % { Sort-Object Name | Out-GridView }
.NOTES
ScriptName : Get-NestedGroups
Created By : Gilbert van Griensven
Date Coded : 06/17/2012
Updated : 08/11/2012
The script iterates through all nested groups and skips circular nested groups.
.LINK
#>
[CmdletBinding(SupportsShouldProcess=$True)]
Param (
[Parameter(Mandatory=$True,ValueFromPipeline=$True,HelpMessage="Please enter a username")] $UserName
)
Begin {
$PipelineInput = -not $PSBoundParameters.ContainsKey("UserName")
Write-Verbose "Looking for ActiveDirectory module"
$Script:ADModuleUnload = $False
If (!(Get-Module ActiveDirectory)) {
Write-Verbose "ActiveDirectory module not loaded - checking availability"
If (Get-Module -ListAvailable | ? {$_.Name -eq "ActiveDirectory"}) {
Write-Verbose "ActiveDirectory module is available - loading module"
Import-Module ActiveDirectory
} Else {
Write-Verbose "ActiveDirectory Module is not available"
$Script:ADModuleUnload = $True
}
} Else {
Write-Verbose "ActiveDirectory Module is already loaded"
$Script:ADModuleUnload = $True
}
Function GetNestedGroups {
Get-ADGroup $_ -Properties MemberOf | Select-Object -ExpandProperty MemberOf | % {
If (!(($Script:GroupMembership | Select-Object -ExpandProperty DistinguishedName) -contains (Get-ADGroup $_).DistinguishedName)) {
$Script:GroupMembership += (Get-ADGroup $_)
GetNestedGroups $_
}
}
}
Function GetDirectGroups {
$InputType = $_.GetType().Name
If (($InputType -ne "ADUser") -and ($InputType -ne "String")) {
Write-Error "Invalid input type `'$($_.GetType().FullName)`'" -Category InvalidType -TargetObject $_
Break
}
If ($InputType -eq "String") {
Try {
Write-Verbose "Querying Active Directory for user `'$($_)`'"
$UserObject = Get-ADUser $_
}
Catch {
Write-Verbose "$_"
Write-Error $_ -Category ObjectNotFound -TargetObject $_
Break
}
} Else { $UserObject = $_ }
$Script:GroupMembership = @()
$Script:GroupMembership += (Get-ADGroup "Domain Users")
Get-ADUser $UserObject -Properties MemberOf | Select-Object -ExpandProperty MemberOf | % {
$Script:GroupMembership += (Get-ADGroup $_)
}
$Script:GroupMembership | ForEach-Object {GetNestedGroups $_}
}
}
Process {
If ($PipelineInput) {
GetDirectGroups $_
, $Script:GroupMembership
} Else {
$UserName | ForEach-Object {
GetDirectGroups $_
$Script:GroupMembership
}
}
}
End {
If (!($Script:ADModuleUnload)) {
Write-Verbose "Removing module ActiveDirectory"
Remove-Module ActiveDirectory -ErrorAction SilentlyContinue
}
}
}
|
PowerShellCorpus/PoshCode/Test if file is writable.ps1
|
Test if file is writable.ps1
|
function get-IsWritable(){
<#
.Synopsis
Command tests if a file is present and writable.
.Description
Command to test if a file is writeable. Returns true if file can be opened for write access.
.Example
get-IsWritable -path $foo
Test if file $foo is accesible for write access.
.Example
$bar | get-IsWriteable
Test if each file object in $bar is accesible for write access.
.Parameter Path
Psobject containing the path or object of the file to test for write access.
#>
[CmdletBinding()]
param([Parameter(Mandatory=$true,ValueFromPipeline=$true)][psobject]$path)
process{
Write-Verbose "Test if file $path is writeable"
if (Test-Path -Path $path -PathType Leaf){
Write-Verbose "File is present"
$target = Get-Item $path -Force
Write-Verbose "File is readable"
try{
Write-Verbose "Trying to openwrite"
$writestream = $target.Openwrite()
Write-Verbose "Openwrite succeded"
$writestream.Close() | Out-Null
Write-Verbose "Closing file"
Remove-Variable -Name writestream
Write-Verbose "File is writable"
Write-Output $true
}
catch{
Write-Verbose "Openwrite failed"
Write-Verbose "File is not writable"
Write-Output $false
}
Write-Verbose "Tidying up"
Remove-Variable -Name target
}
else{
Write-Verbose "File $path does not exist or is a directory"
Write-Output $false
}
}
}
|
PowerShellCorpus/PoshCode/Get-UserLogonLogoffScrip.ps1
|
Get-UserLogonLogoffScrip.ps1
|
##############################################################################\n##\n## Get-UserLogonLogoffScript\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 logon or logoff scripts assigned to a specific user\n\n.EXAMPLE\n\nGet-UserLogonLogoffScript LEE-DESK\\LEE Logon\nGets all logon scripts for the user 'LEE-DESK\\Lee'\n\n#>\n\nparam(\n ## The username to examine\n [Parameter(Mandatory = $true)]\n $Username,\n\n [Parameter(Mandatory = $true)]\n [ValidateSet("Logon","Logoff")]\n $ScriptType\n)\n\nSet-StrictMode -Version Latest\n\n## Find the SID for the username\n$account = New-Object System.Security.Principal.NTAccount $username\n$sid =\n $account.Translate([System.Security.Principal.SecurityIdentifier]).Value\n\n## Map that to their group policy scripts\n$registryKey = "HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\" +\n "Group Policy\\State\\$sid\\Scripts"\n\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-2011SGScriptingScore.ps1
|
Get-2011SGScriptingScore.ps1
|
Function Get-2011SGScriptingScore ([Parameter(Mandatory=$True)][STRING]$Contestant) {
$WebClient = New-Object System.Net.WebClient
$Results = $WebClient.DownloadString("https://2011sg.poshcode.org/Reports/TopUsers?filter=Beginner")+$WebClient.DownloadString
("https://2011sg.poshcode.org/Reports/TopUsers?filter=Advanced")
$meIndex = $results.indexof($Contestant)
if($meIndex -eq -1) {
write-output "Contestant name `"$Contestant`" not found"
}
else
{
$myName = $results.substring($meIndex,$Contestant.Length).trim()
$remainingtext = $results.substring($meIndex + $Contestant.length)
$remainingtext = $remainingtext.substring($remainingtext.indexof(">")+1)
$remainingtext = $remainingtext.substring($remainingtext.indexof(">")+1)
$remainingtext = $remainingtext.substring($remainingtext.indexof(">")+1)
$myscore = $remainingtext.substring(0,$remainingtext.indexof("<")).trim()
$remainingtext = $remainingtext.substring($remainingtext.indexof(">")+1)
$remainingtext = $remainingtext.substring($remainingtext.indexof(">")+1)
$myScripts = $remainingtext.substring(0,$remainingtext.indexof("<")).trim()
$remainingtext = $remainingtext.substring($remainingtext.indexof(">")+1)
$remainingtext = $remainingtext.substring($remainingtext.indexof(">")+1)
$myRatings = $remainingtext.substring(0,$remainingtext.indexof("<")).trim()
write-output "Contestant `"$Myname`" has scored $MyScore points from $MyScripts scripts that have accumulated $MyRatings
ratings"
}
<#
.Synopsis
Retrieves Scripting Games score data for a given contestant
.Description
Retrieves HTML from the PoshCode.org site from both the beginning and advanced leaderboards and contatenates the full text output.
The text is then searched for the name of the contestant, and relevant data is retrieved using horrible, horrible text matching code.
.Parameter Contestant
Contestant is a String parameter used to identify the participant in the scripting games. This is a case-insensitive match against
the name under which the user registered for the Scripting Games
.Example
Get-2011SGScriptingScore "ScriptingWife"
Contestant "ScriptingWife" has scored 20.88 points from 9 scripts that have accumulated 24 ratings
.Example
Get-2011SGScriptingScore "NoSuchPlayer"
Contestant name "NoSuchPlayer" not found
#>
}
|
PowerShellCorpus/PoshCode/Set vSphere CDP LinkDisc_1.ps1
|
Set vSphere CDP LinkDisc_1.ps1
|
function set-vSwitchLinkDiscovery {
Param (
#Switch to enable vSwitch Discovery On
[Parameter(Mandatory=$true,ValueFromPipeline=$true)] [string] $vSwitchName = "vSwitch0",
#Host on which the vSwitch Resides
[Parameter(Mandatory=$true,HelpMessage="Need Host Name to connect with")] [string] $VMHost = "NoHostPassed"
) #Param
PROCESS{
#Variables
$linkProtocol = "cdp"
$linkOperation = "both"
#Get the specification for the vSwitch
$networkview = (get-vmhostnetwork -vmhost $VMHost | get-view)
$vSwitchSpec = ($networkView.NetworkConfig.vSwitch | Where {$_.Name -eq $vSwitchName}).Spec
#Set Protocol Type and Operation
$vSwitchSpec.Bridge.LinkDiscoveryProtocolConfig.protocol = $linkProtocol
$vSwitchSpec.Bridge.LinkDiscoveryProtocolConfig.operation = $linkOperation
#Commit Changes
$networkview.updateVirtualSwitch($vSwitchName,$vSwitchSpec)
"Updated " + $VMHost + "'s virtual switch " + $vSwitchName + " to do CDP"
}
}
|
PowerShellCorpus/PoshCode/Add-SqlTable_6.ps1
|
Add-SqlTable_6.ps1
|
try {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop}
catch {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo"}
try {add-type -AssemblyName "Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop}
catch {add-type -AssemblyName "Microsoft.SqlServer.Smo"}
#######################
function Get-SqlType
{
param([string]$TypeName)
switch ($TypeName)
{
'Boolean' {[Data.SqlDbType]::Bit}
'Byte[]' {[Data.SqlDbType]::VarBinary}
'Byte' {[Data.SQLDbType]::VarBinary}
'Datetime' {[Data.SQLDbType]::DateTime}
'Decimal' {[Data.SqlDbType]::Decimal}
'Double' {[Data.SqlDbType]::Float}
'Guid' {[Data.SqlDbType]::UniqueIdentifier}
'Int16' {[Data.SQLDbType]::SmallInt}
'Int32' {[Data.SQLDbType]::Int}
'Int64' {[Data.SqlDbType]::BigInt}
'UInt16' {[Data.SQLDbType]::SmallInt}
'UInt32' {[Data.SQLDbType]::Int}
'UInt64' {[Data.SqlDbType]::BigInt}
'Single' {[Data.SqlDbType]::Decimal}
default {[Data.SqlDbType]::VarChar}
}
} #Get-SqlType
#######################
<#
.SYNOPSIS
Creates a SQL Server table from a DataTable
.DESCRIPTION
Creates a SQL Server table from a DataTable using SMO.
.EXAMPLE
$dt = Invoke-Sqlcmd2 -ServerInstance "Z003\\R2" -Database pubs "select * from authors"; Add-SqlTable -ServerInstance "Z003\\R2" -Database pubscopy -TableName authors -DataTable $dt
This example loads a variable dt of type DataTable from a query and creates an empty SQL Server table
.EXAMPLE
$dt = Get-Alias | Out-DataTable; Add-SqlTable -ServerInstance "Z003\\R2" -Database pubscopy -TableName alias -DataTable $dt
This example creates a DataTable from the properties of Get-Alias and creates an empty SQL Server table.
.NOTES
Add-SqlTable uses SQL Server Management Objects (SMO). SMO is installed with SQL Server Management Studio and is available
as a separate download: http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=ceb4346f-657f-4d28-83f5-aae0c5c83d52
Version History
v1.0 - Chad Miller - Initial Release
v1.1 - Chad Miller - Updated documentation
v1.2 - Chad Miller - Add loading Microsoft.SqlServer.ConnectionInfo
v1.3 - Chad Miller - Added error handling
v1.4 - Chad Miller - Add VarCharMax and VarBinaryMax handling
v1.5 - Chad Miller - Added AsScript switch to output script instead of creating table
v1.6 - Chad Miller - Updated Get-SqlType types
#>
function Add-SqlTable
{
[CmdletBinding()]
param(
[Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance,
[Parameter(Position=1, Mandatory=$true)] [string]$Database,
[Parameter(Position=2, Mandatory=$true)] [String]$TableName,
[Parameter(Position=3, Mandatory=$true)] [System.Data.DataTable]$DataTable,
[Parameter(Position=4, Mandatory=$false)] [string]$Username,
[Parameter(Position=5, Mandatory=$false)] [string]$Password,
[ValidateRange(0,8000)]
[Parameter(Position=6, Mandatory=$false)] [Int32]$MaxLength=1000,
[Parameter(Position=7, Mandatory=$false)] [switch]$AsScript
)
try {
if($Username)
{ $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $ServerInstance,$Username,$Password }
else
{ $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $ServerInstance }
$con.Connect()
$server = new-object ("Microsoft.SqlServer.Management.Smo.Server") $con
$db = $server.Databases[$Database]
$table = new-object ("Microsoft.SqlServer.Management.Smo.Table") $db, $TableName
foreach ($column in $DataTable.Columns)
{
$sqlDbType = [Microsoft.SqlServer.Management.Smo.SqlDataType]"$(Get-SqlType $column.DataType.Name)"
if ($sqlDbType -eq 'VarBinary' -or $sqlDbType -eq 'VarChar')
{
if ($MaxLength -gt 0)
{$dataType = new-object ("Microsoft.SqlServer.Management.Smo.DataType") $sqlDbType, $MaxLength}
else
{ $sqlDbType = [Microsoft.SqlServer.Management.Smo.SqlDataType]"$(Get-SqlType $column.DataType.Name)Max"
$dataType = new-object ("Microsoft.SqlServer.Management.Smo.DataType") $sqlDbType
}
}
else
{ $dataType = new-object ("Microsoft.SqlServer.Management.Smo.DataType") $sqlDbType }
$col = new-object ("Microsoft.SqlServer.Management.Smo.Column") $table, $column.ColumnName, $dataType
$col.Nullable = $column.AllowDBNull
$table.Columns.Add($col)
}
if ($AsScript) {
$table.Script()
}
else {
$table.Create()
}
}
catch {
$message = $_.Exception.GetBaseException().Message
Write-Error $message
}
} #Add-SqlTable
|
PowerShellCorpus/PoshCode/PSTUtility_1.psm1.ps1
|
PSTUtility_1.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/Magister SOAP Webrequest.ps1
|
Magister SOAP Webrequest.ps1
|
# Execute-MagisterSOAP.ps1
# We are reading a list of students from a Magister SOAP webrequest.
# 20120330
# Paul Wiegmans
Clear
Set-StrictMode -Version 2
$mijnpad = Split-Path -parent $MyInvocation.MyCommand.Definition
Echo "Mijn pad is: $mijnpad "
# This is the Magister webquery URL
$layout = "Basis"
$username = "user"
$passwd = "pass"
$WebqueryUrl = "https://bonhoeffer.swp.nl:8800/doc?Function=GetData"`
+"&Library=Data&SessionToken=$username%3B$passwd&Layout=$layout"`
+"&Parameters=leerjaar%3D1112&Type=CSV"
function Doe-Webquery ($Url) {
# .SYNOPSIS
# Voert een SOAP webquery uit
# .DESCRIPTION
# Voert een SOAP webquery uit.
# Retourneert het resultaat van de qebquery in een array met string
# .PARAMETER Url
# De URL van de webquery
# .EXAMPLE
# $lines = Doe-Webquery "https://bonhoeffer.swp.nl:8800/doc?Bladibla..."
# .NOTES
# Auteur: Paul Wiegmans
# Datum: 30 mrt 2012
$request = [System.Net.WebRequest]::Create($Url)
$response = $request.GetResponse()
$requestStream = $response.GetResponseStream()
$MagisterEncoding = [System.Text.Encoding]::UTF7
# We must read the Magister webquery in UTF7 to preserve the accents!
$readStream = new-object System.IO.StreamReader( $requestStream, $MagisterEncoding )
$result = $readStream.ReadToEnd() -split "`n" # convert to array of strings
$readStream.Close()
$response.Close()
return $result
}
$lines = Doe-Webquery $WebQueryUrl
Echo "Webquery geeft $($lines.count) regels"
$velden = $lines[0] -split ";" # list of fieldnames
$lijst = $lines[1..$lines.Count] #
# uitvoer naar file
$lines | Out-File -FilePath "$mijnpad\\soap.csv" -Encoding utf8 # encoding is utf8 of ascii
|
PowerShellCorpus/PoshCode/Get-RemoteRegistry_1.ps1
|
Get-RemoteRegistry_1.ps1
|
## Get-RemoteRegistry
########################################################################################
## Version: 2.0
## + I added the "Properties" parameter so you can select specific registry values
## NOTE: you have to have access, and the remote registry service has to be running
########################################################################################
## USAGE:
## Get-RemoteRegistry $RemotePC "HKLM\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP"
## * Returns a list of subkeys (because this key has no properties)
## Get-RemoteRegistry $RemotePC "HKLM\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v2.0.50727"
## * Returns a list of subkeys and all the other "properties" of the key
## Get-RemoteRegistry $RemotePC "HKLM\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v2.0.50727\\Version"
## * Returns JUST the full version of the .Net SP2 as a STRING (to preserve prior behavior)
## Get-RemoteRegistry $RemotePC "HKLM\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v2.0.50727" Version
## * Returns a custom object with the property "Version" = "2.0.50727.3053" (your version)
## Get-RemoteRegistry $RemotePC "HKLM\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v2.0.50727" Version,SP
## * Returns a custom object with "Version" and "SP" (Service Pack) properties
##
## For fun, get all versions (2.0 and greater) and return version + service pack:
## Get-RemoteRegistry $RemotePC "HKLM:\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP" |
## Select -Expand Subkeys |
## ForEach-Object { Get-RemoteRegistry Duo "HKLM:\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\$_" Version,SP }
##
########################################################################################
# Function Get-RemoteRegistry {
param(
[string]$computer = $(Read-Host "Remote Computer Name")
,[string]$Path = $(Read-Host "Remote Registry Path (must start with HKLM,HKCU,etc)")
,[string[]]$Properties
,[switch]$Verbose
)
if ($Verbose) { $VerbosePreference = 2 } # Only affects this script.
$root, $last = $Path.Split("\\")
$last = $last[-1]
$Path = $Path.Substring($root.Length + 1,$Path.Length - ( $last.Length + $root.Length + 2))
#split the path to get a list of subkeys that we will need to access
# ClassesRoot, CurrentUser, LocalMachine, Users, PerformanceData, CurrentConfig, DynData
switch($root) {
"HKCR" { $root = "ClassesRoot"}
"HKCU" { $root = "CurrentUser" }
"HKLM" { $root = "LocalMachine" }
"HKU" { $root = "Users" }
"HKPD" { $root = "PerformanceData"}
"HKCC" { $root = "CurrentConfig"}
"HKDD" { $root = "DynData"}
default { return "Path argument is not valid" }
}
#Access Remote Registry Key using the static OpenRemoteBaseKey method.
Write-Verbose "Accessing $root from $computer"
$rootkey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($root,$computer)
if(-not $rootkey) { Write-Error "Can't open the remote $root registry hive" }
Write-Verbose "Opening $Path"
$key = $rootkey.OpenSubKey( $Path )
if(-not $key) { Write-Error "Can't open $($root + '\\' + $Path) on $computer" }
$subkey = $key.OpenSubKey( $last )
$output = new-object object
if($subkey -and $Properties -and $Properties.Count) {
foreach($property in $Properties) {
Add-Member -InputObject $output -Type NoteProperty -Name $property -Value $subkey.GetValue($property)
}
Write-Output $output
} elseif($subkey) {
Add-Member -InputObject $output -Type NoteProperty -Name "Subkeys" -Value @($subkey.GetSubKeyNames())
foreach($property in $subkey.GetValueNames()) {
Add-Member -InputObject $output -Type NoteProperty -Name $property -Value $subkey.GetValue($property)
}
Write-Output $output
}
else
{
$key.GetValue($last)
}
# }
|
PowerShellCorpus/PoshCode/Get-WebFile 3.1.ps1
|
Get-WebFile 3.1.ps1
|
## Get-WebFile.ps1 (aka wget for PowerShell)
##############################################################################################################
## Downloads a file or page from the web
## History:
## v3.1 - Unwrap the filename when it has quotes around it
## v3 - rewritten completely using HttpWebRequest + HttpWebResponse to figure out the file name, if possible
## v2 - adds a ton of parsing to make the output pretty
## - added measuring the scripts involved in the command, (uses Tokenizer)
##############################################################################################################
#function wget {
param(
$url = (Read-Host "The URL to download"),
$fileName
)
$req = [System.Net.HttpWebRequest]::Create($url);
$res = $req.GetResponse();
if($fileName -and !(Split-Path $fileName)) {
$fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName
}
elseif(($fileName -eq $null) -or (Test-Path -PathType "Container" $fileName))
{
# if( -and !((Test-Path -PathType "Leaf" $fileName) -or ((Test-Path -PathType "Container" (Split-Path $fileName)) -and -not )))
[string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $res.Headers["Content-Disposition"] ).Groups[1].Value
$fileName = $fileName.trim("\\/""'")
if(!$fileName) {
$fileName = $res.ResponseUri.Segments[-1]
$fileName = $fileName.trim("\\/")
if(!$fileName) {
$fileName = Read-Host "Please provide a file name"
}
$fileName = $fileName.trim("\\/")
if(!([IO.FileInfo]$fileName).Extension) {
$fileName = $fileName + "." + $res.ContentType.Split(";")[0].Split("/")[1]
}
}
$fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName
}
if($res.StatusCode -eq 200) {
$reader = new-object System.IO.StreamReader $res.GetResponseStream()
$writer = new-object System.IO.StreamWriter $fileName
# TODO: stick this in a loop and give progress reports
$writer.Write($reader.ReadToEnd())
$reader.Close();
$writer.Close();
}
$res.Close();
ls $fileName
#}
|
PowerShellCorpus/PoshCode/New-ObjectRecursive_1.ps1
|
New-ObjectRecursive_1.ps1
|
<#
.Synopsis
Creates new object based on hashtable definition
.Description
Function is wrapper for New-Object that allows user to create nested objects using nested hashtable as definition.
If you want to take advantage of type use 'Type' key within hashtable that defines object.
.Example
$obj = New-ObjectRecursive @{Test = @{ InnerTest = 'Value'; AnotherInner = 'Another'; InnerwithInner = @{ Deepest = 'It is very deep'}}; Flat = 'SomeValue'}
$obj.Test.InnerwithInner.Deepest
It is very deep
Create simpe custom object with several inner psobjects, depending of hashtable structure.
.Example
(New-ObjectRecursive @{ Type = 'Windows.Forms.Form'; Size = @{ Type = 'Drawing.Size'; width = 400; Height = 400}; Text = 'Title of window'}).ShowDialog()
Display windows form of size 400 x 400 and title 'Title of window', assuming Windows.Forms are loaded.
#>
param(
$Property
)
if ($Property -is [hashtable]) {
if ($Type = $Property.Type) {
$Property.Remove('Type')
} else {
$Type = 'PSObject'
}
$PropertyHash = @{}
foreach ($key in $Property.keys) {
$PropertyHash.Add($key, $(New-ObjectRecursive $Property[$key]))
}
Try {
New-Object $Type -Property $PropertyHash -ErrorAction SilentlyContinue
if (!$?) {
Write-Host -ForegroundColor Red $Error[0].Exception.Message
}
} catch {
Write-Host -ForegroundColor Red "Problems with creating object of type: $Type. Try to use PSObject instead . . ."
New-Object PSObject -Property $PropertyHash -ErrorAction SilentlyContinue
Write-Host -ForegroundColor Red "Error message:" $_.Exception.Message
}
} else {
$Property
}
|
PowerShellCorpus/PoshCode/Send-FTP 1.0.ps1
|
Send-FTP 1.0.ps1
|
function Send-FTP {
Param(
$Server = "ilncenter.net"
, $Credentials = $(Get-Credential)
, [Parameter(ValueFromPipeline=$true)]
$LocalFile
, $Path = "/"
, $RemoteFile = $(Split-Path $LocalFile -Leaf)
, $ParentProgressId = -1 ## Just ignore this ;)
, $ProgressActivity = "Uploading $LocalFile"
)
Process {
## Assert the existence of the file in question
if( -not (Test-Path $LocalFile) ) {
Throw "File '$LocalFile' does not exist!"
}
## Create the server string (and make sure it uses forward slashes and ftp://)
$upload = "ftp://" + $Server + ( Join-Path (Join-Path "/" $Path) $RemoteFile ) -replace "\\\\", "/"
#$Upload = $upload
$total = (gci $LocalFile).Length
Write-Debug $upload
## Create FTP request
$request = [Net.FtpWebRequest]::Create($upload)
## NOTE: we do not create a folder here...
# [System.Net.WebRequestMethods+Ftp]::MakeDirectory
$request.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$request.Credentials = $Credentials.GetNetworkCredential()
$request.UsePassive = $true
$request.UseBinary = $true
$request.KeepAlive = $false
try {
## Load the file
$read = [IO.File]::OpenRead( (Convert-Path $LocalFile) )
$write = $request.GetRequestStream();
$buffer = new-object byte[] 20KB
$offset = 0
$progress = 0
do {
$offset = $read.Read($buffer, 0, $buffer.Length)
$progress += $offset
$write.Write($buffer, 0, $offset);
Write-Progress $ProgressActivity "Uploading" -Percent ([int]($progress/$total * 100)) -Parent $ParentProgressId
} while($offset -gt 0)
} finally {
Write-Debug "Closing Handles"
$read.Close()
$write.Close()
}
}
}
|
PowerShellCorpus/PoshCode/Get-Entropy_1.ps1
|
Get-Entropy_1.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/Get-DefragAnalysis.ps1
|
Get-DefragAnalysis.ps1
|
# defrag_analysis.ps1
#
# Displays Defrag Analysis Info for a remote server.
#
# Author: tojo2000@tojo2000.com
Set-PSDebug -Strict`
trap [Exception] {
continue
}
function GenerateForm {
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
$form1 = New-Object System.Windows.Forms.Form
$richTextBox1 = New-Object System.Windows.Forms.RichTextBox
$textBox1 = New-Object System.Windows.Forms.TextBox
$button1 = New-Object System.Windows.Forms.Button
$handler_button1_Click = {
$richTextBox1.Text = ''
$volumes = @(gwmi Win32_Volume -ComputerName $textBox1.Text `
-Filter 'DriveType = 3')
foreach ($volume in $volumes) {
$analysis = $volume.DefragAnalysis().DefragAnalysis
Write-TextBox "Drive : $($volume.DriveLetter)"
Write-TextBox "Volume Name : $($analysis.VolumeName)"
Write-TextBox ("Volume Size : " +
"{0:0.00}GB" -f ($analysis.VolumeSize/1GB))
Write-TextBox "Total Fragmentation : $($analysis.TotalPercentFragmentation)%"
Write-TextBox ""
Write-TextBox "Free Space : $($analysis.FreeSpacePercent)%"
Write-TextBox ("Free Space Frag. : " +
"$($analysis.FreeSpacePercentFragmentation)%")
Write-TextBox ""
Write-TextBox "Files : $($analysis.TotalFiles)"
Write-TextBox "Fragmented Files : $($analysis.TotalFragmentedFiles)"
Write-TextBox "File Fragmentation : $($analysis.FilePercentFragmentation)%"
Write-TextBox ""
Write-TextBox "Folders : $($analysis.TotalFolders)"
Write-TextBox "Fragmented Folders : $($analysis.FragmentedFolders)"
Write-TextBox ""
Write-TextBox "MFT Usage : $($analysis.MFTPercentInUse)%"
Write-TextBox "MFT Fragments : $($analysis.TotalMFTFragments)"
Write-TextBox "MFT Records : $($analysis.MFTRecordCount)"
Write-TextBox ""
Write-TextBox ("PageFile Size : " +
"{0:0.00}GB" -f ($analysis.PageFileSize/1GB))
Write-TextBox "PageFile Fragments : $($analysis.TotalPageFileFragments)"
Write-TextBox ""
Write-TextBox "----------------------------"
}
}
$handler_form1_Load = {
$textBox1.Select()
}
$form1.Name = 'form1'
$form1.Text = 'Defrag Info 1.0'
$form1.BackColor = [System.Drawing.Color]::FromArgb(255,227,227,227)
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 428
$System_Drawing_Size.Height = 404
$form1.ClientSize = $System_Drawing_Size
$form1.add_Load($handler_form1_Load)
$richTextBox1.Text = ''
$richTextBox1.TabIndex = 2
$richTextBox1.Name = 'richTextBox1'
$richTextBox1.Font = New-Object System.Drawing.Font("Courier New",10,0,3,0)
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 343
$System_Drawing_Size.Height = 315
$richTextBox1.Size = $System_Drawing_Size
$richTextBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 40
$System_Drawing_Point.Y = 61
$richTextBox1.Location = $System_Drawing_Point
$form1.Controls.Add($richTextBox1)
$textBox1.Text = '<Enter Server Name>'
$textBox1.Name = 'textBox1'
$textBox1.TabIndex = 1
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 250
$System_Drawing_Size.Height = 20
$textBox1.Size = $System_Drawing_Size
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 40
$System_Drawing_Point.Y = 21
$textBox1.Location = $System_Drawing_Point
$textBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$form1.Controls.Add($textBox1)
$button1.UseVisualStyleBackColor = $True
$button1.Text = 'Analyze'
$button1.DataBindings.DefaultDataSourceUpdateMode = 0
$button1.TabIndex = 0
$button1.Name = 'button1'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 75
$System_Drawing_Size.Height = 23
$button1.Size = $System_Drawing_Size
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 308
$System_Drawing_Point.Y = 19
$button1.Location = $System_Drawing_Point
$button1.add_Click($handler_button1_Click)
$form1.Controls.Add($button1)
$form1.ShowDialog()| Out-Null
}
function Write-TextBox {
param([string]$text)
$richTextBox1.Text += "$text`n"
}
# Launch the form
GenerateForm
|
PowerShellCorpus/PoshCode/Resolve-Url.ps1
|
Resolve-Url.ps1
|
###################################
## Figure out the real url behind those shortened forms
function Resolve-URL([string[]]$urls) {
[regex]$snip = "(?:https?://)?(?:snurl|snipr|snipurl)\\.com/([^?/ ]*)\\b"
[regex]$tiny = "(?:https?://)?TinyURL.com/([^?/ ]*)\\b"
[regex]$isgd = "(?:https?://)?is.gd/([^?/ ]*)\\b"
[regex]$twurl = "(?:https?://)?twurl.nl/([^?/ ]*)\\b"
switch -regex ($urls) {
$snip {
write-output $snip.Replace( $_, (new-object System.Net.WebClient
).DownloadString("http://snipurl.com/resolveurl?id=$($snip.match( $_ ).groups[1].value)"))
}
$tiny {
$doc = ConvertFrom-Html "http://tinyurl.com/preview.php?num=$($tiny.match( $_ ).groups[1].value)"
write-output $tiny.Replace( $_, "$($doc.SelectSingleNode(""//a[@id='redirecturl']"").href)" )
}
$isgd {
$doc = ConvertFrom-Html "http://is.gd/$($isgd.match( $_ ).groups[1].value)-"
write-output $isgd.Replace( $_, "$($doc.SelectSingleNode(""//div[@id='main']/p/a"").href)")
}
$twurl {
$doc = ConvertFrom-Html "http://tweetburner.com/links/$($twurl.match( $_ ).groups[1].value)"
write-output $twurl.Replace($_, "$($doc.selectsingleNode(""//div[@id='main-content']/p/a"").href)" )
}
default { write-output $_ }
}
}
|
PowerShellCorpus/PoshCode/AddTo-HostsFile_1.ps1
|
AddTo-HostsFile_1.ps1
|
function AddTo-HostsFile{
<#
.DESCRIPTION
This function checks to see if an entry exists in the hosts file.
If it does not, it attempts to add it and verifies the entry.
.EXAMPLE
Networkign.AddTo-Hosts -IPAddress 192.168.0.1 -HostName MyMachine
.EXTERNALHELP
None.
.FORWARDHELPTARGETNAME
None.
.INPUTS
System.String.
.LINK
None.
.NOTES
None.
.OUTPUTS
System.String.
.PARAMETER IPAddress
A string representing an IP address.
.PARAMETER HostName
A string representing a host name.
.SYNOPSIS
Add entries to the hosts file.
#>
param(
[parameter(Mandatory=$true,position=0)]
[string]
$IPAddress,
[parameter(Mandatory=$true,position=1)]
[string]
$HostName
)
$HostsLocation = "$env:windir\\System32\\drivers\\etc\\hosts";
$NewHostEntry = "`t$IPAddress`t$HostName";
if((gc $HostsLocation) -contains $NewHostEntry)
{
Write-Host "$(Time-Stamp): The hosts file already contains the entry: $NewHostEntry. File not updated.";
}
else
{
Write-Host "$(Time-Stamp): The hosts file does not contain the entry: $NewHostEntry. Attempting to update.";
Add-Content -Path $HostsLocation -Value $NewHostEntry;
}
# Validate entry
if((gc $HostsLocation) -contains $NewHostEntry)
{
Write-Host "$(Time-Stamp): New entry, $NewHostEntry, added to $HostsLocation.";
}
else
{
Write-Host "$(Time-Stamp): The new entry, $NewHostEntry, was not added to $HostsLocation.";
}
}
|
PowerShellCorpus/PoshCode/Get-Field_2.ps1
|
Get-Field_2.ps1
|
function Get-Field{
[CmdletBinding()]
param (
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)]
$InputObject,
[Parameter(Position=1,Mandatory=$false)]
[string]$Name,
[switch]$Force,
[switch]$AsHashtable
)
$publicNonPublic = [Reflection.BindingFlags]::Public -bor [Reflection.BindingFlags]::NonPublic
$instance = $publicNonPublic -bor [Reflection.BindingFlags]::Instance
$getField = $instance -bor [Reflection.BindingFlags]::GetField
$type = $InputObject.gettype()
$result = @()
while ($type -ne [object] -and $type -ne [MarshalByRefObject] ) {
$fields = $type.GetFields($instance)
$result += $fields | Select-Object @{n="Name";e={$_.Name}},@{n="Value";e={$type.InvokeMember($_.Name, $getField, $null, $InputObject, $null)}}
$type = $type.BaseType
if (!$Force) { break; }
}
if (!$Name) {
if ($AsHashtable) {
$hash = @{}
$result | Foreach-Object {
$hash[$_.Name] = $_.Value
}
return $hash
}
else {
return $result
}
}
$result | ForEach-Object { if ($_.Name -eq $Name) { $_.Value } }
}
New-Alias -Name gf -Value Get-Field -Force
|
PowerShellCorpus/PoshCode/Get-PDC09Videos.ps1
|
Get-PDC09Videos.ps1
|
#requires -version 2.0
PARAM (
[Parameter(Position=1, Mandatory=$true)]
[ValidateSet("wmv","wmvhigh","ppt")] # the "mp4" files aren't there yet
[String]$MediaType,
[string]$Destination = $PWD
)
Import-Module BitsTransfer
$Extension = $(switch -wildcard($MediaType){"wmv*"{"wmv"} "mp4"{"mp4"} "ppt"{"pptx"}})
$xfer = Start-BitsTransfer -Suspended `
$("http://ecn.channel9.msdn.com/o9/pdc09/{0}/KYN01-PGM.{1}" -f $MediaType, $Extension),
$("http://ecn.channel9.msdn.com/o9/pdc09/{0}/KYN02-PGM.{1}" -f $MediaType, $Extension) `
$(Join-Path $Destination "Keynote1.$Extension" ),
$(Join-Path $Destination "Keynote2.$Extension" )
foreach( $session in "CL09","CL18","FT02","FT06","FT11","PR05","SVC01","SVC10","SVC20","SVR03",
"CL30","CL33","FT30","FT31","PR31","SVC30","SVC37","SVR33","VTL30","VTL32","CL04","CL14","CL25",
"FT18","FT19","FT25","PR02","SVC13","SVR01","SVR14","CL13","CL29","FT10","FT28","FT57","PR11",
"SVC52","SVR15","SVR17","CL11","CL17","CL23","FT03","FT08","PR10","SVR16","VTL01","CL01","FT50",
"FT52","FT55","FT59","PR13","SVC02","SVC03","SVC15","CL31","CL34","FT32","FT34","FT36","SVC31",
"SVC32","SVR31","VTL31","CL15","FT12","FT17","FT58","SVC16","SVC28","SVC53","SVR11","VTL05",
"CL06","FT04","FT07","FT29","PR06","SVC09","SVC17","SVR13","VTL04","CL12","CL22","FT22","FT23",
"FT26","SVC04","SVC14","SVC19","SVC54","SVR12","CL02","CL05","CL16","FT21","FT56","PR03","SVC08",
"SVC18","SVR10","VTL03","CL10","FT13","FT53","FT60","PR07","SVC06","SVC25","SVR07","SVR18",
"VTL02","CL03","CL21","CL27","FT14","FT20","FT24","PR09","SVC12","SVR09","SVR19","CL32","CL35",
"CL36","FT33","FT35","PR30","PR33","SVC33","SVC36","SVR32","CL07","CL24","CL28","FT09","FT16",
"FT27","PR12","SVC27","SVR02","SVR06","CL26","FT05","FT54","PR01","PR14","SVC23","SVC26","SVR08")
{
Add-BitsFile $xfer $("http://ecn.channel9.msdn.com/o9/pdc09/{0}/{2}.{1}" -f $MediaType, $session, $Extension) $(Join-Path $Destination "${Session}.${Extension}")
}
Resume-BitsTransfer $xfer
|
PowerShellCorpus/PoshCode/New-Shortcut_2.ps1
|
New-Shortcut_2.ps1
|
[CmdletBinding()]
param (
[parameter(Mandatory=$true)]
[ValidateScript( {[IO.File]::Exists($_)} )]
[System.IO.FileInfo] $Target,
[ValidateScript( {[IO.Directory]::Exists($_)} )]
[System.IO.DirectoryInfo] $OutputDirectory,
[string] $Name,
[string] $Description,
[string] $Arguments,
[System.IO.DirectoryInfo] $WorkingDirectory,
[string] $HotKey,
[int] $WindowStyle = 1,
[string] $IconLocation,
[switch] $Elevated
)
try {
#region Create Shortcut
if ($Name) {
[System.IO.FileInfo] $LinkFileName = [System.IO.Path]::ChangeExtension($Name, "lnk")
} else {
[System.IO.FileInfo] $LinkFileName = [System.IO.Path]::ChangeExtension($Target.Name, "lnk")
}
if ($OutputDirectory) {
[System.IO.FileInfo] $LinkFile = [IO.Path]::Combine($OutputDirectory, $LinkFileName)
} else {
[System.IO.FileInfo] $LinkFile = [IO.Path]::Combine($Target.Directory, $LinkFileName)
}
$wshshell = New-Object -ComObject WScript.Shell
$shortCut = $wshShell.CreateShortCut($LinkFile)
$shortCut.TargetPath = $Target.Name
$shortCut.WindowStyle = $WindowStyle
$shortCut.Description = $Description
$shortCut.WorkingDirectory = $WorkingDirectory
$shortCut.HotKey = $HotKey
$shortCut.Arguments = $Arguments
if ($IconLocation) {
$shortCut.IconLocation = $IconLocation
}
$shortCut.Save()
#endregion
#region Elevation Flag
if ($Elevated) {
$tempFileName = [IO.Path]::GetRandomFileName()
$tempFile = [IO.FileInfo][IO.Path]::Combine($LinkFile.Directory, $tempFileName)
$writer = new-object System.IO.FileStream $tempFile, ([System.IO.FileMode]::Create)
$reader = $LinkFile.OpenRead()
while ($reader.Position -lt $reader.Length)
{
$byte = $reader.ReadByte()
if ($reader.Position -eq 22) {
$byte = 34
}
$writer.WriteByte($byte)
}
$reader.Close()
$writer.Close()
$LinkFile.Delete()
Rename-Item -Path $tempFile -NewName $LinkFile.Name
}
#endregion
} catch {
Write-Error "Failed to create shortcut. The error was '$_'."
return $null
}
return $LinkFile
|
PowerShellCorpus/PoshCode/TabExpansion.ps1
|
TabExpansion.ps1
|
## Tab-Completion
#################
## Please dot souce this script file.
## In first loading, it may take a several minutes, in order to generate ProgIDs and TypeNames list.
## What this can do is:
##
## [datetime]::n<tab>
## [datetime]::now.d<tab>
## $foo[0].<tab>
## $foo[0].n.b<tab>
## $function:a<tab>
## $env:a<tab>
## [System.Type].a<tab>
## [datetime].Assembly.a<tab>
## ).a<tab> # shows System.Type properties and methods...
## #native command name expansion
## fsu<tab>
## #command option name expansion (for fsutil ipconfig net powershell only)
## fsutil <tab>
## ipconfig <tab>
## net <tab>
## powershell <tab>
## #TypeNames expansion
## [Dec<tab>
## [Microsoft.PowerShell.Com<tab>
## New-Object -TypeName IO.Dir<tab>
## New-Object System.Management.Auto<tab>
## #ProgIDs expansion
## New-Object -Com shel<tab>
## #Enum option expansion
## Set-ExecutionPolicy <tab>
## Set-ExecutionPolicy All<tab>
## Set-ExcusionPolisy -ex <tab>
## Get-TraceSourceÅ@Inte<tab>
## iex -Err <tab> -wa Sil<tab>
## #WmiClasses expansion
## Get-WmiObject -class Win32_<tab>
## gwmi __Instance<tab>
## #Encoding expansion
## [Out-File | Export-CSV | Select-String | Export-Clixml] -enc <tab>
## [Add-Content | Get-Content | Set-Content} -Encoding Big<tab>
## #PSProvider name expansion
## [Get-Location | Get-PSDrive | Get-PSProvider | New-PSDrive | Remove-PSDrive] [-PSProvider] <tab>
## Get-PSProvider <tab>
## pwd -psp al<tab>
## #PSDrive name expansion
## [Get-PSDrive | New-PSDrive | Remove-PSDrive] [-Name] <tab>
## Get-PSDrive <tab>
## pwd -psd <tab>
## #PSSnapin name expansion
## [Add-PSSnapin | Get-PSSnapin | Remove-PSSnapin ] [-Name] <tab>
## Get-Command -PSSnapin <tab>
## Remove-PSSnapin <tab>
## Get-PSSnapin M<tab>
## #Eventlog name and expansion
## Get-Eventlog -Log <tab>
## Get-Eventlog w<tab>
## #Eventlog's entrytype expansion
## Get-EventLog -EntryType <tab>
## Get-EventLog -EntryType Er<tab>
## Get-EventLog -Ent <tab>
## #Service name expansion
## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-Name] <tab>
## New-Service -DependsOn <tab>
## New-Service -Dep e<tab>
## Get-Service -n <tab>
## Get-Service <tab>,a<tab>,p<tab>
## gsv <tab>
## #Service display name expansion
## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-DisplayName] <tab>
## Get-Service -Dis <tab>
## gsv -Dis <tab>,w<tab>,b<tab>
## #Cmdlet and Topic name expansion
## Get-Help [-Name] about_<tab>
## Get-Help <tab>
## #Category name expansion
## Get-Help -Category c<tab>,<tab>
## #Command name expansion
## Get-Command [-Name] <tab>
## Get-Command -Name <tab>
## gcm a<tab>,<tab>
## #Scope expansion
## [Clear-Variable | Export-Alias | Get-Alias | Get-PSDrive | Get-Variable | Import-Alias
## New-Alias | New-PSDrive | New-Variable | Remove-Variable | Set-Alias | Set-Variable] -Scope <tab>
## Clear-Variable -Scope G<tab>
## Set-Alias -s <tab>
## #Process name expansion
## [Get-Process | Stop-Process] [-Name] <tab>
## Stop-Process -Name <tab>
## Stop-Process -N pow<tab>
## Get-Process <tab>
## ps power<tab>
## #Trace sources expansion
## [Trace-Command | Get-TraceSource | Set-TraceSource] [-Name] <tab>,a<tab>,p<tab>
## #Trace -ListenerOption expansion
## [Set-TraceSource | Trace-Command] -ListenerOption <tab>
## Set-TraceSource -Lis <tab>,n<tab>
## #Trace -Option expansion
## [Set-TraceSource | Trace-Command] -Option <tab>
## Set-TraceSource -op <tab>,con<tab>
## #ItemType expansion
## New-Item -Item <tab>
## ni -ItemType d<tab>
## #ErrorAction and WarningAction option expansion
## CMDLET [-ErrorAction | -WarningAction] <tab>
## CMDLET -Error s<tab>
## CMDLET -ea con<tab>
## CMDLET -wa <tab>
## #Continuous expansion with comma when parameter can treat multiple option
## # if there are spaces, occur display bug in the line
## # if strings contains '$' or '-', not work
## Get-Command -CommandType <tab>,<tab><tab>,cm<tab>
## pwd -psp <tab>,f<tab>,va<tab>
## Get-EventLog -EntryType <tab>,i<tab>,s<tab>
### Generate ProgIDs list...
if ($_ProgID -eq $null) {
$_HKCR = [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\")
[Object[]] $_ProgID = $null
foreach ( $_subkey in $_HKCR.GetSubKeyNames() )
{
foreach ( $_i in [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\$_subkey\\ProgID") )
{
if ($_i -ne $null)
{
$_ProgID += $_i.GetValue("")
}
}
}
'$_ProgID was updated...' | Out-Host
$_ProgID = $_ProgID|sort -Unique
Export-Clixml -InputObject $_TypeNames -Path $PSHOME\\ProgIDs.txt
Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_ProgID = Import-Clixml -Path C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\ProgIDs.txt;'
}
### Generate TypeNames list...
if ( $_TypeNames -eq $null ) {
[Object[]] $_TypeNames = $null
foreach ( $_asm in [AppDomain]::CurrentDomain.GetAssemblies() )
{
foreach ( $_type in $_asm.GetTypes() )
{
$_TypeNames += $_type.FullName
}
}
'$_TypeNames was updated...' | Out-Host
$_TypeNames = $_TypeNames | sort -Unique
Export-Clixml -InputObject $_TypeNames -Path $PSHOME\\TypeNames.txt
Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_TypeNames = Import-Clixml -Path $PSHOME\\TypeNames.txt;'
}
if ( $_TypeNames_System -eq $null ) {
[Object[]] $_TypeNames_System = $null
foreach ( $_type in $_TypeNames -like "System.*" )
{
$_TypeNames_System += $_type.Substring(7)
}
'$_TypeNames_System was updated...' | Out-Host
Export-Clixml -InputObject $_TypeNames_System -Path $PSHOME\\TypeNames_System.txt
Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_TypeNames_System = Import-Clixml -Path $PSHOME\\TypeNames_System.txt;'
}
### Generate WMIClasses list...
if ( $_WMIClasses -eq $null ) {
[Object[]] $_WMIClasses = $null
foreach ( $_class in gwmi -List )
{
$_WMIClasses += $_class.Name
}
$_WMIClasses = $_WMIClasses | sort -Unique
'$_WMIClasses was updated...' | Out-Host
Set-Content -Value $_WMIClasses -Path $PSHOME\\WMIClasses.txt
}
$global:_snapin = $null
function TabExpansion {
# This is the default function to use for tab expansion. It handles simple
# member expansion on variables, variable name expansion and parameter completion
# on commands. It doesn't understand strings so strings containing ; | ( or { may
# cause expansion to fail.
param($line, $lastWord)
& {
# Helper function to write out the matching set of members. It depends
# on dynamic scoping to get $_base, _$expression and $_pat
function Write-Members ($sep='.')
{
# evaluate the expression to get the object to examine...
Invoke-Expression ('$_val=' + $_expression)
$_method = [Management.Automation.PSMemberTypes] `
'Method,CodeMethod,ScriptMethod,ParameterizedProperty'
if ($sep -eq '.')
{
$members =
(
[Object[]](Get-Member -InputObject $_val.PSextended $_pat) +
[Object[]](Get-Member -InputObject $_val.PSadapted $_pat) +
[Object[]](Get-Member -InputObject $_val.PSbase $_pat)
) | sort MemberType,Name -Unique
foreach ($_m in $members)
{
if ($_m.MemberType -band $_method)
{
# Return a method...
$_base + $_expression + $sep + $_m.name + '('
}
else {
# Return a property...
$_base + $_expression + $sep + $_m.name
}
}
}
else
{
foreach ($_m in Get-Member -Static -InputObject $_val $_pat |
Sort-Object membertype,name)
{
if ($_m.MemberType -band $_method)
{
# Return a method...
$_base + $_expression + $sep + $_m.name + '('
}
else {
# Return a property...
$_base + $_expression + $sep + $_m.name
}
}
}
}
switch -regex ($lastWord)
{
# Handle property and method expansion rooted at variables...
# e.g. $a.b.<tab>
'(^.*)(\\$(\\w|\\.)+)\\.(\\w*)$' {
$_base = $matches[1]
$_expression = $matches[2]
[void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock]
$_pat = $matches[4] + '*'
Write-Members
break;
}
# Handle simple property and method expansion on static members...
# e.g. [datetime]::n<tab>
'(^.*)(\\[(\\w|\\.)+\\])\\:\\:(\\w*)$' {
$_base = $matches[1]
$_expression = $matches[2]
$_pat = $matches[4] + '*'
Write-Members '::'
break;
}
# Handle complex property and method expansion on static members
# where there are intermediate properties...
# e.g. [datetime]::now.d<tab>
'(^.*)(\\[(\\w|\\.)+\\]\\:\\:(\\w+\\.)+)(\\w*)$' {
$_base = $matches[1] # everything before the expression
$_expression = $matches[2].TrimEnd('.') # expression less trailing '.'
$_pat = $matches[5] + '*' # the member to look for...
Write-Members
break;
}
# Handle variable name expansion...
'(^.*\\$)(\\w+)$' {
$_prefix = $matches[1]
$_varName = $matches[2]
foreach ($_v in Get-ChildItem ('variable:' + $_varName + '*'))
{
$_prefix + $_v.name
}
break;
}
# Handle env&function drives variable name expansion...
'(^.*\\$)(.*\\:)(\\w+)$' {
$_prefix = $matches[1]
$_drive = $matches[2]
$_varName = $matches[3]
if ($_drive -eq "env:" -or $_drive -eq "function:")
{
foreach ($_v in Get-ChildItem ($_drive + $_varName + '*'))
{
$_prefix + $_drive + $_v.name
}
}
break;
}
# Handle array's element property and method expansion...
# e.g. foo[0].a<tab>
'(^.*)(\\$(\\w|\\.)+\\[(\\w|\\.)+\\])\\.(\\w*)$'
{
$_base = $matches[1]
$_expression = $matches[2]
$_pat = $Matches[$matches.Count-1] + '*'
Write-Members
break;
}
# Handle array's element property and method expansion
# where there are intermediate properties...
# e.g. foo[0].n.b<tab>
'(^.*)((\\$(\\w|\\.)+\\[(\\w|\\.)+\\])\\.(\\w+\\.)+)(\\w*)$'
{
$_base = $matches[1]
$_expression = $matches[2].TrimEnd('.')
$_pat = $Matches[$matches.Count-1] + '*'
Write-Members
break;
}
# Handle property and method expansion rooted at type object...
# e.g. [System.Type].a<tab>
'(^\\[(\\w|\\.)+\\])\\.(\\w*)$'
{
if ( $(iex $Matches[1]) -isnot [System.Type] ) { break; }
$_expression = $Matches[1]
$_pat = $Matches[$matches.Count-1] + '*'
Write-Members
break;
}
# Handle complex property and method expansion on type object members
# where there are intermediate properties...
# e.g. [datetime].Assembly.a<tab>
'^(\\[(\\w|\\.)+\\]\\.(\\w+\\.)+)(\\w*)$' {
$_expression = $matches[1].TrimEnd('.') # expression less trailing '.'
$_pat = $matches[4] + '*' # the member to look for...
if ( $(iex $_expression) -eq $null ) { break; }
Write-Members
break;
}
# Handle property and method expansion rooted at close parenthes...
# e.g. (123).a<tab>
'^(.*)\\)((\\w|\\.)*)\\.(\\w*)$' {
$_base = $Matches[1] + ")"
if ( $matches[3] -eq $null) { $_expression = '[System.Type]' }
else { $_expression = '[System.Type]' + $Matches[2] }
$_pat = $matches[4] + '*'
iex "$_expression | Get-Member $_pat | sort MemberType,Name" |
% {
if ( $_.MemberType -like "*Method*" -or $_.MemberType -like "*Parameterized*" ) { $parenthes = "(" }
if ( $Matches[2] -eq "" ) { $_base + "." + $_.Name + $parenthes }
else { $_base + $Matches[2] + "." + $_.Name + $parenthes }
}
break;
}
# Handle .NET type name expansion ...
# e.g. [Microsoft.PowerShell.Com<tab>
'^\\[((\\w+\\.?)+)$' {
$_opt = $matches[1] + '*'
foreach ( $_exp in $_TypeNames_System -like $_opt )
{
'[' + $_exp
}
foreach ( $_exp in $_TypeNames -like $_opt )
{
'[' + $_exp
}
break;
}
# Do completion on parameters...
'^-([\\w0-9]*)' {
$_pat = $matches[1] + '*'
# extract the command name from the string
# first split the string into statements and pipeline elements
# This doesn't handle strings however.
$_cmdlet = [regex]::Split($line, '[|;=]')[-1]
# Extract the trailing unclosed block e.g. ls | foreach { cp
if ($_cmdlet -match '\\{([^\\{\\}]*)$')
{
$_cmdlet = $matches[1]
}
# Extract the longest unclosed parenthetical expression...
if ($_cmdlet -match '\\(([^()]*)$')
{
$_cmdlet = $matches[1]
}
# take the first space separated token of the remaining string
# as the command to look up. Trim any leading or trailing spaces
# so you don't get leading empty elements.
$_cmdlet = $_cmdlet.Trim().Split()[0]
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0]
}
# expand the parameter sets and emit the matching elements
foreach ($_n in $_cmdlet.ParameterSets |
Select-Object -expand parameters | Sort-Object -Unique name)
{
$_n = $_n.name
if ($_n -like $_pat) { '-' + $_n }
}
break;
}
# try to find a matching command...
default {
if ( $line[-1] -eq " " )
{
$_cmdlet = $line.TrimEnd(" ").Split()[-1]
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0]
}
if ( "Set-ExecutionPolicy" -eq $_cmdlet.Name )
{
"Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" | sort
break;
}
if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name )
{
Get-TraceSource | % { $_.Name } | sort -Unique
break;
}
if ( "New-Object" -eq $_cmdlet.Name )
{
$_TypeNames_System
$_TypeNames
break;
}
if ( $_cmdlet.Noun -like "*WMI*" )
{
$_WMIClasses
break;
}
if ( "Get-Process" -eq $_cmdlet.Name )
{
Get-Process | % { $_.Name } | sort
break;
}
if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name )
{
if ( $global:_snapin -ne $null )
{
$global:_snapin
break;
}
else
{
$global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique;
$global:_snapin
break;
}
}
if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" `
-contains $_cmdlet.Name -and "Name" )
{
Get-PSDrive | sort
break;
}
if ( "Get-Eventlog" -eq $_cmdlet.Name )
{
Get-EventLog -List | % { $_base + ($_.Log -replace '\\s','` ') }
break;
}
if ( "Get-Help" -eq $_cmdlet.Name )
{
Get-Help -Category all | % { $_.Name } | sort -Unique
break;
}
if ( "Get-Service", "Restart-Service", "Resume-Service",
"Start-Service", "Stop-Service", "Suspend-Service" `
-contains $_cmdlet.Name )
{
Get-Service | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Get-Command" -eq $_cmdlet.Name )
{
Get-Command -CommandType All | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
}
if ( $line[-1] -eq " " )
{
# extract the command name from the string
# first split the string into statements and pipeline elements
# This doesn't handle strings however.
$_cmdlet = [regex]::Split($line, '[|;=]')[-1]
# Extract the trailing unclosed block e.g. ls | foreach { cp
if ($_cmdlet -match '\\{([^\\{\\}]*)$')
{
$_cmdlet = $matches[1]
}
# Extract the longest unclosed parenthetical expression...
if ($_cmdlet -match '\\(([^()]*)$')
{
$_cmdlet = $matches[1]
}
# take the first space separated token of the remaining string
# as the command to look up. Trim any leading or trailing spaces
# so you don't get leading empty elements.
$_cmdlet = $_cmdlet.Trim().Split()[0]
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'Application' $_cmdlet)[0]
if ( $_cmdlet.Name -eq "powershell.exe" )
{
"-PSConsoleFile", "-Version", "-NoLogo", "-NoExit", "-Sta", "-NoProfile", "-NonInteractive",
"-InputFormat", "-OutputFormat", "-EncodedCommand", "-File", "-Command" | sort
break;
}
if ( $_cmdlet.Name -eq "fsutil.exe" )
{
"behavior query", "behavior set", "dirty query", "dirty set",
"file findbysid", "file queryallocranges", "file setshortname", "file setvaliddata", "file setzerodata", "file createnew",
"fsinfo drives", "fsinfo drivetype", "fsinfo volumeinfo", "fsinfo ntfsinfo", "fsinfo statistics",
"hardlink create", "objectid query", "objectid set", "objectid delete", "objectid create",
"quota disable", "quota track", "quota enforce", "quota violations", "quota modify", "quota query",
"reparsepoint query", "reparsepoint delete", "sparse setflag", "sparse queryflag", "sparse queryrange", "sparse setrange",
"usn createjournal", "usn deletejournal", "usn enumdata", "usn queryjournal", "usn readdata", "volume dismount", "volume diskfree" | sort
break;
}
if ( $_cmdlet.Name -eq "net.exe" )
{
"ACCOUNTS ", " COMPUTER ", " CONFIG ", " CONTINUE ", " FILE ", " GROUP ", " HELP ",
"HELPMSG ", " LOCALGROUP ", " NAME ", " PAUSE ", " PRINT ", " SEND ", " SESSION ",
"SHARE ", " START ", " STATISTICS ", " STOP ", " TIME ", " USE ", " USER ", " VIEW" | sort
break;
}
if ( $_cmdlet.Name -eq "ipconfig.exe" )
{
"/?", "/all", "/renew", "/release", "/flushdns", "/displaydns",
"/registerdns", "/showclassid", "/setclassid"
break;
}
}
if ( $line -match '\\s+(\\w+(\\.|[^\\s\\.])*)$' )
{
#$_opt = $Matches[1] + '*'
$_cmdlet = $line.TrimEnd(" ").Split()[-2]
$_opt = $Matches[1].Split(" ,")[-1] + '*'
$_base = $Matches[1].Substring(0,$Matches[1].Length-$Matches[1].Split(" ,")[-1].length)
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0]
}
if ( "Set-ExecutionPolicy" -eq $_cmdlet.Name )
{
"Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" -like $_opt | sort
break;
}
if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name )
{
Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "New-Object" -eq $_cmdlet.Name )
{
$_TypeNames_System -like $_opt
$_TypeNames -like $_opt
break;
}
if ( $_cmdlet.Name -like "*WMI*" )
{
$_WMIClasses -like $_opt
break;
}
if ( "Get-Process" -eq $_cmdlet.Name )
{
Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name )
{
if ( $global:_snapin -ne $null )
{
$global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') }
break;
}
else
{
$global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique;
$global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') }
break;
}
}
if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" `
-contains $_cmdlet.Name -and "Name" )
{
Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-PSProvider" -eq $_cmdlet.Name )
{
Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Eventlog" -eq $_cmdlet.Name )
{
Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') }
break;
}
if ( "Get-Help" -eq $_cmdlet.Name )
{
Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique
break;
}
if ( "Get-Service", "Restart-Service", "Resume-Service",
"Start-Service", "Stop-Service", "Suspend-Service" `
-contains $_cmdlet.Name )
{
Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Get-Command" -eq $_cmdlet.Name )
{
Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
}
if ( $line -match '(-(\\w+))\\s+([^-]*$)' )
{
$_param = $matches[2] + '*'
$_opt = $Matches[3].Split(" ,")[-1] + '*'
$_base = $Matches[3].Substring(0,$Matches[3].Length-$Matches[3].Split(" ,")[-1].length)
#$_opt = ($Matches[3] -replace '(^.*\\s*,?\\s*)\\w*$','$1') + '*'
# extract the command name from the string
# first split the string into statements and pipeline elements
# This doesn't handle strings however.
$_cmdlet = [regex]::Split($line, '[|;=]')[-1]
# Extract the trailing unclosed block e.g. ls | foreach { cp
if ($_cmdlet -match '\\{([^\\{\\}]*)$')
{
$_cmdlet = $matches[1]
}
# Extract the longest unclosed parenthetical expression...
if ($_cmdlet -match '\\(([^()]*)$')
{
$_cmdlet = $matches[1]
}
# take the first space separated token of the remaining string
# as the command to look up. Trim any leading or trailing spaces
# so you don't get leading empty elements.
$_cmdlet = $_cmdlet.Trim().Split()[0]
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0]
}
if ( $_param.TrimEnd("*") -eq "ea" -or $_param.TrimEnd("*") -eq "wa" )
{
"SilentlyContinue", "Stop", "Continue", "Inquire" |
? { $_ -like $_opt } | sort -Unique
break;
}
if ( "Out-File","Export-CSV","Select-String","Export-Clixml" -contains $_cmdlet.Name `
-and "Encoding" -like $_param)
{
"Unicode", "UTF7", "UTF8", "ASCII", "UTF32", "BigEndianUnicode", "Default", "OEM" |
? { $_ -like $_opt } | sort -Unique
break;
}
if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name `
-and "Name" -like $_param)
{
Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "New-Object" -like $_cmdlet.Name )
{
if ( "ComObject" -like $_param )
{
$_ProgID -like $_opt | % { $_ -replace '\\s','` ' }
break;
}
if ( "TypeName" -like $_param )
{
$_TypeNames_System -like $_opt
$_TypeNames -like $_opt
break;
}
}
if ( "New-Item" -eq $_cmdlet.Name )
{
if ( "ItemType" -like $_param )
{
"directory", "file" -like $_opt
break;
}
}
if ( "Get-Location", "Get-PSDrive", "Get-PSProvider", "New-PSDrive", "Remove-PSDrive" `
-contains $_cmdlet.Name `
-and "PSProvider" -like $_param )
{
Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Location" -eq $_cmdlet.Name -and "PSDrive" -like $_param )
{
Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" `
-contains $_cmdlet.Name -and "Name" -like $_param )
{
Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Command" -eq $_cmdlet.Name -and "PSSnapin" -like $_param)
{
if ( $global:_snapin -ne $null )
{
$global:_snapin -like $_opt | % { $_base + $_ }
break;
}
else
{
$global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique;
$global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') }
break;
}
}
if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" `
-contains $_cmdlet.Name -and "Name" -like $_param )
{
if ( $global:_snapin -ne $null )
{
$global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') }
break;
}
else
{
$global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique;
$global:_snapin -like $_opt | % { $_base + $_ }
break;
}
}
if ( "Clear-Variable", "Export-Alias", "Get-Alias", "Get-PSDrive", "Get-Variable", "Import-Alias",
" New-Alias", "New-PSDrive", "New-Variable", "Remove-Variable", "Set-Alias", "Set-Variable" `
-contains $_cmdlet.Name -and "Scope" -like $_param )
{
"Global", "Local", "Script" -like $_opt
break;
}
if ( "Get-Process", "Stop-Process", "Wait-Process" -contains $_cmdlet.Name -and "Name" -like $_param )
{
Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Eventlog" -eq $_cmdlet.Name -and "LogName" -like $_param )
{
Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') }
break;
}
if ( "Get-Help" -eq $_cmdlet.Name )
{
if ( "Name" -like $_param )
{
Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique
break;
}
if ( "Category" -like $_param )
{
"Alias", "Cmdlet", "Provider", "General", "FAQ",
"Glossary", "HelpFile", "All" -like $_opt | sort | % { $_base + $_ }
break;
}
}
if ( "Get-Service", "Restart-Service", "Resume-Service",
"Start-Service", "Stop-Service", "Suspend-Service" `
-contains $_cmdlet.Name )
{
if ( "Name" -like $_param )
{
Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "DisplayName" -like $_param )
{
Get-Service -Name $_opt | sort DisplayName | % { $_base + ($_.DisplayName -replace '\\s','` ') }
break;
}
}
if ( "New-Service" -eq $_cmdlet.Name -and "dependsOn" -like $_param )
{
Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Get-EventLog" -eq $_cmdlet.Name -and "EntryType" -like $_param )
{
"Error", "Information", "FailureAudit", "SuccessAudit", "Warning" -like $_opt | sort | % { $_base + $_ }
break;
}
if ( "Get-Command" -eq $_cmdlet.Name -and "Name" -like $_param )
{
Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( $_cmdlet.Noun -like "*WMI*" )
{
if ( "Class" -like $_param )
{
$_WMIClasses -like $_opt
break;
}
}
select -InputObject $_cmdlet -ExpandProperty ParameterSets | select -ExpandProperty Parameters |
? { $_.Name -like $_param } | ? { $_.ParameterType.IsEnum } |
% { [Enum]::GetNames($_.ParameterType) } | ? { $_ -like $_opt } | sort -Unique | % { $_base + $_ }
}
if ( $line[-1] -match "\\s" ) { break; }
if ( $lastWord -ne $null -and $lastWord.IndexOfAny('/\\') -eq -1 ) {
$command = $lastWord
$pattern = $command + "*"
gcm -Name $pattern -CommandType All | % { $_.Name } | sort -Unique
}
}
}
}
}
|
PowerShellCorpus/PoshCode/Is-Prime.ps1
|
Is-Prime.ps1
|
#########################################################################
#
# Is-Prime
#
#Written by Tynen
#
#########################################################################
function Is-Prime{
param ($number)
if($number -is [int] -or $number -is [long] -or $number -is [double] -or $number -is [single]){
$i = 1
do {
$math = $number / $i
$i++
if(is-natural($math)){
$Result += @($math)
}
}while ($i -le $number)
}else{return "Error: Did not receive an integer"}
if($Result.Count -eq 2 -or $Result.Count -eq 1){
return $true
}else{return $false}
}
|
PowerShellCorpus/PoshCode/ShowUI Binary Clock.ps1
|
ShowUI Binary Clock.ps1
|
<#
.SYNOPSIS
Displays a Binary Coded Sexagesimal clock using the ShowUI module.
.DESCRIPTION
This clock displays time using three rows of blocks. The top row represents
hours, the middle is minutes and the bottom is seconds. Each of the six columns
represents a binary digit. The values for each digit in the order displayed
are: 32 16 8 4 2 1. Adding the values of each of the "On" blocks in a row yields
the value for the row's corresponding time part.
Press the 'h' key to toggle the Helper values.
Press the 't' key to toggle the Time text.
Press the 'd' key to toggle the Date text.
Pres the '+'/'-' keys to resize the window (pressing Shift is not required).
Click and drag to move the window.
Double-click the window to close.
This script was inspired by Boe Prox's post at:
http://learn-powershell.net/2011/07/06/building-a-binary-clock-with-powershell/
.PARAMETER OnColor
The color of the "On" blocks which represent the 1 digits in a binary number.
This value must be able to convert to a System.Windows.Media.Brush type. (e.g.
"Blue","Red","Transparent","#FF00FF")
The default value is "#00D000"
.PARAMETER OnColor
The color of the "Off" blocks which represent the 0 digits in a binary number.
This value must be able to convert to a System.Windows.Media.Brush type. (e.g.
"Blue","Red","Transparent","#FF00FF")
The default value is "#606060"
.PARAMETER GridColor
The color of the space between the blocks.
This value must be able to convert to a System.Windows.Media.Brush type. (e.g.
"Blue","Red","Transparent","#FF00FF")
The default value is "#202020"
.PARAMETER TextColor
The color of the text on the blocks. All text is off by default. Press 'h' for
Help values, 't' for Time or 'd' for Date.
This value must be able to convert to a System.Windows.Media.Brush type. (e.g.
"Blue","Red","Transparent","#FF00FF")
The default value is "#FFFFFF"
.PARAMETER Topmost
This switch determines the window's Topmost attribute.
.EXAMPLE
C:\\PS>.\\Show-BinaryClock.ps1 -OnColor '#8000F0' -OffColor '#808080' -GridColor '#FFFFFF' -Topmost
Displays a topmost clock with a white grid, gray off blocks and purple on blocks.
.EXAMPLE
C:\\PS>.\\Show-BinaryClock.ps1 -OnColor '#F08000' -OffColor 'Transparent' -GridColor 'Transparent'
Displays a clock where the on blocks and any text are the only visible elements.
.NOTES
NAME: Show-BinaryClock.ps1
VERSION: 1.0
DATE: 2011-07-08
AUTHOR: Ryan Grant
#>
param(
$OnColor = '#00D000',
$OffColor = '#606060',
$GridColor = '#202020',
$TextColor = '#FFFFFF',
[switch] $Topmost
)
Import-Module ShowUI -ErrorAction Stop
$GLOBAL:backColor = @{'0'=$OffColor ;'1'= $OnColor}
$windowParams = @{
Width = 160
Height = 90
WindowStyle = 'None'
AllowsTransparency = $true
Background = $GridColor
Topmost = $Topmost
}
Window @windowParams -Show `
-Content {
# Create 3 Rows of 6 TextBlocks in a UniformGrid. The top row represents the hour,
# the middle row represents the minute, and the bottom row represents the second.
UniformGrid -Name ClockGrid -Columns 6 -Margin 2 -Children {
foreach($part in @('Hour','Minute','Second'))
{0..5|%{TextBlock -Name "$part$_" -Margin 2 -Foreground $TextColor}}
}
} -On_Loaded {
Register-PowerShellCommand -In '0:0:0.5' -Run -ScriptBlock {
$time = Get-Date
# Convert the time values to a binary format string
$vals = @($time.Hour, $time.Minute, $time.Second)|
%{[convert]::ToString($_,2)}|
%{('0'*(6-$_.ToString().Length))+$_}
# Set the TextBlock background colors to the appropriate value for each digit in the
# binary formatted string. Using the $backColor hash table, 0 = $OffColor and 1 = $OnColor
foreach($d in 0..5) {
(Get-Variable "Hour$d").Value.Background = $backColor[[string]$vals[0][$d]]
(Get-Variable "Minute$d").Value.Background = $backColor[[string]$vals[1][$d]]
(Get-Variable "Second$d").Value.Background = $backColor[[string]$vals[2][$d]]
}
# Display the time text
# Multiplying by $IsShowTime creates an empty string if it is $False
'Hour','Minute'|
%{(Get-Variable ($_+"0")).Value.Text = ("{0:00}" -f $time.$_) * $IsShowTime}
# Only set the second text if the helper text is off, since they occupy the same TextBlock
if(!$IsHelpers)
{(Get-Variable ("Second0")).Value.Text = ("{0:00}" -f $time.Second) * $IsShowTime}
# Display the date text
$Hour3.Text = ("{0:00}" -f $time.Month) * $IsShowDate
$Hour4.Text = ("{0:00}" -f $time.Day) * $IsShowDate
$Hour5.Text = ($time.Year.ToString().Substring(2,2)) * $IsShowDate
}
} -On_KeyDown {
switch ($_.Key){
# Toggle helper text, and turn off time text
'H' {
$IsShowTime = 0
$IsHelpers = $IsHelpers -bxor 1
}
# Toggle time text, and turn off helper text
'T' {
$IsHelpers = 0
$IsShowTime = $IsShowTime -bxor 1
}
# Toggle date text
'D' {
$IsShowDate = $IsShowDate -bxor 1
}
# Increase the size of the window
{'Add','OemPlus' -contains $_} {
$window.Width *= 1.1
$window.Height *= 1.1
}
# Decrease the size of the window
{'Subtract','OemMinus' -contains $_} {
if($window.Width -gt 50) {
$window.Width /= 1.1
$window.Height /= 1.1
}
}
}
# Set digit value helper text
1..5| %{(Get-Variable "Second$_").Value.Text = "{0:00}" -f [math]::Pow(2,(5-$_)) * $IsHelpers}
# Only set leftmost digit helper if not displaying the time text
if(!$IsShowTime) {(Get-Variable "Second0").Value.Text = '32' * $IsHelpers}
} `
-On_MouseDoubleClick {$window.Close()}`
-On_MouseLeftButtonDown {$window.DragMove()}
|
PowerShellCorpus/PoshCode/New-StoredProcFunction.ps1
|
New-StoredProcFunction.ps1
|
# New-StoredProcFunction.ps1
# Steven Murawski
# http://blog.usepowershell.com
# 04/08/2009
# Example: ./New-StoredProcFunction.ps1 'DataSource=MySqlServer;Database=Northwind;User=AnythingButSa;Password=abc123' sp_createnewcustomer
# Example 'sp_createnewcustomer | ./New-StoredProcFunction.ps1 'DataSource=MySqlServer;Database=Northwind;User=AnythingButSa;Password=abc123'
param($ConnectionString, [String[]]$StoredProc= $null)
BEGIN
{
if ($StoredProc.count -gt 0)
{
$StoredProc | New-StoredProcFunction $ConnectionString
}
function Get-StoredProcText()
{
param ($ProcName, $ConnectionString)
$query = @'
SELECT ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_BODY = 'SQL' AND ROUTINE_NAME LIKE '$_'
'@
$connection = New-Object System.Data.SqlClient.SqlConnection $connectionString
$command = New-Object System.Data.SqlClient.SqlCommand $query,$connection
$connection.Open()
$adapter = New-Object System.Data.SqlClient.SqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
[void] $adapter.Fill($dataSet)
$result = $dataSet.Tables | ForEach-Object {$_.Rows}
$connection.Close()
return $Result.ROUTINE_DEFINITION
}
function Get-FunctionParameter()
{
param ($Text)
[regex]$EndRegex = '\\)\\s+AS'
[regex]$ParamRegex = '@(?<Parameter>\\w+?)\\s+(?<DataType>\\w+(\\(\\d+\\))*)(,|\\s+)*(?<Output>out)*'
$ParamStart = $Text.indexof('(')
$ParamEnd = $EndRegex.Match($text).index
$ParamText = $Text.Substring($ParamStart, ($ParamEnd-$ParamStart))
$RegMatches = $ParamRegex.matches($ParamText)
foreach ($RegMatch in $RegMatches)
{
$Parameter = "" | Select-Object Name, DataType, IsOutput
$Parameter.Name = $RegMatch.Groups[3].value
$Parameter.DataType = $RegMatch.Groups[4].Value
[bool]$Parameter.IsOutput = $RegMatch.Groups[5].Value
$Parameter
}
}
}
PROCESS
{
if ($_ -ne $null)
{
$FunctionName = $_
$StoredProcText = Get-StoredProcText $FunctionName $ConnectionString
$Parameters = Get-FunctionParameter $StoredProcText
[String[]]$InputParamNames = $Parameters | where {-not $_.IsOutput} | ForEach-Object {$_.Name}
[String[]]$OutputParameterNames = $Parameters | Where-Object {$_.IsOutput} | ForEach-Object {$_.Name}
$ScriptText = ' '
if ($InputParamNames.count -gt 0)
{
$OFS = ', $'
$ScriptText += 'param (${0})' -f $InputParamNames
$ScriptText += "`n"
$OFS = ', '
}
$BodyTemplate = @'
$connection = New-Object System.Data.SqlClient.SqlConnection('{0}')
$command = New-Object System.Data.SqlClient.SqlCommand('{1}', $connection)
$command.CommandType = [System.Data.CommandType]::StoredProcedure
'@
$ScriptText += $BodyTemplate -f $ConnectionString, $FunctionName
if ( ($Parameters -ne $null) -or ($Parameters.count -gt 1) )
{
if ($OutputParameterNames.count -gt 0)
{
$ReturnText = ""
$CommandOutput = "" | select $OutputParameterNames
}
#Add the parameters
foreach ($param in $Parameters)
{
if ($param.datatype -match '(?<type>\\w+)\\((?<nbr>\\d+)\\)')
{
$ParamTemplate = '$command.Parameters.Add("@{0}", "{1}", {2}) | out-null '
$ScriptText += "`n"
$ScriptText += $ParamTemplate -f $param.name, $matches.type, $matches.nbr
}
else
{
$ParamTemplate = '$command.Parameters.Add("@{0}", "{1}") | out-null '
$ScriptText += "`n"
$ScriptText += $ParamTemplate -f $param.name, $param.datatype
}
if ($param.IsOutput)
{
$ScriptText += "`n"
$ScriptText += '$command.Parameters["@{0}"].Direction = [System.Data.ParameterDirection]::Output ' -f $param.Name
$ReturnText += "`n"
$ReturnText += '$CommandOutput.{0} = $command.Parameters["@{0}"].Value' -f $param.name
}
else
{
$ScriptText += "`n"
$ScriptText += '$command.Parameters["@{0}"].Value = ${0} ' -f $param.name
}
}
}
$ScriptText += "`n"
$ScriptText += @'
$connection.Open() | out-null
$command.ExecuteNonQuery() | out-null
'@
if ($OutputParameterNames.count -gt 0)
{
$ScriptText += $ReturnText
}
$ScriptText += @'
$connection.Close() | out-null
return $CommandOutput
'@
#$ScriptText
Set-Item -Path function:global:$FunctionName -Value $scripttext
}
}
|
PowerShellCorpus/PoshCode/Enable-HistoryPersistenc.ps1
|
Enable-HistoryPersistenc.ps1
|
##############################################################################\n##\n## Enable-HistoryPersistence\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\nReloads any previously saved command history, and registers for the\nPowerShell.Exiting engine event to save new history when the shell\nexits.\n\n#>\n\nSet-StrictMode -Version Latest\n\n## Load our previous history\n$GLOBAL:maximumHistoryCount = 32767\n$historyFile = (Join-Path (Split-Path $profile) "commandHistory.clixml")\nif(Test-Path $historyFile)\n{\n Import-CliXml $historyFile | Add-History\n}\n\n## Register for the engine shutdown event\n$null = Register-EngineEvent -SourceIdentifier `\n ([System.Management.Automation.PsEngineEvent]::Exiting) -Action {\n\n ## Save our history\n $historyFile = (Join-Path (Split-Path $profile) "commandHistory.clixml")\n $maximumHistoryCount = 1kb\n\n ## Get the previous history items\n $oldEntries = @()\n if(Test-Path $historyFile)\n {\n $oldEntries = Import-CliXml $historyFile -ErrorAction SilentlyContinue\n }\n\n ## And merge them with our changes\n $currentEntries = Get-History -Count $maximumHistoryCount\n $additions = Compare-Object $oldEntries $currentEntries `\n -Property CommandLine | Where-Object { $_.SideIndicator -eq "=>" } |\n Foreach-Object { $_.CommandLine }\n\n $newEntries = $currentEntries | ? { $additions -contains $_.CommandLine }\n\n ## Keep only unique command lines. First sort by CommandLine in\n ## descending order (so that we keep the newest entries,) and then\n ## re-sort by StartExecutionTime.\n $history = @($oldEntries + $newEntries) |\n Sort -Unique -Descending CommandLine | Sort StartExecutionTime\n\n ## Finally, keep the last 100\n Remove-Item $historyFile\n $history | Select -Last 100 | Export-CliXml $historyFile\n}
|
PowerShellCorpus/PoshCode/Add-Namespace_2.ps1
|
Add-Namespace_2.ps1
|
trap [System.Management.Automation.RuntimeException]
{
$entryException = $_
if ($_.CategoryInfo.Category -eq [System.Management.Automation.ErrorCategory]::InvalidOperation)
{
if ($_.FullyQualifiedErrorId -eq "TypeNotFound")
{
$targetName = $_.CategoryInfo.TargetName
try
{
$isAmbiguous = $global:__ambiguousTypeNames.Contains($targetName)
}
catch
{
throw $entryException
}
if ($isAmbiguous)
{
$message = New-Object System.Text.StringBuilder
$message.AppendFormat("The type [{0}] is ambiguous. Specify one of the following: ", $targetName).AppendLine() | Out-Null
[System.Type]::GetType("System.Management.Automation.TypeAccelerators")::Get.GetEnumerator() | ForEach-Object {
if (($_.Key.Split('.'))[-1] -eq $targetName)
{
$message.Append($_.Key).AppendLine() | Out-Null
}
}
$exception = New-Object System.Management.Automation.RuntimeException -ArgumentList $message.ToString()
$errorId = "TypeNotFound"
$errorCategory = [System.Management.Automation.ErrorCategory]::InvalidOperation
$targetObject = $_.TargetObject
throw New-Object System.Management.Automation.ErrorRecord -ArgumentList $exception, $errorId, $errorCategory, $targetObject
}
}
}
}
<#
.SYNOPSIS
Imports the types in the specified namespaces in the specified assemblies.
.DESCRIPTION
The Add-Namespace function adds a type accelerator for each type found in the specified namespaces in the specified assemblies that satisfy a set of conditions. For more information see the NOTES section.
.PARAMETER Assembly
The namespace to import.
.PARAMETER Namespace
Specifies one or more namespaces to import.
.INPUTS
System.Reflection.Assembly
You can pipe an assembly to Add-Namespace.
.OUTPUTS
None
This function does not return any output.
.NOTES
The type accelerator for the type is added if the type:
- Has a base type which is not System.Attribute, System.Delegate or System.MulticastDelegate
- Is not abstract
- Is not an interface
- Is not nested
- Is public
- Is visible
- Is qualified by the namespace specified in the Namespace parameter
This function also comes with an exception handler in the form of a trap block. Type name collisions occur when a type has the same name of another type which is in a different namespace. When this happens, the function adds or replaces the type accelerator for that type using its fully-qualified type name. If a type resolution occurs during runtime, the trap block will determine if the type was unresolved during any of the calls made to Add-Namespace and throw an exception listing valid replacements.
The type accelerators added by this function exist only in the current session. To use the type accelerators in all sessions, add them to your Windows PowerShell profile. For more information about the profile, see about_profiles.
Be aware that namspaces can span multiple assemblies, in which case you would have to import the namespace for each assembly that it exists in.
This function will not attempt to add or replace types which already exist under the same name.
.EXAMPLE
C:\\PS> [System.Reflection.Assembly]::LoadWithPartialName("mscorlib") | Add-Namespace System.Reflection
C:\\PS> [Assembly]::LoadWithPartialName("System.Windows.Forms")
This example shows how to import namespaces from an assembly. The assembly must be loaded non-reflectively into the current application domain.
.EXAMPLE
C:\\PS> $assemblies = @([System.Reflection.Assembly]::LoadWithPartialName("mscorlib"), [System.Reflection.Assembly]::LoadWithPartialName("System"), [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms"), [System.Reflection.Assembly]::LoadWithPartialName("System.Xml"), [System.Reflection.Assembly]::LoadWithPartialName("System.Xml.Linq"))
C:\\PS> $assemblies | Add-Namespace System, System.Collections, System.Collections.Generic, System.Net, System.Net.NetworkInformation, System.Reflection, System.Windows.Forms, System.Xml.Linq
This example shows how to import multiple namespaces from multiple assemblies.
.LINK
about_trap
#>
function Add-Namespace
{
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[Parameter(ValueFromPipeline = $true)]
[System.Reflection.Assembly]$Assembly,
[Parameter(Mandatory = $true, Position = 0)]
[ValidateNotNullOrEmpty()]
[String[]]$Namespace
)
BEGIN
{
if ($global:__ambiguousTypeNames -eq $null)
{
$global:__ambiguousTypeNames = New-Object 'System.Collections.Generic.List[System.String]'
}
$genericRegex = [Regex]'(?<Name>.*)`\\d+'
$typeAccelerators = [System.Type]::GetType("System.Management.Automation.TypeAccelerators")
$typeDictionary = $typeAccelerators::Get
}
PROCESS
{
$_.GetTypes() | Where-Object {
($_.BaseType -ne [System.Attribute]) -and
($_.BaseType -ne [System.Delegate]) -and
($_.BaseType -ne [System.MulticastDelegate]) -and
!$_.IsAbstract -and
!$_.IsInterface -and
!$_.IsNested -and
$_.IsPublic -and
$_.IsVisible -and
($Namespace -contains $_.Namespace)
} | ForEach-Object {
$name = $_.Name
$fullName = $_.FullName
if ($_.IsGenericType)
{
if ($_.Name -match $genericRegex)
{
$name = $Matches["Name"]
}
if ($_.FullName -match $genericRegex)
{
$fullName = $Matches["Name"]
}
}
if ($typeDictionary.ContainsKey($name))
{
if ($typeDictionary[$name] -eq $_)
{
return
}
}
if ($typeDictionary.ContainsKey($fullName))
{
if ($typeDictionary[$fullName] -eq $_)
{
return
}
}
if ($global:__ambiguousTypeNames.Contains($name))
{
$typeAccelerators::Add($fullName, $_)
return
}
if ($typeDictionary.ContainsKey($name))
{
$type = $typeDictionary[$name]
if ($_ -ne $type)
{
$global:__ambiguousTypeNames.Add($name)
$newName = $typeDictionary[$name].FullName
if ($newName -match $genericRegex)
{
$newName = $Matches["Name"]
}
$typeAccelerators::Remove($name)
$typeAccelerators::Add($newName, $type)
$typeAccelerators::Add($fullName, $_)
}
return
}
$typeAccelerators::Add($name, $_)
} | Out-Null
}
END
{
}
}
# Sample usage
# You can do this as an initialization task for your script
@(
[System.Reflection.Assembly]::LoadWithPartialName("mscorlib"),
[System.Reflection.Assembly]::LoadWithPartialName("System"),
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms"),
[System.Reflection.Assembly]::LoadWithPartialName("System.Xml"),
[System.Reflection.Assembly]::LoadWithPartialName("System.Xml.Linq")
) | Add-Namespace -Namespace `
System,
System.Collections,
System.Collections.Generic,
System.Net,
System.Net.NetworkInformation,
System.Reflection,
System.Windows.Forms,
System.Xml.Linq
|
PowerShellCorpus/PoshCode/Get-MemoryChart.ps1
|
Get-MemoryChart.ps1
|
#.Synopsis
# Draw pie charts of server memory usage by process
#.Description
# Uses PowerBoots to draw a pipe-chart of each computer's memory use. While you wait for that information
# to be gathered, it shows you the latest xkcd comic. ##DEPEND-ON -Function Get-Comic
# Uses the Transitionals library for nice transitions ##DEPEND-ON -Assembly Transitionals http://www.codeplex.com/transitionals
#.Parameter hosts
# The hostnames of the computers you want memory charts for
#.Example
# Get-MemoryChart localhost
#
# Returns a pie-chart of the memory on your local PC
#.Example
# Get-MemoryChart Server01,Server02
#
# Returns a pie-chart of the memory on Server01, and Server02
# Note that this requires WMI and authorization...
#
Param([string[]]$hosts = "localhost")
Import-Module PowerBoots
if(!(Get-Command Chart -EA SilentlyContinue)) {
Add-BootsContentProperty 'DataPoints', 'Series'
Add-BootsFunction -Assembly "~\\Documents\\WindowsPowershell\\Libraries\\WPFVisifire.Charts.dll" 2>$Null
Add-BootsFunction -Assembly "~\\Documents\\WindowsPowershell\\Libraries\\Transitionals.dll"
}
## And this is how you use a script which might not be there...
$comical = Get-Command Get-Comic -EA SilentlyContinue
if($comical) {
$script:comic = Get-Comic xkcd
$image = [system.drawing.image]::fromfile( $comic.FullName )
$script:width = $image.Width
$image.Dispose()
}
#$window = Boots { Image -Source $xkcd -MinHeight 100 } -Popup -Async
$limitsize = 10mb
$labellimitsize = 15mb
$window = Boots {
DockPanel {
ListBox -DisplayMember Name -Ov global:list ` # -width 0
-On_SelectionChanged { $global:container[0].Content = $global:list[0].SelectedItem }
# TransitionElement -Transition $(RotateTransition -Angle 45) `
Frame `
-Name TransitionBox -Ov global:container `
-MinWidth 400 -MinHeight 400 -MaxHeight 600 `
-Content {
StackPanel {
Label -FontSize 42 "Loading ..."
if($comical) {
Image -Source $comic.FullName -MaxWidth $width
}
} |
Set-AttachedProperty ([System.Windows.Navigation.JournalEntry]::NameProperty) "XKCD Comic"
}
} -LastChildFill $true
} -MinHeight 400 -Async -Popup -Passthru
sleep 2;
$jobs = @()
ForEach($pc in $hosts) {
$jobs += gwmi Win32_Process -ComputerName $pc -AsJob;
}
while($jobs) {
$job = Wait-Job -Any $jobs
Invoke-BootsWindow $window {
if($list -is [System.Collections.ArrayList]) {
$list = $list[0];
$list.Padding = "2,2,5,2"
}
$name = $($job.Location -Replace "[^a-zA-Z_0-9]" -replace "(^[0-9])",'_$1')
# $null = $list.Items.Add(
$global:container[0].Content = `
$( Chart {
DataSeries -LabelText $job.Location {
ForEach($proc in (Receive-Job $job | Sort WorkingSetSize)) {
if($proc.WorkingSetSize -gt $limitsize) {
DataPoint -YValue $proc.WorkingSetSize -LabelText $proc.Name `
-LabelEnabled $($proc.WorkingSetSize -gt $labellimitsize) `
-ToolTipText "$($proc.Name): #YValue (#Percentage%)"
}
}
} -RenderAs Pie -ShowInLegend $false
} -Watermark $false -AnimationEnabled $true -Name $name |
Set-AttachedProperty ([System.Windows.Navigation.JournalEntry]::NameProperty) $name
)
); $list.SelectedIndex = $list.Items.Count - 1
}
$jobs = $jobs -ne $job
Remove-Job $job.Id
Sleep 5
}
|
PowerShellCorpus/PoshCode/Get-ProfilesList_1.ps1
|
Get-ProfilesList_1.ps1
|
function Get-ProfilesList {
$hive = "HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList"
gci $hive | % -b {$prof = @()} -p {$dest = "" | select UserName, Sid, ProfilePath
$dest.Sid = $_.PSChildName
$dest.ProfilePath = (gp ($hive + "\\" + $_.PSChildName)).ProfileImagePath
$dest.UserName = Split-Path $dest.ProfilePath -leaf
$prof += $dest
} -end {$prof | ft -a}
}
|
PowerShellCorpus/PoshCode/93a65603-30b1-4887-8fef-5b0d188f44a2.ps1
|
93a65603-30b1-4887-8fef-5b0d188f44a2.ps1
|
function Using-Culture
{
<#
.SYNOPSIS
Runs a PowerShell script under a different locale to test localization features.
.DESCRIPTION
Runs a PowerShell script under a different locale to test localization features.
Copied from http://rkeithhill.wordpress.com/2009/10/21/windows-powershell-2-0-string-localization/
and converted to a Cmdlet including help comments.
.LINK
Import-LocalizedData
Convert-FromStringData
http://rkeithhill.wordpress.com/2009/10/21/windows-powershell-2-0-string-localization/
.PARAMETER Culture
The culture (language) to run the script in.
.PARAMETER Script
The scriptblock or script (wrapped in a scriptblock) to run.
.EXAMPLE
PS C:\\> Using-Culture fr-FR { .\\test.ps1 }
Runs the script test.ps1 under French language settings.
#>
[CmdletBinding()]
Param([Parameter(Mandatory = $true, HelpMessage = 'The culture (language) to run the script in.')]
[ValidateNotNull()]
[System.Globalization.CultureInfo]
$Culture,
[Parameter(Mandatory = $true, HelpMessage = 'The scriptblock or wrapped script to run.')]
[ValidateNotNull()]
[ScriptBlock]
$Script
)
$OldCulture = [System.Threading.Thread]::CurrentThread.CurrentCulture
$OldUICulture = [System.Threading.Thread]::CurrentThread.CurrentUICulture
try
{
[System.Threading.Thread]::CurrentThread.CurrentCulture = $culture
[System.Threading.Thread]::CurrentThread.CurrentUICulture = $culture
Invoke-Command $script
}
finally
{
[System.Threading.Thread]::CurrentThread.CurrentCulture = $OldCulture
[System.Threading.Thread]::CurrentThread.CurrentUICulture = $OldUICulture
}
}
|
PowerShellCorpus/PoshCode/Export-CustomProperty.ps1
|
Export-CustomProperty.ps1
|
## An example of how to make a custom object with strongly-typed properties, custom enumeration values, and custom validators, etc.
function Export-CustomProperty {
param(
[Parameter(ValueFromPipeline=$true)]
[PSCustomObject]$Object
)
process {
foreach($property in Get-Member Get_*,Set_* -Input $Object -Type Methods | Group-Object { $_.Name.Split("_",2)[1] }) {
$GetAccessor = $SetAccessor = {}
foreach($accessor in $property.Group) {
switch($accessor.Name.Split("_")[0]) {
"Get" {
$GetAccessor = [ScriptBlock]::Create('$this.' + $accessor.Name + '()')
}
"Set" {
$SetAccessor = [ScriptBlock]::Create('try { $this.' + $accessor.Name + '( $args ) } catch { throw $_.Exception.Message.Split(":",2)[1].trim('' "'') }')
}
}
}
Add-Member -Input $Object -Type ScriptProperty -Name $Property.Name -Value $GetAccessor $SetAccessor
}
Write-Output $Object
}
}
## USAGE:
$customThing = New-Module -AsCustomObject {
## The FooBar property: a variable, two accessor methods and later, a ScriptProperty.
[string]$FooBar = 'foo'
[string[]]$FooBarValues = 'foo','bar'
function Get_FooBar { $FooBar }
function Set_FooBar {
param([string]$value)
if($FooBarValues -notcontains $Value) {
throw "You can't set FooBar to '$value', valid values are $($FooBarValues -join ', ').";
}
$script:FooBar = $value
}
## The Enabled property: just a strongly-typed variable
[bool]$Enabled = $False
## The UserName property: a variable, two accessor methods (and a validation method) and later, a ScriptProperty.
[String]$UserName = $Env:UserName
function Test-ADUser {
[CmdletBinding()]
param([string]$UserName)
$ads = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'')
$ads.filter = "(&(objectClass=Person)(samAccountName=$UserName))"
return [bool]$ads.FindOne()
}
function Get_UserName { $UserName }
function Set_UserName {
param([string]$value)
if(!(Test-ADUser $Value)) {
throw "You can't set UserName to '$value', that user doesn't exist.";
}
$script:UserName = $value
}
Export-ModuleMember -Function Get_*,Set_* -Variable Enabled
} | Export-CustomProperty
#### Sample Validation Output:
##############################################################################
# C:\\PS> $customThing.UserName = 'Nobody'
#
# Exception setting "UserName": "You can't set UserName to 'Nobody', that user doesn't exist."
# At line:1 char:6
# + $customThing. <<<< UserName = 'Nobody'
# + CategoryInfo : InvalidOperation: (:) [], RuntimeException
# + FullyQualifiedErrorId : PropertyAssignmentException
#
#
# C:\\PS> $customThing.FooBar = 'foobar'
#
# Exception setting "FooBar": "You can't set FooBar to 'foobar', valid values are foo, bar."
# At line:1 char:6
# + $customThing. <<<< FooBar = 'foobar'
# + CategoryInfo : InvalidOperation: (:) [], RuntimeException
# + FullyQualifiedErrorId : PropertyAssignmentException
#
#
# C:\\PS> $customThing.Enabled = "what"
#
# Cannot convert value "System.String" to type "System.Boolean", parameters of this type only accept booleans or numbers, use $true, $false, 1 or 0 instead.
# At line:1 char:6
# + $customThing. <<<< Enabled = "what"
# + CategoryInfo : InvalidOperation: (:) [], RuntimeException
# + FullyQualifiedErrorId : PropertyAssignmentException
|
PowerShellCorpus/PoshCode/FastNFS - PowerCLI.ps1
|
FastNFS - PowerCLI.ps1
|
# fastNFS
# Description: Mounts NFS datastore to a group of ESX hosts.
# Usage: Enter a list of ESX hosts (by IP or hostname). Then enter the IP, path, and datastore name of the share.
#
#
# Enter the name or IP of the NFS server
$nfssrv = Read-Host "Enter the name or IP of the NFS server"
# Enter the full path to the share
$nfspath = Read-Host "Enter the full path to the share"
# Give a name for the new NFS datastore
$nfsds = Read-Host "Enter a name for the new NFS datastore"
# Create an empty array for $esx
$esx = @()
# Will continue to prompt for ESX hosts until you stop entering them.
do {
$input = Read-Host "Add an ESX host by FQDN or IP"
if ($input -ne ""){
$esx += $input
}
}
until ($input -eq "")
# Mounts the datastore
foreach ($name in $esx)
{
New-Datastore -VMHost $name -Name $nfsds -Path $nfspath -Nfshost $nfssrv -Nfs
}
|
PowerShellCorpus/PoshCode/Get-Weather_1.ps1
|
Get-Weather_1.ps1
|
Function Get-Weather {
<#
.SYNOPSIS
Display weather data for a specific country and city.
.DESCRIPTION
Display weather data for a specific country and city. There is a possibility for this to fail if the web service being used is unavailable.
.PARAMETER Country
URL of the website to test access to.
.PARAMETER ListCities
Use the currently authenticated user's credentials
.PARAMETER City
Used to connect via a proxy
.NOTES
Name: Get-Weather
Author: Boe Prox
DateCreated: 15Feb2011
.LINK http://www.webservicex.net/ws/default.aspx
.LINK http://boeprox.wordpress.com
.EXAMPLE
Get-Weather -Country "United States" -ListCities
Description
------------
Returns all of the available cities that are available to retrieve weather information from.
.EXAMPLE
Get-Weather -Country "United States" -City "San Francisco"
Description
------------
Retrieves the current weather information for San Francisco
#>
[cmdletbinding(
DefaultParameterSetName = 'Weather',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = '',
ValueFromPipeline = $True)]
[string]$Country,
[Parameter(
Position = 1,
Mandatory = $False,
ParameterSetName = 'listcities')]
[switch]$ListCities,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[string]$City
)
Begin {
$psBoundParameters.GetEnumerator() | % {
Write-Verbose "Parameter: $_"
}
Try {
#Make connection to known good weather service
Write-Verbose "Create web proxy connection to weather service"
$weather = New-WebServiceProxy 'http://www.webservicex.net/globalweather.asmx?WSDL'
}
Catch {
Write-Warning "$($Error[0])"
Break
}
}
Process {
#Determine if we are only to list the cities for a given country or get the weather from a city
Switch ($PSCmdlet.ParameterSetName) {
ListCities {
Try {
#List all cities available to query for weather
Write-Verbose "Listing cities in country: $($country)"
(([xml]$weather.GetCitiesByCountry("$country")).newdataset).table | Sort City | Select City
Break
}
Catch {
Write-Warning "$($Error[0])"
Break
}
}
Weather {
Try {
#Get the weather for the city and country
Write-Verbose "Getting weather for Country: $($country), City $($city)"
([xml]$weather.GetWeather("$city", "$country")).CurrentWeather
}
Catch {
Write-Warning "$($Error[0])"
}
}
}
}
End {
Write-Verbose "End function, performing clean-up"
Remove-Variable city -Force
Remove-Variable country -Force
}
}
|
PowerShellCorpus/PoshCode/Cisco-Inventory.ps1
|
Cisco-Inventory.ps1
|
#==================================================================================================
# File Name : CiscoInventory.ps1
# Original Author : Kenneth C. Mazie (kcmjr)
# Description : As written it will poll Cisco routers and switches and if the snmp OID's
# : match it will pull out model, serial, and IOS version. The resulting
# : spreadsheet contains IP, host name, serial, model, IOS version, and
# : rack location.
#
# Notes : Normal operation is with no command line options.
# : This PowerShell script was cobbled together from various sources around
# : the Internet. It was inspired by an article by David Davis over at ZDNet
# : but came about because I had yet to find a PowerShell script to do what
# : it does in any of my searches.
# :
# : The script requires net-snmp tools. The script will first attempt to
# : ping a target, then process it if the ping succeeds. Our devices use a
# : standard naming convention of 12 characters. The script parses the host
# : name and determines the location of the device by what it finds in
# : character position 2 and 3 so you may want to remove that section or
# : edit it for your needs.
# :
# : The script creates an excel spreadsheet and saves it as a date & time
# : stamped file on the root of C:, so you need Excel installed. Target
# : systems are read from a file named "devices.txt" that should reside in
# : the same folder as the script and contain a list of target IP addresses,
# : one per line.
# :
# Warnings : None
# :
# Legal : Script provided "AS IS" without warranties or guarantees of any
# : kind. USE AT YOUR OWN RISK. Public domain, no rights reserved.
# : Please keep this header in tact if at all possible.
# :
# Credits : Code snippets and/or ideas came from many sources including but
# :
# Last Update by : Kenneth C. Mazie
# Version History : v1.0 - 06-24-10 - Original
# Change History : v1.1 -
#
#=======================================================================================
Clear-Host
#--[ Global presets ]----------------------------------
$Invocation = (Get-Variable MyInvocation -Scope 0).Value
#$ScriptPath = Split-Path $Invocation.MyCommand.Path
$strExe = "f:\\usr\\bin\\snmpget.exe" #--[ Set the location of the net-snmp tools bin folder ]---------
$strCommunity = "Public" #--[ set your community string ]---------
#--[ Assorted Excel presets settings ]----------------------------------
$xlAutomatic = -4105 #
$xlBottom = -4107 # Text alignment bottom
$xlCenter = -4108 # Text alignment center
$xlContext = -5002 # Text alignment
$xlContinuous = 1 #
$xlDiagonalDown = 5 # Cell line position
$xlDiagonalUp = 6 # Cell line position
$xlEdgeBottom = 9 # Cell line position
$xlEdgeLeft = 7 # Cell line position
$xlEdgeRight = 10 # Cell line position
$xlEdgeTop = 8 # Cell line position
$xlInsideHorizontal = 12 # Cell line position
$xlInsideVertical = 11 # Cell line position
$xlDash = -4115 # Dashed line
$xlDashDot = 4 # Alternating dashes and dots
$xlDashDotDot = 5 # Dash followed by two dots
$xlDot = -4118 # Dotted line
$xlDouble = -4119 # Double line
$xlNone = -4142 # No line
$xlSlantDashDot = 13 # Slanted dashes.
$xlThick = 4 # Thick line
$xlThin = 2 # Thin line
$sortCol = 5 # what column to place sort code in
#--[ Create Spreadsheet ]-------------------------------
$Excel = New-Object -comobject Excel.Application
$Excel.Visible = $True
$Excel = $Excel.Workbooks.Add(1)
$WorkSheet = $Excel.Worksheets.Item(1)
$WorkSheet.Cells.Item(1,1) = "Target IP"
$WorkSheet.Cells.Item(1,2) = "Hostname"
$WorkSheet.Cells.Item(1,3) = "Model #"
$WorkSheet.Cells.Item(1,4) = "Serial #"
$WorkSheet.Cells.Item(1,5) = "IOS Ver"
$WorkSheet.Cells.Item(1,6) = "Location"
$Workbook = $WorkSheet.UsedRange
$WorkBook.Interior.ColorIndex = 8
$WorkBook.Font.ColorIndex = 11
$WorkBook.Font.Bold = $True
$WorkBook.EntireColumn.AutoFit()
#--[ Formatting ]----------------------------
$Col = 1
while ($Col -le 6){
$Edge = 7
while ($Edge -le 10){
$WorkSheet.Cells.Item(1,$Col).Borders.Item($Edge).LineStyle = 1
#$WorkSheet.Cells.Item(1,$Col).Borders.Item($Edge).Weight = 4 #--[ uncomment to make borders bold ]---------
$Edge++
}
$Col++
}
#$arrDevices = @("192.168.10.2","192.168.10.252")
$arrDevices = Get-Content ($ScriptPath + "\\devicelist.txt")
$intRow = 1
$count = 0
# NOTE: Cisco MIB for chassis serial # = mib-2.47.1.1.1.1.11.1001
# NOTE: Cisco MIB for chassis model # = mib-2.47.1.1.1.1.13.1001
# NOTE: Cisco MIB for IOS Ver = mib-2.47.1.1.1.1.13.1001
# NOTE: Cisco MIB for hostname = sysName.0
#--[ populate spreadsheet with data ]------------------
foreach ($strTarget in $arrDevices){ #--[ Cycle through targets ]--------
$intRow = $intRow + 1
$WorkSheet.Cells.Item($intRow,1) = $strTarget #--[ Place Target IP in current row, column A ]----------
Write-Host "Processing..... " $strTarget
if (test-connection $strTarget) {
if ($count = 5) {$count = 0}
$strSerial = iex "cmd.exe /c `"$strExe -v 1 -c $strCommunity $strTarget mib-2.47.1.1.1.1.11.1001`""
$strModel = iex "cmd.exe /c `"$strExe -v 1 -c $strCommunity $strTarget mib-2.47.1.1.1.1.13.1001`""
$strIOS = iex "cmd.exe /c `"$strExe -v 1 -c $strCommunity $strTarget mib-2.47.1.1.1.1.9.1001`""
$strHostName = iex "cmd.exe /c `"$strExe -v 1 -c $strCommunity $strTarget sysName.0`""
#--[ If we get back a model place it in current row, column C ]----------
if ($strModel.Length -gt 1) {$WorkSheet.Cells.Item($intRow,3) = ($strModel.Split('"'))[1]}
#--[ If we get back a serial # place it in current row, column D ]----------
if ($strSerial.Length -gt 1) {$WorkSheet.Cells.Item($intRow,4) = ($strSerial.Split('"'))[1]}
#--[ If we get back an IOS version place it in current row, column E ]----------
if ($strIOS.Length -gt 1) {$WorkSheet.Cells.Item($intRow,5) = ($strIOS.Split('"'))[1]}
#--[ If we get back a hostname place it in current row, column B ]----------
if ($strHostname.Length -gt 1) {
$strHostName = ($strHostName.Split(' '))[3]
$WorkSheet.Cells.Item($intRow,2) = $strHostName
switch($strHostName.substring(1,2)) {
"00" { $errorcode = 'Rack 00' }
"01" { $errorcode = 'Rack 01' }
"02" { $errorcode = 'Rack 02' }
"03" { $errorcode = 'Rack 03' }
"04" { $errorcode = 'Rack 04' }
"05" { $errorcode = 'Rack 05' }
"06" { $errorcode = 'Rack 06' }
"07" { $errorcode = 'Rack 07' }
"08" { $errorcode = 'Rack 08' }
"09" { $errorcode = 'Rack 09' }
"10" { $errorcode = 'Rack 10' }
"11" { $errorcode = 'Rack 11' }
"12" { $errorcode = 'Rack 12' }
"13" { $errorcode = 'Rack 13' }
"14" { $errorcode = 'Rack 14' }
default { $errorcode = 'Unknown' }
}
$WorkSheet.Cells.Item($intRow,6) = $errorcode #--[ Place location in current row, column F ]----------
}
}
else
{
$WorkSheet.Cells.Item($intRow,2) = "Unreachable" #--[ Place model # in current row, column B ]----------
}
$count = $count + 1
if ($count =5) {$WorkBook.EntireColumn.AutoFit()}
}
$WorkBook.EntireColumn.AutoFit() #--[ Adjust column width across used columns ]---------
$WorkSheet.Cells.Item($intRow + 2, 1) = "DONE"
$strFilename = "c:\\CiscoInventory-{0:dd-MM-yyyy_HHmm}.xls" -f (Get-Date) #--[ Places a date stamped spreadsheet in the root of C: ]------
$Excel.SaveAs($StrFilename)
Write-Host ("Output saved to " + $strFilename)
Write-Host "Done..."
|
PowerShellCorpus/PoshCode/Stop service and wait....ps1
|
Stop service and wait....ps1
|
<#
This script stops the service, then waits for the service to stop before continuing with the reboot/shutdown
The scritp can be pushed to a server/Pc using Group Policy or Registry or run manually.
The shutdown script Registry key is:
HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Group Policy\\State\\Machine\\Scripts\\Shutdown\\
#>
# type the name of the service in the quotes here
$ServiceName = 'Service Name'
Stop-Service $ServiceName
write-host $ServiceName'...' -NoNewLine
$TestService = Get-Service $Service | Select-Object 'Status'
While($TestService | where {$_.Status -eq 'Running'}){
Write-Host '.'-NoNewLine
Sleep 2
}
# If you want to shutdown the computer add the command "Shutdown /t 0" (without quoutes)onto the bottom line.
# If you want to Reboot the computer then add the command "Restart-computer" (without quotes) on the line below.
|
PowerShellCorpus/PoshCode/Get-Parameter.ps1
|
Get-Parameter.ps1
|
param($Cmdlet) $CmdletInfo = Get-Command -CommandType Cmdlet -Name $Cmdlet
if ( $? ) {
if ($CmdletInfo.GetType().Name -eq "CmdletInfo" ) {
$parsed = $CmdletInfo.Definition `
-replace "\\] \\[", "]`n[" `
-replace "> \\[", ">`n[" `
-replace "$Cmdlet " `
-split "`n" `
-replace "\\[-" `
-replace "\\]$"
$parsed = $parsed | Sort-Object -Unique
switch -regex ($parsed) {
"^\\[" { Write-host -ForegroundColor Green $_ }
"Confirm|Debug|Verbose|WhatIf" { Write-Host -ForegroundColor Blue $_ }
Default { Write-Host $_ }
}
}
}
|
PowerShellCorpus/PoshCode/image2excel_1.ps1
|
image2excel_1.ps1
|
<#
.Description
image2excel converts image to excel file
#>
param (
[parameter(Mandatory=$true,
ValueFromPipeline=$true,
HelpMessage="Image file path"
)]
[ValidateScript({Test-Path $_})]
[String]
$filename
)
[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") | Out-Null
function color2excel($color)
{
$color.R * 256*256 + $color.G * 256 + $color.B
}
$image = New-Object System.Drawing.Bitmap $filename
$o = New-Object -ComObject Excel.Application
$wb = $o.Workbooks.Add()
$sh = $wb.ActiveSheet
$sh.Cells.ColumnWidth =0.25;
$sh.Cells.RowHeight = 2.5;
$o.Visible = $true
$total = $image.Width * $image.Height
foreach($x in 0..($image.Width-1))
{
foreach($y in 0..($image.Height-1))
{
Write-Progress "Exporting..." "$x,$y" -PercentComplete ((($x * $image.Height + $y) / $total ) * 100)
$sh.Cells.Item($y+1, $x+1).Interior.Color = color2excel($image.GetPixel($x, $y))
}
}
|
PowerShellCorpus/PoshCode/Get-DLRestriction_1.ps1
|
Get-DLRestriction_1.ps1
|
###########################################
# Get-DLRestriction
#
# Uses QAD cmdlets to retrieve distribution list restriction attributes
# and then provides a list of users which can send email messages to the group.
#
# Usage: Get-DLRestriction "Worldwide Everyone"
#
# Dmitry Sotnikov, http://dmitrysotnikov.wordpress.com
############################################
function Get-DLRestriction {
param([System.String] $DLName )
"Checking restrictions for $DLName"
$DL = Get-QADGroup $DLName `
-IncludedProperties AuthOrig, UnauthOrig, dLMemRejectPerms,`
dLMemSubmitPerms, msExchRequireAuthToSendTo
# we'll set this to true if we see a restriction
$restricted = $false
# if the group with such a name is found
if ( $DL -ne $null ) {
if ( $DL.AuthOrig -ne $null ) {
$restricted = $true
"`nThe following users can send messages to this list:"
$DL.AuthOrig | Get-QADUser
}
if ( $DL.UnauthOrig -ne $null ) {
$restricted = $true
"`nAnyone BUT the following users can send messages to this list:"
$DL.UnauthOrig | Get-QADUser
}
if ( $DL.dLMemSubmitPerms -ne $null ) {
$restricted = $true
"`nMembers of this group can send messages to this list: $($DL.dLMemSubmitPerms | Get-QADGroup)) :"
Get-QADGroupMember $DL.dLMemSubmitPerms
}
if ( $DL.dLMemRejectPerms -ne $null ) {
$restricted = $true
"`nAnyone BUT members of this group can send messages to this list: $($DL.dLMemRejectPerms | Get-QADGroup)) :"
Get-QADGroupMember $DL.dLMemRejectPerms
}
if ( $DL.msExchRequireAuthToSendTo ) {
$restricted = $true
"`nOnly authenticated users can send messages to this list.`nExternal senders get blocked."
}
if ( -not $restricted ) {
"`nThis list is not restricted. Anyone can email it."
}
} else {
"`nDL $DLName not found."
}
}
|
PowerShellCorpus/PoshCode/Get-QADGroupNesting.ps1
|
Get-QADGroupNesting.ps1
|
Param (
[Parameter(Mandatory=$true,
Position=0,
ValueFromPipeline=$true,
HelpMessage="DN or ObjectGUID of the AD Group."
)]
[string]$groupIdentity,
[switch]$showTree
)
#Validate Quest PSSnapin is loaded
Add-PSSnapin -Name Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue
$global:numberOfRecursiveGroupMemberships = 0
$lastGroupAtALevelFlags = @()
function Get-GroupNesting ([string] $identity, [int] $level, [hashtable] $groupsVisitedBeforeThisOne, [bool] $lastGroupOfTheLevel)
{
$group = $null
$group = Get-QADGroup -Identity $identity -SizeLimit 0
if($lastGroupAtALevelFlags.Count -le $level)
{
$lastGroupAtALevelFlags = $lastGroupAtALevelFlags + 0
}
if($group -ne $null)
{
if($showTree)
{
for($i = 0; $i -lt $level - 1; $i++)
{
if($lastGroupAtALevelFlags[$i] -ne 0)
{
Write-Host -ForegroundColor Blue -NoNewline " "
}
else
{
Write-Host -ForegroundColor Blue -NoNewline "„ "
}
}
if($level -ne 0)
{
if($lastGroupOfTheLevel)
{
Write-Host -ForegroundColor Blue -NoNewline "„¤„ź"
}
else
{
Write-Host -ForegroundColor Blue -NoNewline "„Ą„ź"
}
}
Write-Host -ForegroundColor Blue $group.Name
}
$groupsVisitedBeforeThisOne.Add($group.DN,$null)
$global:numberOfRecursiveGroupMemberships ++
$groupMemberShipCount = $group.memberOf.Count
if ($groupMemberShipCount -gt 0)
{
$maxMemberGroupLevel = 0
$count = 0
foreach($groupDN in $group.memberOf)
{
$count++
$lastGroupOfThisLevel = $false
if($count -eq $groupMemberShipCount){$lastGroupOfThisLevel = $true; $lastGroupAtALevelFlags[$level] = 1}
if(-not $groupsVisitedBeforeThisOne.Contains($groupDN)) #prevent cyclic dependancies
{
$memberGroupLevel = Get-GroupNesting -Identity $groupDN -Level $($level+1) -GroupsVisitedBeforeThisOne $groupsVisitedBeforeThisOne -lastGroupOfTheLevel $lastGroupOfThisLevel
if ($memberGroupLevel -gt $maxMemberGroupLevel){$maxMemberGroupLevel = $memberGroupLevel}
}
}
$level = $maxMemberGroupLevel
}
else #we've reached the top level group, return it's height
{
return $level
}
return $level
}
}
$global:numberOfRecursiveGroupMemberships = 0
$groupObj = Get-QADGroup -Identity $groupIdentity -SizeLimit 0
if($groupObj)
{
[int]$maxNestingLevel = Get-GroupNesting -Identity $groupIdentity -Level 0 -GroupsVisitedBeforeThisOne @{} -lastGroupOfTheLevel $false
Add-Member -InputObject $groupObj -MemberType NoteProperty -Name MaxNestingLevel -Value $maxNestingLevel -Force
Add-Member -InputObject $groupObj -MemberType NoteProperty -Name NestedGroupMembershipCount -Value $($global:numberOfRecursiveGroupMemberships - 1) -Force
$groupObj | Select-Object Name,DN,MaxNestingLevel,NestedGroupMembershipCount | Format-List
}
|
PowerShellCorpus/PoshCode/Get-WebSite_1.ps1
|
Get-WebSite_1.ps1
|
function Get-WebSite {
<#
.SYNOPSIS
Retrieves information about a website.
.DESCRIPTION
Retrieves information about a website.
.PARAMETER Url
URL of the website to test access to.
.PARAMETER UseDefaultCredentials
Use the currently authenticated user's credentials
.PARAMETER Proxy
Used to connect via a proxy
.PARAMETER TimeOut
Timeout to connect to site, in milliseconds
.PARAMETER Credential
Provide alternate credentials
.NOTES
Name: Get-WebSite
Author: Boe Prox
DateCreated: 08Feb2011
.EXAMPLE
Get-WebSite -url "http://www.bing.com"
Description
------------
Returns information about Bing.Com to include StatusCode and type of web server being used to host the site.
#>
[cmdletbinding(
DefaultParameterSetName = 'url',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = '',
ValueFromPipeline = $True)]
[string][ValidatePattern("^(http|https)\\://*")]$Url,
[Parameter(
Position = 1,
Mandatory = $False,
ParameterSetName = 'defaultcred')]
[switch]$UseDefaultCredentials,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[string]$Proxy,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[Int]$Timeout,
[Parameter(
Mandatory = $False,
ParameterSetName = 'altcred')]
[switch]$Credential
)
Begin {
$psBoundParameters.GetEnumerator() | % {
Write-Verbose "Parameter: $_"
}
#Create the initial WebRequest object using the given url
Write-Verbose "Creating the web request object"
$webRequest = [net.WebRequest]::Create($url)
#Use Proxy address if specified
If ($PSBoundParameters.ContainsKey('Proxy')) {
#Create Proxy Address for Web Request
Write-Verbose "Creating proxy address and adding into Web Request"
$webRequest.Proxy = New-Object -TypeName Net.WebProxy($proxy,$True)
}
#Set timeout
If ($PSBoundParameters.ContainsKey('TimeOut')) {
#Setting the timeout on web request
Write-Verbose "Setting the timeout on web request"
$webRequest.Timeout = $timeout
}
#Determine if using Default Credentials
If ($PSBoundParameters.ContainsKey('UseDefaultCredentials')) {
#Set to True, otherwise remains False
Write-Verbose "Using Default Credentials"
$webrequest.UseDefaultCredentials = $True
}
#Determine if using Alternate Credentials
If ($PSBoundParameters.ContainsKey('Credentials')) {
#Prompt for alternate credentals
Write-Verbose "Prompt for alternate credentials"
$wc.Credential = (Get-Credential).GetNetworkCredential()
}
#Set TimeStamp prior to attempting connection
$then = get-date
}
Process {
Try {
#Make connection to gather response from site
$response = $webRequest.GetResponse()
#If successful, get the date for comparison
$now = get-date
#Generate report
Write-Verbose "Generating report from website connection and response"
$report = @{
URL = $url
StatusCode = $response.Statuscode -as [int]
StatusDescription = $response.StatusDescription
ResponseTime = "$(($now - $then).totalseconds)"
WebServer = $response.Server
Size = $response.contentlength
}
}
Catch {
#Get timestamp of failed attempt
$now = get-date
#Put the current error into a variable for later use
$errorstring = "$($error[0])"
#Generate report
$report = @{
URL = $url
StatusCode = ([regex]::Match($errorstring,"\\b\\d{3}\\b")).value
StatusDescription = (($errorstring.split('\\)')[2]).split('.\\')[0]).Trim()
ResponseTime = "$(($now - $then).totalseconds)"
WebServer = $response.Server
Size = $response.contentlength
}
}
}
End {
#Display Report
New-Object PSObject -property $report
}
}
|
PowerShellCorpus/PoshCode/Get-HostsFile.ps1
|
Get-HostsFile.ps1
|
Function Get-HostsFile {
<#
.SYNOPSIS
Retrieves the contents of a hosts file on a specified system
.DESCRIPTION
Retrieves the contents of a hosts file on a specified system
.PARAMETER Computer
Computer name to view host file from
.NOTES
Name: Get-HostsFile
Author: Boe Prox
DateCreated: 15Mar2011
.LINK
http://boeprox.wordpress.com
.EXAMPLE
Get-HostsFile "server1"
Description
-----------
Retrieves the contents of the hosts file on 'server1'
#>
[cmdletbinding(
DefaultParameterSetName = 'Default',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
ValueFromPipeline = $True)]
[string[]]$Computer
)
Begin {
$psBoundParameters.GetEnumerator() | % {
Write-Verbose "Parameter: $_"
}
If (!$PSBoundParameters['computer']) {
Write-Verbose "No computer name given, using local computername"
[string[]]$computer = $Env:Computername
}
$report = @()
}
Process {
Write-Verbose "Starting process of computers"
ForEach ($c in $computer) {
Write-Verbose "Testing connection of $c"
If (Test-Connection -ComputerName $c -Quiet -Count 1) {
Write-Verbose "Validating path to hosts file"
If (Test-Path "\\\\$c\\C$\\Windows\\system32\\drivers\\etc\\hosts") {
Switch -regex -file ("\\\\$c\\c$\\Windows\\system32\\drivers\\etc\\hosts") {
"^\\d\\w+" {
Write-Verbose "Adding information to collection"
$temp = "" | Select Computer, IP, Hostname, Notes
$new = $_.Split("") | ? {$_ -ne ""}
$temp.Computer = $c
$temp.IP = $new[0]
$temp.HostName = $new[1]
If ($new[2] -eq $Null) {
$temp.Notes = "NA"
}
Else {
$temp.Notes = $new[2]
}
$report += $temp
}
}
}#EndIF
ElseIf (Test-Path "\\\\$c\\C$\\WinNT\\system32\\drivers\\etc\\hosts") {
Switch -regex -file ("\\\\$c\\c$\\WinNT\\system32\\drivers\\etc\\hosts") {
"^\\d\\w+" {
Write-Verbose "Adding information to collection"
$temp = "" | Select Computer, IP, Hostname, Notes
$new = $_.Split("") | ? {$_ -ne ""}
$temp.Computer = $c
$temp.IP = $new[0]
$temp.HostName = $new[1]
If ($new[2] -eq $Null) {
$temp.Notes = "NA"
}
Else {
$temp.Notes = $new[2]
}
$report += $temp
}
}
}#End ElseIf
Else {
Write-Verbose "No host file found"
$temp = "" | Select Computer, IP, Hostname, Notes
$temp.Computer = $c
$temp.IP = "NA"
$temp.Hostname = "NA"
$temp.Notes = "Unable to locate host file"
$report += $temp
}#End Else
}
Else {
Write-Verbose "No computer found"
$temp = "" | Select Computer, IP, Hostname, Notes
$temp.Computer = $c
$temp.IP = "NA"
$temp.Hostname = "NA"
$temp.Notes = "Unable to locate Computer"
$report += $temp
}
}
}
End {
Write-Output $report
}
}
|
PowerShellCorpus/PoshCode/Get-GrowthRate.ps1
|
Get-GrowthRate.ps1
|
function Get-GrowthRate {
param( $Start, $End, $Period )
$rate = [math]::Abs( [math]::Pow( ( $End / $Start ),( 1 / $per - 1 ) ) - 1 )
"{0:P}" -f $rate
}
|
PowerShellCorpus/PoshCode/Get-DellWarranty by API.ps1
|
Get-DellWarranty by API.ps1
|
## Dane Kantner 4/19/2013
##
$computers="localhost","Chiv5908-2009","anyothercomputers","NYSPC-JJAJ68YG6"
foreach ($computer in $computers) {
$obj=get-wmiobject win32_systemenclosure -computername $computer -ErrorAction SilentlyContinue
if ($obj -eq $null) { # unable to retrieve, system may be offline
write-output "Computer $computer unavailable (offline or WMI inaccessible).`n"
} else {
$WarrantyObject=Get-DellWarranty -ServiceTag $obj.SerialNumber | select @{name = "ComputerName";expression = {$Computer}},ServiceLevelCode,ServiceLevelDescription,Provider,StartDate,EndDate,DaysLeft,EntitlementType
#each computer itself will have a $warrantyobject returned that can have multiple warranty lines attached.
#based off of this you can do various output scenarios.
$DaysLeft=0
$HighestServiceDesc=""
foreach ($line in $WarrantyObject) {
if ($line.ServiceLevelCode -ne $Null) { #The last line is a null line from the dell service, discard with an if neq null check
if ($DaysLeft -lt $line.DaysLeft) { #this warranty lasts longer than the prior line item for this computer.
$DaysLeft=$line.DaysLeft
$HighestServiceDesc=$line.ServiceLevelDescription
}
write-output $line
#you could output it to a file here instead -- or instead when calling script do scripts.ps1 > filenametosave.txt
}
} #end foreach $warrantyobject
# in this coding scenario, an HP computer would just return a null object.
if ($warrantyObject -ne $null) {
write-output "Maximum warranty for computer $Computer has $DaysLeft days remaining. $HighestServiceDesc`n"
} else {
write-output "Dell returned no warranty information for $Computer. Is it a Dell?"
} #end if WarrantyObject is not null
} #end if obj null because WMI failed to retrieve serial
} #end foreach computer
Function Get-DellWarranty {
## This function was created based off of modifying code from http://itx-solutions.nl/2013/01/dell-powershell-script-to-get-dell-warranty-information/
[CmdletBinding()]
param(
[Parameter(Mandatory=$False,Position=0,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
[alias("serialnumber")]
[string[]]$ServiceTag
)
$WebProxy=New-WebServiceProxy -Uri http://xserv.dell.com/services/assetservice.asmx
$WarrantyInformation=$WebProxy.GetAssetInformation(([guid]::NewGuid()).Guid,"Dell warranty",$serviceTag)
$WarrantyInformation | Select-Object -ExpandProperty Entitlements
return $WarrantyInformation
}
|
PowerShellCorpus/PoshCode/Test-Port_3.ps1
|
Test-Port_3.ps1
|
function Test-Port{
<#
.SYNOPSIS
Tests port on computer.
.DESCRIPTION
Tests port on computer.
.PARAMETER computer
Name of server to test the port connection on.
.PARAMETER port
Port to test
.PARAMETER tcp
Use tcp port
.PARAMETER udp
Use udp port
.PARAMETER UDPTimeOut
Sets a timeout for UDP port query. (In milliseconds, Default is 1000)
.PARAMETER TCPTimeOut
Sets a timeout for TCP port query. (In milliseconds, Default is 1000)
.NOTES
Name: Test-Port.ps1
Author: Boe Prox
DateCreated: 18Aug2010
List of Ports: http://www.iana.org/assignments/port-numbers
To Do:
Add capability to run background jobs for each host to shorten the time to scan.
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Test-Port -computer 'server' -port 80
Checks port 80 on server 'server' to see if it is listening
.EXAMPLE
'server' | Test-Port -port 80
Checks port 80 on server 'server' to see if it is listening
.EXAMPLE
Test-Port -computer @("server1","server2") -port 80
Checks port 80 on server1 and server2 to see if it is listening
.EXAMPLE
@("server1","server2") | Test-Port -port 80
Checks port 80 on server1 and server2 to see if it is listening
.EXAMPLE
(Get-Content hosts.txt) | Test-Port -port 80
Checks port 80 on servers in host file to see if it is listening
.EXAMPLE
Test-Port -computer (Get-Content hosts.txt) -port 80
Checks port 80 on servers in host file to see if it is listening
.EXAMPLE
Test-Port -computer (Get-Content hosts.txt) -port @(1..59)
Checks a range of ports from 1-59 on all servers in the hosts.txt file
#>
[cmdletbinding(
DefaultParameterSetName = '',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = '',
ValueFromPipeline = $True)]
[array]$computer,
[Parameter(
Position = 1,
Mandatory = $True,
ParameterSetName = '')]
[array]$port,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[int]$TCPtimeout=1000,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[int]$UDPtimeout=1000,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[switch]$TCP,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[switch]$UDP
)
Begin {
If (!$tcp -AND !$udp) {$tcp = $True}
#Typically you never do this, but in this case I felt it was for the benefit of the function
#as any errors will be noted in the output of the report
$ErrorActionPreference = "SilentlyContinue"
$report = @()
}
Process {
ForEach ($c in $computer) {
ForEach ($p in $port) {
If ($tcp) {
#Create temporary holder
$temp = "" | Select Server, Port, TypePort, Open, Notes
#Create object for connecting to port on computer
$tcpobject = new-Object system.Net.Sockets.TcpClient
#Connect to remote machine's port
$connect = $tcpobject.BeginConnect($c,$p,$null,$null)
#Configure a timeout before quitting
$wait = $connect.AsyncWaitHandle.WaitOne($TCPtimeout,$false)
#If timeout
If(!$wait) {
#Close connection
$tcpobject.Close()
Write-Verbose "Connection Timeout"
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "TCP"
$temp.Open = "False"
$temp.Notes = "Connection to Port Timed Out"
}
Else {
$error.Clear()
$tcpobject.EndConnect($connect) | out-Null
#If error
If($error[0]){
#Begin making error more readable in report
[string]$string = ($error[0].exception).message
$message = (($string.split(":")[1]).replace('"',"")).TrimStart()
$failed = $true
}
#Close connection
$tcpobject.Close()
#If unable to query port to due failure
If($failed){
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "TCP"
$temp.Open = "False"
$temp.Notes = "$message"
}
#Successfully queried port
Else{
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "TCP"
$temp.Open = "True"
$temp.Notes = ""
}
}
#Reset failed value
$failed = $Null
#Merge temp array with report
$report += $temp
}
If ($udp) {
#Create temporary holder
$temp = "" | Select Server, Port, TypePort, Open, Notes
#Create object for connecting to port on computer
$udpobject = new-Object system.Net.Sockets.Udpclient($p)
#Set a timeout on receiving message
$udpobject.client.ReceiveTimeout = $UDPTimeout
#Connect to remote machine's port
Write-Verbose "Making UDP connection to remote server"
$udpobject.Connect("$c",$p)
#Sends a message to the host to which you have connected.
Write-Verbose "Sending message to remote host"
$a = new-object system.text.asciiencoding
$byte = $a.GetBytes("$(Get-Date)")
[void]$udpobject.Send($byte,$byte.length)
#IPEndPoint object will allow us to read datagrams sent from any source.
Write-Verbose "Creating remote endpoint"
$remoteendpoint = New-Object system.net.ipendpoint([system.net.ipaddress]::Any,0)
Try {
#Blocks until a message returns on this socket from a remote host.
Write-Verbose "Waiting for message return"
$receivebytes = $udpobject.Receive([ref]$remoteendpoint)
[string]$returndata = $a.GetString($receivebytes)
}
Catch {
If ($Error[0].ToString() -match "\\bRespond after a period of time\\b") {
#Close connection
$udpobject.Close()
#Make sure that the host is online and not a false positive that it is open
If (Test-Connection -comp $c -count 1 -quiet) {
Write-Verbose "Connection Open"
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "UDP"
$temp.Open = "True"
$temp.Notes = ""
}
Else {
<#
It is possible that the host is not online or that the host is online,
but ICMP is blocked by a firewall and this port is actually open.
#>
Write-Verbose "Host maybe unavailable"
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "UDP"
$temp.Open = "False"
$temp.Notes = "Unable to verify if port is open or if host is unavailable."
}
}
ElseIf ($Error[0].ToString() -match "forcibly closed by the remote host" ) {
#Close connection
$udpobject.Close()
Write-Verbose "Connection Timeout"
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "UDP"
$temp.Open = "False"
$temp.Notes = "Connection to Port Timed Out"
}
Else {
$udpobject.close()
}
}
#Merge temp array with report
$report += $temp
}
}
}
}
End {
#Generate Report
$report
}
}
|
PowerShellCorpus/PoshCode/Logger.psm1 0.4.ps1
|
Logger.psm1 0.4.ps1
|
<#
Name : Universal Log4Net Logging Module (Logger.psm1)
Version : 0.3
Author : Joel Bennett (MVP)
Site : http://www.HuddledMasses.org/
Version History:
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 Log4Net : http`://logging.apache.org/log4net/download.html
Documentation: http`://logging.apache.org/log4net/release/sdk/
NOTES:
By default, this overwrites the Write-* cmdlets for Error, Warning, Debug, Verbose, and even Host.
This means that you may end up logging a lot of stuff you didn't intend to log (ie: verbose output from other scripts)
To avoid this behavior, remove the aliases after importing it
Import-Module Logger; Remove-Item Alias:Write-*
Write-Warning "This is your warning"
Write-Debug "You should know that..."
Write-Verbose "Everything would be logged, otherwise"
***** NOTE: IT ONLY OVERRIDES THE DEFAULTS FOR SCRIPTS *****
It currently has no effect on error/verbose/warning that is logged from cmdlets.
#>
Add-Type -Path $PSScriptRoot\\log4net.dll
function Get-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:
"%date %-5level %logger [%property{NDC}] - %message%newline"
For a complete list of possible pattern names, see:
http://logging.apache.org/log4net/release/sdk/log4net.Layout.PatternLayout.html
.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)]
[ValidateSet("DEBUG","INFO","WARN","ERROR","FATAL","VERBOSE","HOST","WARNING")]
[string]$Level = "DEBUG"
,
[Parameter(Mandatory=$false)]
$MessagePattern = "%date %-5level %logger [%property{NDC}] - %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
,
[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
}
}
Remove-Variable Loggers -EA 0
[log4net.LogManager]::GetCurrentLoggers() | Where-Object { $_.Logger.Name -Like $Name } | Tee-Object -Variable Loggers
if((!$Loggers -or $Force) -and !$Name.Contains('*')) {
if($Level -eq "VERBOSE") { $Level = "INFO" }
if($Level -eq "HOST") { $Level = "INFO" }
if($Level -eq "WARNING") { $Level = "WARN" }
$AppenderRefs = ''
if($Email) {
if(!$PSEmailServer) { throw "You need to specify your SMTP mail server by setting the global $PSEmailServer variable" }
$AppenderRefs += "<appender-ref ref=""SmtpAppender"" />`n"
$Null,$Domain = $email -split "@",2
}
if($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\\log4net.xslt)"?>
"@
}
if($EventLog) { $AppenderRefs += "<appender-ref ref=""EventLogAppender"" />`n" }
if($TraceLog) { $AppenderRefs += "<appender-ref ref=""TraceAppender"" />`n" }
if($DebugLog){ $AppenderRefs += "<appender-ref ref=""DebugAppender"" />`n" }
if($FileLog) { $AppenderRefs += "<appender-ref ref=""FileAppender"" />`n" }
if($RollingFileLog) { $AppenderRefs += "<appender-ref ref=""RollingFileAppender"" />`n" }
if($UdpSend) { $AppenderRefs += "<appender-ref ref=""UdpAppender"" />`n" }
if($ChainsawSend) { $AppenderRefs += "<appender-ref ref=""UdpLog4JAppender"" />`n" }
if($XmlLog) { $AppenderRefs += "<appender-ref ref=""XmlAppender"" />`n" }
if($RollingXmlLog) { $AppenderRefs += "<appender-ref ref=""RollingXmlAppender"" />`n"
if($VerbosePreference -gt "SilentlyContinue") { "Created XML viewer for you at: ${Folder}\\${Name}View.Xml" }
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>
"@
}
$xslt = $xslt -replace "<","<" -replace ">",">" -replace '"',"'"
if($ConsoleLog -or ($AppenderRefs.Length -eq 0)) { $AppenderRefs += "<appender-ref ref=""ColoredConsoleAppender"" />`n" }
[log4net.LogManager]::GetLogger($Name) | Tee-Object -Variable Script:Logger | Where { $Loggers -notcontains $_ }
[xml]$config = @"
<log4net>
<appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
<mapping>
<level value="FATAL" />
<foreColor value="Red, HighIntensity" />
<backColor value="White, HighIntensity" />
</mapping>
<mapping>
<level value="ERROR" />
<foreColor value="Red, HighIntensity" />
</mapping>
<mapping>
<level value="DEBUG" />
<foreColor value="Green, HighIntensity" />
</mapping>
<mapping>
<level value="INFO" />
<foreColor value="Cyan, HighIntensity" />
</mapping>
<mapping>
<level value="WARN" />
<foreColor value="Yellow, HighIntensity" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="$MessagePattern" />
</layout>
</appender>
<appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
<applicationName value="$Name" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="$MessagePattern" />
</layout>
</appender>
<appender name="TraceAppender" type="log4net.Appender.TraceAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="$MessagePattern" />
</layout>
</appender>
<appender name="DebugAppender" type="log4net.Appender.DebugAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="$MessagePattern" />
</layout>
</appender>
<appender name="FileAppender" type="log4net.Appender.FileAppender">
<file value="$Folder\\$Name.Log" />
<appendToFile value="true" />
<lockingModel type="log4net.Appender.FileAppender+$LockMode" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="$MessagePattern" />
</layout>
</appender>
<appender name="XmlAppender" type="log4net.Appender.FileAppender">
<file value="$Folder\\$Name.xml" />
<appendToFile value="false" />
<lockingModel type="log4net.Appender.FileAppender+$LockMode" />
<layout type="log4net.Layout.XmlLayout">
<Header value="<?xml version='1.0' ?>
$xslt
<events version='1.2' xmlns='http`://logging.apache.org/log4net/schemas/log4net-events-1.2'>
"/>
<Footer value="</events>"/>
</layout>
</appender>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="$Folder\\$Name.Log" />
<appendToFile value="true" />
<maximumFileSize value="250KB" />
<maxSizeRollBackups value="2" />
<lockingModel type="log4net.Appender.FileAppender+$LockMode" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="$MessagePattern" />
</layout>
</appender>
<appender name="RollingXmlAppender" type="log4net.Appender.RollingFileAppender">
<file value="$Folder\\$Name.xml" />
<appendToFile value="true" />
<maximumFileSize value="500KB" />
<maxSizeRollBackups value="2" />
<lockingModel type="log4net.Appender.FileAppender+$LockMode" />
<layout type="log4net.Layout.XmlLayout">
<prefix value="" />
</layout>
</appender>
<appender name="UdpAppender" type="log4net.Appender.UdpAppender">
<RemoteAddress value="localhost" />
<RemotePort value="8080" />
<Encoding value="utf-8" />
<layout type="log4net.Layout.XmlLayout">
<Prefix value="" />
</layout>
<threshold value="DEBUG" />
</appender>
<appender name="UdpLog4JAppender" type="log4net.Appender.UdpAppender">
<RemoteAddress value="127.0.0.1" />
<RemotePort value="8080" />
<Encoding value="utf-8" />
<layout type="log4net.Layout.XmlLayoutSchemaLog4j, log4net" />
<threshold value="DEBUG" />
</appender>
<appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
<to value="$EmailTo" />
<from value="PoshLogger@$Domain" />
<subject value="PowerShell Logger Message" />
<smtpHost value="$PSEmailServer" />
<bufferSize value="512" />
<lossy value="true" />
<evaluator type="log4net.Core.LevelEvaluator">
<threshold value="WARN"/>
</evaluator>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%newline$MessagePattern%newline%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
</root>
<logger name="$Name">
<level value="$Level" />
$AppenderRefs
</logger>
</log4net>
"@
[log4net.Config.XmlConfigurator]::Configure( $config.log4net )
}
elseif($Loggers -and @($Loggers).Count -eq 1) {
$script:Logger = @($Loggers)[0]
}
}
function Set-Logger {
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[log4net.Core.LogImpl]$Logger
)
$script:Logger = $Logger
}
function Close-Logger {
param(
[Parameter(Mandatory=$false, ValueFromPipeline=$true)]
[log4net.Core.LogImpl]$Logger
)
PROCESS {
if($Logger) {
$Logger.Logger.CloseNestedAppenders()
$Logger.Logger.RemoveAllAppenders()
} else {
[log4net.LogManager]::Shutdown()
}
}
}
function Push-LogContext {
param(
[Parameter(Mandatory=$true)]
[string]$Name
)
[log4net.NDC]::Push($Name)
}
function Pop-LogContext {
[log4net.NDC]::Pop()
}
function Write-DebugLog {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
[Alias('Msg')]
[AllowEmptyString()]
[System.String]
${Message}
,
[Parameter(Mandatory=$false, Position=99)]
${Logger})
begin
{
try {
if($PSBoundParameters.ContainsKey("Logger")) {
if($Logger -is [log4net.Core.LogImpl]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" }
$null = $PSBoundParameters.Remove("Logger")
}
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Debug', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$script:logger.debug($Message) #Write-Debug
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Write-Debug
.ForwardHelpCategory Cmdlet
#>
}
function Write-VerboseLog {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
[Alias('Msg')]
[AllowEmptyString()]
[System.String]
${Message}
,
[Parameter(Mandatory=$false, Position=99)]
${Logger})
begin
{
try {
if($PSBoundParameters.ContainsKey("Logger")) {
if($Logger -is [log4net.Core.LogImpl]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" }
$null = $PSBoundParameters.Remove("Logger")
}
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Verbose', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$script:logger.info($Message)
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Write-Verbose
.ForwardHelpCategory Cmdlet
#>
}
function Write-WarningLog {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
[Alias('Msg')]
[AllowEmptyString()]
[System.String]
${Message}
,
[Parameter(Mandatory=$false, Position=99)]
${Logger})
begin
{
try {
if($PSBoundParameters.ContainsKey("Logger")) {
if($Logger -is [log4net.Core.LogImpl]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" }
$null = $PSBoundParameters.Remove("Logger")
}
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Warning', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$script:logger.warn($Message) #Write-Warning
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Write-Warning
.ForwardHelpCategory Cmdlet
#>
}
function Write-ErrorLog {
[CmdletBinding(DefaultParameterSetName='NoException')]
param(
[Parameter(ParameterSetName='WithException', Mandatory=$true)]
[System.Exception]
${Exception},
[Parameter(ParameterSetName='NoException', Mandatory=$true, Position=0, ValueFromPipeline=$true)]
[Parameter(ParameterSetName='WithException')]
[Alias('Msg')]
[AllowNull()]
[AllowEmptyString()]
[System.String]
${Message},
[Parameter(ParameterSetName='ErrorRecord', Mandatory=$true)]
[System.Management.Automation.ErrorRecord]
${ErrorRecord},
[Parameter(ParameterSetName='NoException')]
[Parameter(ParameterSetName='WithException')]
[System.Management.Automation.ErrorCategory]
${Category},
[Parameter(ParameterSetName='WithException')]
[Parameter(ParameterSetName='NoException')]
[System.String]
${ErrorId},
[Parameter(ParameterSetName='NoException')]
[Parameter(ParameterSetName='WithException')]
[System.Object]
${TargetObject},
[System.String]
${RecommendedAction},
[Alias('Activity')]
[System.String]
${CategoryActivity},
[Alias('Reason')]
[System.String]
${CategoryReason},
[Alias('TargetName')]
[System.String]
${CategoryTargetName},
[Alias('TargetType')]
[System.String]
${CategoryTargetType}
,
[Parameter(Mandatory=$false, Position=99)]
${Logger})
begin
{
try {
if($PSBoundParameters.ContainsKey("Logger")) {
if($Logger -is [log4net.Core.LogImpl]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" }
$null = $PSBoundParameters.Remove("Logger")
}
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Error', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$script:logger.error($Message,$Exception) #Write-Error
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Write-Error
.ForwardHelpCategory Cmdlet
#>
}
function Write-HostLog {
[CmdletBinding()]
param(
[Parameter(Position=0, ValueFromPipeline=$true, ValueFromRemainingArguments=$true)]
[System.Object]
${Object},
[Switch]
${NoNewline},
[System.Object]
${Separator} = $OFS,
[System.ConsoleColor]
${ForegroundColor},
[System.ConsoleColor]
${BackgroundColor}
,
[Parameter(Mandatory=$false, Position=99)]
${Logger})
begin
{
try {
if($PSBoundParameters.ContainsKey("Logger")) {
if($Logger -is [log4net.Core.LogImpl]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" }
$null = $PSBoundParameters.Remove("Logger")
}
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Host', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$script:logger.info(($Object -join $Separator)) #Write-Verbose
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Write-Host
.ForwardHelpCategory Cmdlet
#>
}
Set-Alias Write-Debug Write-DebugLog
Set-Alias Write-Verbose Write-VerboseLog
Set-Alias Write-Warning Write-WarningLog
Set-Alias Write-Error Write-ErrorLog
#Set-Alias Write-Host Write-HostLog
Export-ModuleMember -Function * -Alias *
$script:Logger = Get-Logger "PowerShellLogger" -RollingFile
## THIS IS THE DEFAULT LOGGER. CONFIGURE AS YOU SEE FIT
|
PowerShellCorpus/PoshCode/NetSnmp.psm1.ps1
|
NetSnmp.psm1.ps1
|
#requires -version 2
$NetSnmp = Join-Path $env:programfiles "Net-SNMP\\bin"
if ( -not ( Test-Path "$NetSnmp\\snmpwalk.exe" ) ) {
Throw "Net-SNMP binaries not found in $NetSnmp. Please install to this folder `
or edit the NetSnmp variable as appropriate."
}
# Modeled after SNMPWALK http://www.net-snmp.org/docs/man/snmpwalk.html
function Get-SnmpValue {
param (
[Parameter( Position = 0, Mandatory = $true )] $Agent,
[Parameter( Position = 1, Mandatory = $true )] $OID,
$Port = 161,
$Community = "public",
$Version = "2c"
)
&"$NetSnmp\\snmpwalk.exe" "-v$Version" "-c$Community" "${Agent}:$Port" "$OID"
}
|
PowerShellCorpus/PoshCode/_3.168.1.1.ps1
|
_3.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/Grant-RegistryAccessFull.ps1
|
Grant-RegistryAccessFull.ps1
|
##############################################################################\n##\n## Grant-RegistryAccessFullControl\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\nGrants full control access to a user for the specified registry key.\n\n.EXAMPLE\n\nPS >$registryPath = "HKLM:\\Software\\MyProgram"\nPS >Grant-RegistryAccessFullControl "LEE-DESK\\LEE" $registryPath\n\n#>\n\nparam(\n ## The user to grant full control\n [Parameter(Mandatory = $true)]\n $User,\n\n ## The registry path that should have its permissions modified\n [Parameter(Mandatory = $true)]\n $RegistryPath\n)\n\nSet-StrictMode -Version Latest\n\nPush-Location\nSet-Location -LiteralPath $registryPath\n\n## Retrieve the ACL from the registry key\n$acl = Get-Acl .\n\n## Prepare the access rule, and set the access rule\n$arguments = $user,"FullControl","Allow"\n$accessRule = New-Object Security.AccessControl.RegistryAccessRule $arguments\n$acl.SetAccessRule($accessRule)\n\n## Apply the modified ACL to the regsitry key\n$acl | Set-Acl .\n\nPop-Location
|
PowerShellCorpus/PoshCode/UIAutomation.ps1
|
UIAutomation.ps1
|
# #
# Select-Window Notepad | Remove-Window -passthru #
# ## And later ... #
# Select-Window Notepad | Select-ChildWindow | Send-Keys "%N" #
# ## OR ## #
# Select-Window Notepad | Select-ChildWindow | #
# Select-Control -title "Do&n't Save" -recurse | Send-Click #
# #
# #
# PS notepad | Select-Window | Select-ChildWindow | %{ New-Object Huddled.Wasp.Window $_ } #
# #
# cp C:\\Users\\Joel\\Projects\\PowerShell\\Wasp\\trunk\\WASP\\bin\\Debug\\Wasp.dll .\\Modules\\WASP\\ #
# Import-Module WASP
# function formatter { END {
# $input | Format-Table @{l="Text";e={$_.Text.SubString(0,25)}}, ClassName, FrameworkId -Auto
# }}
Add-Type -AssemblyName UIAutomationClient
Add-Type -AssemblyName UIAutomationTypes
$SWA = "System.Windows.Automation"
Import-Module Accelerators
Add-Accelerator AutoElement "$SWA.AutomationElement" -EA SilentlyContinue
Add-Accelerator InvokePattern "$SWA.InvokePattern" -EA SilentlyContinue
Add-Accelerator ValuePattern "$SWA.ValuePattern" -EA SilentlyContinue
Add-Accelerator TextPattern "$SWA.TextPattern" -EA SilentlyContinue
Add-Accelerator Condition "$SWA.Condition" -EA SilentlyContinue
Add-Accelerator AndCondition "$SWA.TextPattern" -EA SilentlyContinue
Add-Accelerator OrCondition "$SWA.TextPattern" -EA SilentlyContinue
Add-Accelerator NotCondition "$SWA.TextPattern" -EA SilentlyContinue
Add-Accelerator PropertyCondition "$SWA.PropertyCondition" -EA SilentlyContinue
Add-Accelerator AutoElementIds "$SWA.AutomationElementIdentifiers" -EA SilentlyContinue
Add-Accelerator TransformIds "$SWA.TransformPatternIdentifiers" -EA SilentlyContinue
$FalseCondition = [Condition]::FalseCondition
$TrueCondition = [Condition]::TrueCondition
Add-Type -AssemblyName System.Windows.Forms
Add-Accelerator SendKeys System.Windows.Forms.SendKeys -EA SilentlyContinue
function New-UIAElement {
[CmdletBinding()]
PARAM(
[Parameter(ValueFromPipeline=$true)]
[AutoElement]$Element
)
PROCESS {
$Element | Add-Member -Name Text -Type ScriptProperty -PassThru -Value {
$this.GetCurrentPropertyValue([AutoElementIds]::NameProperty)
} | Add-Member -Name ClassName -Type ScriptProperty -Passthru -Value {
$this.GetCurrentPropertyValue([AutoElementIds]::ClassNameProperty)
} | Add-Member -Name FrameworkId -Type ScriptProperty -Passthru -Value {
$this.GetCurrentPropertyValue([AutoElementIds]::FrameworkIdProperty)
} | Add-Member -Name ProcessId -Type ScriptProperty -Passthru -Value {
$this.GetCurrentPropertyValue([AutoElementIds]::ProcessIdProperty)
} | Add-Member -Name ControlTypeL18D -Type ScriptProperty -Passthru -Value {
$this.GetCurrentPropertyValue([AutoElementIds]::LocalizedControlTypeProperty)
}
}
}
function Select-Window {
[CmdletBinding()]
PARAM(
[Parameter()]
[Alias("Name")]
[string]$Text="*"
,
[Parameter()]
[string]$ClassName="*"
,
[Parameter(ValueFromPipeline=$true)]
[AutoElement]$Parent = [AutoElement]::RootElement
)
PROCESS {
$Parent.FindAll( "Children", $TrueCondition ) | New-UIAElement |
Where-Object {
($_.ClassName -like $ClassName) -AND
($_.Text -like $Text) }
}
}
function formatter { END {
$input | Format-Table @{l="Text";e={$_.Text.SubString(0,25)}}, ClassName, FrameworkId -Auto
}}
function Invoke-Element {
[CmdletBinding()]
PARAM(
[Parameter(ValueFromPipeline=$true)]
[AutoElement]$Target
)
PROCESS {
$Target.GetCurrentPattern([InvokePattern]::Pattern).Invoke()
}
}
function Set-ElementText {
[CmdletBinding()]
PARAM(
[Parameter()]
[string]$Text
,
[Parameter(ValueFromPipeline=$true)]
[AutoElement]$Target
)
PROCESS {
$Target.SetFocus();
$textPattern = $valuePattern = $null
try {
$textPattern = $Target.GetCurrentPattern([TextPattern]::Pattern)
Write-Host "textPattern:`n$($textPattern | gm)"
} catch { }
try {
$valuePattern = $Target.GetCurrentPattern([ValuePattern]::Pattern)
Write-Host "valuePattern:`n$($valuePattern | gm)"
} catch { }
$Target.SetFocus();
if($valuePattern) {
$valuePattern.SetValue( $Text )
}
if($textPattern) {
[SendKeys]::SendWait("^{HOME}");
[SendKeys]::SendWait("^+{END}");
[SendKeys]::SendWait("{DEL}");
[SendKeys]::SendWait( $Text )
}
}
}
|
PowerShellCorpus/PoshCode/Get-OnlineHelp_1.ps1
|
Get-OnlineHelp_1.ps1
|
## An update using New-WebServiceProxy to the MSDN ContentService instead of HttpRest
## See: http: //services.msdn.microsoft.com/ContentServices/ContentService.asmx
## This is a VERY EARLY prototype of a function that could retrieve cmdlet help from TechNet ...
## and hypothetically, other online help sites which used the same format (none)
param(
[Parameter(Mandatory=$true,Position=0)]
[String]$Name
,
[Parameter(Mandatory=$false,Position=1)]
[String[]]$Sections= @("Name", "Synopsis", "Syntax", "Description")
)
# http://poshcode.org/1718
function Select-Expand {
<#
.Synopsis
Like Select-Object -Expand, but with recursive iteration of a select chain
.Description
Takes a dot-separated series of properties to expand, and recursively iterates the output of each property ...
.Parameter Property
A collection of property names to expand.
Each property can be a dot-separated series of properties, and each one is expanded, iterated, and then evaluated against the next
.Parameter InputObject
The input to be selected from
.Parameter Unique
If set, this becomes a pipeline hold-up, and the total output is checked to ensure uniqueness
.Parameter EmptyToo
If set, Select-Expand will include empty/null values in it's output
.Example
Get-Help Get-Command | Select-Expand relatedLinks.navigationLink.uri -Unique
This will return the online-help link for Get-Command. It's the equivalent of running the following command:
C:\\PS> Get-Help Get-Command | Select-Object -Expand relatedLinks | Select-Object -Expand navigationLink | Select-Object -Expand uri | Where-Object {$_} | Select-Object -Unique
#>
param(
[Parameter(ValueFromPipeline=$false,Position=0)]
[string[]]$Property
,
[Parameter(ValueFromPipeline=$true)]
[Alias("IO")]
[PSObject[]]$InputObject
,
[Switch]$Unique
,
[Switch]$EmptyToo
)
begin {
if($unique) {
$output = @()
}
}
process {
foreach($io in $InputObject) {
foreach($prop in $Property -split "\\.") {
if($io -ne $null) {
$io = $io | Select-Object -Expand $prop
Write-Verbose $($io | out-string)
}
}
if(!$EmptyToo -and ($io -ne $null)) {
$io = $io | Where-Object {$_}
}
if($unique) {
$output += @($io)
}
else {
Write-Output $io
}
}
}
end {
if($unique) {
Write-Output $output | Select-Object -Unique
}
}
}
# New-Alias slep Select-Expand
# http://poshcode.org/1722
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
}
# New-Alias Resolve-ShortUri Select-Expand
if($MtpsWebServiceProxy -isnot [Mtps.ContentService]) {
$MtpsWebServiceProxy = New-WebServiceProxy "http://services.msdn.microsoft.com/ContentServices/ContentService.asmx?wsdl" -Namespace Mtps
}
function Get-OnlineHelpContent {
param(
[Parameter(Mandatory=$true,Position=0)]
[String]$Name
,
[Parameter(Mandatory=$false,Position=1)]
[String[]]$Sections= @("Name", "Synopsis", "Syntax", "Description")
)
process {
$uri = Get-Help $Name | Select-Expand relatedLinks.navigationLink.uri -Unique | Get-HttpResponseUri
if(!$uri) { throw "Couldn't find online help URL for $Name" }
$id = [IO.Path]::GetFileNameWithoutExtension( $uri.segments[-1] )
write-verbose "Content Id: $id"
$content = $MtpsWebServiceProxy.GetContent( (New-Object 'Mtps.getContentRequest' -Property @{locale = $PSUICulture; contentIdentifier = $id; requestedDocuments = (New-Object Mtps.requestedDocument -Property @{Selector="Mtps.Failsafe"}) }) )
$global:OnlineHelpContent = $content.primaryDocuments |?{$_.primaryFormat -eq "Mtps.Failsafe"} | Select -Expand Any
$NameNode = $global:OnlineHelpContent.SelectSingleNode("//*[local-name()='div' and @class='topic']/*[local-name()='div' and @class='title']")
$NameNode.SetAttribute("header","NAME")
$global:OnlineHelpContent = $global:OnlineHelpContent.SelectSingleNode("//*[local-name()='div' and @id='mainBody']")
$Synopsis = $global:OnlineHelpContent.SelectSingleNode("*[local-name()='p']")
$Synopsis.SetAttribute("header","SYNOPSIS")
$headers = $OnlineHelpContent.h2 | ForEach-Object { $_.get_InnerText().Trim() }
$content = $OnlineHelpContent.div | ForEach-Object { $_ }
$global:help = @{Name=$NameNode; Synopsis=$Synopsis}
if($headers.Count -ne $content.Count) {
Write-Warning "Unmatched content"
foreach($header in $headers) {
$help.$header = $OnlineHelpContent.SelectNodes( "//*[preceding-sibling::*[1][local-name()='h2' and normalize-space()='$header']]" )
$help.$header.SetAttribute("header",$header.ToUpper())
}
}
else {
for($h=0;$h -lt $headers.Count; $h++){
$help.($headers[$h]) = $content[$h]
$help.($headers[$h]).SetAttribute("header",$headers[$h].ToUpper())
}
}
$help
$content[$Sections] | ForEach-Object {
Write-Output
Write-Output $_.Header
Write-Output
Write-Output ($_.get_InnerText() -replace '^[\\n\\s]*\\n|\\n\\s+$')
}
}
}
Get-OnlineHelpContent $Name | out-null
$help[$Sections] | ForEach-Object {
Write-Host
Write-Host $_.Header -Fore Cyan
Write-Host
Write-Host ($_.get_InnerText() -replace '^[\\n\\s]*\\n|\\n\\s+$')
}
|
PowerShellCorpus/PoshCode/HTML Parse Demo.ps1
|
HTML Parse Demo.ps1
|
$page = Invoke-WebRequest "http://www.apk.se"
$html = $page.parsedHTML
$products = $html.body.getElementsByTagName("TR")
$headers = @()
foreach($product in $products)
{
$colID = 0;
$hRow = $false
$returnObject = New-Object Object
foreach($child in $product.children)
{
if ($child.tagName -eq "TH")
{
$headers += @($child.outerText)
$hRow = $true
}
if ($child.tagName -eq "TD")
{
$returnObject | Add-Member NoteProperty $headers[$colID] $child.outerText
}
$colID++
}
if (-not $hRow) { $returnObject }
}
|
PowerShellCorpus/PoshCode/get-ESXiHostConfigBackup_2.ps1
|
get-ESXiHostConfigBackup_2.ps1
|
<#
.SYNOPSIS
Creates config bundle backup for ESXi hosts. Works where 80 is blocked to ESXi host
Originally script by Alan Renouf (http://www.virtu-al.net/2011/02/23/backing-up-the-esxi-system-image)
Heavily Modified by Jimmy Hester
.DESCRIPTION
Checks for connection to a vCenter or ESXi server
If not connected, connects to the server specified
If already connected, connects to the server listed in $Global:DefaultVIServer
Connects to each vmhost in a vCenter, pulls a backup of its configuration, and saves it to the client machine.
If connected to an ESXi host, it will backup that host.
Once backed up, it will disconnect from the server if the connection was intially created by this script. It will leave pre-existing connections intact.
If run in an environment where access to the ESXi host(s) on port 80 (from the machine running this script) is blocked,
the script will bypass the access failure and download the config bundle directly.
See this VMware Community thread for details: http://communities.vmware.com/thread/419926
.PARAMETER <paramName>
VIServer = The name of the vCenter server or ESXi host to use. If a vCenter server is specified, all the hosts in the vCenter will be backed up
If an ESXi host is specified, only that host will be backed up.
#>
Param (
[string]$VIServer
)
#Check for PowerCLI
If ( (Get-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin VMware.VimAutomation.Core
}
#Change this to a local folder that already exists
$RootFolder = "C:\\admin\\ESXi_Backups\\"
If (($VIServer) -and (-not($VIServer -eq $global:defaultviserver))) {
Connect-VIServer $VIServer -Credential (Get-Credential) | Out-Null
Write-Host ""
Write-Host "Connecting to $VIServer"
Write-Host ""
$Disconnect = $true
}
elseif (!$global:DefaultVIServer) {
Write-Host "Cannot determine which VCenter to use. No backups taken."
Write-Host ""
break
}
else {
$VIServer = $global:DefaultVIServer
Write-Host "Connected to $VIServer"
Write-Host ""
}
$VMhosts = Get-VMHost -Server $VIServer
$Date = Get-Date -f yyyyMMdd_hhmm
Foreach ($VMhost in $VMhosts) {
Write-Host "Backing up state for $VMhost"
$Folder = $RootFolder + "$($VIServer)\\" + $Date
If (-not (test-path $Folder)) {
MD $Folder | Out-Null
}
Get-VMHostFirmware $VMhost -BackupConfiguration -DestinationPath $Folder -ErrorAction SilentlyContinue | Out-Null
#Uncomment next line if the path for $Folder has hyphens
#MV ($RootFolder + "*") $Folder -ErrorAction SilentlyContinue
#This will bypass the port http get failure in environments where port 80 is blocked to the ESXi host.
#This tests to see if the Get-VMHostFirmware cmdlet was able to download the config bundle.
#If not, calls the same https URL as the Get-VMHostFirmware cmdlet
If (-not (test-path $Folder\\configBundle-$vmhost.tgz)){
Invoke-Webrequest https://$vmhost/downloads/configBundle-$vmhost.tgz -outfile $folder\\configBundle-$vmhost-$date.tgz
}
}
If ($Disconnect) {
Write-Host "Disconnecting from $VIServer"
Disconnect-VIServer $VIServer -Confirm:$false | Out-Null
}
Write-Host ""
Write-Host "The config backups for $VIServer are located at:"
Write-Host $Folder
Write-Host ""
|
PowerShellCorpus/PoshCode/PowerWatin 0.5.ps1
|
PowerWatin 0.5.ps1
|
## CHANGE this to point to your WatiN.Core.dll
$WatinPath = Convert-Path (Resolve-Path "$(Split-Path $Profile)\\Libraries\\Watin2\\WatiN.Core.dll")
## Load the assembly
$global:watin = [Reflection.Assembly]::LoadFrom( $WatinPath )
$WFind = [Watin.Core.Find]
## The rest of this is generated ... I've pasted the generation code in a comment at the bottom
Function get-InternetExplorer {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_InternetExplorer() | Where $Where
}
}
Function get-AutoClose {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_AutoClose() | Where $Where
}
}
Function set-AutoClose {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.set_AutoClose() | Where $Where
}
}
Function get-HtmlDialogs {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_HtmlDialogs() | Where $Where
}
}
Function get-HtmlDialogsNoWait {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_HtmlDialogsNoWait() | Where $Where
}
}
Function get-NativeBrowser {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_NativeBrowser() | Where $Where
}
}
Function get-Visible {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_Visible() | Where $Where
}
}
Function set-Visible {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.set_Visible() | Where $Where
}
}
Function get-hWnd {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_hWnd() | Where $Where
}
}
Function get-ProcessID {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_ProcessID() | Where $Where
}
}
Function get-NativeDocument {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_NativeDocument() | Where $Where
}
}
Function get-DialogWatcher {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_DialogWatcher() | Where $Where
}
}
Function get-Html {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_Html() | Where $Where
}
}
Function get-Body {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_Body() | Where $Where
}
}
Function get-Text {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_Text() | Where $Where
}
}
Function get-Uri {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_Uri() | Where $Where
}
}
Function get-Url {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_Url() | Where $Where
}
}
Function get-Title {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_Title() | Where $Where
}
}
Function get-ActiveElement {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_ActiveElement() | Where $Where
}
}
Function get-Frames {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_Frames() | Where $Where
}
}
Function get-DomContainer {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_DomContainer() | Where $Where
}
}
Function set-DomContainer {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.set_DomContainer() | Where $Where
}
}
Function get-Areas {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_Areas() | Where $Where
}
}
Function get-Buttons {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_Buttons() | Where $Where
}
}
Function get-CheckBoxes {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_CheckBoxes() | Where $Where
}
}
Function get-Elements {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_Elements() | Where $Where
}
}
Function get-FileUploads {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_FileUploads() | Where $Where
}
}
Function get-Forms {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_Forms() | Where $Where
}
}
Function get-Labels {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_Labels() | Where $Where
}
}
Function get-Links {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_Links() | Where $Where
}
}
Function get-Paras {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_Paras() | Where $Where
}
}
Function get-RadioButtons {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_RadioButtons() | Where $Where
}
}
Function get-SelectLists {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_SelectLists() | Where $Where
}
}
Function get-Tables {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_Tables() | Where $Where
}
}
Function get-TableBodies {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_TableBodies() | Where $Where
}
}
Function get-TableCells {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_TableCells() | Where $Where
}
}
Function get-TableRows {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_TableRows() | Where $Where
}
}
Function get-TextFields {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_TextFields() | Where $Where
}
}
Function get-Spans {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_Spans() | Where $Where
}
}
Function get-Divs {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_Divs() | Where $Where
}
}
Function get-Images {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_Images() | Where $Where
}
}
Function get-Description {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.get_Description() | Where $Where
}
}
Function set-Description {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(ValueFromPipeline=$true, Position = 0)]
[ScriptBlock]$Where = {$true}
)
process {
$InputObject.set_Description() | Where $Where
}
}
Function Find-Area {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(Position=0, ParameterSetName='Set0')]
[String]$Id
,
[Parameter(Position=0, ParameterSetName='Set1')]
[Regex]$Pattern
,
[Parameter(Position=0, ParameterSetName='Set2')]
[WatiN.Core.Constraints.Constraint]$findBy
,
[Parameter(Position=0, ParameterSetName='Set3')]
[ScriptBlock]$Where
)
process {
if($PSCmdlet.ParameterSetName -eq 'Set0'){ $InputObject.Area( $Id ) }
if($PSCmdlet.ParameterSetName -eq 'Set1'){ $InputObject.Area( $Pattern ) }
if($PSCmdlet.ParameterSetName -eq 'Set2'){ $InputObject.Area( $findBy ) }
if($PSCmdlet.ParameterSetName -eq 'Set3'){ $InputObject.Area( $Where ) }
}
}
Function Find-Button {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(Position=0, ParameterSetName='Set0')]
[String]$Id
,
[Parameter(Position=0, ParameterSetName='Set1')]
[Regex]$Pattern
,
[Parameter(Position=0, ParameterSetName='Set2')]
[ScriptBlock]$Where
,
[Parameter(Position=0, ParameterSetName='Set3')]
[WatiN.Core.Constraints.Constraint]$findBy
)
process {
if($PSCmdlet.ParameterSetName -eq 'Set0'){ $InputObject.Button( $Id ) }
if($PSCmdlet.ParameterSetName -eq 'Set1'){ $InputObject.Button( $Pattern ) }
if($PSCmdlet.ParameterSetName -eq 'Set2'){ $InputObject.Button( $Where ) }
if($PSCmdlet.ParameterSetName -eq 'Set3'){ $InputObject.Button( $findBy ) }
}
}
Function Find-CheckBox {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(Position=0, ParameterSetName='Set0')]
[String]$Id
,
[Parameter(Position=0, ParameterSetName='Set1')]
[Regex]$Pattern
,
[Parameter(Position=0, ParameterSetName='Set2')]
[ScriptBlock]$Where
,
[Parameter(Position=0, ParameterSetName='Set3')]
[WatiN.Core.Constraints.Constraint]$findBy
)
process {
if($PSCmdlet.ParameterSetName -eq 'Set0'){ $InputObject.CheckBox( $Id ) }
if($PSCmdlet.ParameterSetName -eq 'Set1'){ $InputObject.CheckBox( $Pattern ) }
if($PSCmdlet.ParameterSetName -eq 'Set2'){ $InputObject.CheckBox( $Where ) }
if($PSCmdlet.ParameterSetName -eq 'Set3'){ $InputObject.CheckBox( $findBy ) }
}
}
Function Find-Element {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(Position=0, ParameterSetName='Set0')]
[String]$Id
,
[Parameter(Position=0, ParameterSetName='Set1')]
[Regex]$Pattern
,
[Parameter(Position=0, ParameterSetName='Set2')]
[WatiN.Core.Constraints.Constraint]$findBy
,
[Parameter(Position=0, ParameterSetName='Set3')]
[ScriptBlock]$Where
)
process {
if($PSCmdlet.ParameterSetName -eq 'Set0'){ $InputObject.Element( $Id ) }
if($PSCmdlet.ParameterSetName -eq 'Set1'){ $InputObject.Element( $Pattern ) }
if($PSCmdlet.ParameterSetName -eq 'Set2'){ $InputObject.Element( $findBy ) }
if($PSCmdlet.ParameterSetName -eq 'Set3'){ $InputObject.Element( $Where ) }
}
}
Function Find-ElementWithTag {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(Position=0, ParameterSetName='Set0')]
[System.String]$tagName
,
[Parameter(Position=1, ParameterSetName='Set0')]
[WatiN.Core.Constraints.Constraint]$findBy
,
[Parameter(Position=2, ParameterSetName='Set0')]
[System.String[]]$inputTypes
)
process {
if($PSCmdlet.ParameterSetName -eq 'Set0'){ $InputObject.ElementWithTag( $inputTypes
,
$inputTypes
,
$inputTypes ) }
}
}
Function Find-ElementOfType {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(Position=0, ParameterSetName='Set0')]
[String]$Id
,
[Parameter(Position=0, ParameterSetName='Set1')]
[Regex]$Pattern
,
[Parameter(Position=0, ParameterSetName='Set2')]
[WatiN.Core.Constraints.Constraint]$findBy
,
[Parameter(Position=0, ParameterSetName='Set3')]
[]$predicate
)
process {
if($PSCmdlet.ParameterSetName -eq 'Set0'){ $InputObject.ElementOfType( $Id ) }
if($PSCmdlet.ParameterSetName -eq 'Set1'){ $InputObject.ElementOfType( $Pattern ) }
if($PSCmdlet.ParameterSetName -eq 'Set2'){ $InputObject.ElementOfType( $findBy ) }
if($PSCmdlet.ParameterSetName -eq 'Set3'){ $InputObject.ElementOfType( $predicate ) }
}
}
Function Find-ElementsOfType {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
)
process {
if($PSCmdlet.ParameterSetName -eq 'Set0'){ $InputObject.ElementsOfType( ) }
}
}
Function Find-FileUpload {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(Position=0, ParameterSetName='Set0')]
[String]$Id
,
[Parameter(Position=0, ParameterSetName='Set1')]
[Regex]$Pattern
,
[Parameter(Position=0, ParameterSetName='Set2')]
[WatiN.Core.Constraints.Constraint]$findBy
,
[Parameter(Position=0, ParameterSetName='Set3')]
[ScriptBlock]$Where
)
process {
if($PSCmdlet.ParameterSetName -eq 'Set0'){ $InputObject.FileUpload( $Id ) }
if($PSCmdlet.ParameterSetName -eq 'Set1'){ $InputObject.FileUpload( $Pattern ) }
if($PSCmdlet.ParameterSetName -eq 'Set2'){ $InputObject.FileUpload( $findBy ) }
if($PSCmdlet.ParameterSetName -eq 'Set3'){ $InputObject.FileUpload( $Where ) }
}
}
Function Find-Form {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(Position=0, ParameterSetName='Set0')]
[String]$Id
,
[Parameter(Position=0, ParameterSetName='Set1')]
[Regex]$Pattern
,
[Parameter(Position=0, ParameterSetName='Set2')]
[WatiN.Core.Constraints.Constraint]$findBy
,
[Parameter(Position=0, ParameterSetName='Set3')]
[ScriptBlock]$Where
)
process {
if($PSCmdlet.ParameterSetName -eq 'Set0'){ $InputObject.Form( $Id ) }
if($PSCmdlet.ParameterSetName -eq 'Set1'){ $InputObject.Form( $Pattern ) }
if($PSCmdlet.ParameterSetName -eq 'Set2'){ $InputObject.Form( $findBy ) }
if($PSCmdlet.ParameterSetName -eq 'Set3'){ $InputObject.Form( $Where ) }
}
}
Function Find-Label {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(Position=0, ParameterSetName='Set0')]
[String]$Id
,
[Parameter(Position=0, ParameterSetName='Set1')]
[Regex]$Pattern
,
[Parameter(Position=0, ParameterSetName='Set2')]
[WatiN.Core.Constraints.Constraint]$findBy
,
[Parameter(Position=0, ParameterSetName='Set3')]
[ScriptBlock]$Where
)
process {
if($PSCmdlet.ParameterSetName -eq 'Set0'){ $InputObject.Label( $Id ) }
if($PSCmdlet.ParameterSetName -eq 'Set1'){ $InputObject.Label( $Pattern ) }
if($PSCmdlet.ParameterSetName -eq 'Set2'){ $InputObject.Label( $findBy ) }
if($PSCmdlet.ParameterSetName -eq 'Set3'){ $InputObject.Label( $Where ) }
}
}
Function Find-Link {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(Position=0, ParameterSetName='Set0')]
[String]$Id
,
[Parameter(Position=0, ParameterSetName='Set1')]
[Regex]$Pattern
,
[Parameter(Position=0, ParameterSetName='Set2')]
[WatiN.Core.Constraints.Constraint]$findBy
,
[Parameter(Position=0, ParameterSetName='Set3')]
[ScriptBlock]$Where
)
process {
if($PSCmdlet.ParameterSetName -eq 'Set0'){ $InputObject.Link( $Id ) }
if($PSCmdlet.ParameterSetName -eq 'Set1'){ $InputObject.Link( $Pattern ) }
if($PSCmdlet.ParameterSetName -eq 'Set2'){ $InputObject.Link( $findBy ) }
if($PSCmdlet.ParameterSetName -eq 'Set3'){ $InputObject.Link( $Where ) }
}
}
Function Find-Para {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(Position=0, ParameterSetName='Set0')]
[String]$Id
,
[Parameter(Position=0, ParameterSetName='Set1')]
[Regex]$Pattern
,
[Parameter(Position=0, ParameterSetName='Set2')]
[WatiN.Core.Constraints.Constraint]$findBy
,
[Parameter(Position=0, ParameterSetName='Set3')]
[ScriptBlock]$Where
)
process {
if($PSCmdlet.ParameterSetName -eq 'Set0'){ $InputObject.Para( $Id ) }
if($PSCmdlet.ParameterSetName -eq 'Set1'){ $InputObject.Para( $Pattern ) }
if($PSCmdlet.ParameterSetName -eq 'Set2'){ $InputObject.Para( $findBy ) }
if($PSCmdlet.ParameterSetName -eq 'Set3'){ $InputObject.Para( $Where ) }
}
}
Function Find-RadioButton {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(Position=0, ParameterSetName='Set0')]
[String]$Id
,
[Parameter(Position=0, ParameterSetName='Set1')]
[Regex]$Pattern
,
[Parameter(Position=0, ParameterSetName='Set2')]
[WatiN.Core.Constraints.Constraint]$findBy
,
[Parameter(Position=0, ParameterSetName='Set3')]
[ScriptBlock]$Where
)
process {
if($PSCmdlet.ParameterSetName -eq 'Set0'){ $InputObject.RadioButton( $Id ) }
if($PSCmdlet.ParameterSetName -eq 'Set1'){ $InputObject.RadioButton( $Pattern ) }
if($PSCmdlet.ParameterSetName -eq 'Set2'){ $InputObject.RadioButton( $findBy ) }
if($PSCmdlet.ParameterSetName -eq 'Set3'){ $InputObject.RadioButton( $Where ) }
}
}
Function Find-SelectList {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(Position=0, ParameterSetName='Set0')]
[String]$Id
,
[Parameter(Position=0, ParameterSetName='Set1')]
[Regex]$Pattern
,
[Parameter(Position=0, ParameterSetName='Set2')]
[WatiN.Core.Constraints.Constraint]$findBy
,
[Parameter(Position=0, ParameterSetName='Set3')]
[ScriptBlock]$Where
)
process {
if($PSCmdlet.ParameterSetName -eq 'Set0'){ $InputObject.SelectList( $Id ) }
if($PSCmdlet.ParameterSetName -eq 'Set1'){ $InputObject.SelectList( $Pattern ) }
if($PSCmdlet.ParameterSetName -eq 'Set2'){ $InputObject.SelectList( $findBy ) }
if($PSCmdlet.ParameterSetName -eq 'Set3'){ $InputObject.SelectList( $Where ) }
}
}
Function Find-Table {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(Position=0, ParameterSetName='Set0')]
[String]$Id
,
[Parameter(Position=0, ParameterSetName='Set1')]
[Regex]$Pattern
,
[Parameter(Position=0, ParameterSetName='Set2')]
[WatiN.Core.Constraints.Constraint]$findBy
,
[Parameter(Position=0, ParameterSetName='Set3')]
[ScriptBlock]$Where
)
process {
if($PSCmdlet.ParameterSetName -eq 'Set0'){ $InputObject.Table( $Id ) }
if($PSCmdlet.ParameterSetName -eq 'Set1'){ $InputObject.Table( $Pattern ) }
if($PSCmdlet.ParameterSetName -eq 'Set2'){ $InputObject.Table( $findBy ) }
if($PSCmdlet.ParameterSetName -eq 'Set3'){ $InputObject.Table( $Where ) }
}
}
Function Find-TableBody {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(Position=0, ParameterSetName='Set0')]
[String]$Id
,
[Parameter(Position=0, ParameterSetName='Set1')]
[Regex]$Pattern
,
[Parameter(Position=0, ParameterSetName='Set2')]
[WatiN.Core.Constraints.Constraint]$findBy
,
[Parameter(Position=0, ParameterSetName='Set3')]
[ScriptBlock]$Where
)
process {
if($PSCmdlet.ParameterSetName -eq 'Set0'){ $InputObject.TableBody( $Id ) }
if($PSCmdlet.ParameterSetName -eq 'Set1'){ $InputObject.TableBody( $Pattern ) }
if($PSCmdlet.ParameterSetName -eq 'Set2'){ $InputObject.TableBody( $findBy ) }
if($PSCmdlet.ParameterSetName -eq 'Set3'){ $InputObject.TableBody( $Where ) }
}
}
Function Find-TableCell {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(Position=0, ParameterSetName='Set0', Mandatory = $true)]
[Parameter(Position=0, ParameterSetName='Set1', Mandatory = $true)]
[String]$Id
,
[Parameter(Position=1, ParameterSetName='Set1', Mandatory = $true)]
[Parameter(Position=1, ParameterSetName='Set2', Mandatory = $true)]
[System.Int32]$index
,
[Parameter(Position=0, ParameterSetName='Set2', Mandatory = $true)]
[Parameter(Position=0, ParameterSetName='Set3', Mandatory = $true)]
[Regex]$Pattern
,
[Parameter(Position=0, ParameterSetName='Set4')]
[WatiN.Core.Constraints.Constraint]$findBy
,
[Parameter(Position=0, ParameterSetName='Set5')]
[ScriptBlock]$Where
)
process {
if($PSCmdlet.ParameterSetName -eq 'Set0'){ $InputObject.TableCell( $Id ) }
if($PSCmdlet.ParameterSetName -eq 'Set1'){ $InputObject.TableCell( $Id, $index ) }
if($PSCmdlet.ParameterSetName -eq 'Set2'){ $InputObject.TableCell( $Pattern, $index ) }
if($PSCmdlet.ParameterSetName -eq 'Set3'){ $InputObject.TableCell( $Pattern ) }
if($PSCmdlet.ParameterSetName -eq 'Set4'){ $InputObject.TableCell( $findBy ) }
if($PSCmdlet.ParameterSetName -eq 'Set5'){ $InputObject.TableCell( $Where ) }
}
}
Function Find-TableRow {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(Position=0, ParameterSetName='Set0')]
[String]$Id
,
[Parameter(Position=0, ParameterSetName='Set1')]
[Regex]$Pattern
,
[Parameter(Position=0, ParameterSetName='Set2')]
[WatiN.Core.Constraints.Constraint]$findBy
,
[Parameter(Position=0, ParameterSetName='Set3')]
[ScriptBlock]$Where
)
process {
if($PSCmdlet.ParameterSetName -eq 'Set0'){ $InputObject.TableRow( $Id ) }
if($PSCmdlet.ParameterSetName -eq 'Set1'){ $InputObject.TableRow( $Pattern ) }
if($PSCmdlet.ParameterSetName -eq 'Set2'){ $InputObject.TableRow( $findBy ) }
if($PSCmdlet.ParameterSetName -eq 'Set3'){ $InputObject.TableRow( $Where ) }
}
}
Function Find-TextField {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(Position=0, ParameterSetName='Set0')]
[String]$Id
,
[Parameter(Position=0, ParameterSetName='Set1')]
[Regex]$Pattern
,
[Parameter(Position=0, ParameterSetName='Set2')]
[WatiN.Core.Constraints.Constraint]$findBy
,
[Parameter(Position=0, ParameterSetName='Set3')]
[ScriptBlock]$Where
)
process {
if($PSCmdlet.ParameterSetName -eq 'Set0'){ $InputObject.TextField( $Id ) }
if($PSCmdlet.ParameterSetName -eq 'Set1'){ $InputObject.TextField( $Pattern ) }
if($PSCmdlet.ParameterSetName -eq 'Set2'){ $InputObject.TextField( $findBy ) }
if($PSCmdlet.ParameterSetName -eq 'Set3'){ $InputObject.TextField( $Where ) }
}
}
Function Find-Span {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(Position=0, ParameterSetName='Set0')]
[String]$Id
,
[Parameter(Position=0, ParameterSetName='Set1')]
[Regex]$Pattern
,
[Parameter(Position=0, ParameterSetName='Set2')]
[WatiN.Core.Constraints.Constraint]$findBy
,
[Parameter(Position=0, ParameterSetName='Set3')]
[ScriptBlock]$Where
)
process {
if($PSCmdlet.ParameterSetName -eq 'Set0'){ $InputObject.Span( $Id ) }
if($PSCmdlet.ParameterSetName -eq 'Set1'){ $InputObject.Span( $Pattern ) }
if($PSCmdlet.ParameterSetName -eq 'Set2'){ $InputObject.Span( $findBy ) }
if($PSCmdlet.ParameterSetName -eq 'Set3'){ $InputObject.Span( $Where ) }
}
}
Function Find-Div {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(Position=0, ParameterSetName='Set0')]
[String]$Id
,
[Parameter(Position=0, ParameterSetName='Set1')]
[Regex]$Pattern
,
[Parameter(Position=0, ParameterSetName='Set2')]
[WatiN.Core.Constraints.Constraint]$findBy
,
[Parameter(Position=0, ParameterSetName='Set3')]
[ScriptBlock]$Where
)
process {
if($PSCmdlet.ParameterSetName -eq 'Set0'){ $InputObject.Div( $Id ) }
if($PSCmdlet.ParameterSetName -eq 'Set1'){ $InputObject.Div( $Pattern ) }
if($PSCmdlet.ParameterSetName -eq 'Set2'){ $InputObject.Div( $findBy ) }
if($PSCmdlet.ParameterSetName -eq 'Set3'){ $InputObject.Div( $Where ) }
}
}
Function Find-Image {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(Position=0, ParameterSetName='Set0')]
[String]$Id
,
[Parameter(Position=0, ParameterSetName='Set1')]
[Regex]$Pattern
,
[Parameter(Position=0, ParameterSetName='Set2')]
[WatiN.Core.Constraints.Constraint]$findBy
,
[Parameter(Position=0, ParameterSetName='Set3')]
[ScriptBlock]$Where
)
process {
if($PSCmdlet.ParameterSetName -eq 'Set0'){ $InputObject.Image( $Id ) }
if($PSCmdlet.ParameterSetName -eq 'Set1'){ $InputObject.Image( $Pattern ) }
if($PSCmdlet.ParameterSetName -eq 'Set2'){ $InputObject.Image( $findBy ) }
if($PSCmdlet.ParameterSetName -eq 'Set3'){ $InputObject.Image( $Where ) }
}
}
Function New-WatinIE {
PARAM(
[string]$URL = "http://www.PoshCode.org"
,
[switch]$Passthru
)
## Create an initial window (I'm creating IE, but WatiN handles Firefox too)
$global:WatinIE = new-object WatiN.Core.IE $URL
if($Passthru) { $global:WatinIE }
}
Function Get-WatinIE {
PARAM(
[string]$URL = "http://www.PoshCode.org"
,
[switch]$Passthru
)
## Find an existing window (I'm using IE, but WatiN handles Firefox too)
$global:WatinIE = [WatiN.Core.IE]::InternetExplorers()[0]
if($Passthru) { $global:WatinIE }
Set-WatinUrl $url
}
function Set-WatinUrl {
Param($url)
$global:WatinIE.Goto( $url )
}
function Send-Text {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[Parameter(Position=0)]
[string]$text
,
[switch]$passthru
,
[switch]$append
)
process {
if($append) {
$InputObject.AppendText( $text )
} else {
$InputObject.TypeText( $text )
}
if($Passthru){$InputObject}
}
}
function Send-Click {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[switch]$passthru
)
process {
$InputObject.Click()
}
}
function Select-Element {
param(
[Parameter(ValueFromPipeline=$true)]$InputObject = $global:WatinIE
,
[switch]$passthru
)
process {
$InputObject.Select()
}
}
###################################################################################################
## This is the code to generate the functions above... Note at the end it puts it on the clipboard.
###################################################################################################
## $methods = [WatiN.Core.IE].GetMethods( "Public, Instance, InvokeMethod" ) | Group Name
##
## $properties = $methods | where { $_.Count -eq 1 -and $_.Name -match "_" }
## $getproperties = $properties | %{if($_.Name -match "get_"){ $_.Group }} | Group { $_.Name -replace "get_" } | sort Name
##
## $lessmethods = $methods | where { $_.Name -notmatch "_" }
##
## $findMethods = $lessmethods | Where {
## $type = @($_.Group)[0].ReturnType
## $type.IsSubclassOf( ([WatiN.Core.Element]) ) -or
## $type.Equals( ([WatiN.Core.Element]) ) -or
## ($type.IsGenericType -and $type.GetGenericArguments()[0].IsSubclassOf( ([WatiN.Core.Element]) ))
## } | sort Name
##
## $lessmethods = $lessmethods | Where { $findMethods -notcontains $_ }
##
## $newline = "`n`t`t"
##
## $function = New-Object System.Text.StringBuilder
##
## ## All of this bit indented here is just to line up the properties with the methods
## $matchedProperties = @($getproperties | ? { $_.Name -eq "TableBodies" })
## $matchedFindMethods = @($findMethods | ? { $_.Name -eq "TableBody" })
##
## foreach($f in $findMethods) {
## foreach($p in $getproperties) {
## if($p.Name -match "^$($f.Name).{1,3}$") {
## $matchedProperties += $p
## $matchedFindMethods += $f
## }
## }
## }
##
## $lessproperties = $properties | Where { @($matchedProperties | %{ $_.Group } | Select -Expand Name) -notcontains $_.Name }
## $lessfindMethods = $findMethods | Where { @($matchedFindMethods | %{ $_.Group } | Select -Expand Name) -notcontains $_.Name }
##
## foreach($property in $lessproperties | %{ $_.Group }) {
## $name = $property.Name -replace "^get_","Get-" -replace "^set_","Set-"
##
## $null = $function.Append(@"
##
## Function $name {
## param(
## [Parameter(ValueFromPipeline=`$true)]`$InputObject = `$global:WatinIE
## ,
## [Parameter(ValueFromPipeline=`$true, Position = 0)]
## [ScriptBlock]`$Where = {`$true}
## )
## process {
## `$InputObject.$($property.Name)() | Where `$Where
## }
## }
##
## "@)
## }
##
##
##
## for($i = 0; $i -lt $matchedProperties.Length; $i++) {
##
## $Property = $MatchedProperties[$i]
## $Method = $MatchedFindMethods[$i]
##
## foreach($property in $properties | %{ $_.Group }) {
## $name = $property.Name -replace "_","-"
##
## $null = $function.Append(@"
##
## Function $name {
## param(
## [Parameter(ValueFromPipeline=`$true)]`$InputObject = `$global:WatinIE
## ,
## [Parameter(ValueFromPipeline=`$true, Position = 0)]
## [ScriptBlock]`$Where = {`$true}
## )
## process {
## `$InputObject.$($property.Name)() | Where `$Where
## }
## }
##
## "@)
## }
##
## foreach($method in $findMethods) {
## $name = $method.Name
## $ParameterSet = 0
## $Parameters = "[Parameter(ValueFromPipeline=`$true)]`$InputObject = `$global:WatinIE"
## $CodeBlock = ""
## foreach($m in $method.Group) {
## $Position = 0;
## $SetName = "Set$ParameterSet"
## $ParameterSet++
## $params = $m.GetParameters() | % {
## $TypeName = $_.ParameterType.FullName
## $ParamName = $_.Name
## if($TypeName -match "System.Predicate") { $TypeName = "ScriptBlock"; $ParamName = "Where" }
## if($TypeName -match "System.Text.RegularExpressions.Regex" -and $ParamName -eq "elementId") { $TypeName = "Regex"; $ParamName = "Pattern" }
## if($TypeName -match "System.String" -and $ParamName -eq "elementId") { $TypeName = "String"; $ParamName = "Id" }
## "[Parameter(Position=$($Position; $Position++), ParameterSetName='$SetName')]${newline}[$TypeName]`$$ParamName"
## }
## if(@($m.GetParameters()).Length) {
## $Parameters = @(@($Parameters)+@($params)) -join "$newline,$newline"
## }
## $block = $m.GetParameters() | % { "`$$ParamName" }
## $CodeBlock += "${newline}if(`$PSCmdlet.ParameterSetName -eq '$SetName'){ `$InputObject.$Name( $(@($block) -join "$newline,$newline") ) }"
## }
## $null = $function.Append(@"
##
## Function Find-$name {
## param(
## $Parameters
## )
## process {
## $CodeBlock
## }
## }
##
## "@)
## }
##
## $function.ToString() | clip
##
|
PowerShellCorpus/PoshCode/TruncatePath_3.ps1
|
TruncatePath_3.ps1
|
###
# TruncatePath
# Version 1.0.6 (05 Nov 2008)
# Description: Replaces long provider paths in the prompt with ellipses
# Notes: Place in your profile
#
# By Mike Hays, http://www.mike-hays.net
###
$maxPathLength = 40
$showFullPath = $false
Function Prompt
{
$currentPath = (Get-Location).Path
if ( ($currentPath.Length -gt $maxPathLength) -and ($showFullPath -ne $true) `
-and (($currentPath.Split("\\")).Count -gt 3) )
{
$currentPathSplit = $currentPath.Split("\\")
$truncatedPath = $currentPathSplit[0] + "\\" + $currentPathSplit[1] + "\\" `
+ "..." + "\\" + $currentPathSplit[$currentPathSplit.Length - 1]
if ($truncatedPath.Length -lt $currentPath.Length)
{
$displayPath = $truncatedPath
}
else
{
$displayPath = get-location
}
}
else
{
$displayPath = get-location
}
Write-Host ("PS ") -NoNewLine -ForegroundColor DarkYellow ; Write-Host ("" + `
$displayPath + ">") -NoNewLine
return " "
}
|
PowerShellCorpus/PoshCode/Get-SqlWmi_1.ps1
|
Get-SqlWmi_1.ps1
|
try {add-type -AssemblyName "Microsoft.SqlServer.SqlWmiManagement, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop}
catch {add-type -AssemblyName "Microsoft.SqlServer.SqlWmiManagement"}
#######################
<#
.SYNOPSIS
Gets SQL Server WMI information.
.DESCRIPTION
The Get-SqlWmi function gets port, instance and service account wmi information for all SQL instances on a computer.
.EXAMPLE
Get-SqlWmi "Z002"
This command gets information for computername Z002.
.NOTES
Version History
v1.0 - Chad Miller - Initial release
v1.1 - Chad Miller - Fixed instance parsing issue with pathname
#>
function Get-SqlWmi
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullorEmpty()]
[string[]]$ComputerName
)
#Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer only works on SQL 2005 and higher. If we fail to gather info at least output
#null values and computername for 2000 servers in catch block
BEGIN {}
PROCESS {
foreach ($computer in $computername) {
try {
$wmi = new-object "Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer" $Computer -ErrorAction 'Stop'
$ht = @{}
$wmi.Services| where {$_.Type -eq 'SqlServer'} | foreach {$instance = $_.PathName -replace '[^-].+\\s{1}-s',""; $ht.Add($instance,$_.ServiceAccount)}
$wmi.ServerInstances | foreach {
new-object psobject -property @{
ComputerName=$Computer;
Port=$_.ServerProtocols["Tcp"].IPAddresses["IPAll"].IPAddressProperties["TcpPort"].Value;
AccountName=$ht[$_.Name];
Instance=$_.Name }
}
}
catch {
#SQL Server 2000 Does not support the WMI.ManagedComputer class. Try and use SQL-DMO
try {
$dmoServer = New-Object -comobject "SQLDMO.SQLServer"
$dmoServer.loginsecure = $true
$instances = $dmoServer.ListInstalledInstances($computer) | foreach {($_) }
$dmoServer = $null
#Clustered server will list server1\\instance1 and server2\\instance2
#Filter so just server1 is listed
$instances | where { $_ -like "$computer*"} |
foreach {
$dmoServer = New-Object -comobject "SQLDMO.SQLServer"
$dmoServer.loginsecure = $true
$dmoServer.connect($_)
new-object psobject -property @{
ComputerName=$Computer;
Port=$dmoServer.registry.tcpport;
AccountName=$dmoServer.StartupAccount;
Instance = $dmoServer.ServiceName -replace 'MSSQL\\$',''
}
$dmoServer.close()
$dmoServer = $null
}
}
catch {
new-object psobject -property @{ComputerName=$Computer;Port=$null;AccountName=$null;Instance=$null}
}
}
}
}
END {}
} #Get-SqlWmi
|
PowerShellCorpus/PoshCode/Get-GrowthRate_4.ps1
|
Get-GrowthRate_4.ps1
|
function Get-GrowthRate {
param( $Start, $End, $Period )
@@ $rate = [math]::Abs( [math]::Pow( ( $End / $Start ),( 1 / $Period - 1 ) ) - 1 )
"{0:P}" -f $rate
}
|
PowerShellCorpus/PoshCode/Get-Field.ps1
|
Get-Field.ps1
|
function Get-Field{
[CmdletBinding()]
param (
[Parameter(Position=0,Mandatory=$true)]
$InputObject
)
$type = $InputObject.gettype()
$publicNonPublic = [Reflection.BindingFlags]::Public -bor [Reflection.BindingFlags]::NonPublic
$instance = $publicNonPublic -bor [Reflection.BindingFlags]::Instance
$getField = $instance -bor [Reflection.BindingFlags]::GetField
$fields = $type.GetFields($instance)
$result = @{}
$fields | Foreach-Object { $result[$_.Name] = $type.InvokeMember($_.Name, $getField, $null, $InputObject, $null) }
$result
}
##Example:
##$context = (Get-Field $ExecutionContext)._context
##$context
##Get-Field $context
##$sessionState = (Get-Field $context)._enginesessionstate
##$sessionState
##$moduleTable = (Get-Field $sessionState)._moduleTable
##$moduleTable
|
PowerShellCorpus/PoshCode/ISE-FileName.ps1
|
ISE-FileName.ps1
|
#requires -version 2.0
## ISE-FileName module v 1.0
##############################################################################################################
## Provides File and Path cmdlets for working with ISE
## Copy-ISEFullPath - Copy the full path of the current file to the clipboard
## Copy-ISEPath - Copy the path of the current file to the clipboard
## Copy-ISEFileName - Copy the filename of the current file to the clipboard
##
## Usage within ISE or Microsoft.PowershellISE_profile.ps1:
## Import-Module ISE-FileName.psm1
##
## Code found in IseCream (http://psisecream.codeplex.com/) that was authored by Doug Finke
## under the name Copy-ISEFileName.ps1
##
##############################################################################################################
## History:
## 1.0 - Initial release (Doug Finke)
##############################################################################################################
## Get-ISEFullPath
##############################################################################################################
## Function to get the Full Path for use by the other functions
## This code was originaly designed by Doug Finke
##############################################################################################################
Function Get-ISEFullPath {
$psISE.CurrentFile.FullPath
}
## Copy-ISEFullPath
##############################################################################################################
## Copy the full path of the current file to the clipboard
## This code was originaly designed by Doug Finke
##############################################################################################################
Function Copy-ISEFullPath {
(Get-ISEFullPath) | Copy-ToClipBoard
}
## Copy-ISEPath
##############################################################################################################
## Copy the path of the current file to the clipboard
## This code was originaly designed by Doug Finke
##############################################################################################################
Function Copy-ISEPath {
Split-Path (Get-ISEFullPath) | Copy-ToClipBoard
}
## Copy-ISEFileName
##############################################################################################################
## Copy the filename of the current file to the clipboard
## This code was originaly designed by Doug Finke
##############################################################################################################
Function Copy-ISEFileName {
Split-Path -Leaf (Get-ISEFullPath) | Copy-ToClipBoard
}
## Copy-ToClipboard
##############################################################################################################
## Filter to copy the code to the clipboard
## This code was originaly designed by Doug Finke
##############################################################################################################
Filter Copy-ToClipBoard {
$dataObject = New-Object Windows.DataObject
$dataObject.SetText($_, [Windows.TextDataFormat]"UnicodeText")
[Windows.Clipboard]::SetDataObject($dataObject, $true)
}
##############################################################################################################
## Inserts a submenu File/Path Names to ISE's Custom Menu
## Inserts command Copy FullPath to submenu File/Path Names
## Inserts command Copy Path to submenu File/Path Names
## Inserts command Copy Filename to submenu File/Path Names
##############################################################################################################
if (-not( $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus | where { $_.DisplayName -eq "File/Path Names" } ) )
{
$filenameMenu = $psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("_File/Path Names",$null,$null)
$null = $filenameMenu.Submenus.Add("Copy FullPath", {Copy-ISEFullPath}, "Ctrl+Alt+A")
$null = $filenameMenu.Submenus.Add("Copy Path", {Copy-ISEPath}, "Ctrl+Alt+P")
$null = $filenameMenu.Submenus.Add("Copy Filename", {Copy-ISEFileName}, "Ctrl+Alt+F")
}
# If you are using IsePack (http://code.msdn.microsoft.com/PowerShellPack) and IseCream (http://psisecream.codeplex.com/),
# you can use this code to add your menu items. The added benefits are that you can specify the order of the menu items and
# if the shortcut already exists it will add the menu item without the shortcut instead of failing as the default does.
#Add-IseMenu -Name "File/Path Names" @{
# "Copy FullPath" = {Copy-ISEFullPath} | Add-Member NoteProperty order 1 -PassThru | Add-Member NoteProperty ShortcutKey "Ctrl+Alt+A" -PassThru
# "Copy Path" = {Copy-ISEPath} | Add-Member NoteProperty order 2 -PassThru | Add-Member NoteProperty ShortcutKey "Ctrl+Alt+P" -PassThru
# "Copy Filename" = {Copy-ISEFileName} | Add-Member NoteProperty order 3 -PassThru | Add-Member NoteProperty ShortcutKey "Ctrl+Alt+F" -PassThru
#}
|
PowerShellCorpus/PoshCode/Set-SendAs.ps1
|
Set-SendAs.ps1
|
# NAME
# Set-SendAs
#
# SYNOPSIS
# Use the Set-SendAs cmdlet to grant or Remove SendAs permissions on a mailbox
#
# SYNTAX
# Set-SendAs -Identity <MailboxIdParameter> -SendAs <MailboxIdParameter> -ou <OrganizationalUnit> [-Remove <SwitchParameter> [-Confirm [<SwitchParameter>]]] [-DomainController <Fqdn>]
Function EOSet-SendAs ($Identity, $SendAs, $ou, [Switch]$Remove, $DomainController = "dc01", [switch]$Confirm = $true)
{
PROCESS
{
if(!$ou) {throw 'Required paramater $ou is missing.'}
# Use pipeline input when parameter is not specified
if($_)
{
if($_.Identity -and !$Identity) {$Identity = $_.Identity}
if($_.SendAs -and !$SendAs) {$SendAs = $_.SendAs}
if($_.ou -and !$ou) {$ou = $_.ou}
if($_.remove -and !$remove) {$remove = $_.remove}
}
# Verify admin and user are both available
$IdentityMbx = $Identity
$SendAsMbx = $SendAs
if([string]$Identity.GetType() -ne "Microsoft.Exchange.Data.Directory.Management.Mailbox" -and !($IdentityMbx = Get-Mailbox $Identity -DomainController $DomainController -OrganizationalUnit $ou -ErrorAction SilentlyContinue))
{throw "The operation could not be performed becaues the object '$Identity' could not be found in the organization '$ou'"}
if([string]$SendAs.GetType() -ne "Microsoft.Exchange.Data.Directory.Management.Mailbox" -and !($SendAsMbx = Get-Mailbox $SendAs -DomainController $DomainController -OrganizationalUnit $ou -ErrorAction SilentlyContinue))
{throw "The operation could not be performed becaues the object '$SendAs' could not be found in the organization '$ou'"}
# Make changes
If(!$Remove) {$null = Add-ADPermission -Identity $IdentityMbx.DistinguishedName -User $SendAsMbx.DistinguishedName -ExtendedRights Send-As}
Else {$null = Remove-ADPermission -Identity $IdentityMbx.DistinguishedName -User $SendAsMbx.DistinguishedName -ExtendedRights Send-As -Confirm:$Confirm}
}
}
|
PowerShellCorpus/PoshCode/update-powerpackcolumns.ps1
|
update-powerpackcolumns.ps1
|
###################################################################
# Update Columns in PowerPacks
###################################################################
# (c) Dmitry Sotnikov
# http://dmitrysotnikov.wordpress.com
###################################################################
# This script is designed to work around a PowerPack export
# issue in PowerGUI 1.5.1 (fixed in subsequent releases
# The script goes though the PowerGUI configuration
# and PowerPack file and updates the file with column
# selection info from PowerGUI config
###################################################################
###################################################################
# Make sure you set these paths to the old and new pack accordingly
###################################################################
$powergui_cfg_path = "$($env:APPDATA)\\Quest Software\\PowerGUI\\quest.powergui.xml"
$powerpack_path = 'c:\\scripts\\aliases.powerpack'
$updated_powerpack_path = 'C:\\scripts\\new.powerpack'
##################################################
# First extract column data from PowerGUI config
##################################################
# load local PowerGUI configuration
$pg = [xml] (gc $powergui_cfg_path)
# locate column-by-type storage
$uiviews = $null
foreach ($c in $pg.configuration.items.container) {
if ($c.Name -eq 'UI View') { $uiviews = $c; break; }
}
# hash-table to store columns by type
$columns = @{}
if ( $uiviews -ne $null ) {
# for each of these types, create a hash table, storing the column names
foreach ($c in $uiviews.items.container.items.container) {
"Type: $($c.Type)"
$properties = @()
if ( $c.items.container -ne $null ) {
foreach ($col in $c.items.container) {$col.Name; $properties += $col.Name }
if ($properties.Length -gt 0) { $columns[$c.Type] = $properties }
} elseif ( $c.items.item -ne $null ) {
foreach ($col in $c.items.item) {$col.Name; $properties += $col.Name }
if ($properties.Length -gt 0) { $columns[$c.Type] = $properties }
}
}
" === Hash Table === "
$columns
}
##################################################################
# Now go through the PowerPack and add column data when required
##################################################################
$pp = [xml] (gc $powerpack_path)
# This function adds column data to a tree node or link
function AssignTypes {
param($segment)
if ( $segment -ne $null ) {
$segment.returntype
if ($segment.items.container.name -notlike "properties*") {
# no properties assigned
" --- No columns assigned"
if ( ($segment.returntype -ne $null) -and $columns.ContainsKey($segment.returntype) ) {
# construct the columns section
" --- Found columns by type"
$cont = $pp.CreateElement("container")
$cont.SetAttribute("id", [Guid]::NewGuid().ToString())
$cont.SetAttribute("name", "properties_a807f902-4b43-4b22-86d8-724abc4c3d4a")
$segment["items"].AppendChild($cont)
$subitems = $pp.CreateElement("items")
$cont.AppendChild($subitems)
foreach ($c in $columns[$segment.returntype]) {
$item = $pp.CreateElement("item")
$item.SetAttribute("id", [Guid]::NewGuid().ToString())
$item.SetAttribute("name", $c)
$subitems.AppendChild($item)
}
}
} else {
" --- Columns already assigned"
}
}
}
# This function recurses through the navigation tree
function IterateTree {
param($segment)
if (($segment.Type -like 'Script*') -or ($segment.Type -like 'CmdLet*')) {
# found a node, check whether it has columns assigned
AssignTypes $segment
}
if ($segment.items.container -ne $null) {
$segment.items.container | ForEach-Object { IterateTree $_ }
}
}
" === Tree === "
IterateTree $pp.configuration.items.container[0]
" === Links === "
$pp.configuration.items.container[1].items.container |
where { $_.id -eq '481eccc0-43f8-47b8-9660-f100dff38e14' } | ForEach-Object {
# Do both container and item because of possible format variation
$_.items.container | ForEach-Object { AssignTypes $_ }
$_.items.item | ForEach-Object { AssignTypes $_ }
}
# Save updated file
$pp.Save($updated_powerpack_path)
|
PowerShellCorpus/PoshCode/Download DefragTools .ps1
|
Download DefragTools .ps1
|
#requires -version 2.0
<#
.Synopsis
Downloads Channel 9 Defrag Tool Episode Video
.DESCRIPTION
Downloads Channel 9 Defrag Tool Episode Video in the format selected and to a given path.
.EXAMPLE
Downloads all shows in WMV format to the default Downloads Folder for the user.
Get-DefragToolsShow -All -VideoType wmv
.EXAMPLE
Downloads only the last show of the series in MP4 format
Get-DefragToolsShow -Last -VideoType MP4
.NOTES
Author: Carlos Perez carlos_perez[at]darkoperator.com
#>
function Get-DefragToolsShow
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$false,
Position=0)]
$Path = "$($env:USERPROFILE)\\downloads",
[Parameter(Mandatory=$false,
ParameterSetName="All")]
[switch]$All = $true,
[Parameter(Mandatory=$false,
ParameterSetName="Last")]
[switch]$Last = $true,
[Parameter(Mandatory=$false)]
[ValidateSet("MP4HD","MP4","WMVHD","WMV")]
[string]$VideoType = "MP4HD"
)
Begin
{
$WebClient = New-Object System.Net.WebClient
$Global:downloadComplete = $false
$eventDataComplete = Register-ObjectEvent $WebClient DownloadFileCompleted `
-SourceIdentifier WebClient.DownloadFileComplete `
-Action {$Global:downloadComplete = $true}
$eventDataProgress = Register-ObjectEvent $WebClient DownloadProgressChanged `
-SourceIdentifier WebClient.DownloadProgressChanged `
-Action { $Global:DPCEventArgs = $EventArgs }
# Lets change to the proper path
Set-Location (Resolve-Path $Path).Path
}
Process
{
switch ($PsCmdlet.ParameterSetName)
{
"All"{$all = $true}
"Last"{$all = $false}
}
switch ($VideoType)
{
"MP4HD" {$feedURL = "http://channel9.msdn.com/Shows/Defrag-Tools/feed/mp4high"}
"MP4" {$feedURL = "http://channel9.msdn.com/Shows/Defrag-Tools/feed/mp4"}
"WMVHD" {$feedURL = "http://channel9.msdn.com/Shows/Defrag-Tools/feed/wmvhigh"}
"WMV" {$feedURL = "http://channel9.msdn.com/Shows/Defrag-Tools/feed/wmv"}
}
$feed = [xml]$WebClient.DownloadString($feedURL)
if ($All)
{
foreach ($episode in $feed.rss.channel.Item)
{
# Create a proper URI for parsing
$episodeURL = [System.Uri]$episode.enclosure.url
# Get the episode file name
$file = $episodeURL.Segments[-1]
#Check if the file exists if it does skip it
if (!(Test-Path $file))
{
Write-Progress -Activity 'Downloading file' -Status $file
$WebClient.DownloadFileAsync($episodeURL,$file)
while (!($Global:downloadComplete))
{
$pc = $Global:DPCEventArgs.ProgressPercentage
if ($pc -ne $null)
{
Write-Progress -Activity 'Downloading file' -Status $file -PercentComplete $pc
}
}
$Global:downloadComplete = $false
}
}
}
else
{
$episodeURL = [System.Uri]$feed.rss.channel.Item[0].enclosure.url
# Get the episode file name
$file = $episodeURL.Segments[-1]
#Check if the file exists if it does skip it
if (!(Test-Path $file))
{
Write-Progress -Activity 'Downloading file' -Status $file
$WebClient.DownloadFileAsync($episodeURL,$file)
# Lets wait for it to finish
while (!($Global:downloadComplete))
{
$pc = $Global:DPCEventArgs.ProgressPercentage
if ($pc -ne $null)
{
Write-Progress -Activity 'Downloading file' -Status $file -PercentComplete $pc
}
}
}
}
}
End
{
Unregister-Event -SourceIdentifier WebClient.DownloadProgressChanged
Unregister-Event -SourceIdentifier WebClient.DownloadFileComplete
$Global:downloadComplete = $null
$Global:DPCEventArgs = $null
[GC]::Collect()
}
}
|
PowerShellCorpus/PoshCode/chkhash_6.ps1
|
chkhash_6.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)
{
foreach($s in $second)
{
if ($first -eq $s) {return $false}
}
return $true
}
# chkhash.ps1 [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #3] [-u] [-h [path of .xml database]]
# -u updates the XML file database and exits
# otherwise, all files are checked against the XML file database.
# -h specifies location of xml hash database
$hashespath=".\\hashes.xml"
del variable:\\args3 -ea 0
del variable:\\args2 -ea 0
del variable:\\xfiles -ea 0
del variable:\\files -ea 0
del variable:\\exclude -ea 0
$args3=@()
$args2=$args
$nu = 0
$errs = 0
$fc = 0
$upd = $false
$create = $false
for($i=0;$i -lt $args2.count; $i++)
{
if ($args2[$i] -like "-h*") # -help specified?
{
"Usage: .\\chkhash.ps1 [-h] [-u] [-c] [-x <file path of hashes .xml database>] [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #n] [-e <Dirs>]"
"Options: -h - Help display."
" -c - Create hash database. If .xml hash database does not exist, -c will be assumed."
" -u - Update changed files and add new files to existing database."
" -x - specifies .xml database file path to use. Default is .\\hashes.xml"
" -e - exclude dirs. Put this after the files/dirs you want to check with SHA512 and needs to be fullpath (e.g. c:\\users\\bob not ..\\bob)."
""
"Examples: PS>.\\chkhash.ps1 c:\\ d:\\ -c -x c:\\users\\bob\\hashes\\hashes.xml"
" PS>.\\chkhash.ps1 c:\\users\\alice\\pictures\\sunset.jpg -a -x c:\\users\\alice\\hashes\\pictureshashes.xml"
" PS>.\\chkhash.ps1 c:\\users\\eve\\documents d:\\media\\movies -x c:\\users\\eve\\hashes\\private.xml"
" PS>.\\chkhash.ps1 c:\\users\\eve -x c:\\users\\eve\\hashes\\private.xml -e c:\\users\\eve\\hashes"
""
"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++;$hashespath=$args2[$i];continue} # Get hashes xml database path
if ($args2[$i] -like "-e*") # Exclude files, dirs
{
do {
$i++
if ($i -ge $args2.count) {break}
$exclude+=@($args2[$i]) # collect array of excluded directories.
if (($i+1) -ge $args2.count) {break}
} while ($args2[$i+1] -notlike "-*")
continue
}
$args3+=@($args2[$i]) # Add files/dirs
}
"ChkHash.ps1 - .\\chkhash.ps1 -h for usage."
""
if ($args3.count -ne 0)
{
# Get list of files and SHA512 hash them.
"Enumerating files from specified locations..."
$files=@(dir -literalpath $args3 -recurse -ea 0 | ?{$_.mode -notmatch "d"} | ?{noequal $_.directoryname $exclude}) # Get list of files
if ($files.count -eq 0) {"No files found. Exiting."; exit}
if ($create -eq $true -or !(test-path $hashespath)) # Create database?
{
# Create SHA512 hashes of files and write to new database
$files = $files | %{write-host "Hashing $($_.fullname) ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
$files |export-clixml $hashespath
"Created $hashespath"
"$($files.count) file hash(es) saved. Exiting."
exit
}
$xfiles=@(import-clixml $hashespath) # Load database
}
else
{
if (!(test-path $hashespath)) {"No database found or specified, exiting."; exit}
$xfiles=@(import-clixml $hashespath) # Load database and check it
if ($xfiles.count -eq 0) {"No files specified and no files in Database."}
$files=$xfiles
}
"Loaded $($xfiles.count) file hash(es) from $hashespath"
$hash=@{}
for($x=0;$x -lt $xfiles.count; $x++) # Build dictionary (hash) of filenames and indexes into file array
{
if ($hash.contains($xfiles[$x].fullname)) {continue}
$hash.Add($xfiles[$x].fullname,$x)
}
foreach($f in $files)
{
$n=($hash.($f.fullname))
if ($n -eq $null)
{
$nu++ # increment needs/needed updating count
if ($upd -eq $false) {"Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue
"Hashing $($f.fullname) ..."
# Create SHA512 hash of file
if ($f.SHA512)
{
$f.SHA512 = (get-SHA512 $f.fullname)
}
else
{
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
}
$xfiles+=@($f) # then add file + hash to list
continue
}
if ($f.SHA512)
{
$f.SHA512 = (get-SHA512 $f.fullname)
}
else
{
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
}
# Update and continue is specified.
$fc++ # increment files checked.
if ($xfiles[$n].SHA512 -eq $f.SHA512) # Check SHA512 for mixmatch.
{
continue
}
$errs++ # increment mixmatches
if ($upd -eq $true) { $xfiles[$n]=$f; "Updated `"$($f.fullname)`"";continue}
"Bad SHA-512 found: `"$($f.fullname)`""
}
if ($upd -eq $true) # if database updated
{
$xfiles|export-clixml $hashespath # write xml database
"Updated $hashespath"
"$nu file hash(es) added to database."
"$errs file hash(es) updated in database."
exit
}
"$errs SHA-512 mixmatch(es) found."
"$fc file(s) SHA512 matched."
if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
|
PowerShellCorpus/PoshCode/chkhash_9.ps1
|
chkhash_9.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)
{
foreach($s in $second)
{
if ($first -eq $s) {return $false}
}
return $true
}
# chkhash.ps1 [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #3] [-u] [-h [path of .xml database]]
# -u updates the XML file database and exits
# otherwise, all files are checked against the XML file database.
# -h specifies location of xml hash database
$hashespath=".\\hashes.xml"
del variable:\\args3 -ea 0
del variable:\\args2 -ea 0
del variable:\\xfiles -ea 0
del variable:\\files -ea 0
del variable:\\exclude -ea 0
$args3=@()
$args2=$args
$nu = 0
$errs = 0
$fc = 0
$upd = $false
$create = $false
for($i=0;$i -lt $args2.count; $i++)
{
if ($args2[$i] -like "-h*") # -help specified?
{
"Usage: .\\chkhash.ps1 [-h] [-u] [-c] [-x <file path of hashes .xml database>] [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #n] [-e <Dirs>]"
"Options: -h - Help display."
" -c - Create hash database. If .xml hash database does not exist, -c will be assumed."
" -u - Update changed files and add new files to existing database."
" -x - specifies .xml database file path to use. Default is .\\hashes.xml"
" -e - exclude dirs. Put this after the files/dirs you want to check with SHA512 and needs to be fullpath (e.g. c:\\users\\bob not ..\\bob)."
""
"Examples: PS>.\\chkhash.ps1 c:\\ d:\\ -c -x c:\\users\\bob\\hashes\\hashes.xml"
" PS>.\\chkhash.ps1 c:\\users\\alice\\pictures\\sunset.jpg -u -x c:\\users\\alice\\hashes\\pictureshashes.xml"
" PS>.\\chkhash.ps1 c:\\users\\eve\\documents d:\\media\\movies -x c:\\users\\eve\\hashes\\private.xml"
" PS>.\\chkhash.ps1 c:\\users\\eve -x c:\\users\\eve\\hashes\\private.xml -e c:\\users\\eve\\hashes"
""
"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
{
do {
$i++
if ($i -ge $args2.count) {break}
$exclude+=@($args2[$i]) # collect array of excluded directories.
if (($i+1) -ge $args2.count) {break}
} while ($args2[$i+1] -notlike "-*")
continue
}
$args3+=@($args2[$i]) # Add files/dirs
}
"ChkHash.ps1 - .\\chkhash.ps1 -h for usage."
""
if ($args3.count -ne 0)
{
# Get list of files and SHA512 hash them.
"Enumerating files from specified locations..."
$files=@(dir -literalpath $args3 -recurse -ea 0 | ?{$_.mode -notmatch "d"} | ?{noequal $_.directoryname $exclude}) # Get list of files
if ($files.count -eq 0) {"No files found. Exiting."; exit}
if ($create -eq $true -or !(test-path $hashespath)) # Create database?
{
# Create SHA512 hashes of files and write to new database
$files = $files | %{write-host "Hashing $($_.fullname) ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
$files |export-clixml $hashespath
"Created $hashespath"
"$($files.count) file hash(es) saved. Exiting."
exit
}
$xfiles=@(import-clixml $hashespath) # Load database
}
else
{
if (!(test-path $hashespath)) {"No database found or specified, exiting."; exit}
$xfiles=@(import-clixml $hashespath) # Load database and check it
if ($xfiles.count -eq 0) {"No files specified and no files in Database."}
$files=$xfiles
}
"Loaded $($xfiles.count) file hash(es) from $hashespath"
$hash=@{}
for($x=0;$x -lt $xfiles.count; $x++) # Build dictionary (hash) of filenames and indexes into file array
{
if ($hash.contains($xfiles[$x].fullname)) {continue}
$hash.Add($xfiles[$x].fullname,$x)
}
foreach($f in $files)
{
$n=($hash.($f.fullname))
if ($n -eq $null)
{
$nu++ # increment needs/needed updating count
if ($upd -eq $false) {"Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue
if ((get-item $f.fullname -ea 0) -eq $null)
{
continue
}
"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
}
if ((get-item $f.fullname -ea 0) -eq $null) {continue}
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force}
# Update and continue is specified.
$fc++ # increment files checked.
if ($xfiles[$n].SHA512 -eq $f.SHA512) {continue} # Check SHA512 for mixmatch.
$errs++ # increment mixmatches
if ($upd -eq $true) { $xfiles[$n]=$f; "Updated `"$($f.fullname)`"";continue}
"Bad SHA-512 found: `"$($f.fullname)`""
}
if ($upd -eq $true) # if database updated
{
$xfiles|export-clixml $hashespath # write xml database
"Updated $hashespath"
"$nu file hash(es) added to database."
"$errs file hash(es) updated in database."
exit
}
"$errs SHA-512 mixmatch(es) found."
"$fc file(s) SHA512 matched."
if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
|
PowerShellCorpus/PoshCode/Audit Script_1.ps1
|
Audit Script_1.ps1
|
#####################################################
#
# Audit script by Alan Renouf - Virtu-Al #
#
# Blog: http://teckinfo.blogspot.com/ #
#
# #
#
# Usage: Audit.ps1 'path' #
#
# #
#
# The file needs to be a plain text list of #
#
# computers to be audited one on each line #
#
# #
#
#####################################################
param( [string] $auditlist)
if ($auditlist -eq ""){
Write-Host "No list specified, using Localhost"
$targets = "localhost"
}
else
{
if ((Test-Path $auditlist) -eq $false)
{
Write-Host "Invalid audit path specified: $auditlist"
exit
}
else
{
Write-Host "Using Audit list: $auditlist"
$Targets = Get-Content $auditlist
}
}
$Date = Get-Date
Foreach ($Target in $Targets)
{
$Filename = ".\\" + $Target + "_" + $date.Hour + $date.Minute + "_" + $Date.Day + "-" + $Date.Month + "-" + $Date.Year + ".htm"
# =====================================================================================================================
# CREATE HTML OUTPUT
# =====================================================================================================================
Write-Output " "| out-file -Append -encoding ASCII -filepath $Filename
Write-Output '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output '<html ES_auditInitialized='false'><head><title>Audit</title>'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "<META http-equiv=Content-Type content='text/html; charset=windows-1252'>"| out-file -Append -encoding ASCII -filepath $Filename
# ---------- Start of Style Definition Section ------------------------------------------------------------------------
Write-Output "<STYLE type=text/css>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " DIV .expando {DISPLAY: block; FONT-WEIGHT: normal; FONT-SIZE: 8pt; RIGHT: 10px; COLOR: #ffffff; FONT-FAMILY: Tahoma; POSITION: absolute; TEXT-DECORATION: underline}"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " TABLE {TABLE-LAYOUT: fixed; FONT-SIZE: 100%; WIDTH: 100%}"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " #objshowhide {PADDING-RIGHT: 10px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; Z-INDEX: 2; CURSOR: hand; COLOR: #000000; MARGIN-RIGHT: 0px; FONT-FAMILY: Tahoma; TEXT-ALIGN: right; TEXT-DECORATION: underline; WORD-WRAP: normal}"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " .heading0_expanded {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 8px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; WIDTH: 100%; CURSOR: hand; COLOR: #FFFFFF; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; BACKGROUND-COLOR: #cc0000}"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " .heading1 {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 16px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 5px; BORDER-LEFT: #bbbbbb 1px solid; WIDTH: 100%; CURSOR: hand; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; BACKGROUND-COLOR: #7BA7C7}"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " .heading2 {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 16px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 5px; BORDER-LEFT: #bbbbbb 1px solid; WIDTH: 100%; CURSOR: hand; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; BACKGROUND-COLOR: #A5A5A5}"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " .tableDetail {BORDER-RIGHT: #bbbbbb 1px solid; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 16px; FONT-SIZE: 8pt;MARGIN-BOTTOM: -1px; PADDING-BOTTOM: 5px; MARGIN-LEFT: 5px; BORDER-LEFT: #bbbbbb 1px solid; WIDTH: 100%; COLOR: #000000; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; BACKGROUND-COLOR: #f9f9f9}"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " .filler {BORDER-RIGHT: medium none; BORDER-TOP: medium none; DISPLAY: block; BACKGROUND: none transparent scroll repeat 0% 0%; MARGIN-BOTTOM: -1px; FONT: 100%/8px Tahoma; MARGIN-LEFT: 43px; BORDER-LEFT: medium none; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: medium none; POSITION: relative}"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " .Solidfiller {BORDER-RIGHT: medium none; BORDER-TOP: medium none; DISPLAY: block; BACKGROUND: none transparent scroll repeat 0% 0%; MARGIN-BOTTOM: -1px; FONT: 100%/8px Tahoma; MARGIN-LEFT: 0px; BORDER-LEFT: medium none; COLOR: #000000; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: medium none; POSITION: relative; BACKGROUND-COLOR: #000000}"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " td {VERTICAL-ALIGN: TOP; FONT-FAMILY: Tahoma}"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " th {VERTICAL-ALIGN: TOP; COLOR: #cc0000; TEXT-ALIGN: left}"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "</STYLE>"| out-file -Append -encoding ASCII -filepath $Filename
# ---------- End of Style Definition Section --------------------------------------------------------------------------
# ---------- Start of Control Script Section --------------------------------------------------------------------------
Write-Output "<SCRIPT language=vbscript>"| out-file -Append -encoding ASCII -filepath $Filename
# ---------- Declare Global Variables for Routines --------------------------------------------------------------------
Write-Output " strShowHide = 1"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' strShow = "show"'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' strHide = "hide"'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' strShowAll = "show all"'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' strHideAll = "hide all"'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "Function window_onload()"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' If UCase(document.documentElement.getAttribute("ES_auditInitialized")) <> "TRUE" Then'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Set objBody = document.body.all"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " For Each obji in objBody"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " If IsSectionHeader(obji) Then"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " If IsSectionExpandedByDefault(obji) Then"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " ShowSection obji"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Else"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " HideSection obji"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " End If"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " End If"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Next"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " objshowhide.innerText = strShowAll"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' document.documentElement.setAttribute "ES_auditInitialized", "true"'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " End If"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "End Function"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "Function IsSectionExpandedByDefault(objHeader)"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' IsSectionExpandedByDefault = (Right(objHeader.className, Len("_expanded")) = "_expanded")'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "End Function"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "Function document_onclick()"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Set strsrc = window.event.srcElement"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' While (strsrc.className = "sectionTitle" or strsrc.className = "expando")'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Set strsrc = strsrc.parentElement"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Wend"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " If Not IsSectionHeader(strsrc) Then Exit Function"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " ToggleSection strsrc"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " window.event.returnValue = False"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "End Function"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "Sub ToggleSection(objHeader)"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' SetSectionState objHeader, "toggle"'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "End Sub"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "Sub SetSectionState(objHeader, strState)"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " i = objHeader.sourceIndex"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Set all = objHeader.parentElement.document.all"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' While (all(i).className <> "container")'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " i = i + 1"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Wend"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Set objContainer = all(i)"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' If strState = "toggle" Then'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' If objContainer.style.display = "none" Then'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' SetSectionState objHeader, "show" '| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Else"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' SetSectionState objHeader, "hide" '| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " End If"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Else"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Set objExpando = objHeader.children.item(1)"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' If strState = "show" Then'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' objContainer.style.display = "block" '| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " objExpando.innerText = strHide"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' ElseIf strState = "hide" Then'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' objContainer.style.display = "none" '| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " objExpando.innerText = strShow"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " End If"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " End If"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "End Sub"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "Function objshowhide_onClick()"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Set objBody = document.body.all"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Select Case strShowHide"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Case 0"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " strShowHide = 1"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " objshowhide.innerText = strShowAll"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " For Each obji In objBody"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " If IsSectionHeader(obji) Then"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " HideSection obji"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " End If"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Next"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Case 1"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " strShowHide = 0"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " objshowhide.innerText = strHideAll"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " For Each obji In objBody"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " If IsSectionHeader(obji) Then"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " ShowSection obji"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " End If"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Next"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " End Select"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "End Function"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output 'Function IsSectionHeader(obj) : IsSectionHeader = (obj.className = "heading0_expanded") Or (obj.className = "heading1_expanded") Or (obj.className = "heading1") Or (obj.className = "heading2"): End Function'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output 'Sub HideSection(objHeader) : SetSectionState objHeader, "hide" : End Sub'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output 'Sub ShowSection(objHeader) : SetSectionState objHeader, "show": End Sub'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "</SCRIPT>"| out-file -Append -encoding ASCII -filepath $Filename
# ---------- End of Control Script Section ----------------------------------------------------------------------------
Write-Output " </HEAD>"| out-file -Append -encoding ASCII -filepath $Filename
# ---------- End of Head Section --------------------------------------------------------------------------------------
# ---------- Start of Body Section ------------------------------------------------------------------------------------
Write-Output "<BODY>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' <p><b><font face="Arial" size="5">'$Target' Audit<hr size="8" color="#CC0000"></font></b>'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' <font face="Arial" size="1"><b><i>Version 1.0 by Alan Renouf (Virtu-Al)</i></b></font><br>'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' <font face="Arial" size="1">Report generated on ' (Get-Date) '</font></p>'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "<TABLE cellSpacing=0 cellPadding=0>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TBODY>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TR>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TD>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV id=objshowhide tabIndex=0><FONT face=Arial></FONT></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </TD>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </TR>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </TBODY>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "</TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
write-output "Writing Detail for $Target"
$ComputerSystem = Get-WmiObject -computername $Target Win32_ComputerSystem
switch ($ComputerSystem.DomainRole)
{
0 { $ComputerRole = "Standalone Workstation" }
1 { $ComputerRole = "Member Workstation" }
2 { $ComputerRole = "Standalone Server" }
3 { $ComputerRole = "Member Server" }
4 { $ComputerRole = "Domain Controller" }
5 { $ComputerRole = "Domain Controller" }
default { $ComputerRole = "Information not available" }
}
$OperatingSystems = Get-WmiObject -computername $Target Win32_OperatingSystem
$TimeZone = Get-WmiObject -computername $Target Win32_Timezone
$Keyboards = Get-WmiObject -computername $Target Win32_Keyboard
$SchedTasks = Get-WmiObject -computername $Target Win32_ScheduledJob
$BootINI = $OperatingSystems.SystemDrive + "boot.ini"
$RecoveryOptions = Get-WmiObject -computername $Target Win32_OSRecoveryConfiguration
# ---------- Start of COMPUTER DETAILS Section HTML Code --------------------------------------------------------------
Write-Output "<DIV class=heading0_expanded>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>$target Details</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "</DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "<DIV class=filler></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
# ---------- Start of COMPUTER DETAILS - GENERAL Sub Section HTML Code ------------------------------------------------
write-output "..Computer Details"
Write-Output "<DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading1>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>General</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Computer Name</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'> " $ComputerSystem.Name "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Computer Role</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'> $ComputerRole </font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
switch ($ComputerRole)
{
"Member Workstation" { Write-Output " <th width='25%'><b>Computer Domain</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename }
"Domain Controller" { Write-Output " <th width='25%'><b>Computer Domain</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename }
"Member Server" { Write-Output " <th width='25%'><b>Computer Domain</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename }
default { Write-Output " <th width='25%'><b>Computer Workgroup</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename}
}
Write-Output " <td width='75%'>" $ComputerSystem.Domain "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Operating System</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $OperatingSystems.Caption "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Service Pack</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $OperatingSystems.CSDVersion "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>System Root</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $OperatingSystems.SystemDrive "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Manufacturer</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $ComputerSystem.Manufacturer "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Model</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $ComputerSystem.Model "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Number of Processors</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $ComputerSystem.NumberOfProcessors "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Memory</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $ComputerSystem.TotalPhysicalMemory "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Registered User</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $ComputerSystem.PrimaryOwnerName "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Registered Organisation</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $OperatingSystems.Organization "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Last System Boot</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
$LBTime=$OperatingSystems.ConvertToDateTime($OperatingSystems.Lastbootuptime)
Write-Output " <td width='75%'>" $LBTime "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=filler></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
#---------- End of COMPUTER DETAILS - GENERAL Sub-section HTML Code --------------------------------------------------
# ---------- Start of COMPUTER DETAILS - HOFIXES Sub-section HTML Code ------------------------------------------------
write-output "..Hotfix Information"
$colQuickFixes = Get-WmiObject Win32_QuickFixEngineering
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading1>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>HotFixes</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>HotFix Number</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='75%'><b>Description</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
ForEach ($objQuickFix in $colQuickFixes)
{
if ($objQuickFix.HotFixID -ne "File 1")
{
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='25%'>" $objQuickFix.HotFixID "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $objQuickFix.Description "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
}
}
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=filler></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
#---------- End of COMPUTER DETAILS - HOFIXES Sub-section HTML Code --------------------------------------------------
#---------- Start of COMPUTER DETAILS - LOGICAL DISK CONFIGURATION Sub-section HTML Code -----------------------------
write-output "..Logical Disks"
$colDisks = Get-WmiObject -ComputerName $Target Win32_LogicalDisk
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading1>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>Logical Disk Configuration</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='15%'><b>Drive Letter</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='20%'><b>Label</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='20%'><b>File System</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='15%'><b>Disk Size</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='15%'><b>Disk Free Space</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='15%'><b>% Free Space</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Foreach ($objDisk in $colDisks)
{
if ($objDisk.DriveType -eq 3)
{
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='15%'>"$objDisk.DeviceID"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='20%'>"$objDisk.VolumeName"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='20%'>"$objDisk.FileSystem"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
$disksize = [math]::round(($objDisk.size / 1048576))
Write-Output " <td width='15%'>"$disksize" MB</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
$freespace = [math]::round(($objDisk.FreeSpace / 1048576))
Write-Output " <td width='15%'>"$Freespace" MB</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
$percFreespace=[math]::round(((($objDisk.FreeSpace / 1048576)/($objDisk.Size / 1048676)) * 100),0)
Write-Output " <td width='15%'>"$percFreespace" %</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
}
}
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=filler></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
# ---------- End of COMPUTER DETAILS - LOGICAL DISK CONFIGURATION Sub-section HTML Code -------------------------------
# ---------- Start of COMPUTER DETAILS - NIC CONFIGURATION Sub-section HTML Code --------------------------------------
write-output "..Network Configuration"
$NICCount = 0
$colAdapters = Get-WmiObject -ComputerName $Target Win32_NetworkAdapterConfiguration
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading1>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>NIC Configuration</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
$NICCount = 0
Foreach ($objAdapter in $colAdapters)
{
if ($objAdapter.IPEnabled -eq "True")
{
$NICCount = $NICCount + 1
If ($NICCount -gt 1)
{
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=Solidfiller></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Description</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $objAdapter.Description "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Physical address</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $objAdapter.MACaddress "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
If ($objAdapter.IPAddress -ne $Null)
{
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>IP Address / Subnet Mask</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $objAdapter.IPAddress " / " $objAdapter.IPSubnet "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Default Gateway</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $objAdapter.DefaultIPGateway "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>DHCP enabled</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
If ($objAdapter.DHCPEnabled -eq "True")
{
Write-Output " <td width='75%'>Yes</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
Else
{
Write-Output " <td width='75%'>No</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>DNS Servers</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>"| out-file -Append -encoding ASCII -filepath $Filename
If ($objAdapter.DNSServerSearchOrder -ne $Null)
{
Write-Output $objAdapter.DNSServerSearchOrder | out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Primary WINS Server</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $objAdapter.WINSPrimaryServer "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Secondary WINS Server</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $objAdapter.WINSSecondaryServer "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
$NICCount = $NICCount + 1
}
}
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=filler></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
#---------- End of COMPUTER DETAILS - NIC CONFIGURATION Sub-section HTML Code ----------------------------------------
#---------- Start of COMPUTER DETAILS - Software Sub-section HTML Code -------------------------------------------
if ((get-wmiobject -namespace "root/cimv2" -list) | ? {$_.name -match "Win32_Product"})
{
write-output "..Installed Software"
$colShares = get-wmiobject -ComputerName $Target Win32_Product | select Name,Version,Vendor,InstallDate
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading1>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>Software</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Name</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Version</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Vendor</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Install Date</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Foreach ($objShare in $colShares)
{
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='50%'>" $objShare.Name "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='20%'>" $objShare.Version "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='15%'>" $objShare.Vendor "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='15%'>" $objShare.InstallDate "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=filler></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
}
# ---------- End of COMPUTER DETAILS - Software Sub-section HTML Code ---------------------------------------------
#---------- Start of COMPUTER DETAILS - LOCAL SHARES Sub-section HTML Code -------------------------------------------
write-output "..Local Shares"
$colShares = Get-wmiobject -ComputerName $Target Win32_Share
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading1>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>Local Shares</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Share</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Path</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='50%'><b>Comment</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Foreach ($objShare in $colShares)
{
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='25%'>" $objShare.Name "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='25%'>" $objShare.Path "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='50%'>" $objShare.Caption "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=filler></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
#---------- End of COMPUTER DETAILS - LOCAL SHARES Sub-section HTML Code ---------------------------------------------
#---------- Start of COMPUTER DETAILS - PRINTERS Sub-section HTML Code -----------------------------------------------
Write-output "..Printers"
$colInstalledPrinters = Get-WmiObject -ComputerName $Target Win32_Printer
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading1>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>Printers</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Printer</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Location</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Default Printer</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Portname</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Foreach ($objPrinter in $colInstalledPrinters)
{
If ($objPrinter.Name -eq "")
{
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='100%'>No Printers Installed</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
Else
{
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='25%'>" $objPrinter.Name "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='25%'>" $objPrinter.Location "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
if ($objPrinter.Default -eq "True")
{
Write-Output " <td width='25%'>Yes</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
Else
{
Write-Output " <td width='25%'>No</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " <td width='25%'>"$objPrinter.Portname"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=filler></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
#---------- End of COMPUTER DETAILS - PRINTERS Sub-section HTML Code -------------------------------------------------
#---------- Start of COMPUTER DETAILS - SERVICES Sub-section HTML Code -----------------------------------------------
Write-Output "..Services"
$colListOfServices = Get-WmiObject -ComputerName $Target Win32_Service
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading1>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>Services</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='20%'><b>Name</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='20%'><b>Account</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='20%'><b>Start Mode</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='20%'><b>State</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='20%'><b>Expected State</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Foreach ($objService in $colListOfServices)
{
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='20%'>"$objService.Caption"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='20%'>"$objService.Startname"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='20%'>"$objService.StartMode"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
If ($objService.StartMode -eq "Auto")
{
if ($objService.State -eq "Stopped")
{
Write-Output " <td width='20%'><font color='#FF0000'>"$objService.State"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='25%'><font face='Wingdings'color='#FF0000'>ű</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
}
If ($objService.StartMode -eq "Auto")
{
if ($objService.State -eq "Running")
{
Write-Output " <td width='20%'><font color='#009900'>"$objService.State"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='20%'><font face='Wingdings'color='#009900'>ü</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
}
If ($objService.StartMode -eq "Disabled")
{
If ($objService.State -eq "Running")
{
Write-Output " <td width='20%'><font color='#FF0000'>"$objService.State"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='25%'><font face='Wingdings'color='#FF0000'>ű</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
}
If ($objService.StartMode -eq "Disabled")
{
if ($objService.State -eq "Stopped")
{
Write-Output " <td width='20%'><font color='#009900'>"$objService.State"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='20%'><font face='Wingdings'color='#009900'>ü</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
}
If ($objService.StartMode -eq "Manual")
{
Write-Output " <td width='20%'><font color='#009900'>"$objService.State"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='20%'><font face='Wingdings'color='#009900'>ü</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
If ($objService.State -eq "Paused")
{
Write-Output " <td width='20%'><font color='#FF9933'>"$objService.State"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='20%'><font face='Wingdings'color='#009900'>ü</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=filler></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
#---------- End of COMPUTER DETAILS - SERVICES Sub-section HTML Code -------------------------------------------------
#---------- Start of COMPUTER DETAILS - REGIONAL SETTINGS Sub-section HTML Code --------------------------------------
Write-Output "..Regional Options"
$ObjKeyboards = Get-WmiObject -ComputerName $Target Win32_Keyboard
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading1>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>Regional Settings</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Time Zone</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $TimeZone.Description "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Country Code</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $OperatingSystems.Countrycode "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Locale</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $OperatingSystems.Locale"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Operating System Language</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $OperatingSystems.OSLanguage"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
switch ($ObjKeyboards.Layout)
{
"00000402"{ $keyb = "BG" }
"00000404"{ $keyb = "CH" }
"00000405"{ $keyb = "CZ" }
"00000406"{ $keyb = "DK" }
"00000407"{ $keyb = "GR" }
"00000408"{ $keyb = "GK" }
"00000409"{ $keyb = "US" }
"0000040A"{ $keyb = "SP" }
"0000040B"{ $keyb = "SU" }
"0000040C"{ $keyb = "FR" }
"0000040E"{ $keyb = "HU" }
"0000040F"{ $keyb = "IS" }
"00000410"{ $keyb = "IT" }
"00000411"{ $keyb = "JP" }
"00000412"{ $keyb = "KO" }
"00000413"{ $keyb = "NL" }
"00000414"{ $keyb = "NO" }
"00000415"{ $keyb = "PL" }
"00000416"{ $keyb = "BR" }
"00000418"{ $keyb = "RO" }
"00000419"{ $keyb = "RU" }
"0000041A"{ $keyb = "YU" }
"0000041B"{ $keyb = "SL" }
"0000041C"{ $keyb = "US" }
"0000041D"{ $keyb = "SV" }
"0000041F"{ $keyb = "TR" }
"00000422"{ $keyb = "US" }
"00000423"{ $keyb = "US" }
"00000424"{ $keyb = "YU" }
"00000425"{ $keyb = "ET" }
"00000426"{ $keyb = "US" }
"00000427"{ $keyb = "US" }
"00000804"{ $keyb = "CH" }
"00000809"{ $keyb = "UK" }
"0000080A"{ $keyb = "LA" }
"0000080C"{ $keyb = "BE" }
"00000813"{ $keyb = "BE" }
"00000816"{ $keyb = "PO" }
"00000C0C"{ $keyb = "CF" }
"00000C1A"{ $keyb = "US" }
"00001009"{ $keyb = "US" }
"0000100C"{ $keyb = "SF" }
"00001809"{ $keyb = "US" }
"00010402"{ $keyb = "US" }
"00010405"{ $keyb = "CZ" }
"00010407"{ $keyb = "GR" }
"00010408"{ $keyb = "GK" }
"00010409"{ $keyb = "DV" }
"0001040A"{ $keyb = "SP" }
"0001040E"{ $keyb = "HU" }
"00010410"{ $keyb = "IT" }
"00010415"{ $keyb = "PL" }
"00010419"{ $keyb = "RU" }
"0001041B"{ $keyb = "SL" }
"0001041F"{ $keyb = "TR" }
"00010426"{ $keyb = "US" }
"00010C0C"{ $keyb = "CF" }
"00010C1A"{ $keyb = "US" }
"00020408"{ $keyb = "GK" }
"00020409"{ $keyb = "US" }
"00030409"{ $keyb = "USL" }
"00040409"{ $keyb = "USR" }
"00050408"{ $keyb = "GK" }
default { $keyb = "Unknown" }
}
Write-Output " <th width='25%'><b>Keyboard Layout</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $keyb "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </div>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=filler></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
#---------- End of COMPUTER DETAILS - REGIONAL SETTINGS Sub-section HTML Code ----------------------------------------
#---------- Start of COMPUTER DETAILS - EVENT LOGS Sub-section HTML Code ---------------------------------------------
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading1>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>Event Logs</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
#---------- Start of COMPUTER DETAILS - EVENT LOGS - EVENT LOG SETTINGS Sub-section HTML Code ------------------------
Write-Output "..Event Log Settings"
$colLogFiles = Get-WmiObject -ComputerName $Target Win32_NTEventLogFile
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading2>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>Event Log Settings</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Log Name</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Overwrite Outdated Records</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Maximum Size</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Current Size</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
ForEach ($objLogFile in $colLogfiles)
{
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='25%'>" $objLogFile.LogFileName "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
If ($objLogfile.OverWriteOutdated -lt 0)
{
Write-Output " <td width='25%'>Never</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
if ($objLogFile.OverWriteOutdated -eq 0)
{
Write-Output " <td width='25%'>As needed</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
Else
{
Write-Output " <td width='25%'>After " $objLogFile.OverWriteOutdated " days</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " <td width='25%'>" (($objLogfile.MaxFileSize)/1024) " KB</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='25%'>" (($objLogfile.FileSize)/1024) " KB</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=filler></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
#---------- End of COMPUTER DETAILS - EVENT LOGS - EVENT LOG SETTINGS Sub-section HTML Code --------------------------
# ---------- Start of COMPUTER DETAILS - EVENT LOGS - ERROR ENTRIES Sub-section HTML Code -----------------------------
write-output "..Event Log Errors"
$WmidtQueryDT = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime([DateTime]::Now.AddDays(-14))
$colLoggedEvents = Get-WmiObject -computer "Localhost" -query ("Select * from Win32_NTLogEvent Where Type='Error' and TimeWritten >='" + $WmidtQueryDT + "'")
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading2>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>ERROR Entries</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='10%'><b>Event Code</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='10%'><b>Source Name</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='15%'><b>Time</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='10%'><b>Log</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='55%'><b>Message</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
ForEach ($objEvent in $colLoggedEvents)
{
$dtmEventDate = $ObjEvent.ConvertToDateTime($objEvent.TimeWritten)
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='10%'>" $objEvent.EventCode "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='10%'>" $objEvent.SourceName "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='15%'>" $dtmEventDate "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='10%'>" $objEvent.LogFile "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='55%'>" $objEvent.Message "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filen
|
PowerShellCorpus/PoshCode/GPRS Online log_4.ps1
|
GPRS Online log_4.ps1
|
<#
.SYNOPSIS
Get-GprsTime (V3.0 Update for Windows 7) Check the total connect time of any
GPRS devices from a specified date.
Use Get-Help .\\Get-GprsTime -full to view Help for this file.
.DESCRIPTION
Display all the GPRS modem Event Log entries. While applications issued by the
mobile phone manufacturers will invariably monitor only their own usage, this
will show any logged GPRS activity, be it via PCMCIA, USB, mobile phone, etc.
Use the -Verbose switch for some extra information if desired. A default value
can be set with the -Monthly switch but can be temporarily overridden with any
-Start value and deleted by entering an invalid date. Now uses .NET Parse to
use any culture date input. Switches -M and -S cannot be used together.
A Balloon prompt will be issued in the Notification area for the 5 days
before the nominal month end.
NOTE: this can effectively be suppressed by using a value higher than the SIM
card term, ie something like -Account 90 for a 30 day card which will override
the default setting. Use -Today to check only today's usage.
Define a function in $profile to set any permanent switches, for example to
set the account value permanently to 30 days.
function GPRS {
Invoke-Expression "Get-GprsTime -Account 30 $args"
}
.EXAMPLE
.\\Get-GprsTime.ps1 -Monthly 4/8/2011
This will set the default search date to start from 4/8/2011 and is used to
reset the start date each month for the average 30/31 day SIM card.
.EXAMPLE
.\\Get-GprsTime.ps1 -Start 12/07/2009 -Account 100 -Verbose
Search from 12/07/2011 and also show (Verbose) details for each session. The
Account switch will override any balloon prompt near the SIM expiry date.
.EXAMPLE
.\\Get-GprsTime.ps1 5/9/2011 -v
Search one day only and show session details.
.EXAMPLE
.\\Get-GprsTime.ps1 -Today
Show all sessions for today. This always defaults to verbose output.
.EXAMPLE
.\\Get-GprsTime.ps1 -Debug
Shows the first available Event Log record and confirms switch settings.
.NOTES
A shorter total time than that actually used will result if the Event Log
does not contain earlier dates; just increase the log size in such a case.
The author can be contacted at www.SeaStarDevelopment.Bravehost.com and a
(binary compiled) Module version of this procedure is included in the file
Gprs3038.zip download there; the execution time of the module being about
10 times faster than this script.
For the Event Log to record connect & disconnect events, the modem software
should be set to RAS rather than NDIS.
#>
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 196) {
Write-Warning "[$name] Current GPRS variable has been deleted."
$monthly = ""
[Environment]::SetEnvironmentVariable("GPRS",$monthly,"User")
}
else {
Write-Warning "[$name] Date is missing or invalid $SCRIPT:form"
}
exit 1
}
#Establish the Operating System...We only need to confirm XP or later.
function Get-OSVersion($computer,[ref]$osv) {
$os = Get-WmiObject -class Win32_OperatingSystem -computerName $computer
Switch ($os.Version) {
"5.1.2600" { $osv.value = "xp" }
default { "Version not listed" }
}
}
$osv = $null
$version = Get-OSVersion "localhost" ([ref]$osv)
if ($osv -eq 'xp') {
$logname = 'System'
$connEvent = 20158
$discEvent = 20159
$source = 'RemoteAccess'
}
else { #Treat As Vista or Windows 7.
$logname = 'Application'
$connEvent = 20225
$discEvent = 20226
$source = 'RasClient'
}
$entryType = 'Information'
$logEntry = $null
$oldest = Get-eventlog -LogName $logname | #Get the earliest Log record.
Where-Object {$_.Source -eq $source} |
Where-Object {$_.EntryType -eq $entryType } |
Sort-Object TimeGenerated |
Select-Object -first 1
if ($oldest.TimeGenerated) {
$logEntry = "System Event records available from - $($oldest.TimeGenerated.ToLongDateString())"
}
$name = $myInvocation.MyCommand
$newLine = "[$name] The switches -Start and -Monthly can only be used separately."
if ($debug) {
$DebugPreference = 'Continue'
}
if ($start -and $monthly) {
[System.Media.SystemSounds]::Hand.Play()
Write-Warning "$newLine"
exit 1
}
$SCRIPT:form = ""
#In certain cases Culture & UICulture can be different and have been known to
# return conflicting results regarding '-is [DateTime]' queries, etc.
if ($Host.CurrentCulture -eq $Host.CurrentUICulture) {
$SCRIPT:form = '-Use format mm/dd/year'
[Int]$culture = "{0:%d}" -f [DateTime] "6/5/2009" #Returns local day.
If ($culture -eq 6) {
$SCRIPT:form = '-Use format dd/mm/year'
}
}
$ErrorActionPreference = 'SilentlyContinue'
$VerbosePreference = 'SilentlyContinue'
$WarningPreference = 'Continue'
$conn = $disc = $default = $print = $null
$timeNow = [DateTime]::Now
$total = $timeNow - $timeNow #Set initial value to 00:00:00.
$insert = "since"
if ($verbose) {
$VerbosePreference = 'Continue'
}
function CreditMsg ($value, $value2) {
$value = [Math]::Abs($value)
$prefix = "CURRENT"
[DateTime] $creditDT = $value2
$creditDT = $creditDT.AddDays($value) #Add the -Account days.
$thisDay = "{0:M/d/yyyy}" -f [DateTime]::Now #Force US format.
#If we use '$number = $creditDT - (Get-Date)' instead of the line below we
#can sometimes get a value of 1 returned instead 2, hence the above lines.
$number = $creditDT - [DateTime] $thisDay
[String] $credit = $creditDT
$credit = $credit.Replace('00:00:00','') #Remove any trailing time.
$credit = "{0:d}" -f [DateTime]$credit
Switch($number.Days) {
1 {$prefix = "($value days) will expire tomorrow"; break}
0 {$prefix = "($value days) will expire today"; break}
-1 {$prefix = "($value days) expired yesterday"; break}
{($_ -lt 0)} {$prefix = "($value days) expired on $credit"; break}
{($_ -le 5)} {$prefix = "($value days) will expire on $credit"}
Default {$prefix = "CURRENT"} #Only come here if over 5 days.
}
return $prefix
}
function Interval ([String] $value) {
Switch -regex ($value) {
'^00:00:\\d+(.*)$' {$suffix = "seconds"; break}
'^00:\\d+:\\d+(.*)$' {$suffix = "minutes"; break}
'^\\d+:\\d+:\\d+(.*)$' {$suffix = " hours"; break}
'^(\\d+)\\D(\\d+)(.*)$' {$suffix = " hours"
$pDays = $matches[1]
$pHours = $matches[2]
[string]$pMinSec = $matches[3]
[string]$tHours = (([int]$pDays) * 24)+[int]$pHours
$value = $tHours + $pminSec; break}
default {$suffix = " hours"} #Should never come here!
}
return "$value $suffix"
}
function CheckSetting ($value) {
if ($value) { #Correct for local culture.
$print = $default.ToShortDateString()
}
else {
$print = "(Value not set)"
}
return $print
}
#The Script effectively starts here.............................................
$getGprs = [Environment]::GetEnvironmentVariable("GPRS","User")
#First check for GPRS variable and change from US date format to current locale.
if ([DateTime]::TryParse($getGprs, [Ref]$timeNow)) { #No error as date is valid.
$default = "{0:d}" -f [datetime]$getGprs
$default = [DateTime]::Parse($default)
$checkParts = "{0:yyyy},{0:%M}" -f $default
$times = $checkParts.Split(',')
$dayCount = [DateTime]::DaysInMonth($times[0],$times[1]) #Range 28-31.
if($account -eq 0) {
$account = $dayCount
$summary = "$($dayCount.ToString()) days"
}
else {
$summary = "$($account.Tostring()) days"
}
$text = CreditMsg $account $getGprs #Check if within 5 days of expiry date.
if ($text -ne "CURRENT") {
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon
$objNotifyIcon.Icon = [System.Drawing.SystemIcons]::Exclamation
$objNotifyIcon.BalloonTipIcon = "Info"
$objNotifyIcon.BalloonTipTitle = "GPRS online account"
$objNotifyIcon.BalloonTipText = "Credit $text"
$objNotifyIcon.Visible = $True
$objNotifyIcon.ShowBalloonTip(10000)
}
}
else {
$summary = "(Days not set)"
if ((!$today) -and (!$monthly) -and (!$start)) {
[System.Media.SystemSounds]::Hand.Play()
Write-Warning("Monthly date is either invalid or not set.")
exit 1
}
}
if ($start) {
$start = [DateTime]::Parse($start) #Trigger TRAP if invalid!
[DateTime]$limit = $start
$convert = "{0:D}" -f $limit
$print = CheckSetting $default
}
if ($monthly) {
$start = [DateTime]::Parse($monthly) #Trigger TRAP if invalid!
Write-Output "Setting GPRS (monthly) environment variable to: $monthly"
$gprs = [String]$start.Replace('00:00:00','')
[Environment]::SetEnvironmentVariable("GPRS",$gprs,"User")
[DateTime] $limit = $start #Change to required US date format.
$convert = "{0:D}" -f $limit
$print = $limit.ToShortDateString()
$summary = "(Days undetermined)" #Will show next time around.
}
if ($today) {
$verBosePreference = 'Continue' #Show VERBOSE by default.
[DateTime] $limit = (Get-Date)
$convert = "{0:D}" -f $limit
$limit = $limit.Date #Override any start date if using -Today input.
$insert = "for today"
$print = CheckSetting $default
}
if ((!$today) -and (!$monthly) -and (!$start)) {
if ($default) {
$monthly = $default
[DateTime] $limit = $monthly
$convert = "{0:D}" -f $limit
$print = CheckSetting $default
}
}
Write-Verbose "All records $($insert.Replace('for ','')) - $convert"
Write-Verbose "Script activation - User [$($env:UserName)] Computer [$($env:ComputerName)]"
Write-Output ""
Write-Output "Calculating total connect time of all GPRS modem devices..."
#We cannot proceed beyond here without a valid $limit value.
Write-Debug "Using - [Search date] $($limit.ToShortDateString()) [Account] $summary [GPRS Monthly] $print"
if ($logEntry) {
Write-Debug "$logEntry"
}
$lines = Get-EventLog $logname | Where-Object {($_.TimeGenerated -ge $limit) -and `
($_.EventID -eq $discEvent -or $_.EventID -eq $connEvent)}
if ($lines) {
Write-Verbose "A total of $([Math]::Truncate($lines.Count/2)) online sessions extracted from the System Event Log."
}
else {
Write-Output "(There are no events indicated in the System Event Log)"
}
$lines | ForEach-Object {
$source = $_.Source
if ($_.EventID -eq $discEvent) { #Event 20159 is Disconnect.
$disc = $_.TimeGenerated
}
else { #Event 20158 is Connect.
$conn = $_.TimeGenerated
} #We are only interested in matching pairs of DISC/CONN...
if ($disc -ne $null -and $conn -ne $null -and $disc -gt $conn) {
$diff = $disc - $conn
$total += $diff
$convDisc = "{0:G}" -f $disc
$convConn = "{0:G}" -f $conn
$period = Interval $diff
Write-Verbose "Disconnect at $convDisc. Online - $period"
Write-Verbose " Connect at $convConn."
}
} #End ForEach
if (!$source) {
$source = '(Undetermined)'
}
Write-Verbose "Using local event source - System Event Log [$source]"
$period = Interval $total
Write-Output "Total online usage $insert $convert is $($period.Replace(' ',' '))."
Write-Output ""
|
PowerShellCorpus/PoshCode/d0047a4f-cc03-41f0-ba05-197bd8b5f759.ps1
|
d0047a4f-cc03-41f0-ba05-197bd8b5f759.ps1
|
Coresponding to the Scripting Guy blog "How Can I Both Save Information in a File and Display It on the Screen?
" (http://blogs.technet.com/heyscriptingguy/archive/2009/07/07/hey-scripting-guy-how-can-i-both-save-information-in-a-file-and-display-it-on-the-screen.aspx):
My comment is:
"All of the above is cool but can't work if you want your Write-Host or Write-Debug to be redirected to file as well as printing to console.
Maybe the Scripting Guy can explain why (AFAIK these cmdlets are already redirecting their output).
so these examples don't work!:
Write-Debug "blablabla" > File.txt
Write-Debug "blablabla" | Out-File -filepath C:\\File.txt
Write-Debug "blablabla" | Tee -filepath C:\\File.txt
so here's the function I finally use:
Function WriteToDebug ([string]$DebugMessage)
{
$ScriptOut = ((Get-Date -format G ) + "`t$DebugMessage" )
Out-File -FilePath $LogFileDebug -Append -InputObject $ScriptOut
Write-Debug "$ScriptOut"
}
Where i replaced every Write-Debug in the script to WriteToDebug.
|
PowerShellCorpus/PoshCode/ScheduleGPOBackups_2.ps1
|
ScheduleGPOBackups_2.ps1
|
Import-Module grouppolicy
#region ConfigBlock
# What domain are we going to backup GPOs for?
$domain = "mydomain.com"
# Where are we going to store the backups?
$gpoBackupRootDir = "c:\\gpoBackups"
# As I plan to do a new backup set each month I'll setup the directory names to reflect
# the year and month in a nice sortable way.
# Set this up and format to your liking, I prefer $gpoBackupRootDir\\yyyy-MM
$backupDir = "$gpoBackupRootDir\\{0:yyyy-MM}" -f (Get-Date)
# Perform a full backup how often? Day/Week/Month/Year?
#$fullBackupFrequency = "Day"
#$fullBackupFrequency = "Week"
$fullBackupFrequency = "Month"
#$fullBackupFrequency = "Year"
# Perform Incremental backups how often? Hour/Day/Week/Month?
$IncBackupFreqency = "Hour"
# $IncBackupFreqency = "Day"
# $IncBackupFreqency = "Week"
# $IncBackupFreqency = "Month"
# How many full sets to keep?
# Alternatively, how far back do we keep our backup sets?
$numKeepBackupSets = 12
# On what day do we want to consider the start of Week?
#$startOfWeek = "Sunday"
$startOfWeek = "Monday"
#$startOfWeek = "Tuesday"
#$startOfWeek = "Wednesday"
#$startOfWeek = "Thursday"
#$startOfWeek = "Friday"
#$startOfWeek = "Saturday"
# On what day do we want to consider the start of Month?
$startOfMonth = 1
# On what day do we want to consider the start of Year?
$startOfYear = 1
#endregion
$currentDateTime = Get-Date
$doFull = $false
$doInc = $false
# Does our backup directory exist?
# If not attempt to create it and fail the script with an approprate error
if (-not (Test-Path $backupDir))
{
try
{
New-Item -ItemType Directory -Path $backupDir
}
catch
{
Throw $("Could not create directory $backupDir")
}
}
# If we're here then our backup directory is in good shape
# Check if we need to run a full backup or not
# if we do, then run it
if ( Test-Path $backupDir\\LastFullTimestamp.xml )
{
# Import the timestamp from the last recorded complete full
$lastFullTimestamp = Import-Clixml $backupDir\\LastFullTimestamp.xml
# check to see if the timestamp is valid, if not then delete it and run a full
if ( $lastFullTimestamp -isnot [datetime] )
{
$doFull = $true
Remove-Item $backupDir\\LastFullTimestamp.xml
}
else # $lastfulltimestamp is or can be boxed/cast into [datetime]
{
# determine how long it has been since the last recorded full
$fullDelta = $currentDateTime - $lastFullTimestamp
switch ($fullBackupFrequency)
{
Day
{
if ( $fullDelta.days -gt 0 )
{
$doFull = $true
}
}
Week
{
if ( ($currentDateTime.dayOfWeek -eq [DayOfWeek]$startOfWeek) `
-or ($fullDelta.days -gt 7) )
{
$doFull = $true
}
}
Month
{
if ( ($currentDateTime.day -eq $startOfMonth) `
-or ($fullDelta.days -gt 30) )
{
$doFull = $true
}
}
Year
{
if ( ($currentDateTime.dayofyear -eq $startOfYear) `
-or ($fullDelta.days -gt 365) )
{
$doFull = $true
}
}
}
}
}
else # There is no recorded last completed full so we want to run one
{
$doFull = $true
}
if ($doFull)
{
# Run Backup of All GPOs in domain
$GPOs = Get-GPO -domain $domain -All
foreach ($GPO in $GPOs)
{
$GPOBackup = Backup-GPO $GPO.DisplayName -Path $backupDir
# First build the Report path, then generate a report of the backed up settings.
$ReportPath = $backupDir + "\\" + $GPO.ModificationTime.Year + "-" + $GPO.ModificationTime.Month + "-" + $GPO.ModificationTime.Day + "_" + $GPO.Displayname + "_" + $GPOBackup.Id + ".html"
Get-GPOReport -Name $GPO.DisplayName -path $ReportPath -ReportType HTML
}
Export-Clixml -Path $backupDir\\LastFullTimestamp.xml -InputObject ($currentDateTime)
}
else # If we're not running a full check if we need to run an incremental backup
{
if ( Test-Path $backupDir\\LastIncTimestamp.xml )
{
# Import the timestamp from the last recorded complete Incremental
$lastIncTimestamp = Import-Clixml $backupDir\\LastIncTimestamp.xml
# check to see if the timestamp is valid, if not then delete it and run an inc
if ( $lastIncTimestamp -isnot [datetime] )
{
# Import the timestamp from the last recorded complete full
# If we're here then the timestamp is valid. It is checked earlier and if it fails
# or doesn't exist then we run a full and will never get here.
# determine how long it has been since the last recorded full
$lastFullTimestamp = Import-Clixml $backupDir\\LastFullTimestamp.xml
$IncDelta = $currentDateTime - $lastFullTimestamp
$doInc = $true
Remove-Item $backupDir\\LastIncTimestamp.xml
}
else # $lastIncTimestamp is or can be boxed/cast into [datetime]
{
# determine how long it has been since the last recorded full
$IncDelta = $currentDateTime - $lastIncTimestamp
}
}
else # There is no recorded last Incremental
{
# Import the timestamp from the last recorded complete full
# If we're here then the timestamp is valid. It is checked earlier and if it fails
# or doesn't exist then we run a full and will never get here.
# determine how long it has been since the last recorded full
$lastFullTimestamp = Import-Clixml $backupDir\\LastFullTimestamp.xml
$IncDelta = $currentDateTime - $lastFullTimestamp
}
# If we have already determined to run an Inc we want to skip this part
if ($doInc -eq $false)
{
switch ($IncBackupFreqency)
{
Hour
{
if ($IncDelta.hours -gt 0)
{
$doInc = $true
}
}
Day
{
if ($IncDelta.days -gt 0)
{
$doInc = $true
}
}
Week
{
if ( ($currentDateTime.dayOfWeek -eq [DayOfWeek]$startOfWeek) `
-or ($IncDelta.days -gt 7) )
{
$doInc = $true
}
}
Month
{
if ( ($currentDateTime.day -eq $startOfMonth) `
-or ($IncDelta.days -gt 30) )
{
$doInc = $true
}
}
}
}
# Time to check our Incremental flag and run the backup if we need to
if ($doInc)
{
# Run Incremental Backup
$GPOs = Get-GPO -domain $domain -All | Where-Object { $_.modificationTime -gt ($currentDateTime - $incDelta) }
foreach ($GPO in $GPOs)
{
$GPOBackup = Backup-GPO $GPO.DisplayName -Path $backupDir
# First build the Report path, then generate a report of the backed up settings.
$ReportPath = $backupDir + "\\" + $GPO.ModificationTime.Year + "-" + $GPO.ModificationTime.Month + "-" + $GPO.ModificationTime.Day + "_" + $GPO.Displayname + ".html"
Get-GPOReport -Name $GPO.DisplayName -path $ReportPath -ReportType HTML
}
Export-Clixml -Path $backupDir\\LastIncTimestamp.xml -InputObject ($currentDateTime)
}
}
#TODO: Cleanup old backup sets
|
PowerShellCorpus/PoshCode/Get-BogonList_1.ps1
|
Get-BogonList_1.ps1
|
function Get-BogonList {
<#
.SYNOPSIS
Gets the bogon list.
.DESCRIPTION
The Get-BogonList function retrieves the bogon prefix list maintained by Team Cymru.
A bogon prefix is a route that should never appear in the Internet routing table.
A packet routed over the public Internet (not including over VPNs or other tunnels) should never have a source address in a bogon range.
These are commonly found as the source addresses of DDoS attacks. Bogons are defined as Martians (private and reserved addresses defined by RFC 1918 and RFC 5735) and
netblocks that have not been allocated to a regional internet registry (RIR) by the Internet Assigned Numbers Authority.
.PARAMETER Aggregated
By default the unaggregated bogon list is retrieved. Use this switch parameter to retrieve the aggregated list.
.OUTPUTS
PSObject
.EXAMPLE
Get-BogonList
Retrieves the unaggregated bogon list from Team Cymru.
.EXAMPLE
Get-BogonList -Aggregated
Retrieves the aggregated bogon list from Team Cymru.
.NOTES
Name: Get-BogonList
Author: Rich Kusak (rkusak@cbcag.edu)
Created: 2010-01-31
LastEdit: 2010-06-02 13:22
Version: 1.1.0
#Requires -Version 2.0
.LINK
http://www.team-cymru.org/Services/Bogons/
#>
[CmdletBinding()]
param (
[switch]$Aggregated
)
# Create a web client object
$webClient = New-Object System.Net.WebClient
# Parse the bogons sites for the last updated date and current version
$version = $webClient.DownloadString('http://www.team-cymru.org/Services/Bogons/') -split "`n" |
Where-Object {$_ -match 'Bogons Last Updated:' -or $_ -match 'Current version:'} |
ForEach-Object {$_.ToString().Replace('<strong>',"").Replace('</strong><br />',"").Trim()}
# Display title and version information
Write-Host "Team Cymru Bogon List" ; $version
# Retrieve and display the aggregated bogon list
if ($Aggregated) {
foreach ($bogon in $webClient.DownloadString('http://www.team-cymru.org/Services/Bogons/bogon-bn-agg.txt') -split "`n") {
New-Object PSObject -Property @{'Aggregated Bogons' = $bogon}
}
# Retrieve and display the unaggregated bogon list
} else {
foreach ($bogon in $webClient.DownloadString('http://www.team-cymru.org/Services/Bogons/bogon-bn-nonagg.txt') -split "`n") {
New-Object PSObject -Property @{'Unaggregated Bogons' = $bogon}
}
}
}
|
PowerShellCorpus/PoshCode/Check Service on Servers.ps1
|
Check Service on Servers.ps1
|
<#
Author: Matt Schmitt
Date: 11/29/12
Version: 1.0
From: USA
Email: ithink2020@gmail.com
Website: http://about.me/schmittmatt
Twitter: @MatthewASchmitt
Description
A script for checking the status of a service on a group of servers, from a list in a file.
#>
$serverList = Import-Csv 'c:\\serverList.csv'
"Server" +"`t" + "Status" | Out-File c:\\ServerService.csv
foreach ($element in $serverList)
{
$sStatus = get-service -Name "CPSVS" | Select-Object -expand Status
$server = $element | Select-Object -expand Server
$server + "`t" + $sStatus | Out-File -append c:\\ServerServiceStatus.csv
}
Send-MailMessage -From donotreply@test.com -To recipient@domain.com -subject "Spooler Service Report" -Body "Attached is Server Service report." -Attachments "c:\\ServerServiceStatus.csv" -SmtpServer "xxx.xxx.xxx.xxx"
|
PowerShellCorpus/PoshCode/Issue-PendingRequest_1.ps1
|
Issue-PendingRequest_1.ps1
|
#####################################################################
# Issue certificate.ps1
# Version 1.0
#
# Issues certificate request from a pending request
#
# For this function to succeed, the certificate request must be pending
#
# Vadims Podans (c) 2010
# http://en-us.sysadmins.lv/
#####################################################################
#requires -Version 2.0
function Issue-PendingRequest {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, ValueFomPipeline = $true)]
[string]$CAConfig,
[Parameter(Mandatory = $true)]
[int]$RequestID
)
try {$CertAdmin = New-Object -ComObject CertificateAuthority.Admin}
catch {Write-Warning "Unable to instantiate ICertAdmin2 object!"; return}
try {
$status = switch ($CertAdmin.ResubmitRequest($CAConfig,$RequestID)) {
0 {"The request was not completed."}
1 {"The request failed."}
2 {"The request was denied"}
3 {"The certificate was issued."}
4 {"The certificate was issued separately."}
5 {"The request was taken under submission."}
6 {"The certificate is revoked."}
}
}
catch {$_; return}
Write-Host "Operation status for the request '$RequestID': $status"
}
|
PowerShellCorpus/PoshCode/Set-IPConfigv2.ps1
|
Set-IPConfigv2.ps1
|
# script parameters
param(
[string[]] $Computers = $env:computername,
[switch] $ChangeSettings,
[switch] $EnableDHCP,
[switch] $Batch
)
$nl = [Environment]::NewLine
# check for Admin rights
if ($ChangeSettings -or $EnableDHCP){
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")){
Write-Warning "You need Administrator rights to run this script!"
Break
}
}
else{
$nl
Write-Warning "For changing settings add -ChangeSettings as parameter, if not this script is output only"
}
# script variables
$Domain = "domain.local"
$DNSSuffix = @("domain.local", "domain.com")
$DNSServers = @("10.10.0.1", "10.10.0.2", "10.10.0.3", "10.10.0.4")
$WINSServers = @("10.10.0.5", "10.10.0.6")
$Gateway = @("10.10.255.254")
# script functions
Function NewNICDetails($NIC, $Computer){
# retrieve updated values for changed NIC
$UpdatedNIC = Get-WMIObject Win32_NetworkAdapterConfiguration -Computername $Computer | where{$_.Index -eq $NIC.Index}
ShowDetails $UpdatedNIC
}
Function ChangeIPConfig($NIC){
if ($EnableDHCP){$NIC.EnableDHCP()}
#uncomment line(s) if applicable
#$NIC.SetGateways($Gateway)
#$NIC.SetWINSServer($WINSServers)
$DNSServers = Get-random $DNSservers -Count 4
$NIC.SetDNSServerSearchOrder($DNSServers)
$NIC.SetDynamicDNSRegistration("TRUE")
$NIC.SetDNSDomain($Domain)
# remote WMI registry method for updating DNS Suffix SearchOrder
$registry = [WMIClass]"\\\\$computer\\root\\default:StdRegProv"
$HKLM = [UInt32] "0x80000002"
$registry.SetStringValue($HKLM, "SYSTEM\\CurrentControlSet\\Services\\TCPIP\\Parameters", "SearchList", $DNSSuffix)
}
Function ShowDetails($NIC){
Write-Output "$("Hostname = ")$($NIC.DNSHostName)"
Write-Output "$("DNSDomain= ")$($NIC.DNSDomain)"
Write-Output "$("Domain DNS Registration Enabled = ")$($NIC.DomainDNSRegistrationEnabled)"
Write-Output "$("Full DNS Registration Enabled = ")$($NIC.FullDNSRegistrationEnabled)"
Write-Output "$("DNS Domain Suffix Search Order = ")$($NIC.DNSDomainSuffixSearchOrder)"
Write-Output "$("MAC address = ")$($NIC.MACAddress)"
Write-Output "$("DHCP enabled = ")$($NIC.DHCPEnabled)"
# show all IP adresses on this NIC
$x = 0
foreach ($IP in $NIC.IPAddress){
Write-Output "$("IP address $x =")$($NIC.IPAddress[$x])$("/")$($NIC.IPSubnet[$x])"
$x++
}
Write-Output "$("Default IP Gateway = ")$($NIC.DefaultIPGateway)"
Write-Output "$("DNS Server Search Order = ")$($NIC.DNSServerSearchOrder)"
}
# actual script execution
foreach ($Computer in $Computers){
if (Test-connection $Computer -quiet -count 1){
Try {
[array]$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration -Computername $Computer -EA Stop | where{$_.IPEnabled -eq "TRUE"}
}
Catch {
Write-Host $nl " ====INACCESIBLE====" $nl
Write-Warning "$($error[0])"
Write-Output "$($nl)$($Computer.ToUpper())$(" is INACCESIBLE")"
Write-Host $nl
continue
}
# Generate selection menu only if there is indeed more than 1 NIC
$NICindex = $NICs.count
$SelectIndex = 0
if ($NICindex -gt 1){
if ($Batch){
# only perform action if $NICindex -eq 1
Write-Host $nl " ====SKIPPED====" $nl
Write-Output "$($nl)$($Computer.ToUpper())$(" skipped due to multiple NICs")"
continue
}
else{
Write-Host "$nl Selection for " $Computer.ToUpper() ": $nl"
For ($i=0;$i -lt $NICindex; $i++) {
Write-Host -ForegroundColor Green $i --> $($NICs[$i].Description)
}
Write-Host -ForegroundColor Green q --> Quit
Write-Host $nl
# Wait for user selection input
Do {
$SelectIndex = Read-Host "Select connection (default = $SelectIndex) or 'q' to quit"
If ($SelectIndex -NotLike "q*"){$SelectIndex = $SelectIndex -as [int]}
}
Until (($SelectIndex -lt $NICindex -AND $SelectIndex -match "\\d") -OR $SelectIndex -Like "q*")
If ($SelectIndex -Like "q*"){continue}
}
}
# Show selected network card name + current values
Write-Host $nl " ====BEFORE====" $nl
Write-Output "$($nl)$(" IP settings on:")$($Computer.ToUpper())$($nl)$($nl)$(" for ")$($NICs[$SelectIndex].Description)$(":")"
Write-Output $(ShowDetails $NICs[$SelectIndex])$($nl)
# Change settings for selected network card if option is true and show updated values
If ($ChangeSettings){
ChangeIPConfig $NICs[$SelectIndex]
Write-Host $nl " ====AFTER====" $nl
Write-Output "$($nl)$(" IP settings on:")$($Computer.ToUpper())$($nl)$($nl)$(" for ") $($NICs[$SelectIndex].Description)$(":")"
Write-Output $(NewNICDetails $NICs[$SelectIndex] $Computer)$($nl)
}
}
}
|
PowerShellCorpus/PoshCode/Set-Domain_7.ps1
|
Set-Domain_7.ps1
|
function Set-Domain {
param( [switch]$help,
[string]$domain=$(read-host "Please specify the domain to join"),
[System.Management.Automation.PSCredential]$credential = $(Get-Crdential)
)
$usage = "`$cred = get-credential `n"
$usage += "Set-Domain -domain MyDomain -credential `$cred`n"
if ($help) {Write-Host $usage;exit}
$username = $credential.GetNetworkCredential().UserName
$password = $credential.GetNetworkCredential().Password
$computer = Get-WmiObject Win32_ComputerSystem
$computer.JoinDomainOrWorkGroup($domain ,$password, $username, $null, 3)
}
|
PowerShellCorpus/PoshCode/Inovke command exclusive.ps1
|
Inovke command exclusive.ps1
|
function Invoke-CommandEx
{
param
(
[String] $MutexName = $(throw "Name is required."),
[ScriptBlock] $Scriptblock = $(throw "Scriptblock is required."),
[Object[]] $ArgumentList
)
$MutexWasCreated = $false;
$Mutex = $null;
Write-Host "Waiting to acquire lock [$MutexName]..." -f Cyan
[System.Reflection.Assembly]::LoadWithPartialName("System.Threading");
try {
$Mutex = [System.Threading.Mutex]::OpenExisting($MutexName);
}catch{
$Mutex = New-Object System.Threading.Mutex($true,$MutexName,[ref]$MutexWasCreated);
}
try {
if(!$MutexWasCreated){
$Mutex.WaitOne() | Out-Null;
}
}catch{}
Write-Host "Lock [$MutexName] acquired. Executing..." -f Cyan
#region Execute Powershell V1 compatible
foreach($arg in $ArgumentList){
$params += "`"$arg`" ";
}
$cmd = @"
function f{
$Scriptblock
}
f $params
"@;
Invoke-Expression $cmd
#endregion
# This is powershell v2
# Invoke-Command -ScriptBlock $Scriptblock -ArgumentList $ArgumentList
# We're done, Release lock, even if we exit before releasing the mutex will be abandoned
Write-Host "Releasing lock [$MutexName]..." -f Cyan
try {
$Mutex.ReleaseMutex() | Out-Null;
}catch{}
}
|
PowerShellCorpus/PoshCode/Impersonation 1.1.ps1
|
Impersonation 1.1.ps1
|
# Version History
# 1.1 - Added aliases, error handling, help, and cleanup
$MyInvocation.MyCommand.ScriptBlock.Module.OnRemove = {
while($script:ImpContextStack.Count) { Pop-ImpersonationContext }
}
$script:UserToysClass = Add-Type -Namespace Huddled -Name UserToys -MemberDefinition @"
// http://msdn.microsoft.com/en-us/library/aa378184.aspx
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
// http://msdn.microsoft.com/en-us/library/aa379317.aspx
[DllImport("advapi32.dll", SetLastError=true)]
public static extern bool RevertToSelf();
"@ -passthru
$script:ImpContextStack = new-object System.Collections.Generic.Stack[System.Security.Principal.WindowsImpersonationContext]
$script:IdStack = new-object System.Collections.Generic.Stack[System.Security.Principal.WindowsIdentity]
function Push-ImpersonationContext {
<#
.SYNOPSIS
Sets the network credentials for the current thread
.Description
Stores an identity on the stack and impersonate it for network connections
.Parameter Credential
Credentials for authenticating as a new identity.
.Parameter Name
A user name for authenticating as a new identity.
.Parameter Password
The password (as a String or SecureString) for authenticating as a new identity
.Parameter Domain
The domain which goes with the user name for authentication. This is optional, as you can specify a domain or computer name as part of the name using domain\\user or user@domain syntax.
.Parameter Passthru
Causes Push-ImpersonationContext to output the WindowsIdentity that it's impersonating (not the impersonation context).
.Example
Push-ImpersonationContext (Get-Credential)
.Example
Push-ImpersonationContext username@domain (Read-Host "Password" -AsSecureString)
.Example
$Domain1 = Get-Credential
$Id1 = PushIC $Domain1 -Passthru
#>
[CmdletBinding(DefaultParameterSetName="Credential")]
Param(
[Parameter(Position=0,Mandatory=$true,ParameterSetName="Credential")]
[System.Management.Automation.PSCredential]$Credential
,
[Parameter(Position=0,Mandatory=$true,ParameterSetName="Identity")]
[Security.Principal.WindowsIdentity]$Identity
,
[Parameter(Position=0,Mandatory=$true,ParameterSetName="Password")]
[string]$Name
,
[Parameter(Position=1,Mandatory=$true,ParameterSetName="Password")]
[Alias("PW")]
$Password = (Read-Host "Password" -AsSecureString)
,
[Parameter(Position=2,Mandatory=$false,ParameterSetName="Password")]
[string]$Domain
,
[Alias("PT")]
[switch]$Passthru
)
if(!$Identity) {
if(!$Credential) {
if($password -is [string]) {
$secure = New-Object System.Security.SecureString
$password.GetEnumerator() | %{ $secure.AppendChar( $_ ) }
$password = $secure
}
if($domain) {
$user = "${name}@${domain}"
}
$Credential = new-object System.Management.Automation.PSCredential $user, $password
}
Write-Verbose ([Security.Principal.WindowsIdentity]::GetCurrent() | Format-Table Name, Token, User, Groups -Auto | Out-String)
[IntPtr]$userToken = [Security.Principal.WindowsIdentity]::GetCurrent().Token
if(!$UserToysClass::LogonUser(
$Credential.GetNetworkCredential().UserName,
$Credential.GetNetworkCredential().Domain,
$Credential.GetNetworkCredential().Password, 9, 0, [ref]$userToken)
) {
throw (new-object System.ComponentModel.Win32Exception( [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() ) )
}
$Identity = New-Object Security.Principal.WindowsIdentity $userToken
}
$script:IdStack.Push( $Identity )
$context = $Identity.Impersonate()
$null = $script:ImpContextStack.Push( $context )
Write-Verbose ([Security.Principal.WindowsIdentity]::GetCurrent() | Format-Table Name, Token, User, Groups -Auto | Out-String)
if($Passthru) { $script:IdStack.Peek() }
}
function Pop-ImpersonationContext {
<#
.Synopsis
Remove the current impersonation context from the stack and clean it up
.Description
Pops the current impersonation context from the stack and undo and dispose it, leaving the former context in place.
.Param Passthru
Output the old WindowsIdentity before popping it.
#>
param( [switch]$Passthru )
trap {
Write-Error "Impersonation Context Stack is Empty"
while($script:ImpContextStack.Count -lt $script:IdStack.Count) { $null = $script:IdStack.Pop() }
return
}
if($Passthru) { $script:IdStack.Peek() }
$context = $script:ImpContextStack.Pop()
$null = $script:IdStack.Pop()
$context.Undo();
$context.Dispose();
}
function Get-ImpersonationContext {
<#
.Synopsis
Display the currently active WindowsIdentity
#>
trap {
Write-Error "Impersonation Context Stack is Empty"
return
}
Write-Host "There are $($script:ImpContextStack.Count) contexts on the stack"
while($script:ImpContextStack.Count -lt $script:IdStack.Count) { $null = $script:IdStack.Pop() }
if($script:ImpContextStack.Count -eq $script:IdStack.Count) {
$script:IdStack.Peek()
}
}
New-Alias popic Pop-ImpersonationContext
New-Alias pushic Push-ImpersonationContext
New-Alias gic Get-ImpersonationContext
Export-ModuleMember -Function * -Alias *
|
PowerShellCorpus/PoshCode/foreach-withexception_1.ps1
|
foreach-withexception_1.ps1
|
function foreach-withexception ([scriptblock]$process,$outputexception)
{
begin { $global:foreachex = @() }
process {
try
{
$local:inputitem = $_
&$process
}
catch
{
$local:exceptionitem = 1 | select-object object,exception
$local:exceptionitem.object = $local:inputitem
$local:exceptionitem.exception = $_
$global:foreachex += $local:exceptionitem
}
}
end {}
}
set-alias %ex foreach-withexception
100..-5 | %ex { "yo $_" ; 1 / $_ }
$foreachex
|
PowerShellCorpus/PoshCode/PowerBot _2.0.ps1
|
PowerBot _2.0.ps1
|
## PowerBot 2.0
## A simple framework to get you started writing your own IRC bots in PowerShell
####################################################################################################
## Requires Meebey.SmartIrc4net.dll to be in your ...\\WindowsPowerShell\\Libraries\\
## You can get Meebey.SmartIrc4net.dll from
## http://voxel.dl.sourceforge.net/sourceforge/smartirc4net/SmartIrc4net-0.4.0.bin.tar.bz2
####################################################################################################
## Add-Type -path $ProfileDir\\Libraries\\Meebey.SmartIrc4net.dll
$null = [Reflection.Assembly]::LoadFrom("$ProfileDir\\Libraries\\Meebey.SmartIrc4net.dll")
function Start-PowerBot {
PARAM( $server = "irc.freenode.net", [string[]]$channels = @("#PowerShell"), [string[]]$nick = @(Read-Host 'You must provide a nickname'), [string]$password, $realname = "PowerShell Bot", $port = 6667)
if(!$global:irc) {
$global:irc = New-Object Meebey.SmartIrc4net.IrcClient
$irc.ActiveChannelSyncing = $true # $irc will track channels for us
# $irc.Encoding = [Text.Encoding]::UTF8
# $irc.Add_OnError( {Write-Error $_.ErrorMessage} )
$irc.Add_OnQueryMessage( {PrivateMessage} )
$irc.Add_OnChannelMessage( {ChannelMessage} )
}
$irc.Connect($server, $port)
$irc.Login($nick, $realname, 0, $nick, $password)
## $channels | % { $irc.RfcJoin( $_ ) }
foreach($channel in $channels) { $irc.RfcJoin( $channel ) }
Resume-PowerBot # Shortcut so starting this thing up only takes one command
}
## Note that PowerBot stops listening if you press a key ...
## You'll have to re-run Resume-Powerbot to get him to listen again
function Resume-PowerBot {
while(!$Host.UI.RawUI.KeyAvailable) { $irc.ListenOnce($false) }
}
function Stop-PowerBot {
$irc.RfcQuit("If people listened to themselves more often, they would talk less.")
$irc.Disconnect()
}
####################################################################################################
## Event Handlers
####################################################################################################
## Event handlers in powershell have TWO automatic variables: $This and $_
## In the case of SmartIrc4Net:
## $This - usually the connection, and such ...
## $_ - the IrcEventArgs, which just has the Data member:
##
function PrivateMessage {
$Data = $_.Data
# Write-Verbose $Data.From
# Write-Verbose $Data.Message
# Write-Verbose $($Data | Out-String)
$command, $params = $Data.MessageArray
if($PowerBotCommands.ContainsKey($command)) {
&$PowerBotCommands[$command] $params $Data | Out-String -width (510 - $Data.From.Length - $nick.Length - 3) | % { $_.Trim().Split("`n") | %{ $irc.SendMessage("Message", $Data.Channel, $_.Trim() ) }}
}
}
function ChannelMessage {
$Data = $_.Data
# Write-Verbose $Data.From
# Write-Verbose $Data.Channel
# Write-Verbose $Data.Message
# Write-Verbose $($Data | Out-String)
$command, $params = $Data.MessageArray
if($PowerBotCommands.ContainsKey($command)) {
&$PowerBotCommands[$command] $params $Data | Out-String -width (510 - $Data.Channel.Length - $nick.Length - 3) | % { $_.Trim().Split("`n") | %{ $irc.SendMessage("Message", $Data.Channel, $_.Trim() ) }}
}
}
####################################################################################################
## The PowerBotCommands hashtable is extremely simple ...
##
## You register a "command" which must be the FIRST WORD of a message (either private, or channel)
## and you provide a scriptblock to process said message.
## The handler scriptblock gets two parameters, for convenience:
## $Params is the rest of the message text after the command word (which is probably all you need)
## $Data is the Data propert of the IrcEventArgs, which has everything in it that you could want
##
## You may do whatever you want in the scriptblock (this runs on your PC, after all), but the
## simplest thing is to respond by returning "something" which will be sent to wherever the message
## came from.
##
## NOTE 1: Evrything you return is output to Out-String and then the channel or user. Be careful!
## NOTE 2: 510 is the Max IRC Message Length, including the channel name etc.
## http`://www.faqs.org/rfcs/rfc1459.html
##
$PowerBotCommands=@{}
## A sample command to get you started
$PowerBotCommands."Hello" = {Param($Query,$Data)
"Hello, $($Data.Nick)!"
}
##$PowerBotCommands."!Echo" = {Param($Query,$Data)
## "$Query"
##}
##
##$PowerBotCommands."!Get-Help" = {Param($Query)
## $help = get-help $Query | Select Name,Synopsis,Syntax
## if($?) {
## if($help -is [array]) {
## "You're going to need to be more specific, I know all about $((($help | % { $_.Name })[0..($help.Length-2)] -join ', ') + ' and even ' + $help[-1].Name)"
## } else {
## @($help.Synopsis,($help.Syntax | Out-String -width 1000).Trim().Split("`n",4,"RemoveEmptyEntries")[0..3])
## }
## } else {
## "I couldn't find the help file for '$Query', sorry. I probably don't have that snapin loaded."
## }
##}
|
PowerShellCorpus/PoshCode/sudo for Powershell_4.ps1
|
sudo for Powershell_4.ps1
|
## sudo.ps1
#
# Authors: rbellamy, pezhore, mrigns, This guy: http://tsukasa.jidder.de/blog/2008/03/15/scripting-sudo-with-powershell,
# other powershell peoples
#
# Sources:
# http://tsukasa.jidder.de/blog/2008/03/15/scripting-sudo-with-powershell
# http://www.ainotenshi.org/%E2%80%98sudo%E2%80%99-for-powershell-sorta
#
# Version:
# 1.0 Initial version
# 1.1 added -ps flag, cleaned up passed $file/$script full path
# 1.2 Comments
# 1.3 Fixed passing working directory to powershell/auto closing
# 1.4 Added hidden window, with Export/Import-Clixml to pull results into current window
# Doesn't deal well with input PS commands (e.g. 'sudo $Local:WindowsPrincipal.IsInRole("Administrators")')
# is broken.
param (
[switch]$ps = $true, # Switch for running args as powershell script
[string]$file, # Script/Program to run
[string]$arguments = $args # Arguments to program/script
)
$tempPath = "$env:TEMP:\\PoSH-sudo-$PID.xml";
# Find our powershell full path
$powershell = (Get-Command powershell).Definition;
# Get current directory
$dir = Get-Location;
# File verification
if([System.IO.File]::Exists("$(Get-Location)\\$file")) {
# Get full path
$file = (Get-ChildItem $file).Fullname;
}
if ($ps) {
#If we're running this as a elevated powershell script
# Create a powershell process
$psi = New-Object System.Diagnostics.ProcessStartInfo $powershell;
$psi.WorkingDirectory = Get-Location;
# Combine the script and its arguments
$sArgs = $file + " " + $arguments;
# Set the arguments to be the ps script and it's arguments
$psi.Arguments = " -Command Set-Location $dir; $sArgs";
# NOT using the shell to execute!
$psi.UseShellExecute = $false;
# Magic to run as elevated
$psi.Verb = "RunAs";
} else {
# We're running something other than a powershells script
# Same as above, create proccess/working directory/arguments/runas
$psi = New-Object System.Diagnostics.ProcessStartInfo $file;
$psi.Arguments = $arguments;
# Magic to run as elevated
$psi.Verb = "RunAs";
}
$psi.Arguments = $psi.Arguments + " | Export-Clixml -Path `"$tempPath`"";
$psi.WindowStyle = "Hidden";
# Execute the process
[System.Diagnostics.Process]::Start($psi).WaitForExit();
Import-Clixml -Path "$tempPath";
Remove-Item $tempPath;
|
PowerShellCorpus/PoshCode/Get-Environment.ps1
|
Get-Environment.ps1
|
Param($srv=$env:ComputerName)
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine,$Srv)
$key = $regKey.OpenSubkey("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",$false)
$key.GetValueNames() | Select-Object @{n="ValueName";e={$_}},@{n="Value";e={$key.GetValue($_)}}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.