full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PoshCode/Copy-File (Safely).ps1
Copy-File (Safely).ps1
function Copy-File { #.Synopsis # Copies all files and folders in $source folder to $destination folder, but with .copy inserted before the extension if the file already exists param($source,$destination) # create destination if it's not there ... mkdir $destination -force -erroraction SilentlyContinue foreach($original in ls $source -recurse) { $result = $original.FullName.Replace($source,$destination) while(test-path $result -type leaf){ $result = [IO.Path]::ChangeExtension($result,"copy$([IO.Path]::GetExtension($result))") } if($original.PSIsContainer) { mkdir $result -ErrorAction SilentlyContinue } else { copy $original.FullName -destination $result } } }
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/Invoke-SqlCommand.ps1
Invoke-SqlCommand.ps1
##############################################################################\n##\n## Invoke-SqlCommand\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nReturn the results of a SQL query or operation\n\n.EXAMPLE\n\nInvoke-SqlCommand.ps1 -Sql "SELECT TOP 10 * FROM Orders"\nInvokes a command using Windows authentication\n\n.EXAMPLE\n\nPS >$cred = Get-Credential\nPS >Invoke-SqlCommand.ps1 -Sql "SELECT TOP 10 * FROM Orders" -Cred $cred\nInvokes a command using SQL Authentication\n\n.EXAMPLE\n\nPS >$server = "MYSERVER"\nPS >$database = "Master"\nPS >$sql = "UPDATE Orders SET EmployeeID = 6 WHERE OrderID = 10248"\nPS >Invoke-SqlCommand $server $database $sql\nInvokes a command that performs an update\n\n.EXAMPLE\n\nPS >$sql = "EXEC SalesByCategory 'Beverages'"\nPS >Invoke-SqlCommand -Sql $sql\nInvokes a stored procedure\n\n.EXAMPLE\n\nInvoke-SqlCommand (Resolve-Path access_test.mdb) -Sql "SELECT * FROM Users"\nAccess an Access database\n\n.EXAMPLE\n\nInvoke-SqlCommand (Resolve-Path xls_test.xls) -Sql 'SELECT * FROM [Sheet1$]'\nAccess an Excel file\n\n#>\n\nparam(\n ## The data source to use in the connection\n [string] $DataSource = ".\\SQLEXPRESS",\n\n ## The database within the data source\n [string] $Database = "Northwind",\n\n ## The SQL statement(s) to invoke against the database\n [Parameter(Mandatory = $true)]\n [string[]] $SqlCommand,\n\n ## The timeout, in seconds, to wait for the query to complete\n [int] $Timeout = 60,\n\n ## The credential to use in the connection, if any.\n $Credential\n)\n\n\nSet-StrictMode -Version Latest\n\n## Prepare the authentication information. By default, we pick\n## Windows authentication\n$authentication = "Integrated Security=SSPI;"\n\n## If the user supplies a credential, then they want SQL\n## authentication\nif($credential)\n{\n $credential = Get-Credential $credential\n $plainCred = $credential.GetNetworkCredential()\n $authentication =\n ("uid={0};pwd={1};" -f $plainCred.Username,$plainCred.Password)\n}\n\n## Prepare the connection string out of the information they\n## provide\n$connectionString = "Provider=sqloledb; " +\n "Data Source=$dataSource; " +\n "Initial Catalog=$database; " +\n "$authentication; "\n\n## If they specify an Access database or Excel file as the connection\n## source, modify the connection string to connect to that data source\nif($dataSource -match '\\.xls$|\\.mdb$')\n{\n $connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; " +\n "Data Source=$dataSource; "\n\n if($dataSource -match '\\.xls$')\n {\n $connectionString += 'Extended Properties="Excel 8.0;"; '\n\n ## Generate an error if they didn't specify the sheet name properly\n if($sqlCommand -notmatch '\\[.+\\$\\]')\n {\n $error = 'Sheet names should be surrounded by square brackets, ' +\n 'and have a dollar sign at the end: [Sheet1$]'\n Write-Error $error\n return\n }\n }\n}\n\n## Connect to the data source and open it\n$connection = New-Object System.Data.OleDb.OleDbConnection $connectionString\n$connection.Open()\n\nforeach($commandString in $sqlCommand)\n{\n $command = New-Object Data.OleDb.OleDbCommand $commandString,$connection\n $command.CommandTimeout = $timeout\n\n ## Fetch the results, and close the connection\n $adapter = New-Object System.Data.OleDb.OleDbDataAdapter $command\n $dataset = New-Object System.Data.DataSet\n [void] $adapter.Fill($dataSet)\n\n ## Return all of the rows from their query\n $dataSet.Tables | Select-Object -Expand Rows\n}\n\n$connection.Close()
PowerShellCorpus/PoshCode/Out-Colour.ps1
Out-Colour.ps1
function out-colour { if ($Input) { [int[]]$columns = @() # select colors you prefer and the one that a readable on your console.. :) $colours = @('Magenta','Yellow','Cyan','Green') foreach ($obj in ($Input | Out-String -Stream)) { if ($columns.count -eq 0) { $match = $obj | Select-String -AllMatches -Pattern '[^|\\s]-{2,}' | Select-Object -ExpandProperty Matches if ( ($match | Measure-Object | Select-Object -ExpandProperty Count) -ge 2) { $columns = $match | Select-Object -ExpandProperty Index } Write-Host $obj } else { foreach ($char in $obj.ToCharArray()) { $colour = $null $X = $Host.UI.RawUI.CursorPosition.X for ($i=0; $i -lt $columns.count - 1; $i++) { Write-Verbose "i = $i ; X = $X" if ( ( $X -ge $columns[$i]) -and ( $X -lt $columns[$i+1] ) ) { $colour = $colours[($i % $colours.count)] } } if (!$colour) { $colour = $colours[(($columns.count -1) % $colours.count)] } Write-Host -ForegroundColor $colour $char -NoNewline } "`r" } } } }
PowerShellCorpus/PoshCode/VM Disk Report.ps1
VM Disk Report.ps1
$VMs = get-vm $Results = @() foreach ($VM in $VMs) { $Result = new-object PSObject $Result | add-member -membertype NoteProperty -name "Name" -value $VM.Name $Result | add-member -membertype NoteProperty -name "Description" -value $VM.Notes $VMDiskCount = 1 get-harddisk $VM | foreach { $disk = $_ $Result | add-member -name "Disk($VMDiskCount)SizeGB" -value ([math]::Round($disk.CapacityKB / 1MB)) -membertype NoteProperty $Result | add-member -name "Disk($VMDiskCount)Type" -value $disk.DiskType -membertype NoteProperty $VMDiskCount++ } $Results += $Result } $Results | select-object * | export-csv -notypeinformation E:\\VCBDiskReport.csv
PowerShellCorpus/PoshCode/AD_bulk_new_OU.ps1
AD_bulk_new_OU.ps1
param( $searchBase = "OU=Organisation,DC=uza,DC=local", $NewOUs = @(Import-csv -Path "d:\\projects\\AD\\departments.csv" -Delimiter ";"), $SubOUs = @("Computers","Users"), [switch]$ProtectOU ) $Protect = $false If ($ProtectOU){$Protect = $true} foreach ($NewOU in $NewOUs){ New-ADOrganizationalUnit -Name $NewOU.name -Description $NewOU.description -City "Antwerp" -Country "BE" -ManagedBy $NewOU.manager -State "Antwerp" -Path $searchBase -ProtectedFromAccidentalDeletion $Protect $SubOUPath = "OU=" + $Newou.Name + "," + $searchBase foreach ($SubOU in $SubOUs){ New-ADOrganizationalUnit -Name $SubOU -Path $SubOUPath -ProtectedFromAccidentalDeletion $Protect } }
PowerShellCorpus/PoshCode/Create AD Test Lab.ps1
Create AD Test Lab.ps1
# --------------------------------------------------------------------------- ### <Script> ### <Author>Ted Wagner</Author> ### <Version='2.4'> ### <Script Name='Create-ADTestLabContent.ps1'> ### <Derived From='Dmitry Sotnikov - http://dmitrysotnikov.wordpress.com/2007/12/14/setting-demo-ad-environments/'> ### <Description> ### This script design uses the original script (base script) written by Dmitry Sotnikov. The script's ### original comments are included below. I am referring to Dmitry's script as "version 1.0" ### ### My goal is to standardize variables, functions and libraries such that the script is portable. ### This is so that I can place all files for PowerShell on an ISO file and re-use the content ### with as little modification as possible from test scenario to test scenario. ### ### My scripts folder is a directory copied from the ISO file. When I build a virtual environment, ### I bring up a completely configured and empty AD domain. I then attach the ISO to the VM and ### copy the "scripts" folder to the root of C:. I then drop in a default profile.ps1 into the ### WindowsPowerShell directory (the default All Users profile) and run this script. ### ### There is more work, yet to do; I want to "pare down" the functions so that the functions could be added to ### a functions.ps1 "library" file. ### ### The labs I set up for testing use an OU structure similar to the following: ### ### OU=DeptName - ### |- Computers ### |- Groups ### |- Users ### ### The profile.ps1 sets up the PSDrive and then creates a variable to the provider. The profile.ps1 ### script is in the root of the scripts directoy which is copied from the ISO file. ### ### Contents of the profile.ps1 file: ### ### New-PSDrive -name ScriptLib -psProvider FileSystem -root "C:\\Scripts" ### $ScriptLib = 'ScriptLib:' ### ### The Scripts folder contains a subfolder named "LabSetup". The LabSetup folder contains this script, ### titled "Create-ADTestLabContent.ps1" and all of the text files necessary for creating the user ### objects, OU's, etc. You can create your own files and/or edit this script to match your file names. ### I've listed the contents of each file below. ### ### I deviated from the original text files from Dmitry's script. ### My goal was to have a "true" list of random names by utilizing the "select-random" written by ### Joel Bennett. This can be downloaded from poshcode.org. I found that the combination of the ### select-ramdom on the census files and parsing the extra data was extremely time consuming. ### I went to the census.org page for year 2000 and downloaded the top 1000 names spreadsheet. ### Then, I simply stripped off ALL of the extra data (first row and all columns after column A) ### and saved it as an ascii file called "surnames.txt". The link to that page is: ### http://www.census.gov/genealogy/www/data/2000surnames/index.html ### ### Additionally, I did something similar with the first names. ### I downloaded common male and female names from http://infochimps.org/collections/moby-project-word-lists ### Those files are named fgivennames.txt and mgivennames.txt. You can alternately download a text file ### of 21,000+ common given names from the same site instead of using the surnames from census.gov. ### However, for my testing, a sample of 1000 last names was sufficient for my needs. ### ### departments.txt - Name of each Department which will be both an OU, group, and the department ### property on user objects. ### ous.txt - Name of child-containers for each Department OU (Computers, Groups, Users). ### cities.txt - Names of cities I will use on user properties ### dist.all.last.txt - ASCII file of last names downloaded from the Census.gov website ### dist.male.first.txt - ASCII file of male first names downloaded from the Census.gov website ### dist.female.first.txt - ASCII file of female first names downloaded from the Census.gov website ### ### The descriptions of the deparments match the OU name. This differentiates them from the default ### containers created when AD is set up from those added by this script. This allows for easily removing ### containers and all child items quickly during testing. ### </Description> ### ### <Dependencies> ### Requires ActiveRoles Management Shell for Active Directory. This script will check ### for the snapin and add the snapin at runtime. ### </Dependencies> ### ### <History> ### changes 01/08/2010 - version 2.0 ### - Change Display name and full name properties to format of Lastname, Firstname ### - Change password to p@ssw0rd ### Changes 01/11/2010 - version 2.1 ### - Assume base config of empty domain. Create variable for root domain name ### - make sure not attempt is made to duplicate usernames ### - Create containers ### Changes 02/19/2010 - version 2.2 ### - added function to create empty departmental OUs and child containers for users, groups and computers ### Changes 02/22/2010 - version 2.3 ### - added computer account creation to occur when the user is added ### - dot source functions.ps1 ### - added Joel Bennett's select-random v2.2 script to functions.ps1. functions.ps1 in root of scripts folder ### Changes 02/23/2010 ### - Made script more readible by using word-wrap ### - Cleaned up description and commenting ### Changes 02/24/2010 - Version 2.4 ### - Using new ascii files for first and given names (see notes) ### - Removed original lines for parsing census.gov files ### Changes 02/25/2010 ### - added better description for containers added via script to differentiate them to account for ### manually added containers ### - fixed issue with computer object creation - computer objects weren't always getting created ### ### Original Script name: demoprovision.ps1 ################################################## ### Script to provision demo AD labs ### (c) Dmitry Sotnikov, xaegr ### Requires AD cmdlets ################################################## ### ### set folder in which the data files are located ### this folder should contain files from ### http://www.census.gov/genealogy/names/names_files.html ### as well as cities.txt and departments.txt with the ### lists of cities and departments for the lab ### </History> ### </Script> # --------------------------------------------------------------------------- #Load Function Library . $ScriptLib\\functions.ps1 # function to create empty OUs function create-LabOUs (){ # Create Each Dept OU for ($i = 0; $i -le $DeptOUs.Length - 1; $i++){ $OUName = "Test Lab Container - " + $DeptOUs[$i] $CreateDeptOU += @(new-QADObject -ParentContainer $RootDomain.RootDomainNamingContext ` -type 'organizationalUnit' -NamingProperty 'ou' -name $DeptOUs[$i] -description $OUName ) } # Create Child OUs for each Dept foreach ($DeptOU in $CreateDeptOU){ for ($i = 0; $i -le $ChildOUs.Length - 1; $i++){ new-qadObject -ParentContainer $DeptOU.DN -type 'organizationalUnit' -NamingProperty 'ou' ` -name $ChildOUs[$i] } } } function New-RandomADUser (){ # set up random number generator $rnd = New-Object System.Random # pick a male or a female first name if($rnd.next(2) -eq 1) { $fn = $firstm[$rnd.next($firstm.length)] } else { $fn = $firstf[$rnd.next($firstf.length)] } # random last name $ln = $last[$rnd.next($last.length)] # Set proper caps $ln = $ln[0] + $ln.substring(1, $ln.length - 1).ToLower() $fn = $fn[0] + $fn.substring(1, $fn.length - 1).ToLower() # random city and department $city = $cities[$rnd.next($cities.length)] $dept = $depts[$rnd.next($depts.length)] $SName = ($fn.substring(0,1) + $ln) # set user OU variable switch ($dept){ $DeptContainers[0].name {$UserOU = Get-QADObject -SearchRoot $DeptContainers[0].DN | ` where { $_.DN -match "Users" -and $_.Type -ne "user" }} $DeptContainers[1].name {$UserOU = Get-QADObject -SearchRoot $DeptContainers[1].DN | ` where { $_.DN -match "Users" -and $_.Type -ne "user" }} $DeptContainers[2].name {$UserOU = Get-QADObject -SearchRoot $DeptContainers[2].DN | ` where { $_.DN -match "Users" -and $_.Type -ne "user" }} $DeptContainers[3].name {$UserOU = Get-QADObject -SearchRoot $DeptContainers[3].DN | ` where { $_.DN -match "Users" -and $_.Type -ne "user" }} $DeptContainers[4].name {$UserOU = Get-QADObject -SearchRoot $DeptContainers[4].DN | ` where { $_.DN -match "Users" -and $_.Type -ne "user" }} $DeptContainers[5].name {$UserOU = Get-QADObject -SearchRoot $DeptContainers[5].DN | ` where { $_.DN -match "Users" -and $_.Type -ne "user" }} $DeptContainers[6].name {$UserOU = Get-QADObject -SearchRoot $DeptContainers[6].DN | ` where { $_.DN -match "Users" -and $_.Type -ne "user" }} $DeptContainers[7].name {$UserOU = Get-QADObject -SearchRoot $DeptContainers[7].DN | ` where { $_.DN -match "Users" -and $_.Type -ne "user" }} $DeptContainers[8].name {$UserOU = Get-QADObject -SearchRoot $DeptContainers[8].DN | ` where { $_.DN -match "Users" -and $_.Type -ne "user" }} $DeptContainers[9].name {$UserOU = Get-QADObject -SearchRoot $DeptContainers[9].DN | ` where { $_.DN -match "Users" -and $_.Type -ne "user" }} } # Check for account, if not exist, create account if ((get-qaduser $SName) -eq $null){ # Create and enable a user New-QADUser -Name "$ln`, $fn" -SamAccountName $SName -ParentContainer $UserOU -City $city ` -Department $dept -UserPassword "p@ssw0rd" -FirstName $fn -LastName $ln -DisplayName "$ln`, $fn" ` -Description "$city $dept" -Office $city | Enable-QADUser } # set group OU variable switch ($dept){ $DeptContainers[0].name {$GroupOU = Get-QADObject -SearchRoot $DeptContainers[0].DN | ` where { $_.DN -match "Groups" -and $_.Type -ne "group" }} $DeptContainers[1].name {$GroupOU = Get-QADObject -SearchRoot $DeptContainers[1].DN | ` where { $_.DN -match "Groups" -and $_.Type -ne "group" }} $DeptContainers[2].name {$GroupOU = Get-QADObject -SearchRoot $DeptContainers[2].DN | ` where { $_.DN -match "Groups" -and $_.Type -ne "group" }} $DeptContainers[3].name {$GroupOU = Get-QADObject -SearchRoot $DeptContainers[3].DN | ` where { $_.DN -match "Groups" -and $_.Type -ne "group" }} $DeptContainers[4].name {$GroupOU = Get-QADObject -SearchRoot $DeptContainers[4].DN | ` where { $_.DN -match "Groups" -and $_.Type -ne "group" }} $DeptContainers[5].name {$GroupOU = Get-QADObject -SearchRoot $DeptContainers[5].DN | ` where { $_.DN -match "Groups" -and $_.Type -ne "group" }} $DeptContainers[6].name {$GroupOU = Get-QADObject -SearchRoot $DeptContainers[6].DN | ` where { $_.DN -match "Groups" -and $_.Type -ne "group" }} $DeptContainers[7].name {$GroupOU = Get-QADObject -SearchRoot $DeptContainers[7].DN | ` where { $_.DN -match "Groups" -and $_.Type -ne "group" }} $DeptContainers[8].name {$GroupOU = Get-QADObject -SearchRoot $DeptContainers[8].DN | ` where { $_.DN -match "Groups" -and $_.Type -ne "group" }} $DeptContainers[9].name {$GroupOU = Get-QADObject -SearchRoot $DeptContainers[9].DN | ` where { $_.DN -match "Groups" -and $_.Type -ne "group" }} } # Create groups for each department, create group if it doesn't exist if ((get-QADGroup $dept) -eq $null){ New-QADGroup -Name $dept -SamAccountName $dept -ParentContainer $GroupOU -Description "$dept Users" } # Add user to the group based on their department Get-QADUser $SName -SearchRoot $UserOU | Add-QADGroupMember -Identity { $_.Department } # set computer OU variable switch ($dept){ $DeptContainers[0].name {$ComputerOU = Get-QADObject -SearchRoot $DeptContainers[0].DN | ` where { $_.DN -match "Computers" -and $_.Type -ne "computer" }} $DeptContainers[1].name {$ComputerOU = Get-QADObject -SearchRoot $DeptContainers[1].DN | ` where { $_.DN -match "Computers" -and $_.Type -ne "computer" }} $DeptContainers[2].name {$ComputerOU = Get-QADObject -SearchRoot $DeptContainers[2].DN | ` where { $_.DN -match "Computers" -and $_.Type -ne "computer" }} $DeptContainers[3].name {$ComputerOU = Get-QADObject -SearchRoot $DeptContainers[3].DN | ` where { $_.DN -match "Computers" -and $_.Type -ne "computer" }} $DeptContainers[4].name {$ComputerOU = Get-QADObject -SearchRoot $DeptContainers[4].DN | ` where { $_.DN -match "Computers" -and $_.Type -ne "computer" }} $DeptContainers[5].name {$ComputerOU = Get-QADObject -SearchRoot $DeptContainers[5].DN | ` where { $_.DN -match "Computers" -and $_.Type -ne "computer" }} $DeptContainers[6].name {$ComputerOU = Get-QADObject -SearchRoot $DeptContainers[6].DN | ` where { $_.DN -match "Computers" -and $_.Type -ne "computer" }} $DeptContainers[7].name {$ComputerOU = Get-QADObject -SearchRoot $DeptContainers[7].DN | ` where { $_.DN -match "Computers" -and $_.Type -ne "computer" }} $DeptContainers[8].name {$ComputerOU = Get-QADObject -SearchRoot $DeptContainers[8].DN | ` where { $_.DN -match "Computers" -and $_.Type -ne "computer" }} $DeptContainers[9].name {$ComputerOU = Get-QADObject -SearchRoot $DeptContainers[9].DN | ` where { $_.DN -match "Computers" -and $_.Type -ne "computer" }} } # Create a computer account for the user if ((get-qadcomputer "$SName-Computer") -eq $null){ New-QADComputer -Name "$SName-Computer" -SamAccountName "$SName-Computer" -ParentContainer ` $ComputerOU -Location "$city $dept" } } $TestQADSnapin = get-pssnapin | where { $_.Name -eq "Quest.ActiveRoles.ADManagement"} if($TestQADSnapin -eq $null){ add-pssnapin -Name Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue } # number of accounts to generate - edit $num = 50 # Read root domain text $RootDomain = Get-QADRootDSE # Read all text data # OU's to create $DeptOUs = @(Get-Content "$ScriptLib\\LabSetup\\Departments.txt") $ChildOUs = @(Get-Content "$ScriptLib\\labsetup\\ous.txt") # read department and city info $cities = Get-Content C:\\scripts\\LabSetup\\Cities.txt $depts = Get-Content C:\\scripts\\LabSetup\\Departments.txt # read name files # randomly select names from census files # Use Joel Bennet's select-random v 2.2; saved in functions.ps1 1..$num | ForEach-Object { $last += @(Get-Content C:\\scripts\\LabSetup\\surnames.txt | select-random) $firstm += @(Get-Content C:\\scripts\\LabSetup\\mgivennames.txt | select-random) $firstf += @(Get-Content C:\\scripts\\LabSetup\\fgivennames.txt | select-random) } # Let's do the work # Create OUs first - call function create-LabOUs # Retrieve all newly created OU DN's for use in next function $DeptContainers = @(Get-QADObject -Type "organizationalUnit" | where {$_.Name -ne "Computers" -and $_.Name ` -ne "Groups" -and $_.Name -ne "Users" -and $_.Description -match "Test Lab Container"}) foreach ($item in $DeptContainers){ $item.description } # Create users, create dept groups 1..$num | ForEach-Object { New-RandomADUser } trap{ Write-Host "ERROR: script execution was terminated.`n" $_.Exception.Message break }
PowerShellCorpus/PoshCode/Bash Aliases.ps1
Bash Aliases.ps1
## Aliases Module, Bash-style aliases with functions function alias { # pull together all the args and then split on = $alias,$cmd = [string]::join(" ",$args).split("=",2) | % { $_.trim()} if($Host.Version.Major -ge 2) { $cmd = Resolve-Aliases $cmd } New-Item -Path function: -Name "Global:Alias$Alias" -Options "AllScope" -Value @" Invoke-Expression '$cmd `$args' ###ALIAS### "@ Set-Alias -Name $Alias -Value "Alias$Alias" -Description "A UNIX-style alias using functions" -Option "AllScope" -scope Global -passThru } function unalias([string]$Alias,[switch]$Force){ if( (Get-Alias $Alias).Description -eq "A UNIX-style alias using functions" ) { Remove-Item "function:Alias$Alias" -Force:$Force Remove-Item "alias:$alias" -Force:$Force if($?) { "Removed alias '$Alias' and accompanying function" } } else { Remove-Item "alias:$alias" -Force:$Force if($?) { "Removed alias '$Alias'" } } } function Get-AliasFor([string]$CommandName) { ls Alias: | ?{ $_.Definition -match $CommandName } } # Export the public functions using Export-ModuleMember cmdlet Export-ModuleMember alias,unalias,Get-AliasFor
PowerShellCorpus/PoshCode/Backup all ESXi_1.ps1
Backup all ESXi_1.ps1
# Change this to where you would like your backups to go. # There is no versioning so backup theses backups with real backup software (e.g. on an SMB share). $backupDir = "c:\\backups" # Get just your ESXi hosts. $esxiHosts = Get-VMHost | Where { $_ | Get-View -Property Config | Where { $_.Config.Product.ProductLineId -eq "embeddedEsx" } } # Back them all up. $esxiHosts | Foreach { $fullPath = $backupDir + "\\" + $_.Name mkdir $fullPath -ea SilentlyContinue | Out-Null Set-VMHostFirmware -VMHost $_ -BackupConfiguration -DestinationPath $fullPath }
PowerShellCorpus/PoshCode/ComObjects.Types.ps1
ComObjects.Types.ps1
<Types> <Type> <Name>System.__ComObject</Name> <Members> <ScriptMethod> <Name>GetProperty</Name> <Script> param([Parameter(Mandatory=$true,Position=1)]$PropertyName) Write-Verbose "PropertyName: $PropertyName" Write-Verbose "Arguments: $($Args | Out-String)" $this.gettype().invokeMember($PropertyName,[System.Reflection.BindingFlags]::GetProperty,$null,$this,@($Args)) </Script> </ScriptMethod> <ScriptMethod> <Name>SetProperty</Name> <Script> param([Parameter(Mandatory=$true,Position=1)]$PropertyName) $this.gettype().invokeMember($PropertyName,[System.Reflection.BindingFlags]::SetProperty,$null,$this,@($Args)) </Script> </ScriptMethod> <ScriptMethod> <Name>InvokeMethod</Name> <Script> param([Parameter(Mandatory=$true,Position=1)]$MethodName) $this.gettype().invokeMember($MethodName,[System.Reflection.BindingFlags]::InvokeMethod,$null,$this,@($Args)) </Script> </ScriptMethod> </Members> </Type> </Types>
PowerShellCorpus/PoshCode/Set-Domain_6.ps1
Set-Domain_6.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-AvaDomain -domain corp.avanade.org -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/ScriptMethod Example.ps1
ScriptMethod Example.ps1
$x = New-Object PSObject | Add-Member -MemberType ScriptMethod -Name Test -Value { param($message=$(Read-Host "Message")) return "This is the message: $message" } -Passthru # You should now call $x.Test("Hello World") # But if you call $x.Test() it will prompt you for the $message value
PowerShellCorpus/PoshCode/70ca48ee-7e54-4a00-bf91-3c77792224ad.ps1
70ca48ee-7e54-4a00-bf91-3c77792224ad.ps1
[void][system.reflection.Assembly]::LoadWithPartialName("MySql.Data") # Open Connection $connStr = "server=127.0.0.1;port=3306;uid=root;pwd=password;database=test;Pooling=False" $conn = New-Object MySql.Data.MySqlClient.MySqlConnection($connStr) $conn.Open() # write the info $sql = "INSERT INTO table1 (name) VALUES ('billy')"; $cmd = New-Object MySql.Data.MySqlClient.MySqlCommand($sql, $conn) $da = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($cmd) # Populate a dataset and output the query result $ds = New-Object System.Data.DataSet # read the info $sql = "SELECT * FROM table1"; $cmd = New-Object MySql.Data.MySqlClient.MySqlCommand($sql, $conn) $da = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($cmd) # Populate a dataset and output the query result $ds = New-Object System.Data.DataSet $da.Fill($ds) > $null $result = $ds.Tables[0] $result | Format-Table id, name -auto
PowerShellCorpus/PoshCode/Join-Objects 3.0.ps1
Join-Objects 3.0.ps1
<# .Synopsis Performs a join of all properties from two objects .Description Joins the properties of two or more objects together to produce a single custom object Support scriptblock evaluation, and joining objects from the pipeline .Example ls | Join-Object { $_ | Select BaseName } { $_.LastWriteTime } #> #Packaged as a script. Uncomment this top and bottom function {...} lines to embed with other functions. #function Join-Object { [CmdletBinding(DefaultParameterSetName="OneTwo")] PARAM( [Parameter(Position=0, Mandatory=$false)] $First , [Parameter(Position=1, Mandatory=$false)] $Second , [Parameter(ValueFromPipeline=$true, Mandatory = $true, ParameterSetName="FromPipeline")] $InputObject , [Switch]$Quiet ) BEGIN { if($First -and $First -isnot [ScriptBlock]) { Write-Verbose "Setting Output = $First" $Out1 = $First [string[]] $p1 = $First | gm -type Properties | select -expand Name $Output = $Out1 | Select $p1 } else { $Output = $null } } PROCESS { if(!$InputObject -and $Second) { $Out2 = $Second } elseif($Second -is [ScriptBlock]) { $Out2 = $InputObject | &$Second } elseif(!$Second) { $Out2 = $InputObject } if($First -is [ScriptBlock]){ $Out1 = $InputObject | &$First [string[]] $p1 = $Out1 | gm -type Properties | select -expand Name $Output = $Out1 | Select $p1 } elseif($First) { [string[]] $p1 = $First | gm -type Properties | select -expand Name $Output = $First | Select $p1 } elseif(!$Output) { Write-Verbose "Initializing Output From Pipeline = $InputObject" [string[]] $p1 = $InputObject | gm -type Properties | select -expand Name $Output = $InputObject | Select $p1 return } else { ## ToDo: this is lazy. Chache it. [string[]] $p1 = $Output | gm -type Properties | select -expand Name } if($Out2) { $p2 = @($Out2 | gm -type Properties | Where { $p1 -notcontains $_.Name } | select -expand Name) Write-Verbose "Merging $($p2.Count) into the output (which already has $(($Output | gm -type NoteProperty).Count) properties)." if(!$Quiet) { [string[]]$ignored = $Out2 | gm -type Properties | Where { $p1 -contains $_.Name } | select -expand Name if($Ignored) { Write-Warning "Ignoring $($ignored.Count) values which are already present:`n$($out2 | fl -Property $ignored | out-string)" } } foreach($p in $p2) { $Output = Add-Member -in $Output -type NoteProperty -name $p -value $Out2.$p -Passthru } } } END { $Output } #}
PowerShellCorpus/PoshCode/WPF PingMonitor for 1.0.ps1
WPF PingMonitor for 1.0.ps1
if(!(Get-Command New-BootsWindow -EA SilentlyContinue)) { Add-PsSnapin PoshWpf #Import-Module PowerBoots #Add-BootsContentProperty 'DataPoints', 'Series' [Void][Reflection.Assembly]::LoadFrom( (Convert-Path (Resolve-Path "~\\Documents\\WindowsPowershell\\Libraries\\WPFVisifire.Charts.dll")) ) #Add-BootsFunction -Assembly "~\\Documents\\WindowsPowershell\\Libraries\\WPFVisifire.Charts.dll" #Add-BootsFunction ([System.Windows.Threading.DispatcherTimer]) } if(Get-Command Ping-Host -EA SilentlyContinue) { $pingcmd = { (Ping-Host $args[0] -count 1 -Quiet).AverageTime } } else { $pingcmd = { [int]([regex]"time=(\\d+)ms").Match( (ping $args[0] -n 1) ).Groups[1].Value } } $global:onTick = { Param($window=$global:pingWindow) Invoke-BootsWindow $window { try { foreach($s in $window.Content.Series.GetEnumerator()) { $ping = &$pingcmd $s.LegendText $points = $s.DataPoints foreach($dp in 0..$($points.Count - 1)) { if(($dp+1) -eq $points.Count) { $points[$dp].YValue = $ping } else { $points[$dp].YValue = $points[$dp+1].YValue } } } } catch { Write-Output $_ } } } function Add-PingHost { PARAM( [string[]]$target , [Visifire.Charts.RenderAs]$renderAs="Line" , [Windows.Window]$window = $global:pingWindow , [Switch]$Passthru ) if($Window) { Invoke-BootsWindow $Window { foreach($h1 in $target) { Add-PingHostInternal $h1 $renderAs $window } } if($Passthru) { return $Window } } else { return New-PingMonitor $target $renderAs -Passthru:$Passthru } } function Add-PingHostInternal { PARAM( [string]$target , [Visifire.Charts.RenderAs]$renderAs="Line" , [System.Windows.Window]$window = $global:pingWindow ) $start = $(get-random -min 10 -max 20) $ds = New-Object Visifire.Charts.DataSeries $ds.LegendText = $target $ds.RenderAs = $renderAs [void]$window.Content.Series.Add($ds) for($i=0;$i -lt 25;$i++) { $dp = New-Object Visifire.Charts.DataPoint $dp.YValue = $start [void]$ds.DataPoints.Add( $dp ) } } function New-PingMonitor { PARAM ( [string[]]$hosts = $(Read-Host "Please enter the name of a computer to ping") , [Visifire.Charts.RenderAs]$renderAs="Line" , [Switch]$Passthru ) $global:pingWindow = New-BootsWindow -Async { Param($window) # New-Boots passes the window to us ... Write-Debug "Window: $window" # Make a timer $timer = New-Object System.Windows.Threading.DispatcherTimer $timer.Interval = "00:00:01.0" # Make a new scriptblock of the OnTick handle, passing it ourselves $tickover = ({ &$global:onTick $window }).GetNewClosure() $timer.Add_Tick( $tickover ) # Stick the timer into the window.... $window.Tag = @($timer, $tickover) # Make a chart $PingChart = New-Object Visifire.Charts.Chart $PingChart.Height = 300 $PingChart.Width = 800 $PingChart.watermark = $false #$PingChart.Add_Initialized( {$timer.Start();} ) # Make a bunch of data series $hosts | % { $h1 = $_ $start = $(get-random -min 10 -max 20) $ds = New-Object Visifire.Charts.DataSeries $ds.LegendText = $h1 $ds.RenderAs = $renderAs $PingChart.Series.Add($ds) for($i=0;$i -lt 25;$i++) { $dp = New-Object Visifire.Charts.DataPoint $dp.YValue = $start $ds.DataPoints.Add( $dp ) } } # we have to output the chart: whatever we output from here ends up in the window $PingChart } -On_ContentRendered { Write-Debug "Content Rendered. Tag: $($this.tag[0])" $this.tag[0].Start() } -On_Closing { $this.tag[0].Remove_Tick($this.tag[1]) $this.tag[0].Stop() $global:pingWindow = $null } -Title "Ping Monitor" -Passthru if($Passthru) { return $global:pingWindow } }
PowerShellCorpus/PoshCode/2dbab092-67c9-4604-993a-656847e35f4b.ps1
2dbab092-67c9-4604-993a-656847e35f4b.ps1
function Run-Script { if ($psISE.CurrentFile.DisplayName.StartsWith("Untitled")) { return } $script = $psISE.CurrentFile.DisplayName $psISE.CurrentFile.Save() $logfile = "$env:programfiles\\Sea Star Development\\" + "Script Monitor Service\\ScriptMon.txt" #Change to suit. if (!(Test-Path env:\\JobCount)) { $env:JobCount = 1 #This will work across multi Tab sessions. } $number = $env:JobCount.PadLeft(4,'0') $startTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss" $tag = "$startTime [$script] start. --> PSE $($myInvocation.Line)" if (Test-Path $logfile) { $tag | Out-File $logfile -encoding 'Default' -Append } "$startTime [$script] started." Write-EventLog -Logname Scripts -Source Monitor -EntryType Information -EventID 2 -Category 002 -Message "Script Job: $script (PSE$number) started." Invoke-Command -Scriptblock { & "$pwd\\$script" } $endTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss" $tag = "$endTime [$script] ended. --> PSE $($myInvocation.Line)" if (Test-Path $logfile) { $tag | Out-File $logfile -encoding 'Default' -Append } "$endTime [$script] ended." Write-Eventlog -Logname Scripts -Source Monitor -EntryType Information -EventID 1 -Category 001 -Message "Script Job: $script (PSE$number) ended." $env:JobCount = [int]$env:JobCount+1 } $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("Run Script",{Run-Script}, "Alt+R") | Out-Null
PowerShellCorpus/PoshCode/Set-OutlookSignature_1.ps1
Set-OutlookSignature_1.ps1
###########################################################################" # # NAME: Set-OutlookSignature.ps1 # # AUTHOR: Jan Egil Ring # # COMMENT: Script to create an Outlook signature based on user information from Active Directory. # Adjust the variables in the "Custom variables"-section # Create an Outlook-signature from an Outlook-client based on your company template (logo, fonts etc) and copy this signature to the path defined in the $SigSource variable # See the following blog-post for more information: http://blog.crayon.no/blogs/janegil/archive/2010/01/09/outlook-signature-based-on-user-information-from-active-directory.aspx # # Tested on Office 2003,2007 and 2010 beta # # You have a royalty-free right to use, modify, reproduce, and # distribute this script file in any way you find useful, provided that # you agree that the creator, owner above has no warranty, obligations, # or liability for such use. # # VERSION HISTORY: # 1.0 09.01.2010 - Initial release # ###########################################################################" #Custom variables $CompanyName = 'Company Name' $DomainName = 'domain.local' $SigVersion = '1.0' #When the version number are updated the local signature are re-created $SigSource = "\\\\$DomainName\\netlogon\\sig_files\\$CompanyName" $ForceSignatureNew = '1' #When the signature are forced the signature are enforced as default signature for new messages the next time the script runs. 0 = no force, 1 = force $ForceSignatureReplyForward = '0' #When the signature are forced the signature are enforced as default signature for reply/forward messages the next time the script runs. 0 = no force, 1 = force #Environment variables $AppData=(Get-Item env:appdata).value $SigPath = '\\Microsoft\\Signatures' $LocalSignaturePath = $AppData+$SigPath #Get Active Directory information for current user $UserName = $env:username $Filter = "(&(objectCategory=User)(samAccountName=$UserName))" $Searcher = New-Object System.DirectoryServices.DirectorySearcher $Searcher.Filter = $Filter $ADUserPath = $Searcher.FindOne() $ADUser = $ADUserPath.GetDirectoryEntry() $ADDisplayName = $ADUser.DisplayName $ADEmailAddress = $ADUser.mail $ADTitle = $ADUser.title $ADTelePhoneNumber = $ADUser.TelephoneNumber #Setting registry information for the current user $CompanyRegPath = "HKCU:\\Software\\"+$CompanyName if (Test-Path $CompanyRegPath) {} else {New-Item -path "HKCU:\\Software" -name $CompanyName} if (Test-Path $CompanyRegPath'\\Outlook Signature Settings') {} else {New-Item -path $CompanyRegPath -name "Outlook Signature Settings"} $ForcedSignatureNew = (Get-ItemProperty $CompanyRegPath'\\Outlook Signature Settings').ForcedSignatureNew $ForcedSignatureReplyForward = (Get-ItemProperty $CompanyRegPath'\\Outlook Signature Settings').ForcedSignatureReplyForward $SignatureVersion = (Get-ItemProperty $CompanyRegPath'\\Outlook Signature Settings').SignatureVersion Set-ItemProperty $CompanyRegPath'\\Outlook Signature Settings' -name SignatureSourceFiles -Value $SigSource $SignatureSourceFiles = (Get-ItemProperty $CompanyRegPath'\\Outlook Signature Settings').SignatureSourceFiles #Forcing signature for new messages if enabled if ($ForcedSignatureNew -eq '1') { #Set company signature as default for New messages $MSWord = New-Object -com word.application $EmailOptions = $MSWord.EmailOptions $EmailSignature = $EmailOptions.EmailSignature $EmailSignatureEntries = $EmailSignature.EmailSignatureEntries $EmailSignature.NewMessageSignature=$CompanyName $MSWord.Quit() } #Forcing signature for reply/forward messages if enabled if ($ForcedSignatureReplyForward -eq '1') { #Set company signature as default for Reply/Forward messages $MSWord = New-Object -com word.application $EmailOptions = $MSWord.EmailOptions $EmailSignature = $EmailOptions.EmailSignature $EmailSignatureEntries = $EmailSignature.EmailSignatureEntries $EmailSignature.ReplyMessageSignature=$CompanyName $MSWord.Quit() } #Copying signature sourcefiles and creating signature if signature-version are different from local version if ($SignatureVersion -eq $SigVersion){} else { #Copy signature templates from domain to local Signature-folder Copy-Item "$SignatureSourceFiles\\*" $LocalSignaturePath -Recurse -Force #Insert variables from Active Directory to rtf signature-file $MSWord = New-Object -com word.application $MSWord.Documents.Open($LocalSignaturePath+'\\'+$CompanyName+'.rtf') ($MSWord.ActiveDocument.Bookmarks.Item("DisplayName")).Select() $MSWord.Selection.Text=$ADDisplayName ($MSWord.ActiveDocument.Bookmarks.Item("Title")).Select() $MSWord.Selection.Text=$ADTitle ($MSWord.ActiveDocument.Bookmarks.Item("TelephoneNumber")).Select() $MSWord.Selection.Text=$ADTelePhoneNumber ($MSWord.ActiveDocument.Bookmarks.Item("EmailAddress")).Select() $MSWord.Selection.Text=$ADEmailAddress ($MSWord.ActiveDocument).Save() ($MSWord.ActiveDocument).Close() $MSWord.Quit() #Insert variables from Active Directory to htm signature-file $MSWord = New-Object -com word.application $MSWord.Documents.Open($LocalSignaturePath+'\\'+$CompanyName+'.htm') ($MSWord.ActiveDocument.Bookmarks.Item("DisplayName")).Select() $MSWord.Selection.Text=$ADDisplayName ($MSWord.ActiveDocument.Bookmarks.Item("Title")).Select() $MSWord.Selection.Text=$ADTitle ($MSWord.ActiveDocument.Bookmarks.Item("TelephoneNumber")).Select() $MSWord.Selection.Text=$ADTelePhoneNumber ($MSWord.ActiveDocument.Bookmarks.Item("EmailAddress")).Select() $MSWord.Selection.Text=$ADEmailAddress ($MSWord.ActiveDocument).Save() ($MSWord.ActiveDocument).Close() $MSWord.Quit() #Insert variables from Active Directory to txt signature-file (Get-Content $LocalSignaturePath'\\'$CompanyName'.txt') | Foreach-Object {$_ -replace "DisplayName", $ADDisplayName -replace "Title", $ADTitle -replace "TelePhoneNumber", $ADTelePhoneNumber -replace "EmailAddress", $ADEmailAddress} | Set-Content $LocalSignaturePath'\\'$CompanyName'.txt' } #Stamp registry-values for Outlook Signature Settings if they doesn`t match the initial script variables. Note that these will apply after the second script run when changes are made in the "Custom variables"-section. if ($ForcedSignatureNew -eq $ForceSignatureNew){} else {Set-ItemProperty $CompanyRegPath'\\Outlook Signature Settings' -name ForcedSignatureNew -Value $ForceSignatureNew} if ($ForcedSignatureReplyForward -eq $ForceSignatureReplyForward){} else {Set-ItemProperty $CompanyRegPath'\\Outlook Signature Settings' -name ForcedSignatureReplyForward -Value $ForceSignatureReplyForward} if ($SignatureVersion -eq $SigVersion){} else {Set-ItemProperty $CompanyRegPath'\\Outlook Signature Settings' -name SignatureVersion -Value $SigVersion}
PowerShellCorpus/PoshCode/MVP PowerShell.ps1
MVP PowerShell.ps1
# (C) 2012 Dr. Tobias Weltner, MVP PowerShell # www.powertheshell.com # you can freely use and distribute this code # we only ask you to keep this comment including copyright and url # as a sign of respect. # more information and documentation found here: # http://www.powertheshell.com/iseconfig/ <# .SYNOPSIS reads one or more settings for the ISE editor .PARAMETER Name Name of setting to read. You can use wildcards. If you do not supply a name, all settings are retrieved. If you do not use wildcards, only the value will be returned. If you do use wildcards, the setting name will also be returned. .EXAMPLE Get-ISESetting MRUCount Reads the maximum number of files in your MRU list .EXAMPLE Get-ISESetting returns all settings .EXAMPLE Get-ISESetting *wind* returns all settings with "wind" in their name #> Function Get-ISESetting { param ( $Name = '*' ) $folder = (Resolve-Path -Path $env:localappdata\\microsoft_corporation\\powershell_ise*\\3.0.0.0).Path $filename = 'user.config' $path = Join-Path -Path $folder -ChildPath $filename [xml]$xml = Get-Content -Path $path -Raw # wildcards used? $wildCard = $Name -match '\\*' # find all settings available with their correct casing: $settings = $xml.SelectNodes('//setting') | Where-Object serializeAs -EQ String | Select-Object -ExpandProperty Name # translate the user-submitted setting into the correct casing: $CorrectSettingName = @($settings -like $Name) # if no setting is found, try with wildcards if ($CorrectSettingName.Count -eq 0) { $CorrectSettingName = @($settings -like "*$Name*") $wildCard = $true } if ($CorrectSettingName.Count -gt 1 -or $wildCard) { $CorrectSettingName | ForEach-Object { $xml.SelectNodes(('//setting[@name="{0}"]' -f $_)) | Select-Object -Property Name, Value } } elseif ($CorrectSettingName.Count -eq 1) { $xml.SelectNodes(('//setting[@name="{0}"]' -f $CorrectSettingname[0])) | Select-Object -ExpandProperty Value } else { Write-Warning "The setting '$SettingName' does not exist. Try one of these valid settings:" Write-Warning ($settings -join ', ') } } <# .SYNOPSIS sets a settings for the ISE editor .PARAMETER Name Name of setting to change. .PARAMETER Value New value for setting. There is no validation. You are responsible for submitting valid values. .EXAMPLE Set-ISESetting MRUCount 12 Sets the maximum number of files in your MRU list to 12 #> Function Set-ISESetting { param ( [Parameter(Mandatory,ValueFromPipelineByPropertyName)] $Name, [Parameter(Mandatory,ValueFromPipelineByPropertyName)] $Value ) Begin { $folder = (Resolve-Path -Path $env:localappdata\\microsoft_corporation\\powershell_ise*\\3.0.0.0).Path $filename = 'user.config' $path = Join-Path -Path $folder -ChildPath $filename [xml]$xml = Get-Content -Path $path -Raw # find all settings available with their correct casing: $settings = $xml.SelectNodes('//setting') | Where-Object serializeAs -EQ String | Select-Object -ExpandProperty Name } Process { # translate the user-submitted setting into the correct casing: $CorrectSettingName = $settings -like $Name if ($CorrectSettingName) { $xml.SelectNodes(('//setting[@name="{0}"]' -f $CorrectSettingName))[0].Value = [String]$Value } else { Write-Warning "The setting '$SettingName' does not exist. Try one of these valid settings:" Write-Warning ($settings -join ', ') } } End { $xml.Save($Path) } } <# .SYNOPSIS adds a new file path to the MRU list or replaces the list with new files .PARAMETER Path Path to add to the list. Can be an array, can be received from the pipeline. .PARAMETER Append Adds the path(s) to the existing list .EXAMPLE Set-ISEMRUList -Path c:\\dummy -Append Adds a new path to the MRU list, keeping the old paths. .EXAMPLE dir $home *.ps1 -recurse -ea 0 | Select-Object -ExpandProperty Fullname | Set-ISEMRUList replaces existing MRU list with the paths to all powershell script files in your profile If the list exceeds the number of entries defined in the ISE setting MruCount, the remainder is truncated. #> Function Set-ISEMRUList { param ( [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)] [String[]] $Path, [Switch] $Append ) Begin { $folder = (Resolve-Path -Path $env:localappdata\\microsoft_corporation\\powershell_ise*\\3.0.0.0).Path $filename = 'user.config' $configpath = Join-Path -Path $folder -ChildPath $filename [xml]$xml = Get-Content -Path $configpath -Raw $PathList = @() } Process { $Path | ForEach-Object { $PathList += $_ } } End { if ($Append) { $PathList += @($xml.SelectNodes('//setting[@name="MRU"]').Value.ArrayOfString.string) } # is list too long? $max = Get-ISESetting -Name MRUCount $current = $PathList.Count if ($current -gt $max) { if (!$Append) { Write-Warning "Your MRU list is too long. It has $current elements but MRUCount is limited to $max elements." Write-Warning "Truncating the last $($current - $max) elements." Write-Warning 'You can increase the size of your MRU list like this:' Write-Warning "Set-ISESetting -Name MRUCount -Value $current" } $PathList = $PathList[0..$($max-1)] } $xml.SelectNodes('//setting[@name="MRU"]').Value.ArrayOfString.InnerXML = $PathList | ForEach-Object { "<string>$_</string>" } | Out-String $xml.Save($configpath) } } <# .SYNOPSIS dumps the current path names in the ISE MRU list .EXAMPLE Get-ISEMRUList dumps the paths to all recently used files in the ISE editor #> Function Get-ISEMRUList { $newfile = 'c:\\somescript.ps1' $folder = (Resolve-Path -Path $env:localappdata\\microsoft_corporation\\powershell_ise*\\3.0.0.0).Path $filename = 'user.config' $path = Join-Path -Path $folder -ChildPath $filename [xml]$xml = Get-Content -Path $path -Raw $xml.SelectNodes('//setting[@name="MRU"]').Value.ArrayOfString.string }
PowerShellCorpus/PoshCode/381c5978-c4cc-421e-9c0f-9ac6d9e14e61.ps1
381c5978-c4cc-421e-9c0f-9ac6d9e14e61.ps1
<# NAME: WLAN-functions.ps1 AUTHOR: Jan Egil Ring EMAIL: jan.egil.ring@powershell.no COMMENT: PowerShell functions to export and import WLAN profiles in Windows Vista/Windows 7 Required version: Windows PowerShell 2.0 (built-in to Windows 7) Usage: Either copy the functions directly into a PowerShell session, or dot-source the script to make the functions available (. .\\WLAN-functions.ps1) For more information, see the following blog-post: http://blog.powershell.no/2011/01/23/export-and-import-wlan-profiles You have a royalty-free right to use, modify, reproduce, and distribute this script file in any way you find useful, provided that you agree that the creator, owner above has no warranty, obligations, or liability for such use. VERSION HISTORY: 1.0 23.01.2011 - Initial release #> function Export-WLAN { <# .SYNOPSIS Exports all-user WLAN profiles .DESCRIPTION Exports all-user WLAN profiles to Xml-files to the specified directory using netsh.exe .PARAMETER XmlDirectory Directory to export Xml configuration-files to .EXAMPLE Export-WLAN -XmlDirectory c:\\temp\\wlan #> [CmdletBinding()] param ( [parameter(Mandatory=$true)] [string]$XmlDirectory ) #Export all WLAN profiles to specified directory $wlans = netsh wlan show profiles | Select-String -Pattern "All User Profile" | Foreach-Object {$_.ToString()} $exportdata = $wlans | Foreach-Object {$_.Replace(" All User Profile : ",$null)} $exportdata | ForEach-Object {netsh wlan export profile $_ $XmlDirectory} } function Import-WLAN { <# .SYNOPSIS Imports all-user WLAN profiles based on Xml-files in the specified directory .DESCRIPTION Imports all-user WLAN profiles based on Xml-files in the specified directory using netsh.exe .PARAMETER XmlDirectory Directory to import Xml configuration-files from .EXAMPLE Import-WLAN -XmlDirectory c:\\temp\\wlan #> [CmdletBinding()] param ( [parameter(Mandatory=$true)] [string]$XmlDirectory ) #Import all WLAN Xml-files from specified directory Get-ChildItem $XmlDirectory | Where-Object {$_.extension -eq ".xml"} | ForEach-Object {netsh wlan add profile filename=($XmlDirectory+"\\"+$_.name)} }
PowerShellCorpus/PoshCode/Security group monitor_1.ps1
Security group monitor_1.ps1
#Get group membership for a list of security #groups and export to an XML for comparison #against baseline. # $script:WorkingDirectory = split-path $myinvocation.Mycommand.Definition -parent Function Re-Baseline { #First, declare array and hashtable. $securitygroups = @() $table = @{} #Import Security Group list from XML and add to "securitygroups" array. $securitygroupsxml = [XML] (gc "$script:WorkingDirectory\\sg.xml") $securitygroups += $securitygroupsxml.objs.S #Get membership for each group foreach($securitygroup in $securitygroups){ $dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() $root = [ADSI] "LDAP://$($dom.Name)" $searcher = New-Object System.DirectoryServices.DirectorySearcher $root $searcher.filter = "(&(objectCategory=group)(objectClass=group)(sAMAccountName=$securitygroup))" $group = $searcher.findone() $table += @{"$securitygroup"= $group.properties.member} } #Export hashtable to XML. So nice. $table | export-clixml $script:WorkingDirectory\\baseline.xml } # #First, declare hashtable. $comparetable = @{} #Import Security Group list from XML and add to "securitygroups" array. $securitygroupsxml = [XML] (gc "$script:WorkingDirectory\\sg.xml") $securitygroups = $securitygroupsxml.objs.S #Get membership for each group and create a compare table. foreach($securitygroup in $securitygroups){ $dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() $root = [ADSI] "LDAP://$($dom.Name)" $searcher = New-Object System.DirectoryServices.DirectorySearcher $root $searcher.filter = "(&(objectCategory=group)(objectClass=group)(sAMAccountName=$securitygroup))" $group = $searcher.findone() $comparetable += @{"$securitygroup"= $group.properties.member} } #Export hashtable to XML. So nice. $comparetable | export-clixml "$script:WorkingDirectory\\compare.xml" #Import baseline XML to hashtable. $baselinetable = @{} $baselinetable += import-clixml "$script:WorkingDirectory\\baseline.xml" #Import baseline XML to hashtable. $comparetable = @{} $comparetable += import-clixml "$script:WorkingDirectory\\compare.xml" #Compare respective Keys and Values for $comparetable against #$baselinetable and get differences. $passtoemailsubuser = @() $passtoemailbody = @() foreach($securitygroup in $securitygroups) { If($comparetable."$securitygroup" -eq $NULL) { If($baselinetable."$securitygroup" -eq $NULL) { (get-date).tostring() + " - Security Group $securitygroup is empty in the compare and the baseline" >> $script:WorkingDirectory\\log.txt } Else { foreach($entry in $baselinetable."$securitygroup") {$passtoemailbody += "`r" + $entry + " " + "`r`r" + "***WAS REMOVED FROM***: " + "`r`r" + $securitygroup + "`r`r"} $passtoemailbody += "`r" + $securitygroup + " " + "`r`r" + "in AD contains no more objects" + "`r`r" (get-date).tostring() + " - $securitygroup in AD contains no more objects" >> $script:WorkingDirectory\\log.txt } } Else { $baseline = @($baselinetable."$securitygroup") $compare = @($comparetable."$securitygroup") $results = Compare-Object $baseline $compare foreach($result in $results){ if (($result.equals.isinstance -eq $true) -and ($result.sideindicator -eq "=>")) {$passtoemailbody += "`r" + $result.inputobject + " " + "`r`r" + "***WAS ADDED TO***: " + "`r`r" + $securitygroup + "`r`r" $user = $result.inputobject $searcher.filter = "(&(objectCategory=person)(objectClass=user)(distinguishedname=$user))" $user = $searcher.FindOne() $passtoemailsubuser += $user.properties.samaccountname $mod = $true } if (($result.equals.isinstance -eq $true) -and ($result.sideindicator -eq "<=")) {$passtoemailbody += "`r" + $result.inputobject + " " + "`r`r" + "***WAS REMOVED FROM***: " + "`r`r" + $securitygroup + "`r`r" $user = $result.inputobject $searcher.filter = "(&(objectCategory=person)(objectClass=user)(distinguishedname=$user))" $user = $searcher.FindOne() $passtoemailsubuser += $user.properties.samaccountname $mod = $true }} } } if ($mod -eq $true) { $from = New-Object System.Net.Mail.MailAddress "from@address.com" $to = New-Object System.Net.Mail.MailAddress "to@address.com" $message = new-object System.Net.Mail.MailMessage $from, $to $message.Subject = "The following accounts were involved in a security group modification: $passtoemailsubuser" $message.Body = "Note the following security group modification information: `r`r $passtoemailbody" $server = "SMTPSERVERNAME" $client = new-object system.net.mail.smtpclient $server $client.port = 125 $client.Send($message) foreach($entry in $passtoemailbody) {(get-date).tostring() + " - " + $Entry >> $script:WorkingDirectory\\Log.txt} (get-date).tostring() + " - Group Membership compare has been baselined" >> $script:WorkingDirectory\\log.txt re-baseline } else { $from = New-Object System.Net.Mail.MailAddress "from@address.com" $to = New-Object System.Net.Mail.MailAddress "to@address.com" $message = new-object System.Net.Mail.MailMessage $from, $to $message.Subject = "No modifications to the audited security groups have been made." $message.Body = "No modifications to the audited security groups have been made." $server = "SMTPSERVERNAME" $client = new-object system.net.mail.smtpclient $server $client.port = 125 $client.Send($message) "No Changes have been made" }
PowerShellCorpus/PoshCode/Email attachments.ps1
Email attachments.ps1
$file = "MYFILE.TXT" $smtpServer = "MYSMTPSERVER.EMAIL.CO.UK" $msg = new-object Net.Mail.MailMessage $att = new-object Net.Mail.Attachment($file) $smtp = new-object Net.Mail.SmtpClient($smtpServer) $msg.From = "FROMME@EMAIL.CO.UK" $msg.To.Add("TOME@EMAIL.CO.UK") $msg.Subject = "MY SUBJECT" $msg.Body = "MY TEXT FOR THE EMAIL" $msg.Attachments.Add($att) $smtp.Send($msg) $att.Dispose()
PowerShellCorpus/PoshCode/Start-IRCJabberBridge.ps1
Start-IRCJabberBridge.ps1
########################################################################################## ## Depends on the PsXmppHelper.dll from http://CodePlex.com/PowerXmpp ## CONTAINS Read-HostMasked http://powershellcentral.com/scripts/104 ## CONTAINS Out-Working http://powershellcentral.com/scripts/105 ########################################################################################## ## NOTICE: THERE IS WAY TOO LITTLE ERROR HANDLING HERE!!!! ## IF EVERYTHING does not go very well, you will likely get very little explanation ## MAKE SURE YOU ARE USING a registered jabber id and password ########################################################################################## ## Read-HostMasked ## See: http://powershellcentral.com/scripts/104 function Read-HostMasked([string]$prompt="Password") { $password = Read-Host -AsSecureString $prompt; $BSTR = [System.Runtime.InteropServices.marshal]::SecureStringToBSTR($password); $password = [System.Runtime.InteropServices.marshal]::PtrToStringAuto($BSTR); [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($BSTR); return $password; } ########################################################################################## ## Out-Working ## See: http://powershellcentral.com/scripts/105 $fore="White"; $back="red"; $work = @( $Host.UI.RawUI.NewBufferCellArray(@("|"),$fore,$back), $Host.UI.RawUI.NewBufferCellArray(@("/"),$fore,$back), $Host.UI.RawUI.NewBufferCellArray(@("-"),$fore,$back), $Host.UI.RawUI.NewBufferCellArray(@("\\"),$fore,$back) ); [int]$script:w = 0; filter out-working($wait=0) { $cur = $Host.UI.RawUI.Get_CursorPosition(); $cur.X = 0; $cur.Y -=1; $Host.UI.RawUI.SetBufferContents($cur,$work[$script:w++]); if($script:w -gt 3) {$script:w = 0 } Start-Sleep -milli $wait $_ } ########################################################################################## ## Start-IrcJabberBridge - an Xmpp script ## Depends on the PsXmppHelper.dll from http://CodePlex.com/PowerXmpp ## function Start-IRCJabberBridge { param ( $From = $( Read-Host "Your Jabber ID" ) ,$Password = $( Read-HostMasked "Password") ,$Message = $( Read-Host "Your Message!" ) ,$To = $( Read-Host "Recipient's Jabber ID" ) ,$Chat = "PowerShell%irc.FreeNode.net@irc.im.flosoft.biz" # An IRC channel to join! ,$ChatNick = "PowerBot" # Your nickname in IRC ,$ChatPassword = $null ) # Set path appropriately... [reflection.assembly]::LoadFrom( "agsXMPP.dll" ) | fl Location, FullName, GlobalAssemblyCache [reflection.assembly]::LoadFrom( "PsXmppHelper.dll" ) | fl Location, FullName, GlobalAssemblyCache $jidSender = New-Object agsxmpp.jid $From $jidChat = New-Object agsxmpp.jid $chat $jidReceiver = New-Object agsxmpp.jid $To $xmpp = New-Object agsxmpp.XmppClientConnection( [string]$jidSender.Server ) ## Use SRV lookups to determine correct XMPP server if different from the server ## portion of your JID. e.g. user@gmail.com, the server is really talk.google.com # $xmpp.AutoResolveConnectServer = $TRUE $xmpp.SocketConnectionType = [agsXMPP.net.SocketConnectionType]::HttpPolling; $xmpp.ConnectServer = "http://im.flosoft.biz:5280/http-poll/"; # Since this function is only used to send a message, we don't care about doing the # normal discovery and requesting a roster. Leave disabled to quicken the login period. $xmpp.AutoAgents = $false $xmpp.AutoRoster = $false # The following switches may assist in troubleshooting connection issues. # If SSL and StartTLS are disabled, then you can use a network sniffer to inspect the XML #$xmpp.UseSSL = $false #$xmpp.UseStartTLS = $false ### SOME CONSTANTS $MSG = "agsXMPP.protocol.client.Message" $ChatMessage = [agsXMPP.protocol.client.MessageType]::chat $GroupMessage = [agsXMPP.protocol.client.MessageType]::groupchat $queue = New-Object PsXmppClient.MessageQueue $xmpp $muc = New-Object agsXMPP.protocol.x.muc.MucManager $xmpp # Connect and wait ... $xmpp.Open($jidSender.User, $Password) while ( !$xmpp.Authenticated ) { Write-Verbose ("{0} - {1}" -f $xmpp.XmppConnectionState, $xmpp.Authenticated ) [Threading.Thread]::Sleep(200) } Write-Verbose ("{0} - {1}" -f $xmpp.XmppConnectionState, $xmpp.Authenticated ) # Set our status so we're visible $xmpp.Show = "chat" $xmpp.Status = "I'm a PowerShell Bot" $xmpp.SendMyPresence() # Join the chat room (the same as "SendMyPresence", except to a MUC) $muc.JoinRoom($jidChat, $ChatNick, $ChatPassword) # Send the initial message $xmpp.Send((New-Object $MSG $jidReceiver, $ChatMessage, $Message)) $counter = 0 " Press any key to continue" while (!$Host.UI.RawUI.KeyAvailable) { foreach ($m in $queue.Messages) { " <{0}> {1}" -f $m.From.Resource, $m.Body if ($m.From.Bare -eq $To) { $xmpp.Send((New-Object $MSG $jidChat, $GroupMessage, $M.Body)) } else { ## "{0}=={1}" -f $m.From.Bare,$To $xmpp.Send((New-Object $MSG $jidReceiver, $ChatMessage, ("<{0}> {1}" -f $m.From.Resource, $m.Body))) } } $counter++ # Every so often, re-broadcast our continued presence # Over http polling, not doing this was causing vanishing problems... if(($counter % 50) -eq 0 ) { $xmpp.SendMyPresence() $muc.JoinRoom($jidChat, $ChatNick) } out-working 100 } $muc.LeaveRoom($jidChat, $ChatNick); $xmpp.Close(); }
PowerShellCorpus/PoshCode/Test-SqlConnection.ps1
Test-SqlConnection.ps1
####################### <# Version History v1.0 - Chad Miller - Initial release #> ####################### function Test-Ping { param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] [string[]]$ComputerName) process { $ComputerName | foreach {$result=Test-Connection -ComputerName $_ -Count 1 -Quiet; new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args=$_;Result=$result;Message=$null}} } } #Test-Ping ####################### function Test-Wmi { param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] [string[]]$ComputerName) process { try { $ComputerName | foreach {$name=$_; Get-WmiObject -ComputerName $name -Class Win32_ComputerSystem -ErrorAction 'Stop' | out-null; new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$true;Message=$null}} } catch { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message="$($_.ToString())"} } } } #Test-Wmi ####################### function Test-Port { param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] [string[]]$ComputerName ,[Parameter(Mandatory=$true)] [int32]$Port) Process { try { $Computername | foreach { $sock = new-object System.Net.Sockets.Socket -ArgumentList $([System.Net.Sockets.AddressFamily]::InterNetwork),$([System.Net.Sockets.SocketType]::Stream),$([System.Net.Sockets.ProtocolType]::Tcp); $name=$_; ` $sock.Connect($name,$Port) new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$true;Message=$null} $sock.Close()} } catch { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message="$($_.ToString())"} } } } #Test-Port ####################### function Test-SMB { param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] [string[]]$ComputerName) process { Test-Port $ComputerName 445 } } #Test-SMB ####################### function Test-SSIS { param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] [string[]]$ComputerName ,[Parameter(Mandatory=$true)] [ValidateSet("2005", "2008")] [string]$Version ) #Note: Unlike the database engine and replication SSIS is not backwards compatible # Once an assembly is loaded, you can unload it. This means you need to fire up a powershell.exe process # and mixing between 2005 and 2008 SSIS connections are not permitted in same powershell process. # You'll need to test 2005 and 2008 SSIS in separate powershell.exe processes Begin { $ErrorAction = 'Stop' if ($Version -eq 2008) { add-type -AssemblyName "Microsoft.SqlServer.ManagedDTS, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" } else { add-type -AssemblyName "Microsoft.SqlServer.ManagedDTS, Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" } } process { $ComputerName | foreach { $name=$_; ` if ((test-SSISService -ComputerName $name).Result) { try { $app = new-object ("Microsoft.SqlServer.Dts.Runtime.Application") $out = $null $app.GetServerInfo($name,[ref]$out) | out-null new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$true;Message=$null} } catch { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message="$($_.ToString())"}} } else { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message='SSIS Not Running'} } } } } #Test-SSIS ####################### function Test-SQL { param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] [string[]]$ServerInstance) process { $ServerInstance | foreach { $name = $ServerInstance; ` $connectionString = "Data Source={0};Integrated Security=true;Initial Catalog=master;Connect Timeout=3;" -f $name $sqlConn = new-object ("Data.SqlClient.SqlConnection") $connectionString try { $sqlConn.Open() new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$true;Message=$null} } catch { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message="$($_.ToString())"} } finally { $sqlConn.Dispose() } } } } #Test-SQL ####################### function Test-AgentService { param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] [string[]]$ComputerName) process { try { $ComputerName | foreach { $name=$_; ` if (Get-WmiObject -Class Win32_Service -ComputerName $name -Filter {Name Like 'SQLAgent%' and State='Stopped'} -ErrorAction 'Stop') { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message=$null} } else { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$true;Message=$null} } } } catch { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message="$($_.ToString())"} } } } #Test-AgentService ####################### function Test-SqlService { param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] [string[]]$ComputerName) process { try { $ComputerName | foreach { $name=$_; ` if (Get-WmiObject -ComputerName $name ` -query "select Name,State from Win32_Service where (NOT Name Like 'MSSQLServerADHelper%') AND (Name Like 'MSSQL%' OR Name Like 'SQLServer%') And State='Stopped'" ` -ErrorAction 'Stop') { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message=$null} } else { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$true;Message=$null} } } } catch { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message="$($_.ToString())"} } } } #Test-SqlService ####################### function Test-SSISService { param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] [string[]]$ComputerName) process { try { $ComputerName | foreach { $name=$_; ` if (Get-WmiObject -Class Win32_Service -ComputerName $ComputerName -Filter {Name Like 'MsDtsServer%' And State='Stopped'} -ErrorAction 'Stop') { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message=$null} } else { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$true;Message=$null} } } } catch { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message="$($_.ToString())"} } } } #Test-SSISService ####################### <# .SYNOPSIS Runs a T-SQL script. .DESCRIPTION Runs a T-SQL script. Invoke-Sqlcmd2 only returns message output, such as the output of PRINT statements when -verbose parameter is specified .INPUTS None You cannot pipe objects to Invoke-Sqlcmd2 .OUTPUTS System.Data.DataTable .EXAMPLE Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -Query "SELECT login_time AS 'StartTime' FROM sysprocesses WHERE spid = 1" This example connects to a named instance of the Database Engine on a computer and runs a basic T-SQL query. StartTime ----------- 2010-08-12 21:21:03.593 .EXAMPLE Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -InputFile "C:\\MyFolder\\tsqlscript.sql" | Out-File -filePath "C:\\MyFolder\\tsqlscript.rpt" This example reads a file containing T-SQL statements, runs the file, and writes the output to another file. .EXAMPLE Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -Query "PRINT 'hello world'" -Verbose This example uses the PowerShell -Verbose parameter to return the message output of the PRINT command. VERBOSE: hello world .NOTES Version History v1.0 - Chad Miller - Initial release v1.1 - Chad Miller - Fixed Issue with connection closing v1.2 - Chad Miller - Added inputfile, SQL auth support, connectiontimeout and output message handling. Updated help documentation v1.3 - Chad Miller - Added As parameter to control DataSet, DataTable or array of DataRow Output type #> function Invoke-Sqlcmd2 { [CmdletBinding()] param( [Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance, [Parameter(Position=1, Mandatory=$false)] [string]$Database, [Parameter(Position=2, Mandatory=$false)] [string]$Query, [Parameter(Position=3, Mandatory=$false)] [string]$Username, [Parameter(Position=4, Mandatory=$false)] [string]$Password, [Parameter(Position=5, Mandatory=$false)] [Int32]$QueryTimeout=600, [Parameter(Position=6, Mandatory=$false)] [Int32]$ConnectionTimeout=15, [Parameter(Position=7, Mandatory=$false)] [ValidateScript({test-path $_})] [string]$InputFile, [Parameter(Position=8, Mandatory=$false)] [ValidateSet("DataSet", "DataTable", "DataRow")] [string]$As="DataRow" ) if ($InputFile) { $filePath = $(resolve-path $InputFile).path $Query = [System.IO.File]::ReadAllText("$filePath") } $conn=new-object System.Data.SqlClient.SQLConnection if ($Username) { $ConnectionString = "Server={0};Database={1};User ID={2};Password={3};Trusted_Connection=False;Connect Timeout={4}" -f $ServerInstance,$Database,$Username,$Password,$ConnectionTimeout } else { $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerInstance,$Database,$ConnectionTimeout } $conn.ConnectionString=$ConnectionString #Following EventHandler is used for PRINT and RAISERROR T-SQL statements. Executed when -Verbose parameter specified by caller if ($PSBoundParameters.Verbose) { $conn.FireInfoMessageEventOnUserErrors=$true $handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] {Write-Verbose "$($_)"} $conn.add_InfoMessage($handler) } $conn.Open() $cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn) $cmd.CommandTimeout=$QueryTimeout $ds=New-Object system.Data.DataSet $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd) [void]$da.fill($ds) $conn.Close() switch ($As) { 'DataSet' { Write-Output ($ds) } 'DataTable' { Write-Output ($ds.Tables) } 'DataRow' { Write-Output ($ds.Tables[0]) } } } #Invoke-Sqlcmd2 ####################### function ConvertTo-Hashtable { param([string]$key, $value) Begin { $hash = @{} } Process { $thisKey = $_.$Key $hash.$thisKey = $_.$Value } End { Write-Output $hash } } #ConvertTo-Hashtable ####################### function Test-DatabaseOnline { param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] [string[]]$ServerInstance) begin { $query = @" SELECT name, DATABASEPROPERTYEX(name,'Status') AS 'Status' FROM sysdatabases WHERE DATABASEPROPERTYEX(name,'Status') <> 'ONLINE' "@ } process { try { $ServerInstance | foreach { $name=$_; ` $ht = Invoke-Sqlcmd2 -ServerInstance $name -Database master -Query $query | ConvertTo-Hashtable -key name -value status if ($ht.count -eq 0) { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$true;Message=$null} } else { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message=$ht} } } } catch { new-object psobject -property @{Test="$($myinvocation.mycommand.name)";Args="$name";Result=$false;Message="$($_.ToString())"} } } } #Test-DatabaseOnline ####################### filter ConvertTo-ComputerName { param ($ServerInstance) if ($_) { $ServerInstance = $_ } $ServerInstance -replace "\\\\.*" } #ConvertTo-ComputerName
PowerShellCorpus/PoshCode/Invoke-Sql.ps1
Invoke-Sql.ps1
<# .SYNOPSIS Runs a T-SQL Query and optional outputs results to a delimited file. .DESCRIPTION Invoke-Sql script will run a T-SQL query or stored procedure and optionally outputs a delimited file. .EXAMPLE PowerShell.exe -File "C:\\Scripts\\Invoke-Sql.ps1" -ServerInstance "Z003\\sqlprod2" -Database orders -Query "EXEC usp_accounts '12445678'" This example connects to Z003\\sqlprod2.Orders and executes a stored procedure which does not return a result set .EXAMPLE PowerShell.exe -File "C:\\Scripts\\Invoke-Sql.ps1" -ServerInstance "Z003\\sqlprod2" -Database orders -Query "SELECT * FROM dbo.accounts" -FilePath "C:\\Scripts\\accounts.txt" -Delimiter "," This example connects to Z003\\sqlprod2.Orders and selects the records from the accounts tables, the data is outputed to a CSV file .NOTES Version History v1.0 - Chad Miller - 12/14/2010 - Initial release IMPORTANT!!! The EventLog source which is set to the application needs to be registered with the Event log: New-EventLog -LogName Application -Source $Application #> param( #ServerInstance is Mandatory! [Parameter(Position=0, Mandatory=$false)] [string]$ServerInstance, #Database is Mandatory! [Parameter(Position=1, Mandatory=$false)] [string]$Database, #Query is Mandatory! [Parameter(Position=2, Mandatory=$false)] [string]$Query, [Parameter(Position=3, Mandatory=$false)] [string]$Application="Invoke-Sql.ps1", [Parameter(Position=4, Mandatory=$false)] [string]$FilePath, [Parameter(Position=7, Mandatory=$false)] [string]$Delimiter="|", #If UserName isn't supplied a trusted connection will be used [Parameter(Position=5, Mandatory=$false)] [string]$UserName, [Parameter(Position=6, Mandatory=$false)] [string]$Password, [Parameter(Position=8, Mandatory=$false)] [Int32]$QueryTimeout=600, [Parameter(Position=9, Mandatory=$false)] [Int32]$ConnectionTimeout=15 ) #This must be run as administrator on Windows 2008 and higher! New-EventLog -LogName Application -Source $Application -EA SilentlyContinue $Error.Clear() ####################### function Invoke-SqlCmd2 { param( [Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance, [Parameter(Position=1, Mandatory=$true)] [string]$Database, [Parameter(Position=2, Mandatory=$true)] [string]$Query, [Parameter(Position=3, Mandatory=$false)] [string]$UserName, [Parameter(Position=4, Mandatory=$false)] [string]$Password, [Parameter(Position=5, Mandatory=$false)] [Int32]$QueryTimeout, [Parameter(Position=6, Mandatory=$false)] [Int32]$ConnectionTimeout ) try { if ($Username) { $ConnectionString = "Server={0};Database={1};User ID={2};Password={3};Trusted_Connection=False;Connect Timeout={4}" -f $ServerInstance,$Database,$Username,$Password,$ConnectionTimeout } else { $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerInstance,$Database,$ConnectionTimeout } $conn=new-object System.Data.SqlClient.SQLConnection $conn.ConnectionString=$ConnectionString $conn.Open() $cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn) $cmd.CommandTimeout=$QueryTimeout $ds=New-Object system.Data.DataSet $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd) [void]$da.fill($ds) Write-Output ($ds.Tables[0]) } finally { $conn.Dispose() } } #Invoke-SqlCmd2 ####################### # MAIN # ####################### if ($PSBoundParameters.Count -eq 0) { get-help $myInvocation.MyCommand.Path -full break } try { $msg = $null $msg += "Application/Job Name: $Application`n" $msg += "Query: $Query`n" $msg += "ServerInstance: $ServerInstance`n" $msg += "Database: $Database`n" $msg += "FilePath: $FilePath`n" Write-EventLog -LogName Application -Source "$Application" -EntryType Information -EventId 12345 -Message "Starting`n$msg" $dt = Invoke-SqlCmd2 -ServerInstance $ServerInstance -Database $Database -Query $Query -UserName $UserName -Password $Password -QueryTimeOut $QueryTimeOut -ConnectionTimeout $ConnectionTimeout if ($FilePath) { if ($dt) { $dt | export-csv -Delimiter $Delimiter -Path $FilePath -NoTypeInformation } else #Query Returned No Output! {Write-EventLog -LogName Application -Source "$Application" -EntryType Warning -EventId 12345 -Message "NoOutput`n$msg" } } Write-EventLog -LogName Application -Source "$Application" -EntryType Information -EventId 12345 -Message "Completed`n$msg" } catch { $Exception = "{0}, {1}" -f $_.Exception.GetType().FullName,$( $_.Exception.Message -replace "'" ) Write-EventLog -LogName Application -Source "$Application" -EntryType Error -EventId 12345 -Message "Error`n$msg`n$Exception" throw }
PowerShellCorpus/PoshCode/New-XVM_9.ps1
New-XVM_9.ps1
Function New-OSCVM { [cmdletbinding()] Param ( [Parameter(Mandatory=$false,Position=1)] [string]$ComputerName=$env:COMPUTERNAME, [Parameter(Mandatory=$true,Position=2)] [string]$Name, [Parameter(Mandatory=$true,Position=3)] [string]$SwitchName, [Parameter(Mandatory=$true,Position=4)] [ValidateSet("NoVHD","ExistingVHD","NewVHD","Differencing")] [string]$VhdType, [Parameter(Mandatory=$false,Position=5)] [hashtable]$Configuration ) DynamicParam { Switch ($VhdType) { "ExistingVHD" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "ByParam" $attributes.Mandatory = $true $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $vhdPath = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("VhdPath", [String], $attributeCollection) $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary $paramDictionary.Add("VhdPath",$vhdPath) return $paramDictionary break } "NewVHD" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "ByParam" $attributes.Mandatory = $false $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $diskType = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("DiskType", [String], $attributeCollection) $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary $paramDictionary.Add("DiskType",$diskType) $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "ByParam" $attributes.Mandatory = $false $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $diskSize = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("DiskSize", [uint64], $attributeCollection) $paramDictionary.Add("DiskSize",$diskSize) return $paramDictionary break } "Differencing" { $attributes = New-Object System.Management.Automation.ParameterAttribute $attributes.ParameterSetName = "ByParam" $attributes.Mandatory = $true $attributeCollection = New-Object -Type System.Collections.ObjectModel.Collection[System.Attribute] $attributeCollection.Add($attributes) $parentVhdPath = New-Object -Type System.Management.Automation.RuntimeDefinedParameter("ParentVhdPath", [String], $attributeCollection) $paramDictionary = New-Object -Type System.Management.Automation.RuntimeDefinedParameterDictionary $paramDictionary.Add("ParentVhdPath",$parentVhdPath) return $paramDictionary } } } Begin { Try { $vmHost = Get-VMHost -ComputerName $ComputerName -ErrorAction:Stop } Catch { $PSCmdlet.ThrowTerminatingError($Error[0]) } $defaultVirtualHardDiskPath = $vmHost.VirtualHardDiskPath } Process { $validConfigNames = "MemoryStartupBytes","BootDevice" $configParams = @() Switch ($VhdType) { "NoVHD" { $newVhdPath = $null } "ExistingVHD" { $newVhdPath = $vhdPath.Value } "NewVhd" { if (-not $diskType.IsSet) {$diskType.Value = "Dynamic"} if (-not $diskSize.IsSet) {$diskSize.Value = 127GB} $newVhdPath = Join-Path -Path $defaultVirtualHardDiskPath -ChildPath "$Name.vhdx" Switch ($diskType.Value) { "Fixed" { $vhdFile = New-VHD -Fixed -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop } "Dynamic" { $vhdFile = New-VHD -Dynamic -SizeBytes $diskSize.Value -Path $newVhdPath -ErrorAction Stop } } } "Differencing" { $newVhdPath = Join-Path -Path $defaultVirtualHardDiskPath -ChildPath "$Name.vhdx" $vhdFile = New-VHD -Differencing -ParentPath $parentVhdPath.Value -Path $newVhdPath -ErrorAction Stop } } if ($vhdFile -ne $null) { $command = "New-VM -ComputerName $ComputerName -Name '$Name' -SwitchName '$SwitchName' -VHDPath '$($vhdFile.Path)'" } else { $command = "New-VM -ComputerName $ComputerName -Name '$Name' -SwitchName '$SwitchName' -NoVHD" } if ($Configuration -ne $null) { foreach ($configName in $Configuration.Keys.GetEnumerator()) { if ($validConfigNames -contains $configName) { $configParams += "-$configName" + " " + $Configuration[$configName] } } $configParams = $configParams -join " " } if ($configParams.Count -eq 0) { $command += " -ErrorAction Stop" } else { $command += " $configParams -ErrorAction Stop" } Try { Invoke-Expression -Command $command } Catch { $PSCmdlet.WriteError($Error[0]) Remove-Item -Path $vhdFile.Path } } End {} }
PowerShellCorpus/PoshCode/finddupe_5.ps1
finddupe_5.ps1
function Get-MD5([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]')) { $stream = $null; $cryptoServiceProvider = [System.Security.Cryptography.MD5CryptoServiceProvider]; $hashAlgorithm = new-object $cryptoServiceProvider $stream = $file.OpenRead(); $hashByteArray = $hashAlgorithm.ComputeHash($stream); $stream.Close(); ## We have to be sure that we close the file stream if any exceptions are thrown. trap { if ($stream -ne $null) { $stream.Close(); } break; } foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }} return [string]$result; } write-host "Usage: finddupe.ps1 <directory/file #1> <directory/file #2> ... <directory/file #N>" $matches = 0 # initialize number of matches for summary. if ($args.count -eq 0) { $files = (dir -recurse | ? {$_.psiscontainer -ne $true})} else {$files = (dir $args -recurse | ? {$_.psiscontainer -ne $true})} if ($files -eq $null) {write-host "No files found." -f red; exit} 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/GET-NewPasswordPlus.ps1
GET-NewPasswordPlus.ps1
Function global:GET-NEWpassword( $Length, $Complexity) { # $Length variable serves a dual Purpose # It assumes nobody wants a tiny password less than # 8 characters so anything less than than it used # to pull up one of 8 predined password templates If ($Length -eq $NULL) { $Length = 0 } # If you're going "100%" random you can provide a second # value which is complexity. # # 1 - just random lowercase letter3 # 3 - is pretty decent (upper/lower/numbers) # 9 - is "Muah hahaahahahahah!!!" If ($Complexity -eq $NULL) { $Complexity = 3 } # If password Length provided is less than eight # Function will use one of 8 predefined templates # Default Settings 8 Character SemiPronouncable Password from a previous # password generator on Poshcode.org # # These are predinable password sets, as long as you like, max *8* # C = Upper Case Consanant # c = Lower Case Consanant # L = Upper Case Alphabet # l = Lower Case Alphabet # D = Decimal numbers # h = Hexidecimal series with Lowercase a-f # H = Hexidecimal series with Uppercase A-F # * = Any defined character in the sets $passwordTemplateList=,"Cvcvcdd." $passwordTemplateList+=,"CvCddvVc" $passwordTemplateList+=,"********" $passwordTemplateList+=,"CccddVvv" $passwordTemplateList+=,"HHHHHHHH" $passwordTemplateList+=,"d.d.d.d." $passwordTemplateList+=,"dddddddd" $passwordTemplateList+=,"0V0cC.0C" $PasswordTemplate=$NULL # All character sets are part of a single Dynamic Array which you # can easily add to #Lowercase $AsciiArray=,("l","abcdefghijklmnopqrstuvwxyz") #Uppercase $AsciiArray+=,("L","ABCDEFGHIJKLMNOPQRSTUVWXYZ") #Decimal Numbers $AsciiArray+=,("d","0123456789") #Punctuation $AsciiArray+=,(".","!#$%'()*+,-./:;=>?@[]^_") #Lowercase Vowels $AsciiArray+=,("v","aeiou") #Uppercase Vowels $AsciiArray+=,("V","AEIOU") #HexadecimalNumbers (lowercase on the a-f) $AsciiArray+=,("h","0123456789abcdef") #HexadecimalNumbers (UPPERCASE on the A-F) $AsciiArray+=,("H","0123456789ABCDEF") #Lowercase Consonants $AsciiArray+=,("c","abcdfghjklmnpqrstvwxyz") #Uppercase Consonants $AsciiArray+=,("C","ABCDFGHJKLMNPQRSTVWXYZ") # This variable is important. If you ADD to the Array # It checks the size for all of the calculations below # First Character in the Array such as l,L,d,v etc # identifies the contents of that row of the array # such as lowercaseletter, UPPERCASELETTER, Decimalnumber # vowel $Arraysize=($AsciiArray.Length)-1 # Here is part of the magic # # If we have a password length less than 8 supplied # from the parameter, we will call up one of 8 # predefined templates and use THAT format for # the password. # If ($Length -lt 8) { $PasswordTemplate = $PasswordTemplateList[$Length]; $Complexity = $Arraysize } # # Otherwise it is a large password and we will build # A Pseudo template where each character is our "*" # wildcard Else { Foreach ($count in 1..$Length) { $PasswordTemplate+="*" } } # Blank out the new Password for good measure, JUST CUZ! $NewPassword=$NULL # First loop. Look at and ACT upon each character in the template # to produce the appropriate content for that position in the # password Foreach ( $item in 0..(($passwordTemplate.Length)-1) ) { $Asciiset = $passwordtemplate[$item] # Here is our second loop. We're going to match the Type of # Character being used against the master list in the array # When found, we use that set # Special scenario. If we're doing a "Wildcard" "*" then we have to pick # a random set from the Array to be able to pick a random character If ($AsciiSet -eq "*"){ $Asciiset=$AsciiArray[(GET-RANDOM $Complexity)][0]} $Arraypos=0 # While the two don't match, keep checking the sets. while ([byte][char]$AsciiSet -ne [byte][char]($AsciiArray[$Arraypos][0])){$Arraypos++} # $Arraypos holds the correct set. Pull out the String of Characters # Get the length of the array, and use GET-RANDOM to pick a byte $String=$AsciiArray[$ArrayPos][1] $StringLength=$String.Length # Now add that to the password $NewPassword+=$String.substring((GET-RANDOM $StringLength),1) # End of loop - this goes on until the password is built } # this line doesn't work in Windows XP natively, but you can download a utility # called "ToClip" that does the same thing. REplace "Clip" with "ToClip" # http://www.fullspan.com/proj/toclip/index.html # # Send the password to the Clipboard $NewPassword | clip # Return the password in Plaintext and as Secure-String Return $NewPassword, (CONVERTTO-Securestring $NewPassword -asplaintext -force) }
PowerShellCorpus/PoshCode/ESXiMgmt module sample 1.ps1
ESXiMgmt module sample 1.ps1
####################################################################################################################### # File: ESXiMgmt_machines_generation_sample.ps1 # # Author: Alexander Petrovskiy # # Publisher: Alexander Petrovskiy, SoftwareTestingUsingPowerShell.WordPress.Com # # Copyright: © 2011 Alexander Petrovskiy, SoftwareTestingUsingPowerShell.WordPress.Com. All rights reserved. # # Prerequisites: The module was tested with Vmware ESXi 4.1 U1 on the server side and # # Vmware PowerCLI 4.1 U1 # # plink.exe 0.60.0.0 # # Usage: To load this module run the following instruction: # # Import-Module -Name ESXiMgmt -Force # # Please provide feedback in the SoftwareTestingUsingPowerShell.WordPress.Com blog. # ####################################################################################################################### param([string]$Server, [string]$User, [string]$Password, [string]$DatastoreName, [string]$Drive, [int]$MachinesNumber, [string]$MachinePrefix, [int]$OperationTimeout ) # USAGE: .\\ESXiMgmt_machines_generation_sample.ps1 192.168.1.1 root 123 datastore3 host1ds3 100 XPSP2_ 300 cls Set-StrictMode -Version Latest Import-Module ESXiMgmt -Force; Connect-ESXi -Server $Server -Port 443 ` -Protocol HTTPS -User $User -Password $Password ` -DatastoreName $DatastoreName -Drive $Drive; # This is to test can or can't plink.exe connect to your server # The answer you need to select in case it questions is obviously Yes. Invoke-ESXiCommand -Server $Server ` -User $User -Password $Password ` -Command 'ls ~; sleep 10s; exit;' -PathToPlink 'C:\\VMTests\\plink.exe' ` -ShowWindow $true -OperationTimeout 10; New-ESXiVMs -TemplateVMName 'template XP SP2 Sv 2' -Count $MachinesNumber ` -Logname "C:\\VMTests\\xpsp2\\100.txt" -NewVMName $MachinePrefix ` -BasePath 'C:\\VMTests\\xpsp2' -OperationTimeout $OperationTimeout;
PowerShellCorpus/PoshCode/VM Performance Report.ps1
VM Performance Report.ps1
<# .SYNOPSIS The script creates an HTML report for given vSphere VM's, that contains VM performance data over a given period. The script then emails the report to a given address. .DESCRIPTION The script requires an input file, supplied as an argument to the script. The first line of this file contains an email address, subsequent lines contain VM names, one per line. The script connects to vCenter, queries for given performance stats (get-stat) and then generates a HTML report, which is then emailed to the recipient. The script can be scheduled via scheduled tasks (when supplied with a credential file for vCenter created with http://poshcode.org/3487) or run interactively. .NOTES File Name : Get-VMPeformanceReport.ps1 Author : Samuel Mulhearn Version History: Version 1.0 28 Jun 2012. Release .LINK http://poshcode.org/3485 .EXAMPLE Call the script with a single argument which should be the path to the input file .\\Get-VMPeformanceReport.ps1 <path\\datafile.txt> #> #Change These Values $VC = "vm-trb-vc02.th.local" #VirtualCenter $SMTPServer = "10.247.50.25" #SMTP Server $SendersAddress = "noreply@tribalgroup.com" #The report comes from this address $SavedCredentialsFile = "C:\\path\\file.txt" #Make this file using http://poshcode.org/3487 $CompanyLogo = "http://placehold.it/150x50" function Out-LogFile { #Log File Function http://poshcode.org/3232 [CmdletBinding(DefaultParameterSetName='Message')] param( [Parameter(ParameterSetName='Message', Position=0, ValueFromPipeline=$true)] [object[]]$Message, [Parameter(ParameterSetName='Message')] [string]$LogFile = $global:DefaultLogPath, [Parameter(ParameterSetName='Message')] [int]$BlankLine = 0, [switch]$WriteHost = $global:WriteHostPreference, [string]$Severity = "I", [Parameter(ParameterSetName='Message')] [switch]$DontFormat, [Parameter(ParameterSetName='Message')] [string]$DateFormat = "dd-MM-yyyy HH:mm:ss", #[Parameter(ParameterSetName='Title',Position=0,Mandatory=$true)] [string]$Title, [System.ConsoleColor]$ForegroundColor = $host.UI.RawUI.ForegroundColor, [System.ConsoleColor]$BackgroundColor = $host.UI.RawUI.BackgroundColor, [ValidateSet('unicode', 'utf7', 'utf8', 'utf32', 'ascii', 'bigendianunicode', 'default', 'oem')] [string]$Encoding = 'Unicode', [switch]$Force ) begin { Write-Verbose "Log File: $LogFile" if ( -not $LogFile ) { Write-Error "The -LogFile parameter must be defined or $global:LogFile must be set."; break} if ( -not (Test-Path $LogFile) ) { New-Item -Path $LogFile -ItemType File -Force | Out-Null } if ( -not (Test-Path $LogFile) ) { Write-Error "Log file can not be found: $LogFile."; break} if ( $Title ) { $text = $Title $Title = $null Out-LogFile -BlankLine 1 -LogFile $LogFile -WriteHost:$WriteHost -Force:$Force -Encoding $Encoding Out-LogFile -Message $text -BlankLine 1 -DontFormat -LogFile $LogFile -WriteHost:$WriteHost -Force:$Force -Encoding $Encoding } } process { if ( $Message ) { $text = $Message foreach ( $text in $Message ) { if ( -not $DontFormat ) { $text = "$(($Severity).ToUpper()): $(Get-Date -Format `"$DateFormat`")" + ": $text" } if ($WriteHost) { Write-Host $text -BackgroundColor $BackgroundColor -ForegroundColor $ForegroundColor} $text | Out-File -FilePath $LogFile -Force:$Force -Encoding $Encoding -Append } } if ( $BlankLine -gt 0 ){ for ($i = 0; $i -lt $BlankLine; $i++ ) { "" | Out-File -FilePath $LogFile -Force:$Force -Encoding $Encoding -Append if ($WriteHost) { Write-Host "" -BackgroundColor $BackgroundColor -ForegroundColor $ForegroundColor } } } } end { } } #end of logfile function #New Line Variable $nl = [Environment]::NewLine #INTERACTIVE: (Prompt for password) Replace code below with: $VCCred = (Get-Credential) #NONE-INTERACTIVE: Store password in a file (using http://poshcode.org/3487), and retrive as below $key = [byte]57,86,59,11,72,75,18,52,73,46,0,21,56,76,47,12 #Must match key used to save password (http://poshcode.org/3487) $VCCred = Import-Csv $SavedCredentialsFile #Make this file using http://poshcode.org/3487 $VCCred.Password = ($VCCred.Password| ConvertTo-SecureString -Key $key) $VCCred = (New-Object -typename System.Management.Automation.PSCredential -ArgumentList $VCCred.Username,$VCCred.Password) #Get Datafile, this wil contain VM's to report on, and an email address to send the report to #Datafile format: first line is email address, subsequent lines are VM's, one per line) if ($args[0] -eq $null) #Test Datafile was supplied as argument to the script, if not error! { Throw "No datafile supplied, supply path to datafile as an argument to the script! e.g .\\SCRIPT.ps1 DATAFILE.txt $nl To create a datafile, the first line of the datafile should be an email address, each subseqenet line should be a VM (one per line)" #$Datafile = "C:\\Path\\datain.txt" #If debugging uncomment this line and comment above to supply a fixed input file } else { $Datafile = $args[0] } #From Datafile, get a log file, and a $LogFile = (($DataFile).SubString(0,(($Datafile).length - 3))) + "log" $Outfile = (($DataFile).SubString(0,(($Datafile).length - 3))) + "htm" $global:WriteHostPreference = $true $global:DefaultLogPath = $LogFile Out-LogFile -Message "Starting script with $datafile" #Load PowerCLI if ( (Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null ) { Add-PsSnapin VMware.VimAutomation.Core } If (!(Get-PSSnapin -Name VMware.VimAutomation.Core)) {Out-LogFile -Message "Failed to load PowerCLI Snap-in. Check PowerCLI is installed." -Severity "E" Exit(1) } #Static HTML $HTMLPreString=@" <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="http://current.bootstrapcdn.com/bootstrap-v204/css/bootstrap-combined.min.css"> <style type="text/css"> body { padding: 20px; } h2 { color: #3A87AD; } .mytable { width: 776px; margin: 12px; } .alert-info { color: #3A87AD; background-color: #D9EDF7; border-color: #BCE8F1; padding: 8px 8px 8px 14px; margin-top: 12px; margin-left: 12px; margin-right: 12px; margin-bottom: 12px; border: 1px solid; border-radius: 4px; } .chart_wrap { width: 800px; border-style:solid; border-width:1px; border-color: #DDDDDD; margin: 0px 0px 10px 0px; } .chart { text-align: center; width: 800px; height: 400px; } </style> <title> Virtual Machine Performance statistics </title> <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript"> google.load('visualization', '1', {packages: ['corechart']}); </script> "@ $HTMLPreString += "$nl" $HTMLBodyBegin ="<body style=`"font-family: Arial;border: 0 none;`"> $nl" $HTMLBodyBegin += "<img src=`"$CompanyLogo`" alt=`"Company Logo`" /> $nl" $HTMLBodyBegin += "<h2>Performance Statistics</h2>$nl" $HTMLPostString=@" <script src= "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script src="http://current.bootstrapcdn.com/bootstrap-v204/js/bootstrap.min.js"</script> <script src="http://current.bootstrapcdn.com/bootstrap-v204/js/bootstrap-tab.js"</script> </body> </html> "@ #Functions for dynamic HTML Function Get-DataTable ($Statistics, $UID, $Summation = $false, $Title) { #https://developers.google.com/chart/interactive/docs/examples#custom_table_example $mystring = "<script type=`"text/javascript`">$nl" $mystring += "function drawVisualization$UID() {$nl" $mystring += "// Create and populate the data table. $nl" $mystring += "var " + "$UID" + "data = new google.visualization.DataTable();$nl" $mystring += "$UID" + "data.addColumn('datetime', 'Time');$nl" $VMs | % {$mystring += "$UID" + "data.addColumn('number', '$_');$nl"} $mystring += "$UID" + "data.addRows(" + $Statistics.Count + ");$nl" $ColumnCount = 0 $RowCount = 0 $Statistics | % { $ColumnCount = 0 $formatteddate = [datetime]::ParseExact(([string]$_.Name),"dd/MM/yyyy H:mm:ss",$null) $JSMonth = (($formatteddate.ToString("MM"))-1) #Javascript Months are base 0 (Jan = 0) $formatteddate = $formatteddate.ToString("yyyy, $JSMonth, dd, HH, mm") $formatteddate = "new Date($formatteddate)" $mystring += "$UID" + "data.setCell($RowCount, $ColumnCount, $formatteddate);$nl" $_.Group | % { $ColumnCount = 0 foreach ($VM in $VMs) { $ColumnCount += 1 If ($_.Entity.Name -eq $VM ) { if ($Summation -eq $true) { $strPercent = (( $_.Value / ( $_.IntervalSecs * 1000)) * 100) #http://kb.vmware.com/kb/2002181 $strPercent = [system.math]::round($strPercent,2) $mystring += "$UID" + "data.setCell($RowCount, $ColumnCount, " + $strPercent + ");$nl" } else { $mystring += "$UID" + "data.setCell($RowCount, $ColumnCount, " + $_.Value + ");$nl" } } } } $RowCount += 1 } $mystring += "$nl new google.visualization.LineChart(document.getElementById('visualization" + "$UID" +"')).$nl" $VisParam = "` { ` legend: {position: 'in',alignment:`"center`"}, ` lineWidth:`"2`", ` curveType: `"none`",` chartArea:{left:60,top:40,width:`"90%`",height:`"75%`"},` focusTarget:`"category`", ` hAxis: {slantedText:`"true`", format:`"E, d MMM`"},` vAxis: {textPosition:`"out`"},` width: 800, ` height: 400, ` title:`"$Title`"}" $mystring += "draw(" + "$UID" + "data, $VisParam);$nl" $mystring +="}$nl" $mystring += "google.setOnLoadCallback(drawVisualization" + "$UID" + ");$nl</script>$nl" return $mystring } function Get-DivHTML ($UID, $Notes) { $tempHTML = "<div class=`"tab-pane fade`" id=`"$UID`">$nl" $tempHTML += " <div class=`"chart_wrap`">$nl" $tempHTML += " <div id=`"visualization" + "$UID" + "`" class=`"chart`"></div>$nl" $tempHTML += " <div class=`"alert alert-info`"><strong>Information: </strong>$Notes</div>$nl" $tempHTML += " </div>$nl" $tempHTML += "</div>$nl" return $tempHTML } #Main Code #Process datafile, get VM's to report on, and an email address to send the report to $DataTable = @(Get-Content $Datafile) $email = $DataTable[0] $VMs = @($DataTable[1..($DataTable.Count)]) #Connect to VC Set-PowerCLIConfiguration -InvalidCertificateAction:Ignore -DefaultVIServerMode:Single -Confirm:$false|Out-Null if ((Connect-VIServer $VC -Credential $VCCred) -eq $null) #Connect to vCenter, exit if fails. { Out-LogFile -Message "Failed to connect to vCenter ($VC)" -Severity "E" -WriteHost Exit (1) } else {Out-LogFile -Message "Connected to vCenter ($VC)"} #Validate VM's exist $VCVMs = (get-vm -name $VMs -ErrorAction SilentlyContinue) $VMs | % { $tmpvm = $_ $Exists = $false $VCVMs | % { if ($_.Name -eq $tmpvm) {$Exists = $true}} If ($Exists){ Out-LogFile -Message "$_ found in vCenter inventory" } Else { Out-LogFile -Message "$_ not found in vCenter inventory" -Severity "W" $VMs = $VMs |? {$_ -ne $tmpvm} } } #To add new Stat #1. Add stat to $metrics (use Get-VM | GetStatType to find new metrics) #2. Create a Variable To hold new stats, $MyVariabe = ($Stats | Where-Object {$_.MetricId -eq $metrics[X]} | Sort-Object TimeStamp |Group-Object -Property Timestamp) #3. Invent a new UID - MyUID ? #4. Build Datatable, add code: $HTMLOut += (Get-DataTable -Statistics $MyVariable -UID "MyUID" -Title "Graph Title") #5. Edit static Tabs HTML below, within <ul class="nav nav-tabs"> add a new <li> - eg: <li><a href="#MyUID" data-toggle="tab">Tab Title</a></li> #6. Add a new Get-DivHTML - eg. $HTMLOut += (Get-DivHTML -UID "MyUID" -Notes "Some notes below the chart") #Start and Finish times $todayMidnight = (Get-Date -Hour 0 -Minute 0 -Second 0).AddMinutes(-1) $metrics = "cpu.usagemhz.average","mem.usage.average","disk.usage.average","net.usage.average","cpu.ready.summation","mem.vmmemctl.average" $start = $todayMidnight.AddDays(-7) #If changed consider changing hAxis.format in $VisParam to include the time. https://developers.google.com/chart/interactive/docs/gallery/linechart $finish = $todayMidnight $startstring = $start.ToString("dddd, dd MMMM yyyy HH:mm") $finishstring = $finish.ToString("dddd, dd MMMM yyyy HH:mm") Out-LogFile -Message "Getting stats from vCenter" #Variable for all stats combined $Stats = Get-Stat -Entity $vms -Stat $metrics -Start $start -Instance "" -Finish $finish -IntervalSecs "1800" #Instance "" accounts for machines with multiple CPU's or NICS, gets machine average Out-LogFile -Message "Got stats from vCenter" Out-LogFile -Message "Sorting and filtering stats" #Split stats out by each indivial metric into individual variable $CPU = ($Stats | Where-Object {$_.MetricId -eq $metrics[0]} | Sort-Object TimeStamp |Group-Object -Property Timestamp) $Memory = ($Stats | Where-Object {$_.MetricId -eq $metrics[1]} | Sort-Object TimeStamp |Group-Object -Property Timestamp) $Disk = ($Stats | Where-Object {$_.MetricId -eq $metrics[2]} | Sort-Object TimeStamp |Group-Object -Property Timestamp) $Net = ($Stats | Where-Object {$_.MetricId -eq $metrics[3]} | Sort-Object TimeStamp |Group-Object -Property Timestamp) $Ready = ($Stats | Where-Object {$_.MetricId -eq $metrics[4]} | Sort-Object TimeStamp |Group-Object -Property Timestamp) $Balloon = ($Stats | Where-Object {$_.MetricId -eq $metrics[5]} | Sort-Object TimeStamp |Group-Object -Property Timestamp) #Creates HTML inside of <head> for javascript for the charts Out-LogFile -Message "Creating HTML" $HTMLOut = $HTMLPreString + (Get-DataTable -Statistics $CPU -UID "CPU" -Title "CPU (MHz)") $HTMLOut += (Get-DataTable -Statistics $Memory -UID "Memory" -Title "Memory (%)") $HTMLOut += (Get-DataTable -Statistics $Disk -UID "Disk" -Title "Disk Activity (KBps)") $HTMLOut += (Get-DataTable -Statistics $Net -UID "Net" -Title "Network I/O (KBps)") $HTMLOut += (Get-DataTable -Statistics $Ready -UID "Ready" -Summation $true -Title "CPU Wait Time (%)") $HTMLOut += (Get-DataTable -Statistics $Balloon -UID "Balloon" -Summation $true -Title "Memory allocated to the balloon driver (KB)") $HTMLOut += "</head>$nl" $HTMLOut += $HTMLBodyBegin + $nl #Navigation Tabs... #Edit below to add a tab, when adding a new metric $HTMLOut += @" <div id="content"> <ul class="nav nav-tabs"> <li class="active"><a href="#Info" data-toggle="tab">Information</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">CPU<b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="#CPU" data-toggle="tab">CPU Usage</a></li> <li><a href="#Ready" data-toggle="tab">CPU Wait Time</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Memory<b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="#Memory" data-toggle="tab">Memory Usage</a></li> <li><a href="#Balloon" data-toggle="tab">Memory Balloon</a></li> </ul> <li> <li><a href="#Disk" data-toggle="tab">Disk</a></li> <li><a href="#Net" data-toggle="tab">Network</a></li> </ul> <div id="my-tab-content" class="tab-content"> <div class="tab-pane fade in active" id="Info"> <div class="chart_wrap"> <div class="alert alert-info"> <strong>Information: </strong> "@ #Info for fist tab $HTMLOut += "Each datapoint represents resource consumption since the last datapoint ` and its value is either an average, maximum, or summation of all usage in that interval. ` Any values that are zero may actually be zero, or may indicate statistics were not ` collected over that period (for example, if a virtual machine was powered off). $nl ` The statistics displayed are from $startstring to $finishstring</div>$nl" #Table that contains VM resource config & limits. $HTMLOut += "<table class=`"mytable table table-striped table-bordered`"><thead><tr><td>VM Name</td><td>Number of CPU's</td><td>Memory (MB)</td><td>CPU Limit</td><td>Memory Limit</td></tr></thead>$nl<tbody>$nl" $VCVMs | % { $tmpname =$_.Name $tmpNumCpu = $_.NumCpu $TmpMemoryMB = $_.MemoryMB $tmpCPULimit = $_.VMResourceConfiguration.CPULimitMhz.ToString().Replace("-1","None") $tmpMemLimit = $_.VMResourceConfiguration.MemLimitMB.ToString().Replace("-1","None") $HTMLOut += " <tr><td>$tmpname</td><td>$tmpNumCpu</td><td>$TmpMemoryMB</td><td>$tmpMemLimit</td><td>$tmpCPULimit</td></tr>$nl" } $HTMLOut += "</tbody></table>$nl" $HTMLOut +=@" </div> </div> "@ #Div elements that contain each chart $HTMLOut += (Get-DivHTML -UID "CPU" -Notes "Average CPU usage, as measured in megahertz, during the interval") $HTMLOut += (Get-DivHTML -UID "Memory" -Notes "Average memory usage as percentage of total configured or available memory") $HTMLOut += (Get-DivHTML -UID "Disk" -Notes "Average disk activity (combinded read & write) in KBps") $HTMLOut += (Get-DivHTML -UID "Net" -Notes "Average network utilization (combined transmit and receive rates) during the interval") $HTMLOut += (Get-DivHTML -UID "Ready" -Notes "The percentage of time that the virtual machine was ready, but could not get scheduled to run on the physical CPU. Values of less than 10% are considered normal") $HTMLOut += (Get-DivHTML -UID "Balloon" -Notes "Amount of memory allocated by the virtual machine memory control driver (vmmemctl), which is installed with VMware Tools. This value should remain at 0 or close to 0") $HTMLOut += @" </div> </div> </div> "@ $datenow = Get-Date -Format "F" $HTMLOut += "<h6>Report generated at $datenow<h6>$nl" $HTMLOut += $HTMLPostString #Finished HTML Out-LogFile -Message "Finished building HTML, writing to $Outfile" $HTMLOut | Out-File -FilePath $Outfile -Encoding "UTF8" #Build Email $body =@" <P>Performance statistics for the Virtual Machines listed below are attached</p> "@ $body += "<p>Statistics are from $startstring to $finishstring<p>" $VMs | % {$body+= "<li>$_</li>" } Out-LogFile -Message "Sending email. Email:$email. SMTP Server:$SMTPServer" #Send email Send-MailMessage -Attachments $Outfile -Body "$body" -BodyAsHtml:$true -Subject "Performance Statistics" -To $email -From $SendersAddress -SmtpServer $SMTPServer Disconnect-VIServer -Confirm:$false Out-LogFile -Message "Disconnected from vCenter" Out-LogFile -Message "Finished"
PowerShellCorpus/PoshCode/Wireless Signal Strength.ps1
Wireless Signal Strength.ps1
# Wireless Statistics into object # Author: Josh Popp # Put Wireless Stats, like Signal Strengh, BSSID, and Channel into an object # First just dump the netsh output into $wlanraw $wlanraw = netsh wlan show interface # Create the object as "empty" $objWLAN = "" | Select-Object Name,SSID,BSSID,Channel,ReceiveRate,TransmitRate,Signal # Populate the object from the output, processing 1 line at a time ForEach ($Line in $wlanraw) { if ([regex]::IsMatch($Line," Name")) { $objWLAN.Name = $Line -Replace " Name : ","" } if ([regex]::IsMatch($Line," SSID")) { $objWLAN.SSID = $Line -Replace" SSID : ","" } if ([regex]::IsMatch($Line," BSSID")) { $objWLAN.BSSID = $Line -Replace" BSSID : ","" } if ([regex]::IsMatch($Line," Channel")) { $objWLAN.Channel = $Line -replace " Channel : ","" } if ([regex]::IsMatch($Line," Receive rate")) { $objWLAN.ReceiveRate = $Line -replace " Receive rate \\(Mbps\\) : ","" } if ([regex]::IsMatch($Line," Transmit rate")) { $objWLAN.TransmitRate = $Line -replace " Transmit rate \\(Mbps\\) : ","" } if ([regex]::IsMatch($Line," Signal")) { $objWLAN.Signal = $Line -replace " Signal : ","" } }
PowerShellCorpus/PoshCode/Send-Growl 3.1.ps1
Send-Growl 3.1.ps1
## This is the first version of a Growl module (just dot-source to use in PowerShell 1.0) ## v 1.0 supports a very simple notice, and no callbacks ## v 2.0 supports registering multiple message types ## supports callbacks ## v 2.1 redesigned to be a module used from apps, rather than it's own "PowerGrowler" app ## v 3.0 Make it a v2-only PowerShell module ## v 3.1 fixes for PowerShell 2 RTM ## TODO: ## * Test sending notices to other PCs directly Set-StrictMode -Version 2 ## this is just a default now, you'll have opportunities to override it... $script:appName = "PowerGrowler" [Reflection.Assembly]::LoadFrom("$(Split-Path (gp HKCU:\\Software\\Growl).'(default)')\\Growl.Connector.dll") | Out-Null if(!(Test-Path Variable:Global:PowerGrowlerNotices)) { $global:PowerGrowlerNotices = @{} } ## We can safely recreate this, it doesn't store much $script:PowerGrowler = New-Object "Growl.Connector.GrowlConnector" function Register-GrowlType { #.Synopsis # Register a new Type name for growl notices from PowerGrowl #.Description # Creates a new type name that can be used for sending growl notices #.Parameter AppName # The name of the application you want to register as #.Parameter Name # The type name to be used sending growls #.Parameter DisplayName # The test to use for display (defaults to use the same value as the type name) #.Parameter Icon # Overrides the default icon of the message (accepts .ico, .png, .bmp, .jpg, .gif etc) #.Parameter MachineName # The name of a remote machine to register remotely instead of locally. #.Parameter Priority # Overrides the default priority of the message (use sparingly) #.Example # Register-GrowlType "PoshTwitter" "Command Completed" # # Registers the type "Command Completed," using the default icon, for sending notifications to the local PC # PARAM( [Parameter(Mandatory=$true,Position=0)] [String]$AppName , [Parameter(Mandatory=$true,Position=1)] [ValidateScript( {!$global:PowerGrowlerNotices.Contains($AppName) -OR !$global:PowerGrowlerNotices.$AppName.Notices.ContainsKey($_)} )] [String]$Name , [Parameter(Mandatory=$false,Position=5)] [String]$Icon = "$PSScriptRoot\\default.ico" , [Parameter(Mandatory=$false,Position=6)] [String]$DisplayName = $Name , [Parameter(Mandatory=$false,Position=7)] [String]$MachineName , [Parameter(Mandatory=$false)] [String]$AppIcon ) [Growl.Connector.NotificationType]$Notice = $Name $Notice.DisplayName = $DisplayName $Notice.Icon = Convert-Path (Resolve-Path $Icon) if($MachineName) { $Notice.MachineName = $MachineName } if(!$global:PowerGrowlerNotices.Contains($AppName)) { $global:PowerGrowlerNotices.Add( $AppName, ([Growl.Connector.Application]$AppName) ) $global:PowerGrowlerNotices.$AppName = Add-Member -input $global:PowerGrowlerNotices.$AppName -Name Notices -Type NoteProperty -Value (New-Object hashtable) -Passthru if($AppIcon) { $global:PowerGrowlerNotices.$AppName.Icon = Convert-Path (Resolve-Path $AppIcon) } } $global:PowerGrowlerNotices.$AppName.Notices.Add( $Name, $Notice ) $script:PowerGrowler.Register( $global:PowerGrowlerNotices.$AppName , [Growl.Connector.NotificationType[]]@($global:PowerGrowlerNotices.$AppName.Notices.Values) ) } function Set-GrowlPassword { #.Synopsis # Set the Growl password #.Description # Set the password and optionally, the encryption algorithm, for communicating with Growl #.Parameter Password # The password for Growl #.Parameter Encryption # The algorithm to be used for encryption (defaults to AES) #.Parameter KeyHash # The algorithm to be used for key hashing (defaults to SHA1) PARAM( [Parameter(Mandatory=$true,Position=0)] [String]$Password , [Parameter(Mandatory=$false,Position=1)] [ValidateSet( "AES", "DES", "RC2", "TripleDES", "PlainText" )] [String]$Encryption = "AES" , [Parameter(Mandatory=$false,Position=2)] [ValidateSet( "MD5", "SHA1", "SHA256", "SHA384", "SHA512" )] [String]$KeyHash = "SHA1" ) $script:PowerGrowler.EncryptionAlgorithm = [Growl.Connector.Cryptography+SymmetricAlgorithmType]::"$Encryption" $script:PowerGrowler.KeyHashAlgorithm = [Growl.Connector.Cryptography+SymmetricAlgorithmType]::"$KeyHash" $script:PowerGrowler.Password = $Password } ## Register the "PowerGrowler" "Default" notice so everything works out of the box Register-GrowlType $script:AppName "Default" -appIcon "$PsScriptRoot\\default.ico" function Register-GrowlCallback { #.Synopsis # Register a script to be called when each notice is finished. #.Description # Registers a scriptblock as a handler for the NotificationCallback event. You should accept two parameters, a Growl.Connector.Response and a Growl.Connector.CallbackData object. # # The NotificationCallback only happens when a callback is requested, which in this Growl library only happens if you pass both CallbackData and CallbackType to the Send-Growl function. #.Example # Register-GrowlCallback { PARAM( $response, $context ) # Write-Host "Response $($response|out-string)" -fore Cyan # Write-Host "Context $($context|fl|out-string)" -fore Green # Write-Host $("Response Type: {0}`nNotification ID: {1}`nCallback Data: {2}`nCallback Data Type: {3}`n" -f $context.Result, $context.NotificationID, $context.Data, $context.Type) -fore Yellow # } # # Registers an informational debugging-style handler. # PARAM( [Parameter(Mandatory=$true)] [Scriptblock]$Handler ) Register-ObjectEvent $script:PowerGrowler NotificationCallback -Action $Handler } function Send-Growl { [CmdletBinding(DefaultParameterSetName="NoCallback")] #.Synopsis # Send a growl notice #.Description # Send a growl notice with the scpecified values #.Parameter Caption # The short caption to display #.Parameter Message # The message to send (most displays will resize to accomodate) #.Parameter NoticeType # The type of notice to send. This MUST be the name of one of the registered types, and senders should bear in mind that each registered type has user-specified settings, so you should not abuse the types, but create your own for messages that will recur. # For example, the user settings allow certain messages to be disabled, set to a different "Display", or to have their Duration and Stickyness changed, as well as have them be Forwarded to another device, have Sounds play, and set different priorities. #.Parameter Icon # Overrides the default icon of the message (accepts .ico, .png, .bmp, .jpg, .gif etc) #.Parameter Priority # Overrides the default priority of the message (use sparingly) #.Example # Send-Growl "Greetings" "Hello World!" # # The Hello World of Growl. #.Example # Send-Growl "You've got Mail!" "Message for you sir!" -icon ~\\Icons\\mail.png # # Displays a message with a couple of movie quotes and a mail icon. # PARAM ( [Parameter(Mandatory=$true, Position=0)] [ValidateScript( {$global:PowerGrowlerNotices.Contains($AppName)} )] [string]$AppName , [Parameter(Mandatory=$true, Position=1)][Alias("Type")] [ValidateScript( {$global:PowerGrowlerNotices.$AppName.Notices.ContainsKey($_)} )] [string]$NoticeType , [Parameter(Mandatory=$true, Position=2)] [string]$Caption , [Parameter(Mandatory=$true, Position=3)] [string]$Message , [Parameter(Mandatory=$true, Position=4, ParameterSetName="UrlCallback")] [Uri]$Url , [Parameter(Mandatory=$true, Position=4, ParameterSetName="DataCallback")] [string]$CallbackData , [Parameter(Mandatory=$true, Position=5, ParameterSetName="DataCallback")] [string]$CallbackType , [string]$Icon , [Growl.Connector.Priority]$Priority = "Normal" ) $notice = New-Object Growl.Connector.Notification $appName, $NoticeType, (Get-Date).Ticks.ToString(), $caption, $Message if($Icon) { $notice.Icon = Convert-Path (Resolve-Path $Icon) } if($Priority) { $notice.Priority = $Priority } if($DebugPreference -gt "SilentlyContinue") { Write-Output $notice } switch( $PSCmdlet.ParameterSetName ) { "UrlCallback" { $context = new-object Growl.Connector.CallbackContext $Url # $urlCb = new-object Growl.Connector.UrlCallbackTarget # $urlCb.Url = $Url # $context.SetUrlCallbackTarget($urlcb) $script:PowerGrowler.Notify($notice, $context) break; } "DataCallback" { $context = new-object Growl.Connector.CallbackContext $CallbackData, $CallbackType $script:PowerGrowler.Notify($notice, $context) break; } "NoCallback" { $script:PowerGrowler.Notify($notice) break; } } } Export-ModuleMember -Function Send-Growl, Set-GrowlPassword, Register-GrowlCallback, Register-GrowlType
PowerShellCorpus/PoshCode/Power state.ps1
Power state.ps1
using System; using System.IO; using System.Reflection; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; [assembly: AssemblyCompany("greg zakharov")] [assembly: AssemblyCopyright("Copyleft (C) 2007 greg zakharov")] [assembly: AssemblyCulture("")] [assembly: AssemblyDescription("Power management utility")] [assembly: AssemblyProduct("pwrman.exe")] [assembly: AssemblyTitle("Power management utility")] [assembly: AssemblyVersion("2.0.0.0")] namespace PowerManagement { internal class AssemblyInfo { private Type asm; public AssemblyInfo() { asm = typeof(Program); } public string Copyleft { get { Type atr = typeof(AssemblyCopyrightAttribute); object[] arr = asm.Assembly.GetCustomAttributes(atr, false); AssemblyCopyrightAttribute cr = (AssemblyCopyrightAttribute) arr[0]; return cr.Copyright; } } public string Description { get { Type atr = typeof(AssemblyDescriptionAttribute); object[] arr = asm.Assembly.GetCustomAttributes(atr, false); AssemblyDescriptionAttribute des = (AssemblyDescriptionAttribute) arr[0]; return des.Description; } } public string Module { get { return Path.GetFileName(asm.Assembly.Location); } } public string Title { get { return asm.Assembly.GetName().Name; } } public string Version { get { return asm.Assembly.GetName().Version.ToString(2); } } } internal static class NativeMethods { public enum ExitWinCmd : uint { EWX_LOGOFF = 0x00000000, EWX_SHUTDOWN = 0x00000001, EWX_REBOOT = 0x00000002, EWX_FORCE = 0x00000004 } [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct TokPriv1Luid { public int Count; public long Luid; public int Attrb; } [DllImport("advapi32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, [MarshalAs(UnmanagedType.Bool)]bool DisableAllPrivileges, ref TokPriv1Luid NewState, uint BufferLength, IntPtr PreviousState, IntPtr ReturnLength); [DllImport("advapi32.dll", CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, ref long lpLuid); [DllImport("advapi32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool OpenProcessToken(IntPtr ProcessHandle, uint DesiredAccess, ref IntPtr TokenHandle); [DllImport("kernel32.dll")] internal static extern IntPtr GetCurrentProcess(); [DllImport("powrprof.dll")] [return: MarshalAs(UnmanagedType.U1)] internal static extern bool SetSuspendState( [In, MarshalAs(UnmanagedType.U1)]bool Hibernate, [In, MarshalAs(UnmanagedType.U1)]bool ForceCritical, [In, MarshalAs(UnmanagedType.U1)]bool DisableWakeEvent ); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool ExitWindowsEx(ExitWinCmd uFlags, uint dwReason); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool LockWorkStation(); // //combine calls into shared functions // internal static void ChangeSystemState(ExitWinCmd flags) { TokPriv1Luid tpl; IntPtr hdl = GetCurrentProcess(); IntPtr tkn = IntPtr.Zero; //TOKEN_ADJUST_PRIVELEGES = 0x00000020 //TOKEN_QUERY = 0x00000008 OpenProcessToken(hdl, (uint)32 | (uint)8, ref tkn); tpl.Count = 1; tpl.Luid = 0; tpl.Attrb = 2; //SE_PRIVILEGE_ENABLED LookupPrivilegeValue(null, "SeShutdownPrivilege", ref tpl.Luid); AdjustTokenPrivileges(tkn, false, ref tpl, 0, IntPtr.Zero, IntPtr.Zero); //SHTDN_REASON_MAJOR_OTHER = 0x00000000 //SHTDN_REASON_MINOR_OTHER = 0x00000000 ExitWindowsEx(flags, (uint)0 | (uint)0); } internal static void Logoff() { ChangeSystemState(ExitWinCmd.EWX_LOGOFF | ExitWinCmd.EWX_FORCE); } internal static void Shutdown() { ChangeSystemState(ExitWinCmd.EWX_SHUTDOWN | ExitWinCmd.EWX_FORCE); } internal static void Reboot() { ChangeSystemState(ExitWinCmd.EWX_REBOOT | ExitWinCmd.EWX_FORCE); } } internal sealed class Program { static void Main(string[] args) { try { //argument should always starts with "-" or "/" char chr = args[0].ToCharArray()[0]; //validate delimiter if (chr == '-' || chr == '/') { //validate argument string par = args[0].ToLower(CultureInfo.CurrentCulture).TrimStart('-', '/'); switch (par) { case "h": NativeMethods.SetSuspendState(true, true, true); break; case "l": NativeMethods.LockWorkStation(); break; case "o": NativeMethods.Logoff(); break; case "r": NativeMethods.Reboot(); break; case "s": NativeMethods.Shutdown(); break; case "w": NativeMethods.SetSuspendState(false, true, true); break; case "?": PrintHelpInfo(); break; default: Console.WriteLine("Error: unknown parameter {0}.", args[0]); break; } } else Console.WriteLine("Invalid parameter. Use \\"/?\\" for additional info."); } catch (IndexOutOfRangeException e) { Console.WriteLine(e.Message); } } static void PrintHelpInfo() { AssemblyInfo ai = new AssemblyInfo(); Console.WriteLine("{0} v{1} - {2}", ai.Title, ai.Version, ai.Description); Console.WriteLine(ai.Copyleft); Console.WriteLine("\\nUsage: {0} [-h][-l][-o][-r][-s][-w]", ai.Module); Console.WriteLine(" -h - hibernate mode"); Console.WriteLine(" -l - lock workstation"); Console.WriteLine(" -o - logoff"); Console.WriteLine(" -r - reboot system"); Console.WriteLine(" -s - shutdown system"); Console.WriteLine(" -w - standby mode"); Console.WriteLine(" -? - this message"); } } }
PowerShellCorpus/PoshCode/USB Script backup.ps1
USB Script backup.ps1
################################################################################ # Copy-Backup.ps1 # This script will backup recently changed .ps1 files from any selected folder # (default is $pwd) to any number of inserted USB devices, on which an archive # folder PSarchive will be created if it does not already exist. # The author may be contacted via www.SeaStarDevelopment.Bravehost.com ################################################################################ Param ([Switch]$debug, [String]$folder = $pwd) If ($debug) { $DebugPreference = 'Continue' } $drive = 'blank' If (!(Test-path $folder -pathType Container )) { [System.Media.SystemSounds]::Hand.Play() Write-Warning "$folder is not a directory - resubmit." Break } Get-WMIObject Win32_LogicalDisk -filter "DriveType = 2" |` Select-Object Name, VolumeName, DriveType, FreeSpace |` Where-Object {$_.VolumeName -ne $null} |` ForEach { $drive = $_.Name #Store these values otherwise overwritten below. $vol = $_.VolumeName $type = $_.DriveType [int]$free = $_.FreeSpace / 1MB Write-Debug "Scanning USB devices - $drive Name = $vol, Free = $free Mb" If ((Test-Path $drive) -eq $False ) { Write-Warning "Error on drive $drive - restart." [System.Media.SystemSounds]::Hand.Play() Break } [int]$files = 0 #Reset counter for each new drive. $newFolder = $drive + "\\PSarchive" #Check if folder exists. If ((Test-Path $newFolder) -eq $False) { New-Item -path ($drive + "\\") -name PSarchive -type directory | Out-Null } (Get-ChildItem $folder -filter *.ps1) | ForEach { $replacing = Get-ChildItem ($drive + "\\PSarchive\\" + $_.Name) ` -ErrorAction SilentlyContinue If (!$replacing) { #An error here means the file not found. $lwt = "None" #Anything to force backup match below. } #File exists, so check before overwriting. Else { $lwt = $replacing.LastWriteTime } If ($lwt -ne $_.LastWriteTime) { #Compare the two times. $output = "{0}\\PSarchive" -f $drive Copy-Item $_.FullName -destination $output -force Write-Host "--> Archiving file:" $_.Name $files++ } } $print = " Backup to USB drive <{0}> (Volume = {2}) completed; {1} files copied." -f $drive, $files, $vol Write-Host "-->$print" } If ($drive -eq 'blank') { [System.Media.SystemSounds]::Asterisk.Play() Write-Warning "No USB drive detected - Insert a device and resubmit." }
PowerShellCorpus/PoshCode/9a32cfaf-77be-4cae-8d11-f85a905dfa06.ps1
9a32cfaf-77be-4cae-8d11-f85a905dfa06.ps1
param ( [Parameter(Mandatory=$true, Position = 0, ValueFromPipeline=$true)] [Parameter(HelpMessage="Specifies the path to the IIS *.log file to import. You can also pipe a path to Import-Iss-Log.")] [ValidateNotNullOrEmpty()] [string] $Path, [Parameter(Position = 1)] [Parameter(HelpMessage="Specifies the delimiter that separates the property values in the IIS *.log file. The default is a spacebar.")] [ValidateNotNullOrEmpty()] [string] $Delimiter = " ", [Parameter(HelpMessage="The character encoding for the IIS *log file. The default is the UTF8.")] [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding] $Encoding = [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]::UTF8 ) begin { $fieldNames = @() $output = New-Object Object Add-Member -InputObject $output -MemberType NoteProperty -Name "DateTime" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ClientHost" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "UserName" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "Service" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "Machine" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ServerIp" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ServerPort" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "Method" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ScriptPath" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "QueryString" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ServiceStatus" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ServiceSubStatus" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "Win32Status" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "BytesSent" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "BytesRecived" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ProcessingTime" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ProtocolVersion" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "Host" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "UserAgent" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "Cookie" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "Referer" -Value $null } process { foreach($line in Get-Content -Path $Path -Encoding $Encoding) { if($line.StartsWith("#Fields: ")) { $fieldNames = @($line.Substring("#Fields: ".Length).Split($Delimiter)); } elseif(-not $line.StartsWith("#")) { $fieldValues = @($line.Split($Delimiter)); for($i = 0; $i -lt $fieldValues.Length; $i++) { $name = $fieldNames[$i] $value = $fieldValues[$i] switch($name) { "date" { $output.DateTime = [DateTime]::Parse($value) } "time" { $output.DateTime += [TimeSpan]::Parse($value) } "c-ip" { $output.ClientHost = [System.Net.IPAddress]::Parse($value) } "cs-username" { $output.UserName = if($value -eq '-') { $null } else { $value } } "s-sitename" { $output.Service = $value } "s-computername" { $output.Machine = $value } "s-ip" { $output.ServerIp = [System.Net.IPAddress]::Parse($value) } "s-port" { $output.ServerPort = [int]$value } "cs-method" { $output.Method = $value } "cs-uri-stem" { $output.ScriptPath = [System.Web.HttpUtility]::UrlDecode($value) } "cs-uri-query" { $output.QueryString = if($value -eq '-') { $null } else { [System.Web.HttpUtility]::UrlDecode($value) } } "sc-status" { $output.ServiceStatus = [int]$value } "sc-substatus" { $output.ServiceSubStatus = [int]$value } "sc-win32-status" { $output.Win32Status = [BitConverter]::ToInt32([BitConverter]::GetBytes([UInt32]($value)), 0) } "sc-bytes" { $output.BytesSent = [UInt64]$value } "cs-bytes" { $output.BytesRecived = [UInt64]$value } "time-taken" { $output.ProcessingTime = [int]$value } "cs-version" { $output.ProtocolVersion = $value } "cs-host" { $output.Host = if($value -eq '-') { $null } else { $value } } "cs(User-Agent)" { $output.UserAgent = if($value -eq '-') { $null } else { $value } } "cs(Cookie)" { $output.Cookie = if($value -eq '-') { $null } else { $value } } "cs(Referer)" { $output.Referer = if($value -eq '-') { $null } else { [System.Web.HttpUtility]::UrlDecode($value) } } } } Write-Output $output } } }
PowerShellCorpus/PoshCode/TabExpansion for V2CTP_3.ps1
TabExpansion for V2CTP_3.ps1
## Tab-Completion ################# ## For V2CTP3. ## This won't work on V1 and V2CTP and V2CTP2. ## Please dot souce this script file. ## In first loading, it may take a several minutes, in order to generate ProgIDs and TypeNames list. ## ## What this can do is: ## ## [datetime]::n<tab> ## [datetime]::now.d<tab> ## $a = New-Object "Int32[,]" 2,3; $b = "PowerShell","PowerShell" ## $c = [ref]$a; $d = [ref]$b,$c ## $d[0].V<tab>[0][0].Get<tab> ## $d[1].V<tab>[0,0].tos<tab> ## $function:a<tab> ## $env:a<tab> ## [System.Type].a<tab> ## [datetime].Assembly.a<tab> ## ).a<tab> # shows System.Type properties and methods... ## #native command name expansion ## fsu<tab> ## #command option name expansion (for fsutil ipconfig net powershell only) ## fsutil <tab> ## ipconfig <tab> ## net <tab> ## powershell <tab> ## #TypeNames and Type accelerators expansion ## [Dec<tab> ## [system.Man<tab>.auto<tab>.p<tab> ## New-Object -TypeName IO.Dir<tab> ## New-Object System.win<tab>.for<tab>.bu<tab> ## #ProgIDs expansion ## New-Object -Com shel<tab> ## #Enum option expansion ## Set-ExecutionPolicy <tab> ## Set-ExecutionPolicy All<tab> ## Set-ExcusionPolisy -ex <tab> ## Get-TraceSource Inte<tab> ## iex -Errora <tab> -wa Sil<tab> ## #WmiClasses expansion ## Get-WmiObject -class Win32_<tab> ## gwmi __Instance<tab> ## #Encoding expansion ## [Out-File | Export-CSV | Select-String | Export-Clixml] -enc <tab> ## [Add-Content | Get-Content | Set-Content} -Encoding Big<tab> ## #PSProvider name expansion ## [Get-Location | Get-PSDrive | Get-PSProvider | New-PSDrive | Remove-PSDrive] -PSProvider <tab> ## Get-PSProvider <tab> ## pwd -psp al<tab> ## #PSDrive name expansion ## [Get-PSDrive | New-PSDrive | Remove-PSDrive] [-Name] <tab> ## Get-PSDrive <tab> ## pwd -psd <tab> ## #PSSnapin name expansion ## [Add-PSSnapin | Get-PSSnapin | Remove-PSSnapin ] [-Name] <tab> ## Get-Command -PSSnapin <tab> ## Remove-PSSnapin <tab> ## Get-PSSnapin M<tab> ## #Eventlog name and expansion ## Get-Eventlog -Log <tab> ## Get-Eventlog w<tab> ## #Eventlog's entrytype expansion ## Get-EventLog -EntryType <tab> ## Get-EventLog -EntryType Er<tab> ## Get-EventLog -Ent <tab> ## #Service name expansion ## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-Name] <tab> ## New-Service -DependsOn <tab> ## New-Service -Dep e<tab> ## Get-Service -n <tab> ## Get-Service <tab>,a<tab>,p<tab> ## gsv <tab> ## #Service display name expansion ## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-DisplayName] <tab> ## Get-Service -Dis <tab> ## gsv -Dis <tab>,w<tab>,b<tab> ## #Cmdlet and Topic name expansion (this also support default help function and man alias) ## Get-Help [-Name] about_<tab> ## Get-Help <tab> ## #Category name expansion (this also support default help function and man alias) ## Get-Help -Category c<tab>,<tab> ## #Command name expansion ## Get-Command [-Name] <tab> ## Get-Command -Name <tab> ## gcm a<tab>,<tab> ## #Scope expansion ## [Clear-Variable | Export-Alias | Get-Alias | Get-PSDrive | Get-Variable | Import-Alias ## New-Alias | New-PSDrive | New-Variable | Remove-Variable | Set-Alias | Set-Variable] -Scope <tab> ## Clear-Variable -Scope G<tab> ## Set-Alias -s <tab> ## #Process name expansion ## [Get-Process | Stop-Process] [-Name] <tab> ## Stop-Process -Name <tab> ## Stop-Process -N pow<tab> ## Get-Process <tab> ## ps power<tab> ## #Trace sources expansion ## [Trace-Command | Get-TraceSource | Set-TraceSource] [-Name] <tab>,a<tab>,p<tab> ## #Trace -ListenerOption expansion ## [Set-TraceSource | Trace-Command] -ListenerOption <tab> ## Set-TraceSource -Lis <tab>,n<tab> ## #Trace -Option expansion ## [Set-TraceSource | Trace-Command] -Option <tab> ## Set-TraceSource -op <tab>,con<tab> ## #ItemType expansion ## New-Item -Item <tab> ## ni -ItemType d<tab> ## #ErrorAction and WarningAction option expansion ## CMDLET [-ErrorAction | -WarningAction] <tab> ## CMDLET -Errora s<tab> ## CMDLET -ea con<tab> ## CMDLET -wa <tab> ## #Continuous expansion with comma when parameter can treat multiple option ## # if there are spaces, occur display bug in the line ## # if strings contains '$' or '-', not work ## Get-Command -CommandType <tab>,<tab><tab>,cm<tab> ## pwd -psp <tab>,f<tab>,va<tab> ## Get-EventLog -EntryType <tab>,i<tab>,s<tab> ## #Enum expansion in method call expression ## # this needs one or more spaces after left parenthesis or comma ## $str = "day night" ## $str.Split( " ",<space>rem<tab> ## >>> $str.Split( " ", "RemoveEmptyEntries" ) <Enter> ERROR ## $str.Split( " ", "RemoveEmptyEntries" -as<space><tab> ## >>> $str.Split( " ", "RemoveEmptyEntries" -as [System.StringSplitOptions] ) <Enter> Success ## $type = [System.Type] ## $type.GetMembers(<space>Def<tab> ## [IO.Directory]::GetFiles( "C:\\", "*",<space>All<tab> ## # this can do continuous enum expansion with comma and no spaces ## $type.GetMembers( "IgnoreCase<comma>Dec<tab><comma>In<tab>" ## [IO.Directory]::GetAccessControl( "C:\\",<space>au<tab><comma>ac<tab><comma>G<tab> ## #Better '$_.' expansion when cmdlet output objects or method return objects ## ls |group { $_.Cr<tab>.Tost<tab>"y")} | tee -var foo| ? { $_.G<tab>.c<tab> -gt 5 } | % { md $_.N<tab> ; copy $_.G<tab> $_.N<tab> } ## [IO.DriveInfo]::GetDrives() | ? { $_.A<tab> -gt 1GB } ## $Host.UI.RawUI.GetBufferContents($rect) | % { $str += $_.c<tab> } ## gcm Add-Content |select -exp Par<tab>| select -ExpandProperty Par<tab> | ? { $_.Par<tab>.N<tab> -eq "string" } ## $data = Get-Process ## $data[2,4,5] | % { $_.<tab> ## #when Get-PipeLineObject failed, '$_.' shows methods and properties name of FileInfo and String and Type ## #Property name expansion by -Property parameter ## [ Format-List | Format-Custom | Format-Table | Format-Wide | Compare-Object | ## ConvertTo-Html | Measure-Object | Select-Object | Group-Object | Sort-Object ] [-Property] <tab> ## Select-Object -ExcludeProperty <tab> ## Select-Object -ExpandProperty <tab> ## gcm Get-Acl|select -exp Par<tab> ## ps |group na<tab> ## ls | ft A<tab>,M<tab>,L<tab> ## #Hashtable key expansion in the variable name and '.<tab>' ## Get-Process | Get-Unique | % { $hash += @{$_.ProcessName=$_} } ## $hash.pow<tab>.pro<tab> ## #Parameter expansion for function, filter and script ## man -f<tab> ## 'param([System.StringSplitOptions]$foo,[System.Management.Automation.ActionPreference]$bar,[System.Management.Automation.CommandTypes]$baz) {}' > foobar.ps1 ## .\\foobar.ps1 -<tab> -b<tab> ## #Enum expansion for function, filter and scripts ## # this can do continuous enum expansion with comma and no spaces ## .\\foobar.ps1 -foo rem<tab> -bar <tab><comma>c<tab><comma>sc<tab> -ea silent<tab> -wa con<tab> ## #Enum expansion for assignment expression ## #needs space(s) after '=' and comma ## #strongly-typed with -as operator and space(s) ## $ErrorActionPreference =<space><tab> ## $cmdtypes = New-Object System.Management.Automation.CommandTypes[] 3 ## $cmdtypes =<space><tab><comma><space>func<tab><comma><space>cmd<tab> -as<space><tab> ## #Path expansion with variable and '\\' or '/' ## $PWD\\../../<tab>\\<tab> ## "$env:SystemDrive/pro<tab>/<tab> ## #Operator expansion which starts with '-' ## "Power","Shell" -m<tab> "Power" -r<tab> '(Pow)(er)','$1d$2' ## 1..9 -co<tab> 5 ## #Keyword expansion ## fu<tab> test { p<tab> $foo, $bar ) b<tab> "foo" } pr<tab> $_ } en<tab> "$bar" } } ## #Variable name expansion (only global scope) ## [Clear-Variable | Get-Variable | New-Variable | Remove-Variable | Set-Variable] [-Name] <tab> ## [Cmdlet | Function | Filter | ExternalScript] -ErrorVariable <tab> ## [Cmdlet | Function | Filter | ExternalScript] -OutVariable <tab> ## Tee-Object -Variable <tab> ## gv pro<tab>,<tab> ## Remove-Variable -Name out<tab>,<tab>,ps<tab> ## ... | ... | tee -v <tab> ## #Alias name expansion ## [Get-Alias | New-Alias | Set-Alias] [-Name] <tab> ## Export-Alias -Name <tab> ## Get-Alias i<tab>,e<tab>,a<tab> ## epal -n for<tab> ## #Property name expansion with -groupBy parameter ## [Format-List | Format-Custom | Format-Table | Format-Wide] -groupBy <tab> ## ps | ft -g <tab> ## gcm | Format-Wide -GroupBy Par<tab> ## #Type accelerators expansion with no charactors ## [<tab> ## New-Object -typename <tab> ## New-Object <tab> ## # File glob expansion with '@' ## ls *.txt@<tab> ## ls file.txt, foo1.txt, 'bar``[1``].txt', 'foo bar .txt' # 1 <tab> expanding with comma ## ls * -Filter *.txt # 2 <tab> refactoring ## ls *.txt # 3 <tab> (or 1 <tab> & 1 <shift>+<tab>) return original glob pattern ## This can also use '^'(hat) or '~'(tilde) for Excluding ## ls <hat>*.txt@<tab> ## ls foo.ps1, 'bar``[1``].xml' # 1 <tab> expanding with comma ## ls * -Filter * -Excluding *.txt # 2 <tab> refactoring ## *.txt<tilde>foo*<tilde>bar*@<tab> ## ls file.txt # 1 <tab> expanding with comma ## ls * -Filter *.txt -Excluding foo*, bar* # 2 <tab> refactoring ## # Ported history expansion from V2CTP3 TabExpansion with '#' ( #<pattern> or #<id> ) ## ls * -Filter * -Excluding foo*, bar*<Enter> ## #ls<tab> ## #1<tab> ## # Command buffer stack with ';'(semicolon) ## ls * -Filter * -Excluding foo*, bar*<semicolon><tab> # push command1 ## echo "PowerShell"<semicolon><tab> # push command2 ## get-process<semicolon><tab> # push command3 ## {COMMAND}<Enter> # execute another command ## get-process # Auto pop command3 from stack by LIFO ## This can also hand-operated pop with ';,'(semicolon&comma) or ';:'(semicolon&colon) ## get-process; <semicolon><comma><tab> ## get-process; echo "PowerShell" # pop command2 from stack by LIFO ## # Function name expansion after 'function' or 'filter' keywords ## function cl<tab> ## #Switch syntax option expansion ## switch -w<tab> -f<tab> ## #Better powershell.exe option expansion with '-' ## powershell -no<tab> -<tab> -en<tab> ## #A part of PowerShell attributes expansion ( CmdletBinding, Parameter, Alias, Validate*, Allow* ) ## [par<tab> ## [cmd<tab> ## #Member expansion for CmdletBinding and Parameter attributes ## [Parameter(man<tab>,<tab>1,val<tab>$true)] ## [CmdletBinding( <tab>"foo", su<tab>$true)] ### Generate ProgIDs list... if ( Test-Path $PSHOME\\ProgIDs.txt ) { $_reader = New-Object IO.StreamReader $PSHOME\\ProgIDs.txt $_ProgID = $_reader.ReadToEnd().Split("", "RemoveEmptyEntries" -as [System.StringSplitOptions]) $_reader.Close() Remove-Variable _reader } else { $_HKCR = [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\") $_ProgID = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) ) foreach ( $_subkey in $_HKCR.GetSubKeyNames() ) { foreach ( $_i in [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\$_subkey\\ProgID") ) { if ($_i -ne $null) { $_ProgID.Add($_i.GetValue("")) } } } '$_ProgID was updated...' | Out-Host $_ProgID = $_ProgID|sort -Unique Set-Content -Value $_ProgID -Path $PSHOME\\ProgIDs.txt -Verbose } ### Generate TypeNames list... if ( Test-Path $PSHOME\\TypeNames.txt ) { $_reader = New-Object IO.StreamReader $PSHOME\\TypeNames.txt $_TypeNames = $_reader.ReadToEnd().Split("", "RemoveEmptyEntries" -as [System.StringSplitOptions]) $_reader.Close() Remove-Variable _reader } else { $_TypeNames = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) ) foreach ( $_asm in [AppDomain]::CurrentDomain.GetAssemblies() ) { foreach ( $_type in $_asm.GetTypes() ) { $_TypeNames.Add($_type.FullName) } } '$_TypeNames was updated...' | Out-Host $_TypeNames = $_TypeNames | sort -Unique Set-Content -Value $_TypeNames -Path $PSHOME\\TypeNames.txt -Verbose } if ( Test-Path $PSHOME\\TypeNames_System.txt ) { $_reader = New-Object IO.StreamReader $PSHOME\\TypeNames_System.txt $_TypeNames_System = $_reader.ReadToEnd().Split("", "RemoveEmptyEntries" -as [System.StringSplitOptions]) $_reader.Close() Remove-Variable _reader } else { $_TypeNames_System = $_TypeNames -like "System.*" -replace '^System\\.' '$_TypeNames_System was updated...' | Out-Host Set-Content -Value $_TypeNames_System -Path $PSHOME\\TypeNames_System.txt -Verbose } ### Generate WMIClasses list... if ( Test-Path $PSHOME\\WMIClasses.txt ) { $_reader = New-Object IO.StreamReader $PSHOME\\WMIClasses.txt $_WMIClasses = $_reader.ReadToEnd().Split("", "RemoveEmptyEntries" -as [System.StringSplitOptions]) $_reader.Close() Remove-Variable _reader } else { $_WMIClasses = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) ) foreach ( $_class in gwmi -List ) { $_WMIClasses.Add($_class.Name) } $_WMIClasses = $_WMIClasses | sort -Unique '$_WMIClasses was updated...' | Out-Host Set-Content -Value $_WMIClasses -Path $PSHOME\\WMIClasses.txt -Verbose } [Reflection.Assembly]::LoadWithPartialName( "System.Windows.Forms" ) | Out-Null $global:_cmdstack = New-Object Collections.Stack $global:_snapin = $null $global:_TypeAccelerators = [type]::gettype("System.Management.Automation.TypeAccelerators")::get.keys | sort iex (@' function prompt { if ($_cmdstack.Count -gt 0) { $line = $global:_cmdstack.Pop() -replace '([[\\]\\(\\)+{}?~%])','{$1}' [System.Windows.Forms.SendKeys]::SendWait($line) } '@ + @" ${function:prompt} } "@) function Write-ClassNames ( $data, $i, $prefix='', $sep='.' ) { $preItem = "" foreach ( $class in $data -like $_opt ) { $Item = $class.Split($sep) if ( $preItem -ne $Item[$i] ) { if ( $i+1 -eq $Item.Count ) { if ( $prefix -eq "[" ) { $suffix = "]" } elseif ( $sep -eq "_" ) { $suffix = "" } else { $suffix = " " } } else { $suffix = "" } $prefix + $_opt.Substring(0, $_opt.LastIndexOf($sep)+1) + $Item[$i] + $suffix $preItem = $Item[$i] } } } function Get-PipeLineObject { $i = -2 $property = $null do { $str = $line.Split("|") # extract the command name from the string # first split the string into statements and pipeline elements # This doesn't handle strings however. $_cmdlet = [regex]::Split($str[$i], '[|;=]')[-1] # take the first space separated token of the remaining string # as the command to look up. Trim any leading or trailing spaces # so you don't get leading empty elements. $_cmdlet = $_cmdlet.Trim().Split()[0] if ( $_cmdlet -eq "?" ) { $_cmdlet = "Where-Object" } $global:_exp = $_cmdlet # now get the info object for it... $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0] } if ( "Select-Object" -eq $_cmdlet ) { if ( $str[$i] -match '\\s+-Exp\\w*[\\s:]+(\\w+)' ) { $property = $Matches[1] + ";" + $property } } $i-- } while ( "Get-Unique", "Select-Object", "Sort-Object", "Tee-Object", "Where-Object" -contains $_cmdlet ) if ( $global:_forgci -eq $null ) { $a = @(ls "Alias:\\")[0] $e = @(ls "Env:\\")[0] $f = @(ls "Function:\\")[0] $h = @(ls "HKCU:\\")[0] $v = @(ls "Variable:\\")[0] $c = @(ls "cert:\\")[0] $global:_forgci = gi $PSHOME\\powershell.exe | Add-Member 'NoteProperty' CommandType $f.CommandType -P | Add-Member 'NoteProperty' Definition $a.Definition -P | Add-Member 'NoteProperty' Description $a.Description -P | Add-Member 'NoteProperty' Key $e.Key -P | Add-Member 'NoteProperty' Location $c.Location -P | Add-Member 'NoteProperty' LocationName $c.LocationName -P | Add-Member 'NoteProperty' Options $a.Options -P | Add-Member 'NoteProperty' ReferencedCommand $a.ReferencedCommand -P | Add-Member 'NoteProperty' ResolvedCommand $a.ResolvedCommand -P | Add-Member 'NoteProperty' ScriptBlock $f.ScriptBlock -P | Add-Member 'NoteProperty' StoreNames $c.StoreNames -P | Add-Member 'NoteProperty' SubKeyCount $h.SubKeyCount -P | Add-Member 'NoteProperty' Value $e.Value -P | Add-Member 'NoteProperty' ValueCount $h.ValueCount -P | Add-Member 'NoteProperty' Visibility $a.Visibility -P | Add-Member 'NoteProperty' Property $h.Property -P | Add-Member 'NoteProperty' ResolvedCommandName $a.ResolvedCommandName -P | Add-Member 'ScriptMethod' Close {} -P | Add-Member 'ScriptMethod' CreateSubKey {} -P | Add-Member 'ScriptMethod' DeleteSubKey {} -P | Add-Member 'ScriptMethod' DeleteSubKeyTree {} -P | Add-Member 'ScriptMethod' DeleteValue {} -P | Add-Member 'ScriptMethod' Flush {} -P | Add-Member 'ScriptMethod' GetSubKeyNames {} -P | Add-Member 'ScriptMethod' GetValue {} -P | Add-Member 'ScriptMethod' GetValueKind {} -P | Add-Member 'ScriptMethod' GetValueNames {} -P | Add-Member 'ScriptMethod' IsValidValue {} -P | Add-Member 'ScriptMethod' OpenSubKey {} -P | Add-Member 'ScriptMethod' SetValue {} -P } if ( $global:_mix -eq $null ) { $f = gi $PSHOME\\powershell.exe $t = [type] $s = "" $global:_mix = ` Add-Member -InputObject (New-Object PSObject) 'NoteProperty' Mode $f.Mode -P | Add-Member 'NoteProperty' Assembly $t.Assembly -P | Add-Member 'NoteProperty' AssemblyQualifiedName $t.AssemblyQualifiedName -P | Add-Member 'NoteProperty' Attributes $f.Attributes -P | Add-Member 'NoteProperty' BaseType $t.BaseType -P | Add-Member 'NoteProperty' ContainsGenericParameters $t.ContainsGenericParameters -P | Add-Member 'NoteProperty' CreationTime $f.CreationTime -P | Add-Member 'NoteProperty' CreationTimeUtc $f.CreationTimeUtc -P | Add-Member 'NoteProperty' DeclaringMethod $t.DeclaringMethod -P | Add-Member 'NoteProperty' DeclaringType $t.DeclaringType -P | Add-Member 'NoteProperty' Exists $f.Exists -P | Add-Member 'NoteProperty' Extension $f.Extension -P | Add-Member 'NoteProperty' FullName $f.FullName -P | Add-Member 'NoteProperty' GenericParameterAttributes $t.GenericParameterAttributes -P | Add-Member 'NoteProperty' GenericParameterPosition $t.GenericParameterPosition -P | Add-Member 'NoteProperty' GUID $t.GUID -P | Add-Member 'NoteProperty' HasElementType $t.HasElementType -P | Add-Member 'NoteProperty' IsAbstract $t.IsAbstract -P | Add-Member 'NoteProperty' IsAnsiClass $t.IsAnsiClass -P | Add-Member 'NoteProperty' IsArray $t.IsArray -P | Add-Member 'NoteProperty' IsAutoClass $t.IsAutoClass -P | Add-Member 'NoteProperty' IsAutoLayout $t.IsAutoLayout -P | Add-Member 'NoteProperty' IsByRef $t.IsByRef -P | Add-Member 'NoteProperty' IsClass $t.IsClass -P | Add-Member 'NoteProperty' IsCOMObject $t.IsCOMObject -P | Add-Member 'NoteProperty' IsContextful $t.IsContextful -P | Add-Member 'NoteProperty' IsEnum $t.IsEnum -P | Add-Member 'NoteProperty' IsExplicitLayout $t.IsExplicitLayout -P | Add-Member 'NoteProperty' IsGenericParameter $t.IsGenericParameter -P | Add-Member 'NoteProperty' IsGenericType $t.IsGenericType -P | Add-Member 'NoteProperty' IsGenericTypeDefinition $t.IsGenericTypeDefinition -P | Add-Member 'NoteProperty' IsImport $t.IsImport -P | Add-Member 'NoteProperty' IsInterface $t.IsInterface -P | Add-Member 'NoteProperty' IsLayoutSequential $t.IsLayoutSequential -P | Add-Member 'NoteProperty' IsMarshalByRef $t.IsMarshalByRef -P | Add-Member 'NoteProperty' IsNested $t.IsNested -P | Add-Member 'NoteProperty' IsNestedAssembly $t.IsNestedAssembly -P | Add-Member 'NoteProperty' IsNestedFamANDAssem $t.IsNestedFamANDAssem -P | Add-Member 'NoteProperty' IsNestedFamily $t.IsNestedFamily -P | Add-Member 'NoteProperty' IsNestedFamORAssem $t.IsNestedFamORAssem -P | Add-Member 'NoteProperty' IsNestedPrivate $t.IsNestedPrivate -P | Add-Member 'NoteProperty' IsNestedPublic $t.IsNestedPublic -P | Add-Member 'NoteProperty' IsNotPublic $t.IsNotPublic -P | Add-Member 'NoteProperty' IsPointer $t.IsPointer -P | Add-Member 'NoteProperty' IsPrimitive $t.IsPrimitive -P | Add-Member 'NoteProperty' IsPublic $t.IsPublic -P | Add-Member 'NoteProperty' IsSealed $t.IsSealed -P | Add-Member 'NoteProperty' IsSerializable $t.IsSerializable -P | Add-Member 'NoteProperty' IsSpecialName $t.IsSpecialName -P | Add-Member 'NoteProperty' IsUnicodeClass $t.IsUnicodeClass -P | Add-Member 'NoteProperty' IsValueType $t.IsValueType -P | Add-Member 'NoteProperty' IsVisible $t.IsVisible -P | Add-Member 'NoteProperty' LastAccessTime $f.LastAccessTime -P | Add-Member 'NoteProperty' LastAccessTimeUtc $f.LastAccessTimeUtc -P | Add-Member 'NoteProperty' LastWriteTime $f.LastWriteTime -P | Add-Member 'NoteProperty' LastWriteTimeUtc $f.LastWriteTimeUtc -P | Add-Member 'NoteProperty' MemberType $t.MemberType -P | Add-Member 'NoteProperty' MetadataToken $t.MetadataToken -P | Add-Member 'NoteProperty' Module $t.Module -P | Add-Member 'NoteProperty' Name $t.Name -P | Add-Member 'NoteProperty' Namespace $t.Namespace -P | Add-Member 'NoteProperty' Parent $f.Parent -P | Add-Member 'NoteProperty' ReflectedType $t.ReflectedType -P | Add-Member 'NoteProperty' Root $f.Root -P | Add-Member 'NoteProperty' StructLayoutAttribute $t.StructLayoutAttribute -P | Add-Member 'NoteProperty' TypeHandle $t.TypeHandle -P | Add-Member 'NoteProperty' TypeInitializer $t.TypeInitializer -P | Add-Member 'NoteProperty' UnderlyingSystemType $t.UnderlyingSystemType -P | Add-Member 'NoteProperty' PSChildName $f.PSChildName -P | Add-Member 'NoteProperty' PSDrive $f.PSDrive -P | Add-Member 'NoteProperty' PSIsContainer $f.PSIsContainer -P | Add-Member 'NoteProperty' PSParentPath $f.PSParentPath -P | Add-Member 'NoteProperty' PSPath $f.PSPath -P | Add-Member 'NoteProperty' PSProvider $f.PSProvider -P | Add-Member 'NoteProperty' BaseName $f.BaseName -P | Add-Member 'ScriptMethod' Clone {} -P | Add-Member 'ScriptMethod' CompareTo {} -P | Add-Member 'ScriptMethod' Contains {} -P | Add-Member 'ScriptMethod' CopyTo {} -P | Add-Member 'ScriptMethod' Create {} -P | Add-Member 'ScriptMethod' CreateObjRef {} -P | Add-Member 'ScriptMethod' CreateSubdirectory {} -P | Add-Member 'ScriptMethod' Delete {} -P | Add-Member 'ScriptMethod' EndsWith {} -P | Add-Member 'ScriptMethod' FindInterfaces {} -P | Add-Member 'ScriptMethod' FindMembers {} -P | Add-Member 'ScriptMethod' GetAccessControl {} -P | Add-Member 'ScriptMethod' GetArrayRank {} -P | Add-Member 'ScriptMethod' GetConstructor {} -P | Add-Member 'ScriptMethod' GetConstructors {} -P | Add-Member 'ScriptMethod' GetCustomAttributes {} -P | Add-Member 'ScriptMethod' GetDefaultMembers {} -P | Add-Member 'ScriptMethod' GetDirectories {} -P | Add-Member 'ScriptMethod' GetElementType {} -P | Add-Member 'ScriptMethod' GetEnumerator {} -P | Add-Member 'ScriptMethod' GetEvent {} -P | Add-Member 'ScriptMethod' GetEvents {} -P | Add-Member 'ScriptMethod' GetField {} -P | Add-Member 'ScriptMethod' GetFields {} -P | Add-Member 'ScriptMethod' GetFiles {} -P | Add-Member 'ScriptMethod' GetFileSystemInfos {} -P | Add-Member 'ScriptMethod' GetGenericArguments {} -P | Add-Member 'ScriptMethod' GetGenericParameterConstraints {} -P | Add-Member 'ScriptMethod' GetGenericTypeDefinition {} -P | Add-Member 'ScriptMethod' GetInterface {} -P | Add-Member 'ScriptMethod' GetInterfaceMap {} -P | Add-Member 'ScriptMethod' GetInterfaces {} -P | Add-Member 'ScriptMethod' GetLifetimeService {} -P | Add-Member 'ScriptMethod' GetMember {} -P | Add-Member 'ScriptMethod' GetMembers {} -P | Add-Member 'ScriptMethod' GetMethod {} -P | Add-Member 'ScriptMethod' GetMethods {} -P | Add-Member 'ScriptMethod' GetNestedType {} -P | Add-Member 'ScriptMethod' GetNestedTypes {} -P | Add-Member 'ScriptMethod' GetObjectData {} -P | Add-Member 'ScriptMethod' GetProperties {} -P | Add-Member 'ScriptMethod' GetProperty {} -P | Add-Member 'ScriptMethod' GetTypeCode {} -P | Add-Member 'ScriptMethod' IndexOf {} -P | Add-Member 'ScriptMethod' IndexOfAny {} -P | Add-Member 'ScriptMethod' InitializeLifetimeService {} -P | Add-Member 'ScriptMethod' Insert {} -P | Add-Member 'ScriptMethod' InvokeMember {} -P | Add-Member 'ScriptMethod' IsAssignableFrom {} -P | Add-Member 'ScriptMethod' IsDefined {} -P | Add-Member 'ScriptMethod' IsInstanceOfType {} -P | Add-Member 'ScriptMethod' IsNormalized {} -P | Add-Member 'ScriptMethod' IsSubclassOf {} -P | Add-Member 'ScriptMethod' LastIndexOf {} -P | Add-Member 'ScriptMethod' LastIndexOfAny {} -P | Add-Member 'ScriptMethod' MakeArrayType {} -P | Add-Member 'ScriptMethod' MakeByRefType {} -P | Add-Member 'ScriptMethod' MakeGenericType {} -P | Add-Member 'ScriptMethod' MakePointerType {} -P | Add-Member 'ScriptMethod' MoveTo {} -P | Add-Member 'ScriptMethod' Normalize {} -P | Add-Member 'ScriptMethod' PadLeft {} -P | Add-Member 'ScriptMethod' PadRight {} -P | Add-Member 'ScriptMethod' Refresh {} -P | Add-Member 'ScriptMethod' Remove {} -P | Add-Member 'ScriptMethod' Replace {} -P | Add-Member 'ScriptMethod' SetAccessControl {} -P | Add-Member 'ScriptMethod' Split {} -P | Add-Member 'ScriptMethod' StartsWith {} -P | Add-Member 'ScriptMethod' Substring {} -P | Add-Member 'ScriptMethod' ToCharArray {} -P | Add-Member 'ScriptMethod' ToLower {} -P | Add-Member 'ScriptMethod' ToLowerInvariant {} -P | Add-Member 'ScriptMethod' ToUpper {} -P | Add-Member 'ScriptMethod' ToUpperInvariant {} -P | Add-Member 'ScriptMethod' Trim {} -P | Add-Member 'ScriptMethod' TrimEnd {} -P | Add-Member 'ScriptMethod' TrimStart {} -P | Add-Member 'NoteProperty' Chars $s.Chars -P } if ( "Add-Member" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Compare-Object" -eq $_cmdlet ) { $global:_dummy = (Compare-Object 1 2)[0] } if ( "ConvertFrom-SecureString" -eq $_cmdlet ) { $global:_dummy = $null } if ( "ConvertTo-SecureString" -eq $_cmdlet ) { $global:_dummy = convertto-securestring "P@ssW0rD!" -asplaintext -force } if ( "ForEach-Object" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Acl" -eq $_cmdlet ) { $global:_dummy = Get-Acl } if ( "Get-Alias" -eq $_cmdlet ) { $global:_dummy = (Get-Alias)[0] } if ( "Get-AuthenticodeSignature" -eq $_cmdlet ) { $global:_dummy = Get-AuthenticodeSignature $PSHOME\\powershell.exe } if ( "Get-ChildItem" -eq $_cmdlet ) { $global:_dummy = $global:_forgci } if ( "Get-Command" -eq $_cmdlet ) { $global:_dummy = @(iex $str[$i+1])[0] } if ( "Get-Content" -eq $_cmdlet ) { $global:_dummy = (type $PSHOME\\profile.ps1)[0] } if ( "Get-Credential" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Culture" -eq $_cmdlet ) { $global:_dummy = Get-Culture } if ( "Get-Date" -eq $_cmdlet ) { $global:_dummy = Get-Date } if ( "Get-Event" -eq $_cmdlet ) { $global:_dummy = (Get-Event)[0] } if ( "Get-EventLog" -eq $_cmdlet ) { $global:_dummy = @(iex $str[$i+1])[0] } if ( "Get-ExecutionPolicy" -eq $_cmdlet ) { $global:_dummy = Get-ExecutionPolicy } if ( "Get-Help" -eq $_cmdlet ) { $global:_dummy = Get-Help Add-Content } if ( "Get-History" -eq $_cmdlet ) { $global:_dummy = Get-History -Count 1 } if ( "Get-Host" -eq $_cmdlet ) { $global:_dummy = Get-Host } if ( "Get-Item" -eq $_cmdlet ) { $global:_dummy = $global:_forgci } if ( "Get-ItemProperty" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Location" -eq $_cmdlet ) { $global:_dummy = Get-Location } if ( "Get-Member" -eq $_cmdlet ) { $global:_dummy = (1|Get-Member)[0] } if ( "Get-Module" -eq $_cmdlet ) { $global:_dummy = (Get-Module)[0] } if ( "Get-PfxCertificate" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Process" -eq $_cmdlet ) { $global:_dummy = ps powershell } if ( "Get-PSBreakpoint" -eq $_cmdlet ) { $global:_dummy = Add-Member -InputObject (New-Object PSObject) 'NoteProperty' Action '' -P | Add-Member 'NoteProperty' Command '' -P | Add-Member 'NoteProperty' Enabled '' -P | Add-Member 'NoteProperty' HitCount '' -P | Add-Member 'NoteProperty' Id '' -P | Add-Member 'NoteProperty' Script '' -P } if ( "Get-PSCallStack" -eq $_cmdlet ) { $global:_dummy = Get-PSCallStack } if ( "Get-PSDrive" -eq $_cmdlet ) { $global:_dummy = Get-PSDrive Function } if ( "Get-PSProvider" -eq $_cmdlet ) { $global:_dummy = Get-PSProvider FileSystem } if ( "Get-PSSnapin" -eq $_cmdlet ) { $global:_dummy = Get-PSSnapin Microsoft.PowerShell.Core } if ( "Get-Service" -eq $_cmdlet ) { $global:_dummy = (Get-Service)[0] } if ( "Get-TraceSource" -eq $_cmdlet ) { $global:_dummy = Get-TraceSource AddMember } if ( "Get-UICulture" -eq $_cmdlet ) { $global:_dummy = Get-UICulture } if ( "Get-Variable" -eq $_cmdlet ) { $global:_dummy = Get-Variable _ } if ( "Get-WmiObject" -eq $_cmdlet ) { $global:_dummy = @(iex $str[$i+1])[0] } if ( "Group-Object" -eq $_cmdlet ) { $global:_dummy = 1 | group } if ( "Measure-Command" -eq $_cmdlet ) { $global:_dummy = Measure-Command {} } if ( "Measure-Object" -eq $_cmdlet ) { $global:_dummy = Measure-Object } if ( "New-PSDrive" -eq $_cmdlet ) { $global:_dummy = Get-PSDrive Alias } if ( "New-TimeSpan" -eq $_cmdlet ) { $global:_dummy = New-TimeSpan } if ( "Resolve-Path" -eq $_cmdlet ) { $global:_dummy = $PWD } if ( "Select-String" -eq $_cmdlet ) { $global:_dummy = " " | Select-String " " } if ( "Set-Date" -eq $_cmdlet ) { $global:_dummy = Get-Date } if ( $property -ne $null) { foreach ( $name in $property.Split(";", "RemoveEmptyEntries" -as [System.StringSplitOptions]) ) { $global:_dummy = @($global:_dummy.$name)[0] } } } function TabExpansion { # This is the default function to use for tab expansion. It handles simple # member expansion on variables, variable name expansion and parameter completion # on commands. It doesn't understand strings so strings containing ; | ( or { may # cause expansion to fail. param($line, $lastWord) & { # Helper function to write out the matching set of members. It depends # on dynamic scoping to get $_base, _$expression and $_pat function Write-Members ($sep='.') { # evaluate the expression to get the object to examine... Invoke-Expression ('$_val=' + $_expression) if ( $_expression -match '^\\$global:_dummy' ) { $temp = $_expression -replace '^\\$global:_dummy(.*)','$1' $_expression = '$_' + $temp } $_method = [Management.Automation.PSMemberTypes] ` 'Method,CodeMethod,ScriptMethod,ParameterizedProperty' if ($sep -eq '.') { $params = @{view = 'extended','adapted','base'} } else { $params = @{static=$true} } if ( $_val -is [Hashtable] ) { [Object[]]$_keys = $null foreach ( $_name in $_val.Keys ) { $_keys += ` New-Object Microsoft.PowerShell.Commands.MemberDefinition ` [int],$_name,"Property",0 } } if ( $_keys -ne $null ) { $_members = [Object[]](Get-Member @params -InputObject $_val $_pat) + ($_keys | ? {$_.name -like $_pat}) } else { $_members = (Get-Member @params -InputObject $_val $_pat) } foreach ($_m in $_members | Sort-Object membertype,name) { if ($_m.MemberType -band $_method) { # Return a method... $_base + $_expression + $sep + $_m.name + '(' } else { # Return a property... $_base + $_expression + $sep + $_m.name } } } switch -regex ($lastWord) { # Handle property and method expansion at '$_' '(^.*)(\\$_\\.)(\\w*)$' { $_base = $matches[1] $_expression = '$global:_dummy' $_pat = $matches[3] + '*' $global:_dummy = $null Get-PipeLineObject if ( $global:_dummy -eq $null ) { if ( $global:_exp -match '^\\$.*\\(.*$' ) { $type = ( iex $global:_exp.Split("(")[0] ).OverloadDefinitions[0].Split(" ")[0] -replace '\\[[^\\[\\]]*\\]$' -as [type] if ( $_expression -match '^\\$global:_dummy' ) { $temp = $_expression -replace '^\\$global:_dummy(.*)','$1' $_expression = '$_' + $temp } foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } ) { if ($_m.MemberType -eq "Method") { $_base + $_expression + '.' + $_m.name + '(' } else { $_base + $_expression + '.' + $_m.name } } break; } elseif ( $global:_exp -match '^\\[.*\\:\\:.*\\(.*$' ) { $tname, $mname = $_exp.Split(":(", "RemoveEmptyEntries"-as [System.StringSplitOptions])[0,1] $type = @(iex ($tname + '.GetMember("' + $mname + '")'))[0].ReturnType.FullName -replace '\\[[^\\[\\]]*\\]$' -as [type] if ( $_expression -match '^\\$global:_dummy' ) { $temp = $_expression -replace '^\\$global:_dummy(.*)','$1' $_expression = '$_' + $temp } foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } ) { if ($_m.MemberType -eq "Method") { $_base + $_expression + '.' + $_m.name + '(' } else { $_base + $_expression + '.' + $_m.name } } break; } elseif ( $global:_exp -match '^(\\$\\w+(\\[[0-9,\\.]+\\])*(\\.\\w+(\\[[0-9,\\.]+\\])*)*)$' ) { $global:_dummy = @(iex $Matches[1])[0] } else { $global:_dummy = $global:_mix } } Write-Members break; } # Handle property and method expansion rooted at variables... # e.g. $a.b.<tab> '(^.*)(\\$(\\w|\\.)+)\\.(\\w*)$' { $_base = $matches[1] $_expression = $matches[2] $_pat = $matches[4] + '*' [void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock] if ( $_expression -match '^\\$_\\.' ) { $_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1') } Write-Members break; } # Handle simple property and method expansion on static members... # e.g. [datetime]::n<tab> '(^.*)(\\[(\\w|\\.)+\\])\\:\\:(\\w*)$' { $_base = $matches[1] $_expression = $matches[2] $_pat = $matches[4] + '*' Write-Members '::' break; } # Handle complex property and method expansion on static members # where there are intermediate properties... # e.g. [datetime]::now.d<tab> '(^.*)(\\[(\\w|\\.)+\\]\\:\\:(\\w+\\.)+)(\\w*)$' { $_base = $matches[1] # everything before the expression $_expression = $matches[2].TrimEnd('.') # expression less trailing '.' $_pat = $matches[5] + '*' # the member to look for... Write-Members break; } # Handle variable name expansion... '(^.*\\$)(\\w+)$' { $_prefix = $matches[1] $_varName = $matches[2] foreach ($_v in Get-ChildItem ('variable:' + $_varName + '*')) { $_prefix + $_v.name } break; } # Handle env&function drives variable name expansion... '(^.*\\$)(.*\\:)(\\w+)$' { $_prefix = $matches[1] $_drive = $matches[2] $_varName = $matches[3] if ($_drive -eq "env:" -or $_drive -eq "function:") { foreach ($_v in Get-ChildItem ($_drive + $_varName + '*')) { $_prefix + $_drive + $_v.name } } break; } # Handle array's element property and method expansion # where there are intermediate properties... # e.g. foo[0].n.b<tab> '(^.*)(\\$((\\w+\\.)|(\\w+(\\[(\\w|,)+\\])+\\.))+)(\\w*)$' { $_base = $matches[1] $_expression = $matches[2].TrimEnd('.') $_pat = $Matches[8] + '*' [void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock] if ( $_expression -match '^\\$_\\.' ) { $_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1') } Write-Members break; } # Handle property and method expansion rooted at type object... # e.g. [System.Type].a<tab> '(^\\[(\\w|\\.)+\\])\\.(\\w*)$' { if ( $(iex $Matches[1]) -isnot [System.Type] ) { break; } $_expression = $Matches[1] $_pat = $Matches[$matches.Count-1] + '*' Write-Members break; } # Handle complex property and method expansion on type object members # where there are intermediate properties... # e.g. [datetime].Assembly.a<tab> '^(\\[(\\w|\\.)+\\]\\.(\\w+\\.)+)(\\w*)$' { $_expression = $matches[1].TrimEnd('.') # expression less trailing '.' $_pat = $matches[4] + '*' # the member to look for... if ( $(iex $_expression) -eq $null ) { break; } Write-Members break; } # Handle property and method expansion rooted at close parenthes... # e.g. (123).a<tab> '^(.*)\\)((\\w|\\.)*)\\.(\\w*)$' { $_base = $Matches[1] + ")" if ( $matches[3] -eq $null) { $_expression = '[System.Type]' } else { $_expression = '[System.Type]' + $Matches[2] } $_pat = $matches[4] + '*' iex "$_expression | Get-Member $_pat | sort MemberType,Name" | % { if ( $_.MemberType -like "*Method*" -or $_.MemberType -like "*Parameterized*" ) { $parenthes = "(" } if ( $Matches[2] -eq "" ) { $_base + "." + $_.Name + $parenthes } else { $_base + $Matches[2] + "." + $_.Name + $parenthes } } break; } # Handle .NET type name expansion ... # e.g. [Microsoft.PowerShell.Com<tab> '^\\[((\\w+\\.?)*)$' { $_opt = $matches[1] + '*' if ( $_opt -eq "*" ) { $_TypeAccelerators -like $_opt -replace '^(.*)$', '[$1]' } else { $_TypeAccelerators -like $_opt -replace '^(.*)$', '[$1]' "CmdletBinding", "Parameter", "Alias", "ValidateArguments", "ValidateCount", "ValidateEnumeratedArguments", "ValidateLength", "ValidateNotNull", "ValidateNotNullOrEmpty", "ValidatePattern", "ValidateRange", "ValidateScript", "ValidateSet", "AllowEmptyCollection", "AllowEmptyString", "AllowNull" ` -like $_opt -replace '^(.*)$', '[$1(' Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1) '[' Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1) '[' } break; } # Handle file/directory name which contains $env: variable # e.g. $env:windir\\<tab> '^\\$(env:)?\\w+([\\\\/][^\\\\/]*)*$' { $path = iex ('"' + $Matches[0] + '"') if ( $Matches[2].Length -gt 1 ) { $parent = Split-Path $path -Parent $leaf = (Split-Path $path -Leaf) + '*' } else { $parent = $path $leaf = '*' } if ( Test-Path $parent ) { $i = $Matches[0].LastIndexOfAny("/\\") $_base = $Matches[0].Substring(0,$i+1) [IO.Directory]::GetFileSystemEntries( $parent, $leaf ) | % { $_base + ($_.Split("\\/")[-1] -replace '([\\$\\s&])','`$1' -replace '([[\\]])', '````$1') } } } # Handle file glob expansion ... # e.g. *.txt~about*@<tab> '^(\\^?([^~]+))(~(.*))*@$' { if ( $Matches[1] -notlike "^*" ) { $include = $Matches[2] -replace '``','`' if ( $Matches[3] ) { $exclude = $Matches[3].Split("~", "RemoveEmptyEntries" -as [System.StringSplitOptions]) -replace '``','`' } } else { $include = "*" $exclude = $Matches[2] -replace '``','`' } $fse = [IO.Directory]::GetFileSystemEntries($PWD) $fse = $fse -replace '.*[\\\\/]([^/\\\\]*)$','$1' % -in ($fse -like $include) { $fse = $_; $exclude | % { $fse = $fse -notlike $_ } } $fse = $fse -replace '^.*\\s.*$', ("'`$0'") $fse = $fse -replace '([\\[\\]])', '``$1' -replace '^.*([\\[\\]]).*$', ("'`$0'") $fse = $fse -replace "''", "'" $OFS = ", "; "$fse" $OFS = ", "; "* -Filter $include " + $(if($exclude){"-Exclude $exclude"}) $Matches[0].Substring(0, $Matches[0].Length-1) break; } # Handle command buffer stack... '(.*);(.?)$' { $_base = $Matches[1] if ( $Matches[2] -eq ":" -or $Matches[2] -eq "," ) { if ( $_cmdstack.Count -gt 0 ) { $_base + $global:_cmdstack.Pop() } else { "" } } elseif ( $Matches[2] -eq "" ) { $global:_cmdstack.Push($line.SubString(0,$line.Length-1)) [System.Windows.Forms.SendKeys]::SendWait("{ESC}") } } # Do completion on parameters... '^-([\\w0-9]*)' { $_pat = $matches[1] + '*' # extract the command name from the string # first split the string into statements and pipeline elements # This doesn't handle strings however. $_command = [regex]::Split($line, '[|;=]')[-1] # Extract the trailing unclosed block e.g. ls | foreach { cp if ($_command -match '\\{([^\\{\\}]*)$') { $_command = $matches[1] } # Extract the longest unclosed parenthetical expression... if ($_command -match '\\(([^()]*)$') { $_command = $matches[1] } # take the first space separated token of the remaining string # as the command to look up. Trim any leading or trailing spaces # so you don't get leading empty elements. $_command = $_command.Trim().Split()[0] # now get the info object for it... $_command = @(Get-Command -type 'All' $_command)[0] # loop resolving aliases... while ($_command.CommandType -eq 'alias') { $_command = @(Get-Command -type 'All' $_command.Definition)[0] } if ( $_command.name -eq "powershell.exe" ) { if ( $global:_PSexeOption ) { $global:_PSexeOption -like "-$_pat" -replace '^(-[^,]+).*$', '$1' | sort } else { ($global:_PSexeOption = powershell.exe -?) -like "-$_pat" -replace '^(-[^,]+).*$', '$1' | sort } break; } if ( $_command -ne $null ) { # expand the parameter sets and emit the matching elements foreach ($_n in $_command.Parameters.Keys | sort) { if ($_n -like $_pat) { '-' + $_n } } } elseif ( $line -match 'switch\\s+(-\\w+\\s+)*-(\\w*)$') { $_pat = $Matches[2] + '*' "regex", "wildcard", "exact", "casesensitive", "file" -like $_pat -replace '^(.*)$', '-$1' break; } else { "-and", "-as", "-band", "-bnot", "-bor", "-bxor", "-ccontains", "-ceq", "-cge", "-cgt", "-cle", "-clike", "-clt", "-cmatch", "-cne", "-cnotcontains", "-cnotlike", "-cnotmatch", "-contains", "-creplace", "-csplit", "-eq", "-f", "-ge", "-gt", "-icontains", "-ieq", "-ige", "-igt", "-ile", "-ilike", "-ilt", "-imatch", "-ine", "-inotcontains", "-inotlike", "-inotmatch", "-ireplace", "-is", "-isnot", "-isplit", "-join", "-le", "-like", "-lt", "-match", "-ne", "-not", "-notcontains", "-notlike", "-notmatch", "-or", "-replace", "-split", "-xor" -like "-$_pat" } break; } # Tab complete against history either #<pattern> or #<id> '^#(\\w*)' { $_pattern = $matches[1] if ($_pattern -match '^[0-9]+$') { Get-History -ea SilentlyContinue -Id $_pattern | Foreach { $_.CommandLine } } else { $_pattern = '*' + $_pattern + '*' Get-History | Sort-Object -Descending Id| Foreach { $_.CommandLine } | where { $_ -like $_pattern } } break; } # try to find a matching command... default { # parse the script... $_tokens = [System.Management.Automation.PSParser]::Tokenize($line, [ref] $null) if ( $_tokens ) { $_lastToken = $_tokens[$_tokens.count - 1] if ($_lastToken.Type -eq 'Member') { $_pat = $_lastToken.Content + '*' $i=$_tokens.count; do { $i-- } until ( $_tokens[$i].Type -eq "Attribute") if ( $lastWord -match "^(.*)([\\(,])\\w*$" ) { $_base = $matches[1] + $matches[2] } switch ( $_tokens[$i].Content ) { 'Parameter' { [System.Management.Automation.ParameterAttribute].GetProperties() | ? { $_.Name -like $_pat -and $_.Name -ne "TypeId" } | % { $_base + $_.Name + "=" } } 'CmdletBinding' { [System.Management.Automation.CmdletBindingAttribute].GetProperties() | ? { $_.Name -like $_pat -and $_.Name -ne "TypeId" } | % { $_base + $_.Name + "=" } } } break; } if ( $_tokens[1].Type -eq "Attribute") { if ( $line.Split("(").Count -gt $line.Split(")").Count ) { if ( $lastWord -match "^(.*)([\\(,])\\w*$" ) { $_base = $matches[1] + $matches[2] } switch ( $_tokens[1].Content ) { 'Parameter' { [System.Management.Automation.ParameterAttribute].GetProperties() | % { $_base + $_.Name + "=" } } 'CmdletBinding' { [System.Management.Automation.CmdletBindingAttribute].GetProperties() | % { $_base + $_.Name + "=" } } } } break; } } $lastex = [regex]::Split($line, '[|;]')[-1] if ( $lastex -match '^\\s*(\\$\\w+(\\[[0-9,]+\\])*(\\.\\w+(\\[[0-9,]+\\])*)*)\\s*=\\s+(("\\w+"\\s*,\\s+)*)"\\w+"\\s*-as\\s+$' ) { if ( $Matches[6] -ne $nul ) { $brackets = "[]" } '['+ $global:_enum + $brackets + ']' break; } if ( $lastex -match '^\\s*(\\$\\w+(\\[[0-9,]+\\])*(\\.\\w+(\\[[0-9,]+\\])*)*)\\s*=\\s+(("\\w+"\\s*,\\s+)*)\\s*(\\w*)$' ) { $_pat = $Matches[7] + '*' $_type = @(iex $Matches[1])[0].GetType() if ( $_type.IsEnum ) { $global:_enum = $_type.FullName [Enum]::GetValues($_type) -like $_pat -replace '^(.*)$','"$1"' break; } } $lastex = [regex]::Split($line, '[|;=]')[-1] if ($lastex -match '[[$].*\\w+\\(.*-as\\s*$') { '['+ $global:_enum + ']' } elseif ( $lastex -match '([[$].*(\\w+))\\((.*)$' ) { $_method = $Matches[1] if ( $Matches[3] -match "(.*)((`"|')(\\w+,)+(\\w*))$" ) { $continuous = $true $_opt = $Matches[5] + '*' $_base = $Matches[2].TrimStart('"') -replace '(.*,)\\w+$','$1' $position = $Matches[1].Split(",").Length } else { $continuous = $false $_opt = ($Matches[3].Split(',')[-1] -replace '^\\s*','') + "*" $position = $Matches[3].Split(",").Length } if ( ($_mdefs = iex ($_method + ".OverloadDefinitions")) -eq $null ) { $tname, $mname = $_method.Split(":", "RemoveEmptyEntries" -as [System.StringSplitOptions]) $_mdefs = iex ($tname + '.GetMember("' + $mname + '") | % { $_.ToString() }') } foreach ( $def in $_mdefs ) { [void] ($def -match '\\((.*)\\)') foreach ( $param in [regex]::Split($Matches[1], ', ')[$position-1] ) { if ($param -eq $null -or $param -eq "") { continue; } $type = $param.split()[0] if ( $type -like '*`[*' -or $type -eq "Params" -or $type -eq "" ) { continue; } $fullname = @($_typenames -like "*$type*") foreach ( $name in $fullname ) { if ( $continuous -eq $true -and ( $name -as [System.Type] ).IsEnum ) { $output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$',($_base + '$1') $output | sort } elseif ( ( $name -as [System.Type] ).IsEnum ) { $global:_enum = $name $output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$','"$1"' $output | sort } } } } if ( $output -ne $null ) { break; } } if ( $line -match '(function|filter)\\s+(\\w*)$') { $_pat = 'function:\\' + $Matches[2] + '*' Get-ChildItem $_pat| % { $_.Name } break; } if ( $line[-1] -eq " " ) { $_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-1] # now get the info object for it... $_cmdlet = @(Get-Command -type 'cmdlet,alias,function' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias,function' $_cmdlet.Definition)[0] } if ( "Set-ExecutionPolicy" -eq $_cmdlet.Name ) { "Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" | sort break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ) { Get-TraceSource | % { $_.Name } | sort -Unique break; } if ( "New-Object" -eq $_cmdlet.Name ) { $_TypeAccelerators break; } if ( $_cmdlet.Noun -like "*WMI*" ) { $_WMIClasses break; } if ( "Get-Process" -eq $_cmdlet.Name ) { Get-Process | % { $_.Name } | sort break; } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name ) { if ( $global:_snapin -ne $null ) { $global:_snapin break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin break; } } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" ) { Get-PSDrive | sort break; } if ( "Get-Eventlog" -eq $_cmdlet.Name ) { Get-EventLog -List | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name -or "help" -eq $_cmdlet.Name ) { Get-Help -Category all | % { $_.Name } | sort -Unique break; } if ( "Get-Service", "Restart-Service", "Resume-Service", "Start-Service", "Stop-Service", "Suspend-Service" ` -contains $_cmdlet.Name ) { Get-Service | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name ) { Get-Command -CommandType All | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object", "ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" ` -contains $_cmdlet.Name ) { Get-PipeLineObject $_dummy | gm -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name ) { Get-Variable -Scope Global | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name ) { Get-Alias | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( $line[-1] -eq " " ) { # extract the command name from the string # first split the string into statements and pipeline elements # This doesn't handle strings however. $_cmdlet = [regex]::Split($line, '[|;=]')[-1] # Extract the trailing unclosed block e.g. ls | foreach { cp if ($_cmdlet -match '\\{([^\\{\\}]*)$') { $_cmdlet = $matches[1] } # Extract the longest unclosed parenthetical expression... if ($_cmdlet -match '\\(([^()]*)$') { $_cmdlet = $matches[1] } # take the first space separated token of the remaining string # as the command to look up. Trim any leading or trailing spaces # so you don't get leading empty elements. $_cmdlet = $_cmdlet.Trim().Split()[0] # now get the info object for it... $_cmdlet = @(Get-Command -type 'Application' $_cmdlet)[0] if ( $_cmdlet.Name -eq "powershell.exe" ) { "-PSConsoleFile", "-Version", "-NoLogo", "-NoExit", "-Sta", "-NoProfile", "-NonInteractive", "-InputFormat", "-OutputFormat", "-EncodedCommand", "-File", "-Command" | sort break; } if ( $_cmdlet.Name -eq "fsutil.exe" ) { "behavior query", "behavior set", "dirty query", "dirty set", "file findbysid", "file queryallocranges", "file setshortname", "file setvaliddata", "file setzerodata", "file createnew", "fsinfo drives", "fsinfo drivetype", "fsinfo volumeinfo", "fsinfo ntfsinfo", "fsinfo statistics", "hardlink create", "objectid query", "objectid set", "objectid delete", "objectid create", "quota disable", "quota track", "quota enforce", "quota violations", "quota modify", "quota query", "reparsepoint query", "reparsepoint delete", "sparse setflag", "sparse queryflag", "sparse queryrange", "sparse setrange", "usn createjournal", "usn deletejournal", "usn enumdata", "usn queryjournal", "usn readdata", "volume dismount", "volume diskfree" | sort break; } if ( $_cmdlet.Name -eq "net.exe" ) { "ACCOUNTS ", " COMPUTER ", " CONFIG ", " CONTINUE ", " FILE ", " GROUP ", " HELP ", "HELPMSG ", " LOCALGROUP ", " NAME ", " PAUSE ", " PRINT ", " SEND ", " SESSION ", "SHARE ", " START ", " STATISTICS ", " STOP ", " TIME ", " USE ", " USER ", " VIEW" | sort break; } if ( $_cmdlet.Name -eq "ipconfig.exe" ) { "/?", "/all", "/renew", "/release", "/flushdns", "/displaydns", "/registerdns", "/showclassid", "/setclassid" break; } } if ( $line -match '\\w+\\s+(\\w+(\\.|[^\\s\\.])*)$' ) { #$_opt = $Matches[1] + '*' $_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-2] $_opt = $Matches[1].Split(" ,")[-1] + '*' $_base = $Matches[1].Substring(0,$Matches[1].Length-$Matches[1].Split(" ,")[-1].length) # now get the info object for it... $_cmdlet = @(Get-Command -type 'cmdlet,alias,function' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias,function' $_cmdlet.Definition)[0] } if ( "Set-ExecutionPolicy" -eq $_cmdlet.Name ) { "Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" -like $_opt | sort break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ) { Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "New-Object" -eq $_cmdlet.Name ) { $_TypeAccelerators -like $_opt Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1) Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1) break; } if ( $_cmdlet.Name -like "*WMI*" ) { Write-ClassNames $_WMIClasses ($_opt.Split("_").Count-1) -sep '_' break; } if ( "Get-Process" -eq $_cmdlet.Name ) { Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name ) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-PSProvider" -eq $_cmdlet.Name ) { Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Eventlog" -eq $_cmdlet.Name ) { Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name -or "help" -eq $_cmdlet.Name ) { Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique break; } if ( "Get-Service", "Restart-Service", "Resume-Service", "Start-Service", "Stop-Service", "Suspend-Service" ` -contains $_cmdlet.Name ) { Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name ) { Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object", "ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" ` -contains $_cmdlet.Name ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name ) { Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name ) { Get-Alias -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( $line -match '(-(\\w+))\\s+([^-]*$)' ) { $_param = $matches[2] + '*' $_opt = $Matches[3].Split(" ,")[-1] + '*' $_base = $Matches[3].Substring(0,$Matches[3].Length-$Matches[3].Split(" ,")[-1].length) #$_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,Function,Filter,ExternalScript' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'Cmdlet,Alias,Function,Filter,ExternalScript' $_cmdlet.Definition)[0] } if ( $_param.TrimEnd("*") -eq "ea" -or $_param.TrimEnd("*") -eq "wa" ) { "SilentlyContinue", "Stop", "Continue", "Inquire" | ? { $_ -like $_opt } | sort -Unique break; } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide" -contains $_cmdlet.Name ` -and "groupBy" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_.Name } break; } if ( $_param.TrimEnd("*") -eq "ev" -or $_param.TrimEnd("*") -eq "ov" -or "ErrorVariable" -like $_param -or "OutVariable" -like $_param) { Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort break; } if ( "Tee-Object" -eq $_cmdlet.Name -and "Variable" -like $_param ) { Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort break; } if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name ` -and "Name" -like $_param) { Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Export-Alias", "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name ` -and "Name" -like $_param) { Get-Alias -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Out-File","Export-CSV","Select-String","Export-Clixml" -contains $_cmdlet.Name ` -and "Encoding" -like $_param) { "Unicode", "UTF7", "UTF8", "ASCII", "UTF32", "BigEndianUnicode", "Default", "OEM" | ? { $_ -like $_opt } | sort -Unique break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ` -and "Name" -like $_param) { Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "New-Object" -like $_cmdlet.Name ) { if ( "ComObject" -like $_param ) { $_ProgID -like $_opt | % { $_ -replace '\\s','` ' } break; } if ( "TypeName" -like $_param ) { if ( $_opt -eq "*" ) { $_TypeAccelerators -like $_opt } else { $_TypeAccelerators -like $_opt Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1) Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1) } break; } } if ( "New-Item" -eq $_cmdlet.Name ) { if ( "ItemType" -like $_param ) { "directory", "file" -like $_opt break; } } if ( "Get-Location", "Get-PSDrive", "Get-PSProvider", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name ` -and "PSProvider" -like $_param ) { Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Location" -eq $_cmdlet.Name -and "PSDrive" -like $_param ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" -like $_param ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name -and "PSSnapin" -like $_param) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + $_ } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" ` -contains $_cmdlet.Name -and "Name" -like $_param ) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + $_ } break; } } if ( "Clear-Variable", "Export-Alias", "Get-Alias", "Get-PSDrive", "Get-Variable", "Import-Alias", "New-Alias", "New-PSDrive", "New-Variable", "Remove-Variable", "Set-Alias", "Set-Variable" ` -contains $_cmdlet.Name -and "Scope" -like $_param ) { "Global", "Local", "Script" -like $_opt break; } if ( "Get-Process", "Stop-Process", "Wait-Process" -contains $_cmdlet.Name -and "Name" -like $_param ) { Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Eventlog" -eq $_cmdlet.Name -and "LogName" -like $_param ) { Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name -or "help" -eq $_cmdlet.Name ) { if ( "Name" -like $_param ) { Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique break; } if ( "Category" -like $_param ) { "Alias", "Cmdlet", "Provider", "General", "FAQ", "Glossary", "HelpFile", "All" -like $_opt | sort | % { $_base + $_ } break; } } if ( "Get-Service", "Restart-Service", "Resume-Service", "Start-Service", "Stop-Service", "Suspend-Service" ` -contains $_cmdlet.Name ) { if ( "Name" -like $_param ) { Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "DisplayName" -like $_param ) { Get-Service -Name $_opt | sort DisplayName | % { $_base + ($_.DisplayName -replace '\\s','` ') } break; } } if ( "New-Service" -eq $_cmdlet.Name -and "dependsOn" -like $_param ) { Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Get-EventLog" -eq $_cmdlet.Name -and "EntryType" -like $_param ) { "Error", "Information", "FailureAudit", "SuccessAudit", "Warning" -like $_opt | sort | % { $_base + $_ } break; } if ( "Get-Command" -eq $_cmdlet.Name -and "Name" -like $_param ) { Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( $_cmdlet.Noun -like "*WMI*" ) { if ( "Class" -like $_param ) { Write-ClassNames $_WMIClasses ($_opt.Split("_").Count-1) -sep '_' break; } } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object", "ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" ` -contains $_cmdlet.Name -and "Property" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Select-Object" -eq $_cmdlet.Name ) { if ( "ExcludeProperty" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "ExpandProperty" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_.Name } break; } } select -InputObject $_cmdlet -ExpandProperty ParameterSets | select -ExpandProperty Parameters | ? { $_.Name -like $_param } | ? { $_.ParameterType.IsEnum } | % { [Enum]::GetNames($_.ParameterType) } | ? { $_ -like $_opt } | sort -Unique | % { $_base + $_ } } if ($_tokens) { $_lastToken = $_tokens[$_tokens.count - 1] if ($_lastToken.Type -eq 'Command') { $_cmd = $_lastToken.Content # don't look for paths... if ($_cmd.IndexOfAny('/\\') -eq -1) { # handle parsing errors - the last token string should be the last # string in the line... if ($lastword.substring($lastword.length-$_cmd.length) -eq $_cmd) { $_pat = $_cmd + '*' $_base = $lastword.substring(0, $lastword.length-$_cmd.length) "begin {", "break", "catch {", "continue", "data {", "do {", "dynamicparam (", "else {", "elseif (", "end {", "exit", "filter ", "finally {", "for (", "foreach ", "from", "function ", "if (", "in ", "param (", "process {", "return", "switch ", "throw ", "trap ", "try {", "until (", "while (" ` -like $_pat | % {'{0}{1}' -f $_base,$_ } $ExecutionContext.InvokeCommand.GetCommandName($_pat,$true, $false) | Sort-Object -Unique | ForEach-Object {'{0}{1}' -f $_base,$_ } } } } } } } } }
PowerShellCorpus/PoshCode/Get-Exchange-Mail_1.ps1
Get-Exchange-Mail_1.ps1
[Reflection.Assembly]::LoadFile("C:\\Program Files\\Microsoft\\Exchange\\Web Services\\1.1\\Microsoft.Exchange.WebServices.dll") | Out-Null $s = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2007_SP1) $s.Credentials = New-Object Net.NetworkCredential('email@domain', 'password') $s.Url = new-object Uri("https://red001.mail.microsoftonline.com/ews/exchange.asmx") $inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox) $mails = $inbox.FindItems(5) $mails | % {$_.Load()} $mails
PowerShellCorpus/PoshCode/Report-RecipientCounts_1.ps1
Report-RecipientCounts_1.ps1
<# .SYNOPSIS Report-RecipientCounts.ps1 Keep a running total of daily recipient count distribution. .DESCRIPTION Keep a running total of daily recipient count distribution. .PARAMETER Days The number of days back to examine logs. Default = 1 (Yesterday) .EXAMPLE Report-RecipientCounts.ps1 Get the report for yesterday. .EXAMPLE Report-RecipientCounts.ps1 -Days 3 Get the report for 3 days ago, which was missed .NOTES Original framework for this report came from: http://www.msexchange.org/kbase/ExchangeServerTips/ExchangeServer2010/Monitoring/E-mailRecipientNumberDistribution.html I modified the script slightly so we can have a running history and a quick view web page. #> param( [int]$Days= 1 ) # set the time period for the report - default is yesterday $Days = $Days * (-1) $Start = get-date $((get-date).adddays($Days)) -hour 00 -minute 00 -second 00 $End = get-date $((get-date).adddays($Days)) -hour 23 -minute 59 -second 59 #=====> TO DO -- change <webserver> to a location in your environment $HistoryFile = '\\\\<webserver>\\RecipientCounts.CSV' $HTMLOutFile = '\\\\<webserver>\\RecipientCounts.htm' $RecipientCounts = @() If (Test-Path$HistoryFile){$RecipientCounts = Import-Csv $HistoryFile} # Create a new object to hold today's finding $NewCountObj = New-ObjectPSObject $NewCountObj | Add-Member -typeNoteProperty -name Date -value (get-date $Start -Format yyyyMMdd) $NewCountObj | Add-Member -typeNoteProperty -name '1' -value (0) $NewCountObj | Add-Member -typeNoteProperty -name '2' -value (0) $NewCountObj | Add-Member -typeNoteProperty -name '5' -value (0) $NewCountObj | Add-Member -typeNoteProperty -name '10' -value (0) $NewCountObj | Add-Member -typeNoteProperty -name '30' -value (0) $NewCountObj | Add-Member -typeNoteProperty -name '50' -value (0) $NewCountObj | Add-Member -typeNoteProperty -name '75' -value (0) $NewCountObj | Add-Member -typeNoteProperty -name '100' -value (0) $NewCountObj | Add-Member -typeNoteProperty -name '150' -value (0) $NewCountObj | Add-Member -typeNoteProperty -name '200' -value (0) $NewCountObj | Add-Member -typeNoteProperty -name '250' -value (0) $NewCountObj | Add-Member -typeNoteProperty -name '300' -value (0) $NewCountObj | Add-Member -typeNoteProperty -name '350' -value (0) $NewCountObj | Add-Member -typeNoteProperty -name '400' -value (0) $NewCountObj | Add-Member -typeNoteProperty -name '500' -value (0) $NewCountObj | Add-Member -typeNoteProperty -name '600' -value (0) $NewCountObj | Add-Member -typeNoteProperty -name '700' -value (0) $NewCountObj | Add-Member -typeNoteProperty -name '800' -value (0) $NewCountObj | Add-Member -typeNoteProperty -name '900' -value (0) $NewCountObj | Add-Member -typeNoteProperty -name '1000' -value (0) $NewCountObj | Add-Member -typeNoteProperty -name '3000' -value (0) $NewCountObj | Add-Member -typeNoteProperty -name '5000' -value (0) $NewCountObj | Add-Member -typeNoteProperty -name 'Big' -value (0) Get-TransportServer | Get-MessageTrackingLog -ResultSize Unlimited -EventID RECEIVE -Start $Start -End $End | ? {$_.Source -eq "STOREDRIVER"} | Select RecipientCount | ForEach { If ($_.RecipientCount-eq 1) {$NewCountObj.'1'++ } If ($_.RecipientCount-eq 2) {$NewCountObj.'2'++ } If ($_.RecipientCount-gt 2 -and $_.RecipientCount -le 5) {$NewCountObj.'5'++ } If ($_.RecipientCount-gt 5 -and $_.RecipientCount -le 10) {$NewCountObj.'10'++ } If ($_.RecipientCount-gt 10 -and $_.RecipientCount -le 30) {$NewCountObj.'30'++ } If ($_.RecipientCount-gt 30 -and $_.RecipientCount -le 50) {$NewCountObj.'50'++ } If ($_.RecipientCount-gt 50 -and $_.RecipientCount -le 75) {$NewCountObj.'75'++ } If ($_.RecipientCount-gt 75 -and $_.RecipientCount -le 100) {$NewCountObj.'100'++ } If ($_.RecipientCount-gt 100 -and $_.RecipientCount -le 150) {$NewCountObj.'150'++ } If ($_.RecipientCount-gt 150 -and $_.RecipientCount -le 200) {$NewCountObj.'200'++ } If ($_.RecipientCount-gt 200 -and $_.RecipientCount -le 250) {$NewCountObj.'250'++ } If ($_.RecipientCount-gt 250 -and $_.RecipientCount -le 300) {$NewCountObj.'300'++ } If ($_.RecipientCount-gt 300 -and $_.RecipientCount -le 350) {$NewCountObj.'350'++ } If ($_.RecipientCount-gt 350 -and $_.RecipientCount -le 400) {$NewCountObj.'400'++ } If ($_.RecipientCount-gt 400 -and $_.RecipientCount -le 500) {$NewCountObj.'500'++ } If ($_.RecipientCount-gt 500 -and $_.RecipientCount -le 600) {$NewCountObj.'600'++ } If ($_.RecipientCount-gt 600 -and $_.RecipientCount -le 700) {$NewCountObj.'700'++ } If ($_.RecipientCount-gt 700 -and $_.RecipientCount -le 800) {$NewCountObj.'800'++ } If ($_.RecipientCount-gt 800 -and $_.RecipientCount -le 900) {$NewCountObj.'900'++ } If ($_.RecipientCount-gt 900 -and $_.RecipientCount -le 1000) {$NewCountObj.'1000'++ } If ($_.RecipientCount-gt 1000 -and $_.RecipientCount -le 3000) {$NewCountObj.'3000'++ } If ($_.RecipientCount-gt 3000 -and $_.RecipientCount -le 5000) {$NewCountObj.'5000'++ } If ($_.RecipientCount-gt 5000) {$NewCountObj.Big++ } } $NewCounts= @() if ($RecipientCounts) { $NewCounts = @($RecipientCounts) + @($NewCountObj) }Else { $NewCounts = $NewCountObj } $NewCounts=$NewCounts | Sort Date-Descending $NewCounts | Export-Csv $HistoryFile -NoTypeInformation # Simple Headers $Header1 = '<h2><font Color = #151b8d><p style="text-align: center;"><b>Recipient Counts History Report</b></p></font></h2>' $Header2 = '<h4><font Color = #151b8d><p style="text-align: center;"><b>(Updated Daily via[' + $(split-path $MyInvocation.InvocationName -Leaf) + '])</b></p></Font></h4>' $Header3 = '<h3><font Color = #800517><p style="text-align: center;">' + $(Get-Date) + '</font></H3></p>' $a = "<style>" $a = $a + "BODY{background-color:LightCyan;text-align: center;}" $a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;text-align: center;}" $a = $a + "TH{border-width: 1px;padding: 1px;border-style: solid;border-color: black;background-color:Bisque}" $a = $a + "TD{border-width: 1px;padding: 1px;border-style: solid;border-color: black;background-color:AntiqueWhite}" $a = $a + "</style>" $NewCounts | ConvertTo-Html -Head ($A,$Header1,$Header2,$Header3) | out-file $HTMLOutFile -Force
PowerShellCorpus/PoshCode/Import-Certificate_4.ps1
Import-Certificate_4.ps1
function Import-Certificate {\n<#\n .SYNOPSIS\n Imports certificate in specified certificate store.\n\n .DESCRIPTION\n Imports certificate in specified certificate store.\n\n .PARAMETER CertFile\n The certificate file to be imported.\n\n .PARAMETER StoreNames\n The certificate store(s) in which the certificate should be imported.\n\n .PARAMETER LocalMachine\n Using the local machine certificate store to import the certificate\n\n .PARAMETER CurrentUser\n Using the current user certificate store to import the certificate\n\n .PARAMETER CertPassword\n The password which may be used to protect the certificate file\n\n .EXAMPLE\n PS C:\\> Import-Certificate C:\\Temp\\myCert.cer\n\n Imports certificate file myCert.cer into the current users personal store\n \n .EXAMPLE\n PS C:\\> Import-Certificate -CertFile C:\\Temp\\myCert.cer -StoreNames my\n \n Imports certificate file myCert.cer into the current users personal store\n\n .EXAMPLE\n PS C:\\> Import-Certificate -Cert $certificate -StoreNames my -StoreType LocalMachine\n \n Imports the certificate stored in $certificate into the local machines personal store \n\n .EXAMPLE\n PS C:\\> Import-Certificate -Cert $certificate -SN my -ST Machine\n \n Imports the certificate stored in $certificate into the local machines personal store using alias names\n\n .EXAMPLE\n PS C:\\> ls cert:\\currentUser\\TrustedPublisher | Import-Certificate -ST Machine -SN TrustedPublisher\n \n Copies the certificates found in current users TrustedPublishers store to local machines TrustedPublisher using alias \n\n .INPUTS\n System.String|System.Security.Cryptography.X509Certificates.X509Certificate2, System.String, System.String\n\n .OUTPUTS\n NA\n\n .NOTES\n NAME: Import-Certificate\n AUTHOR: Patrick Sczepanksi (Original anti121)\n VERSION: 20110502\n #Requires -Version 2.0\n .LINK\n http://poshcode.org/2643\n http://poshcode.org/1937 (Link to original script)\n\n#>\n\n [CmdletBinding()]\n param\n (\n [Parameter(ValueFromPipeline=$true,Mandatory=$true, Position=0, ParameterSetName="CertFile")]\n [System.IO.FileInfo]\n $CertFile,\n\n [Parameter(ValueFromPipeline=$true,Mandatory=$true, Position=0, ParameterSetName="Cert")]\n [System.Security.Cryptography.X509Certificates.X509Certificate2]\n $Cert,\n \n [Parameter(Position=1)]\n [Alias("SN")]\n [string[]] $StoreNames = "My",\n \n [Parameter(Position=2)]\n [Alias("Type","ST")]\n [ValidateSet("LocalMachine","Machine","CurrentUser","User")]\n [string]$StoreType = "CurrentUser",\n\n [Parameter(Position=3)]\n [Alias("Password","PW")]\n [string] $CertPassword\n )\n \n begin\n {\n [void][System.Reflection.Assembly]::LoadWithPartialName("System.Security")\n }\n \n process \n {\n switch ($pscmdlet.ParameterSetName) {\n "CertFile" {\n try {\n $Cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $($CertFile.FullName),$CertPassword\n }\n catch { \n Write-Error ("Error reading '$CertFile': $_ .") -ErrorAction:Continue\n }\n }\n "Cert" {\n \n }\n default {\n Write-Error "Missing parameter:`nYou need to specify either a certificate or a certificate file name."\n }\n }\n\n switch -regex ($storeType) {\n "Machine$" { $StoreScope = "LocalMachine" }\n "User$" { $StoreScope = "CurrentUser" }\n } \n \n if ( $Cert ) {\n $StoreNames | ForEach-Object {\n $StoreName = $_\n Write-Verbose " [Import-Certificate] :: $($Cert.Subject) ($($Cert.Thumbprint))"\n Write-Verbose " [Import-Certificate] :: Import into cert:\\$StoreScope\\$StoreName"\n \n if (Test-Path "cert:\\$StoreScope\\$StoreName") {\n try\n {\n $store = New-Object System.Security.Cryptography.X509Certificates.X509Store $StoreName, $StoreScope\n $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)\n $store.Add($Cert)\n if ( $CertFile ) {\n Write-Verbose " [Import-Certificate] :: Successfully added '$CertFile' to 'cert:\\$StoreScope\\$StoreName'."\n } else {\n Write-Verbose " [Import-Certificate] :: Successfully added '$($Cert.Subject) ($($Cert.Thumbprint))' to 'cert:\\$StoreScope\\$StoreName'."\n }\n }\n catch\n {\n Write-Error ("Error adding '$($Cert.Subject) ($($Cert.Thumbprint))' to 'cert:\\$StoreScope\\$StoreName': $_ .") -ErrorAction:Continue\n }\n if ( $store ) {\n $store.Close()\n }\n } \n else {\n Write-Warning "Certificate store '$StoreName' does not exist. Skipping..."\n }\n }\n } else {\n Write-Warning "No certificates found."\n }\n }\n \n end { \n Write-Host "Finished importing certificates." \n }\n}
PowerShellCorpus/PoshCode/WSUS-Purge.ps1
WSUS-Purge.ps1
#================================================================================================== # File Name : WSUS-Purge.ps1 # Original Author : Kenneth C. Mazie (kcmjr) # Description : As written it will clear out files left over from Windows Updates. # : # Notes : Normal operation is with no command line options. This PowerShell script # : is a conversion of a VB script I use to clear out leftover files from # : Windows Update on XP. It works on XP, Vista, Win7 and Win2k8 with a # : few caveates. Any OS above the Vista level has changes to the way # : installs and updates are stored. Please see this excellent article for # : more info: http://www.winvistaclub.com/f16.html and also the one linked # : to the bottom of that article. # : # Operation : The script will automatically run with elevated priviledge. It detects # : the OS being used as well as the folder it is being executed from. It # : looks for an existing scheduled task to run itself and if not found # : creates one. Once run it will ruthlessly remove most folders named # : "$ntuninstall...$" in "C:\\Windows" (on XP) as well as the associated # : registry keys in "HKLM:SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\" # : (on XP) and the files stored in "C:\\Windows\\SoftwareDistribution\\Download" # : (all OS vers). All KB log files are also removed from "C:\\windows". OS # : version is also detected and noted in the output (included for future use). # : # : All destructive operations are disabled by default. Comment out the # : "-whatif" statements to enable active processing. Tested on XP and Win7. # : # Warnings : Use of this script will gain you disk space on C: but will make # : uninstalling of patches nearly impossible. See below. # : # Legal : Public Domain. Modify and redistribute freely. No rights reserved. # : SCRIPT PROVIDED "AS IS" WITHOUT WARRANTIES OR GUARANTEES OF ANY KIND. # : USE AT YOUR OWN RISK. NO TECHNICAL SUPPORT PROVIDED. # : # Last Update by : Kenneth C. Mazie # Version History : v1.0 - 12-08-10 - Original # Change History : v2.0 - 12-09-10 - Added options to automatically set a scheduled task to # : run the script on a random day and time. # #================================================================================================== Clear-Host $ErrorActionPreference = "SilentlyContinue" $rand = New-Object System.Random #--[ Execute with admin priviledge ]-- $identity = [Security.Principal.WindowsIdentity]::GetCurrent() $principal = new-object Security.Principal.WindowsPrincipal $identity if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -eq $false) { $Args = '-noprofile -nologo -executionpolicy bypass -file "{0}"' -f $MyInvocation.MyCommand.Path Start-Process -FilePath 'powershell.exe' -ArgumentList $Args -Verb RunAs exit } write-host "Running with Admin Privileges" #Read-Host "PRESS ENTER" #--[ Get script folder ]-- function Get-ParentFolderOfThisScript { $ParentProcessInvocation = Get-Variable MyInvocation -Scope 1 $InvocationInfo = $ParentProcessInvocation.Value $CommandInfo = $InvocationInfo.MyCommand $FullPathToThisScript = $CommandInfo.Path Split-Path $FullPathToThisScript -parent } #--[ Create the scheduled task ]-- Function Create-ScheduledTask { param( [string]$ComputerName = "localhost", [string]$RunAsUser = "System", [string]$RunLevel = "HIGHEST", [string]$TaskName = "WSUS-Purge", [string]$TaskRun = "'powershell.exe -nologo -noninteractive -file $scriptpath\\WSUS-Purge.ps1'", # [string]$TaskRun = "powershell.exe -nologo -noninteractive -command `"& {$scriptpath\\WSUS-Purge.ps1}`"", [string]$Schedule = "Weekly", [string]$Modifier = "second", [string]$Days = (($Array = "SUN","MON","TUE","WED","THU","FRI","SAT" ) | Get-Random), [string]$Months = '"MAR,JUN,SEP,DEC"', [string]$StartTime = "$("{0:D2}" -f $rand.next(0,23)):$("{0:D2}" -f $rand.next(0,59))", [string]$EndTime = "02:00", [string]$Interval = "60" ) Write-Host "Creating new task..." write-host "Time set to $time..." Write-Host "Day set to $Days..." #$Command = "schtasks.exe /create /s $ComputerName /ru $RunAsUser /tn $TaskName /tr $TaskRun /sc $Schedule /mo $Modifier /d $Days /m $Months /st $StartTime /et $EndTime /ri $Interval /F" if ($($os.version.Split(".")[0]) -ge 6){ #--[ Run for Vista and higher ]-- $Command = "schtasks.exe /create /s $ComputerName /ru $RunAsUser /rp $RunAsPwd /rl $RunLevel /tn $TaskName /tr $TaskRun /d $Days /sc $Schedule /st $StartTime /F" } else { #--[ Remove runlevel option for 2003 and lower ]-- $Command = "schtasks.exe /create /s $ComputerName /ru $RunAsUser /rp $RunAsPwd /tn $TaskName /tr $TaskRun /d $Days /sc $Schedule /st $StartTime /F" } Invoke-Expression $Command Clear-Variable Command -ErrorAction SilentlyContinue } #--[ Manage Scheduled Task ]-- $scriptpath = Get-ParentFolderOfThisScript $time = "$("{0:D2}" -f $rand.next(0,23)):$("{0:D2}" -f $rand.next(0,59))" if ($task = Schtasks.exe /query /s "localhost" /v /FO CSV | select-string -pattern “WSUS-Purge”) { Write-Host "Task already exists..." } else { Create-ScheduledTask -StartTime $($time) } #--[ Get Windows version ]-- switch ($os.version) { "5.1.2600" {Write-Host "Running on Windows XP"} "5.2.3790" {Write-Host "Running on Windows Server 2003"} "6.0.6000" {Write-Host "Running on Windows Vista"} "6.0.6001" {Write-Host "Running on Windows Server 2008"} "6.1.7600" {Write-Host "Running on Windows 7 or Server 2008 R2"} default {"The operating system could not be determined."} } #--[ Get %windir% environemnt variable ]-- $windir = [System.Environment]::ExpandEnvironmentVariables("%WINDIR%") #--[ Alternate format ]-- #$windir = $env:windir #--[ Read existing patch folders in %windir% ]-- $dirs = Get-ChildItem $windir -Force | Where-Object { $_.PSIsContainer } | Select-Object Name | Where-Object {$_.Name -like "`$ntuninstallkb*" -or $_.Name -like "$ntuninstallq"} if ($dirs.count -gt 0) { write-host $dirs.count " patches to process" foreach ($dir in $dirs) { $patch = ($($dir.Name).Remove(0,12)).Replace("$", "") Write-Host "Processing " $patch #--[ Delete the registry key ]-- Remove-Item -Path "HKLM:SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\$patch" -recurse -Force -whatif #--[ Alternate format ]-- #Get-ChildItem -path HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall | Where-Object {$_.PSChildName -eq $patch } | Remove-Item -Force -WhatIf #--[ Delete the uninstall folder ]-- Remove-Item "$windir\\$($dir.name)" -recurse -Force -whatif #--[ Alternate format ]-- #Get-ChildItem -path $windir | Where-Object {$_.PSChildName -eq $($dir.name)} | Remove-Item -Force -WhatIf }} else { write-host "No C:\\Windows patch folders to process..." } #--[ Remove left over KB log files ]-- write-host "Removing patch logs..." Remove-Item "$windir\\kb*.log" -recurse -Force -whatif #--[ Remove items stored in the C:|windows\\SoftwareDistribution\\Download folder ]-- write-host "Purging downloaded patches..." Get-childitem $windir\\SoftwareDistribution\\Download\\* -recurse | remove-item -recurse -force -whatif #--[ Remove items stored in the C:|windows\\Installer folder. Disabled by default. May cause applications to malfunction. ]-- #Get-childitem $windir\\Installer\\* -recurse | remove-item -recurse -force -whatif
PowerShellCorpus/PoshCode/NumLock Notifier.ps1
NumLock Notifier.ps1
<# .NOTES Name : NumLockNotifier.ps1 Author : Bryan Jaudon <bryan.jaudon@gmail.com> Version : 1.0 Date : 10/25/2012 .Description Adds a notification icon to show current NumLock status. Double clicking or by using the context menu, allows for toggling of the NumLock status. #> #requires -version 2 param([switch]$Debug) function CheckNumLock { $NumLockStatus=[console]::NumberLock Write-Debug "CheckNumLock - Previous Reading: $Script:PreviousNumLock - Current Reading: $NumLockStatus" if ($PreviousNumLock -ne $NumLockStatus) { if ($NumLockStatus -eq $True) { Write-Debug "CheckNumLock - Update NumLock NotificationIcon to ON" $NotifyIcon.Icon = $IconOn $NotifyIcon.BalloonTipTitle = "NumLock is On" $NotifyIcon.Text="NumLock Status - On" $NotifyIcon.BalloonTipText = "NumLock status has changed to On." } else { Write-Debug "CheckNumLock - Update NumLock NotificationIcon to OFF" $NotifyIcon.Icon = $IconOff $NotifyIcon.BalloonTipTitle = "NumLock is Off" $NotifyIcon.Text="NumLock Status - Off" $NotifyIcon.BalloonTipText = "NumLock status has changed to Off." } Write-Debug "CheckNumLock - Show NotificationIcon BaloonTip" $NotifyIcon.BalloonTipIcon = "Info" $NotifyIcon.Visible = $True $NotifyIcon.ShowBalloonTip(50000) } $Script:PreviousNumLock=$NumLockStatus } function ToggleNumLock { $wshObject=New-Object -ComObject "WScript.Shell" $wshObject.SendKeys('{NUMLOCK}') Write-Debug "ToggleNumLock - wshObject Sendkeys(NUMLOCK)" } Function Hide-PowerShell { $null = $showWindowAsync::ShowWindowAsync((Get-Process -PID $pid).MainWindowHandle, 0) } [void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") [void][reflection.assembly]::loadwithpartialname("System.Drawing") [string]$IconOnb64=@" iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBI WXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3AoZEQ0tIxydPwAABcFJREFUWMO9l09oE9sexz9zZiZ/ amoaaq22SLF/0j+2UEtA3lsUHooK0VYQRF0I4lY3NwvlLfTuVHARUdDFRaWuRLytFEGxIKX4VipY QSyt+CexJrYNrU2TmM7MeYveGZOavqvl6Q8Oc86cM+f37/v7M8qtW7fweDxd69atu6Dr+j+EEB5+ MlmWlc7lckOJROI3TdO0jtra2v+UlZW5+XXk8/l8+zwezz+1qqqqsx6Px22aJkIIdF1HURRnAEXr UntSSgCklM5YvraHaZoYhoGUkrKysvWaruv/sj/QdR1MGHeN80flH8yqs6ioSEUuMZR/CYOCVCQo sD+7n95sL4Y0HMZ/mRkppfO050IIVFXFMAwsy0KTUpbZGwCKpTAn5hgpG2FKn/pbW3YudiIQ3217 0zTRNI18Po+UEmFLp6oqpmmC8vMBYLtNSolmWRb2UFV1VRcW+t22pBDCeb+4uFjknkIXaYV++n9p Zw/7bsMwSoXiVwEKNTAwaPvSxp+TfyJ0gaIoCEWgCOWrttYSABVFoUJWYGD8kAKFPB0XOKGDxCVd VGYqAfB6vei6TjadRVVVdF3HsizHzEIIUKAQyIXWME3TOb9cCMuyvoKwUAO32839+/fZtm0bd+7c we/3E4lEuHTpEul02mEshHDywWpxsyIGhBDMz88zNDTErl27UFUVTdN48eIFiUSCnp4exsbGePr0 Kd3d3dy9e5fPnz8TCARob29ncHCQrVu3snv3bjweT9H9Nk/LshCFUVBIi4uLhEIhpqenGRkZQVEU R4CBgQFM0+Tly5fcvHmTt2/fcv78eXK5HP39/UQiESzL4tq1awwODuLxeEqCcEUX2Ac2bNhAd3c3 z549Y2Ji4pswLfymurqac+fOsWfPHoLBIBcuXKC5uZnJycmS2LB5iv8Vhl++fKG3t5f5+XlGR0ed hJXNZgHIZDLOWZfLBYCmaWia5mBkpegosoAtwHJAWZaF1+slHA4TCATIZDJ0dXUxNjbGqVOniEaj 32j3vQB0kt/hw4d/1zQNXdeLwOL1emloaGDTpk3U19cTDAbp6Oigs7OTrq4ustksx44dIxQK0dbW RmNjI42Njfh8Ppqbm6mtrcXv99PS0kJlZWWRlW2ASylR7t27J91uNz6fj4qKCizLKspmheFmr5fP C6vd8nmpd6qqEo/Hi0FYGAW6rvP48WPOnj3L5OTkd9cIVVUZHx/n5MmTTExMLJX3v8kDJUFomyge j5PP51EUBVVVicViPHr0iKmpKQfN2WyW4eFhRkdHHYC+e/eObDbLmzdveP369VKVXQED36TiUuT1 eunr6yMajbJmzRpisRjXr1+nqamJnp4evF4vCwsLbN++nSNHjqDrOs+fP+fhw4fs3buX1tZWcrlc ySjQVsoDhdZIJpPcuHGDSCTCoUOHiEajXLx4kZaWFtrb2+nr6yMWizE8PEwqlWJ2dpaBgQG2bNnC vn37yOfzP+aC5QLMzc0hpaSmpgYhBMFgkFQqxdTUFJs3b3YS0cGDBykvL2dmZoaPHz+yfv163G53 ybttvlohSpcD6v3791y+fJlwOMzGjRu5cuUKHz584OrVq+zcuZNQKMSJEyeor6/n1atXPHnyhNOn T9PU1ERHRwcPHjygoaGBcDjsuMDONU4nduDAgd+FELhcLsrLy52ElMvlSKVSZDIZqqqqOHr0KKlU iqGhIXbs2MHx48dpbW2lrq6O/v5+NE3jzJkzBAIBFhYWCIfDVFdXk0wmqaurw+v1OpGmKAozMzNL IX/79m2paRp+v5+ampqfngdsAcbGxjBNc6ka2purre2r7QWKQJjJZFaV11dDuVzO6ZREYec6PT29 6s74e0lVVZLJZFFTmrYsy2eaJvF4nFwux9q1a4t8vdIv2o/8mtlNzqdPn0in0w7YNcMwHiiKsh/A MAwSiQSJROKXYUGTUv7bMIydqqqW84vJMIw3/wWZExLRh7QtJQAAAABJRU5ErkJggg== "@ $IconOnstream=[System.IO.MemoryStream][System.Convert]::FromBase64String($IconOnb64) $IconOnbmp=[System.Drawing.Bitmap][System.Drawing.Image]::FromStream($IconOnstream) $IconOnhandle=$IconOnbmp.GetHicon() $IconOn=[System.Drawing.Icon]::FromHandle($IconOnhandle) [string]$IconOffb64=@" iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBI WXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3AoZEQ41G11WqgAABcFJREFUWMO9l0toU+sWx3/7lWTX 1DTUWm2RYh/pwxZqCcg5g8JBUSHaCoKoA0Gc6uRmoNyBnpkKDiIKOjio1JGIp5UiKBakFM9IBSuI pRUfiTWxbWhtmsR07/3dQbv3SWJ6T0/vPS742N9zfetb678eW7pz5w4ej6drw4YNlzRN+0mWZQ// MFmWlcpms0PxePxfqqqqHbW1tX+UlZW5+XHk9Xq9Bzwez89qVVXVeY/H4zZNE1mW0TQNSZKcBhSM S60JIQAQQjiteGw30zQxDAMhBGVlZRtVTdN+sQ9omoYJuMbHqfztN5TZWVAUJCGWLlq+EElamgMy Bw+S6e1FLDPNUzNCCOdr92VZRlEUDMPAsixUIUSZvQBgSRLy3BxlIyNoU1N/qcvFzk5YPrsaMk0T VVXJ5XIIIZBt6RRFwTRNpB8AANtsQghUy7Kwm6Ioa2KYb3dbk7IsO/OLi4sF5sk3kZpvp//X6+xm 8zYMo5Qr/ilA/gswDL61tTH5++9osrzETJaRl1EvhMBaBqAkSYiKCigC4Go1VmACh4EQCJeLdGUl ALquo2kaqUwGRVHQNA3Lshw1y7KMtPwiuQiMkiRhmqazv1gIy7L+BGH+C9xuNw8fPmTHjh3cu3cP n89HOBzmypUrpFIp52J5WUP/C25WxIAsy8zPzzM0NMSePXtQFAVVVXn16hXxeJyenh7GxsZ4/vw5 3d3d3L9/n69fv+L3+2lvb2dwcJDt27ezd+9ePB5PAX/7TsuykPO9oMC/FxcJBoNMT08zMjKCJEmO AAMDA5imyevXr7l9+zbv37/n4sWLZLNZ+vv7CYfDWJbFjRs3GBwcxOPxlAThiiawN2zatInu7m5e vHjBxMTEd26af6a6upoLFy6wb98+AoEAly5dorm5mcnJyZLYsO+U/5sbfvv2jd7eXubn5xkdHXUC ViaTASCdTjt7XS4XAKqqoqqqg5GVvKNAA7YAxYCyLAtd1wmFQvj9ftLpNF1dXYyNjXHmzBkikch3 r1stAJ3gd/To0V9VVUXTtAKw6LpOQ0MDW7Zsob6+nkAgQEdHB52dnXR1dZHJZDhx4gTBYJC2tjYa GxtpbGzE6/XS3NxMbW0tPp+PlpYWKisrC7RsA1wIgfTgwQPhdrvxer1UVFRgWVZBNMt3N3tc3M/P dsX9UnOKohCLxQpBmO8Fmqbx9OlTzp8/z+Tk5KpzhKIojI+Pc/r0aSYmJtA07S/jQEkQ2iqKxWLk cjkkSUJRFKLRKE+ePGFqOU1LkkQmk2F4eJjR0VEHoB8+fCCTyfDu3Tvevn2LaZorYuD7UFyCdF2n r6+PSCTCunXriEaj3Lx5k6amJnp6etB1nYWFBXbu3MmxY8fQNI2XL1/y+PFj9u/fT2trK9lstqQX qCvFgXxtJBIJbt26RTgc5siRI0QiES5fvkxLSwvt7e309fURjUYZHh4mmUwyOzvLwMAA27Zt48CB A+Ryub9ngmIB5ubmEEJQU1ODLMsEAgGSySRTU1Ns3brVCUSHDx+mvLycmZkZPn/+zMaNG3G73SV5 2/eq+SgtBtTHjx+5evUqoVCIzZs3c+3aNT59+sT169fZvXs3wWCQU6dOUV9fz5s3b3j27Blnz56l qamJjo4OHj16RENDA6FQyDGBlJfWhRAohw4d+lWWZVwuF+Xl5U5AymazJJNJ0uk0VVVVHD9+nGQy ydDQELt27eLkyZO0trZSV1dHf38/qqpy7tw5/H4/CwsLhEIhqqurSSQS1NXVoeu642mSJDEzM7Pk 8nfv3hWqquLz+aipqfnH44AtwNjYGKZpLmVDe3GtuX2ttUABCNPp9Jri+loom806lZKcX7lOT0+v uTJeLSmKQiKRKChKU5ZleU3TJBaLkc1mWb9+fYGtV/pF+zu/ZnaR8+XLF1KplAN21TCMR5IkHVwq iA3i8TjxePyHYUEVQvzbMIzdiqKU84PJMIx3/wGYKRLRg2iLeAAAAABJRU5ErkJggg== "@ $IconOffstream=[System.IO.MemoryStream][System.Convert]::FromBase64String($IconOffb64) $IconOffbmp=[System.Drawing.Bitmap][System.Drawing.Image]::FromStream($IconOffstream) $IconOffhandle=$IconOffbmp.GetHicon() $IconOff=[System.Drawing.Icon]::FromHandle($IconOffhandle) $form1 = New-Object System.Windows.Forms.form $NotifyIcon= New-Object System.Windows.Forms.NotifyIcon $ContextMenu = New-Object System.Windows.Forms.ContextMenu $MenuItemToggle = New-Object System.Windows.Forms.MenuItem $MenuItemExit = New-Object System.Windows.Forms.MenuItem $Timer = New-Object System.Windows.Forms.Timer $form1.ShowInTaskbar = $false $form1.WindowState = "minimized" $NotifyIcon.ContextMenu = $ContextMenu $NotifyIcon.contextMenu.MenuItems.AddRange($MenuItemToggle) $NotifyIcon.contextMenu.MenuItems.AddRange($MenuItemExit) $NotifyIcon.Visible = $True $NotifyIcon.add_DoubleClick({ Write-Debug "NotifyIcon - DoubleClickEvent: ToggleNumLock";ToggleNumLock}) $Timer.Interval = 1000 $Timer.add_Tick({ CheckNumLock }) $Timer.start() $MenuItemToggle.Index = 0 $MenuItemToggle.Text = "&Toggle NumLock" $MenuItemToggle.add_Click({ Write-Debug "NotifyIcon - MenuItemEvent: ToggleNumLock"; ToggleNumLock }) $MenuItemExit.Index = 1 $MenuItemExit.Text = "E&xit" $MenuItemExit.add_Click({ Write-Debug "NotifyIcon - ExitEvent"; $Timer.stop(); $NotifyIcon.Visible = $False; $form1.close() }) $script:showWindowAsync = Add-Type -MemberDefinition @" [DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); "@ -name Win32ShowWindowAsync -namespace Win32Functions -PassThru if ($host.name -ne "Windows PowerShell ISE Host") { if ($Debug -ne $True) { Hide-PowerShell } else { $DebugPreference="Continue" } } $Script:PreviousNumLock=[console]::NumberLock if ($Script:PreviousNumLock -eq $True) { Write-Debug "Initilization - NumLock On" $NotifyIcon.Icon = $IconOn $NotifyIcon.Text="NumLock Status - On" } else { Write-Debug "Initilization - NumLock Off" $NotifyIcon.Icon = $IconOff $NotifyIcon.Text="NumLock Status - Off" } [void][System.Windows.Forms.Application]::Run($form1)
PowerShellCorpus/PoshCode/Get-CrawlHealth (MOSS)_1.ps1
Get-CrawlHealth (MOSS)_1.ps1
[reflection.assembly]::LoadWithPartialName("Microsoft.SharePoint") | out-null [reflection.assembly]::LoadWithPartialName("Microsoft.Office.Server") | out-null [reflection.assembly]::LoadWithPartialName("Microsoft.Office.Server.Search") | out-null @@#NOTE: I've set strict crawl freshness/crawl duration/success ratio threshholds. Reset as desired @@# to something that more suits your reality. $crawlFreshnessDayThreshhold = 2 $crawlDurationHourThreshhold = 4 $successRatioThreshhold = 0.9 function Calculate-CrawlDuration( [Microsoft.Office.Server.Search.Administration.SharePointContentSource]$contentSource) { if ($contentSource.CrawlStatus -eq [Microsoft.Office.Server.Search.Administration.CrawlStatus]::Idle) { return "Green - no current crawl" } $timespan = [datetime]::Now - $contentSource.CrawlStarted $timespanFormatted = "Running for $($timespan.TotalDays.ToString('0.00')) Days" + "($($timespan.TotalHours.ToString('0.0')) hours)" if ($timespan.TotalHours -le ($crawlDurationHourThreshhold / 2)) { return "Green - $timespanFormatted" } elseif ($timespan.TotalHours -le ($crawlDurationHourThreshhold)) { return "Yellow - $timespanFormatted" } else { return "Red - $timespanFormatted" } } function Calculate-CrawlFreshness( [Microsoft.Office.Server.Search.Administration.SharePointContentSource]$contentSource) { $timespan = [datetime]::Now - $contentSource.CrawlCompleted $timespanFormatted = "$($timespan.TotalDays.ToString('0.00')) days ago" if ($timespan.Days -le 0) { return "Green - $timespanFormatted" } elseif ($timespan.Days -lt $crawlFreshnessDayThreshhold) { return "Yellow - $timespanFormatted" } else { return "Red - $timespanFormatted" } } function Calculate-IndexHealth( [Microsoft.Office.Server.Search.Administration.SharePointContentSource]$contentSource, $successCount, $warningCount, $errorCount) { $formatted = "($($successCount)/$($warningCount)/$($errorCount))" if ($errorCount -eq 1) { return "Red - exactly 1 error, usually indicates permissions/config error - $formatted" } $successRatio = ([double]$successCount)/([double]($warningCount + $errorCount)) $successRatioMidpointToPerfection = (1.0 - ((1.0 - $successRatioThreshhold)/2.0)) if ($successRatio -ge $successRatioMidpointToPerfection) { return "Green - $formatted" } elseif ($successRatio -ge $successRatioThreshhold) { return "Yellow - $formatted" } else { return "Red - $formatted" } } function Get-CrawlHealth { $serverContext = [Microsoft.Office.Server.ServerContext]::Default $searchContext = [Microsoft.Office.Server.Search.Administration.SearchContext]::GetContext($serverContext) $content = [Microsoft.Office.Server.Search.Administration.Content]$searchContext $history = [Microsoft.Office.Server.Search.Administration.CrawlHistory]$searchContext $contentSources = $content.ContentSources | foreach { $_ } $contentSources | foreach { #unroll DataTable object into more useful DataRow object $crawlHistory = $history.GetLastCompletedCrawlHistory($_.Id) | % { $_ } add-member -inputobject $_ -membertype NoteProperty -name "CurrentCrawlDuration" -value ( Calculate-CrawlDuration $_) add-member -inputobject $_ -membertype NoteProperty -name "CompletedCrawlFreshness" -value ( Calculate-CrawlFreshness $_) add-member -inputobject $_ -membertype NoteProperty -name "IndexHealth" -value ( Calculate-IndexHealth -contentSource $_ -successCount $crawlHistory.SuccessCount -warningCount ( $crawlHistory.WarningCount) -errorCount $crawlHistory.ErrorCount) } $contentSources | select Name, CurrentCrawlDuration, CompletedCrawlFreshness, IndexHealth } @@#USAGE: -Open a PowerShell session on the SharePoint server with elevated credentials @@# (specifically, with access to the SSP - usually the SharePoint farm account) @@# -Tweak the threshholds (they may be too ambitious for your environment) @@# -Paste this text into an open PowerShell window and type (without the # mark) @@# Get-CrawlHealth | Format-List
PowerShellCorpus/PoshCode/ping check using dotNet .ps1
ping check using dotNet .ps1
function check-ping { $erroractionpreference = "SilentlyContinue" $ping = new-object System.Net.NetworkInformation.Ping $rslt = $ping.send($args) if ($rslt.status.tostring() –eq “Success”) { write-host $args + “ ping worked” } else { write-host $args + “ ping failed” } $ping = $null }
PowerShellCorpus/PoshCode/Import-Iis-Log_1.ps1
Import-Iis-Log_1.ps1
param ( [Parameter( Mandatory=$true, Position = 0, ValueFromPipeline=$true, HelpMessage="Specifies the path to the IIS *.log file to import. You can also pipe a path to Import-Iss-Log." )] [ValidateNotNullOrEmpty()] [string] $Path, [Parameter( Position = 1, HelpMessage="Specifies the delimiter that separates the property values in the IIS *.log file. The default is a spacebar." )] [ValidateNotNullOrEmpty()] [string] $Delimiter = " ", [Parameter(HelpMessage="The character encoding for the IIS *log file. The default is the UTF8.")] [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding] $Encoding = [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]::UTF8 ) begin { $fieldNames = @() $output = New-Object Object Add-Member -InputObject $output -MemberType NoteProperty -Name "DateTime" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ClientHost" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "UserName" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "Service" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "Machine" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ServerIp" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ServerPort" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "Method" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ScriptPath" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "QueryString" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ServiceStatus" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ServiceSubStatus" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "Win32Status" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "BytesSent" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "BytesRecived" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ProcessingTime" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "ProtocolVersion" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "Host" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "UserAgent" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "Cookie" -Value $null Add-Member -InputObject $output -MemberType NoteProperty -Name "Referer" -Value $null } process { foreach($line in Get-Content -Path $Path -Encoding $Encoding) { if($line.StartsWith("#Fields: ")) { $fieldNames = @($line.Substring("#Fields: ".Length).Split($Delimiter)); } elseif(-not $line.StartsWith("#")) { $fieldValues = @($line.Split($Delimiter)); for($i = 0; $i -lt $fieldValues.Length; $i++) { $name = $fieldNames[$i] $value = $fieldValues[$i] switch($name) { "date" { $output.DateTime = [DateTime]::Parse($value) } "time" { $output.DateTime += [TimeSpan]::Parse($value) } "c-ip" { $output.ClientHost = [System.Net.IPAddress]::Parse($value) } "cs-username" { $output.UserName = if($value -eq '-') { $null } else { $value } } "s-sitename" { $output.Service = $value } "s-computername" { $output.Machine = $value } "s-ip" { $output.ServerIp = [System.Net.IPAddress]::Parse($value) } "s-port" { $output.ServerPort = [int]$value } "cs-method" { $output.Method = $value } "cs-uri-stem" { $output.ScriptPath = [System.Web.HttpUtility]::UrlDecode($value) } "cs-uri-query" { $output.QueryString = if($value -eq '-') { $null } else { [System.Web.HttpUtility]::UrlDecode($value) } } "sc-status" { $output.ServiceStatus = [int]$value } "sc-substatus" { $output.ServiceSubStatus = [int]$value } "sc-win32-status" { $output.Win32Status = [BitConverter]::ToInt32([BitConverter]::GetBytes([UInt32]($value)), 0) } "sc-bytes" { $output.BytesSent = [UInt64]$value } "cs-bytes" { $output.BytesRecived = [UInt64]$value } "time-taken" { $output.ProcessingTime = [int]$value } "cs-version" { $output.ProtocolVersion = $value } "cs-host" { $output.Host = if($value -eq '-') { $null } else { $value } } "cs(User-Agent)" { $output.UserAgent = if($value -eq '-') { $null } else { $value } } "cs(Cookie)" { $output.Cookie = if($value -eq '-') { $null } else { $value } } "cs(Referer)" { $output.Referer = if($value -eq '-') { $null } else { [System.Web.HttpUtility]::UrlDecode($value) } } } } Write-Output $output } } }
PowerShellCorpus/PoshCode/LoadModuleConfig_3.ps1
LoadModuleConfig_3.ps1
################################################################################ ## Script Name: LoadModuleConfig ## Created On: 01/21/2010 ## Author: Thell Fowler ## File: LoadModuleConfig.ps1 ## Usage: Called from the NestedModules value from a module manifest. ## Version: 1.0.1.0 ## Purpose: Provides automated loading of local configuration data. ## ## Requirements: PowerShell Version 2 ## Last Updated: 01/25/2010 ## History: ## 1.0.1.0 01/25/2010 - Force use of cliXML for adding members. ## 1.0.0.0 01/21/2010 - Initial implementation. ## ## ################################################################################ <# To make use of this script use new-modulemanifest to create a manifest named the with the same name as the manifest you are loading data for but with an extension of 'config.psd1' Enter LoadModuleConfig.ps1 in the NestedModules field. After creating the manifest open it in your editor and edit the PrivateData field to include hashes for LocalUser and Settings. After the Settings key add values as you see fit. Here is an example, as used in the FuncGuard module. # Private data to pass to the module specified in ModuleToProcess PrivateData = @{ "LocalUser" = @{ "Settings"=@{ "ActiveConfiguration" = "PSUnit" "Configurations"=@{ "PSUnit" =@{ "Name"="PSUnit"; "Path"=$(join-path -Path $Env:Temp -ChildPath "FuncGuard.PSUnit"); "Prefix"="PSUNIT" } } } } } After loading the module a global variable will be available with a name convention of $($ModuleName)Settings and the values can be accessed using normal hash retrieval. $config = $FuncGuardSettings["Configurations"].$($FuncGuardSettings["ActiveConfiguration"]) $Path = $config.Path #> #requires -version 2.0 Set-StrictMode -Version 2 $Module = $ExecutionContext.SessionState.Module if (! $Module) { throw ( New-Object System.InvalidOperationException ` "An active module was not found! LoadModuleConfig must be run from a module manifest's NestedModules field.") } $ModuleName = $Module.Name.Replace(".config",$null) $AppData = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::LocalApplicationData) $ModuleConfigPath = join-path -Path $AppData ` -ChildPath "WindowsPowerShell\\Modules\\$ModuleName\\$ModuleName.config.xml" if (! (Test-Path $ModuleConfigPath -PathType Leaf) ) { $configurations = $Module.PrivateData.LocalUser.Settings $configurations.add("InitializeConfigurations", $true) Export-Clixml -InputObject $configurations -Path $ModuleConfigPath } $configurations = Import-Clixml -Path $ModuleConfigPath Add-Member -InputObject $configurations -Name ModuleName -MemberType NoteProperty -force ` -Value $ModuleName Add-Member -InputObject $configurations -Name Export -MemberType ScriptMethod -force ` -Value { $AppData = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::LocalApplicationData) $ModuleConfigPath = join-path -Path $AppData ` -ChildPath "WindowsPowerShell\\Modules\\$ModuleName\\$($this.ModuleName).config.xml" Export-Clixml -InputObject $this -Path $ModuleConfigPath } Set-Variable -Name "$($ModuleName)Settings" -Value $($configurations) -Scope Global ` -Description "$($ModuleName) module configuration settings."
PowerShellCorpus/PoshCode/SMS.psm1.ps1
SMS.psm1.ps1
# SystemsManagementServer.psm1 # written by Tojo2000 <tojo2000@tojo2000.com> # Last updated on 20080921 # # Functions for getting data from MS Systems Management Server. # Set default server and site name here. It should be the server with the SMS # Provider, not necessarily the site server. [string]$default_wmi_provider_server = 'servername' [string]$default_site = 'S00' # Get-SmsWmi # A wrapper for Get-WmiObject that makes it easy to get objects from SMS. # # Args: # $class: the WMI class or nickname to retrieve # $filter: the where clause of the query # $computer_name: the SMS server hosting the SMS Provider # $site: the SMS Site Code of the target site # Returns: # An array of WMI objects function Get-SmsWmi { param([string]$class = $(Throw @" `t ERROR: You must enter a class name or nickname. `t Valid nicknames are: `t AddRemovePrograms AdStatus Advertisement Collection ComputerSystem DistributionPoint LogicalDisk MembershipRule NetworkAdapter NetworkAdapterConfiguration OperatingSystem Package PackageStatus Program Query Server Service Site StatusMessage System WorkstationStatus User `t Note: You only need to type as many characters as necessary to be unambiguous. `t "@), [string]$filter = $null, [string]$computer_name = $default_wmi_provider_server, [string]$site = $default_site) $classes = @{'collection' = 'SMS_Collection'; 'package' = 'SMS_Package'; 'program' = 'SMS_Program'; 'system' = 'SMS_R_System'; 'server' = 'SMS_SystemResourceList'; 'advertisement' = 'SMS_Advertisement'; 'query' = 'SMS_Query'; 'membershiprule' = 'SMS_CollectionMembershipRule'; 'statusmessage' = 'SMS_StatusMessage'; 'site' = 'SMS_Site'; 'user' = 'SMS_R_User'; 'pkgstatus' = 'SMS_PackageStatus'; 'addremoveprograms' = 'SMS_G_System_ADD_REMOVE_PROGRAMS'; 'computersystem' = 'SMS_G_System_COMPUTER_SYSTEM'; 'operatingsystem' = 'SMS_G_System_OPERATING_SYSTEM'; 'service' = 'SMS_G_System_SERVICE'; 'workstationstatus' = 'SMS_G_System_WORKSTATION_STATUS'; 'networkadapter' = 'SMS_G_System_NETWORK_ADAPTER'; 'networkadapterconfiguration' = ('SMS_G_System_NETWORK_' + 'ADAPTER_CONFIGURATION'); 'logicaldisk' = 'SMS_G_System_LOGICAL_DISK'; 'distributionpoint' = 'SMS_DistributionPoint'; 'adstatus' = 'SMS_ClientAdvertisementStatus'} $matches = @(); foreach ($class_name in @($classes.Keys | sort)) { if ($class_name.StartsWith($class.ToLower())) { $matches += $classes.($class_name) } } if ($matches.Count -gt 1) { Write-Error @" `t Warning: Class provided matches more than one nickname. `t Type 'Get-SMSWmi' with no parameters to see a list of nicknames. `t "@ $class = $matches[0] } elseif ($matches.Count -eq 1) { $class = $matches[0] } $query = "Select * From $class" if ($filter) { $query += " Where $filter" } # Now that we have our parameters, let's execute the command. $namespace = 'root\\sms\\site_' + $site gwmi -ComputerName $computer_name -Namespace $namespace -Query $query } # Find-SmsId # Look up an SMS ID. # # Args: # $advertisement_id, # $collection_id, # $package_id, # $resource_id: The id type to look up. Pick only one type. # $id: The ID to look up # # Returns: # An sms object if one was found function Find-SmsID { param([switch]$advertisement_id, [switch]$collection_id, [switch]$resource_id, [switch]$package_id, [string]$id) $Class = '' $Type = '' if ($advertisement_id) { $type = 'AdvertisementID' $class = 'Advertisement' } elseif ($collection_id) { $type = 'CollectionID' $class = 'Collection' } elseif ($package_id) { $type = 'PackageID' $class = 'Package' } elseif ($resource_id) { $type = 'ResourceID' $class = 'System' } else { Throw @" `t You must specify an ID type. Valid switches are: `t `t-advertisement_id `t-collection_id `t-package_id `t-resource_id `t USAGE: Find-SmsID <Type> <ID> `t "@ } if ($resource_id) { trap [System.Exception] { Write-Output "`nERROR: Invalid Input for ResourceID!`n" break } $type = 'ResourceID' $class = 'System' [int]$id = $id # Throws an exception if it's not a number } else{ if ($id -notmatch '^[a-zA-Z0-9]{8}$') { Throw "`n`t`nERROR: Invalid ID format.`n`t`n" } } Get-SmsWmi $class "$type = `"$ID`"" }
PowerShellCorpus/PoshCode/Get-Parameter 1.2.ps1
Get-Parameter 1.2.ps1
function Get-Parameter { [OutputType('System.String')] [CmdletBinding()] param( [Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String]$Command, [Parameter(Position=1)] [String[]]$Name=@('*'), [Parameter()] [ValidateSet('Name','Type','Pos','BV','BP','DV','Aliases','Mandatory','Dynamic')] [String]$SortBy='Name', [Parameter()] [switch]$Descending, [Parameter()] [ValidateSet('Filter','Cmdlet','Function','Alias','ExternalScript')] [String]$CommandType, [switch]$IncludeCommonParameters ) Process { if($CommandType) { switch($CommandType) { "function" { $cmd = Get-Command -Name $Command -CommandType $CommandType -ErrorAction SilentlyContinue | Where-Object {$_.CommandType -eq $CommandType} } "filter" { $cmd = Get-Command -Name $Command -CommandType $CommandType -ErrorAction SilentlyContinue | Where-Object {$_.CommandType -eq $CommandType} } default { $cmd = Get-Command -Name $Command -CommandType $CommandType -ErrorAction SilentlyContinue } } } else { $cmd = Get-Command -Name $Command -CommandType Cmdlet,Function,Alias,ExternalScript -ErrorAction SilentlyContinue } if(!$cmd) { Throw "'$Name' is not a Cmdlet,Function,Filter,Alias or ExternalScript" } if($cmd.length -gt 1) { $types = $cmd | Select-Object -ExpandProperty CommandType -Unique Throw "'$Command' is ambiguous and matches one of $($types -join ","). Use -CommandType to get only a specified type of command." } if($cmd.CommandType -eq 'Alias') { Write-Verbose "'$Name' refers to an Alias, reolving command." $cmd = Get-Command -Name $cmd.ResolvedCommandName } foreach($set in $cmd.ParameterSets) { if($IncludeCommonParameters) { [array]$p = $set.Parameters | Select-Object * } else { # Get a list of common parameters $cp = [System.Management.Automation.Internal.CommonParameters].GetProperties() | Select-Object -ExpandProperty Name [array]$p = $set.Parameters | Where-Object {$cp -notcontains $_.Name} | Select-Object * } if($p.count -le 0 -and !$IncludeCommonParameters) { Write-Warning "The specified cmdlet ('$cmd') has no parameters." return } $params = $p | Foreach-Object {$_.Name} for($i=0;$i -le $p.length;$i++) { $flag=$false for($x=0;$x -le $params[$i].length -and !($flag);$x++) { $regex = "^" + $params[$i].substring(0,$x) if(($params -match $regex).count -eq 1) { $flag=$true $p[$i].Aliases += $regex.substring(1).ToLower() } } } $p | Where-Object {$_.Name -like $Name} | Foreach-Object { $PropertyName = $_.Name $psn = $_.Attributes | Where-Object {$_.ParameterSetName} if($psn.ParameterSetName -notmatch '__AllParameterSets') { $PropertyName="*$PropertyName" } New-Object PSObject -Property @{ ParameterSet = $set.Name Name = $PropertyName BV = $_.ValueFromPipeline BP = $_.ValueFromPipelineByPropertyName Type = $_.ParameterType.Name Aliases = $_.Aliases Pos = if($_.Position -lt 0) {'Named'} else {$_.Position+1} Mandatory = $_.IsMandatory Dynamic = $_.IsDynamic } } | Sort-Object -Descending:$Descending {$_.$SortBy -replace '\\*'} | Format-Table Name,Type,Pos,BV,BP,Aliases,Mandatory,Dynamic -AutoSize -GroupBy ParameterSet | Out-String } } } Set-Alias -Name gprm -Value Get-Parameter
PowerShellCorpus/PoshCode/ESXiMgmt module sample 2.ps1
ESXiMgmt module sample 2.ps1
####################################################################################################################### # File: ESXiMgmt_machines_poweron_sample.ps1 # # Author: Alexander Petrovskiy # # Publisher: Alexander Petrovskiy, SoftwareTestingUsingPowerShell.WordPress.Com # # Copyright: © 2011 Alexander Petrovskiy, SoftwareTestingUsingPowerShell.WordPress.Com. All rights reserved. # # Prerequisites: The module was tested with Vmware ESXi 4.1 U1 on the server side and # # Vmware PowerCLI 4.1 U1 # # plink.exe 0.60.0.0 # # Usage: To load this module run the following instruction: # # Import-Module -Name ESXiMgmt -Force # # Please provide feedback in the SoftwareTestingUsingPowerShell.WordPress.Com blog. # ####################################################################################################################### param([string]$Server, [string]$User, [string]$Password, [string]$DatastoreName, [string]$Drive, [string]$MachinePrefix, [int]$OperationTimeout ) # USAGE: .\\ESXiMgmt_machines_poweron_sample.ps1 192.168.1.1 root 123 datastore3 host1ds3 XPSP2 300 cls Set-StrictMode -Version Latest Import-Module ESXiMgmt -Force; Connect-ESXi -Server $Server -Port 443 ` -Protocol HTTPS -User $User -Password $Password ` -DatastoreName $DatastoreName -Drive $Drive; $VerbosePreference = [System.Management.Automation.ActionPreference]::Continue; $VMs = Get-VM * [int]$grouper = 5; foreach($vm in $VMs) { if ($vm.Name -like "$($MachinePrefix)*" -and ` $vm.PowerState -ne 1) # [VMware.VimAutomation.ViCore.Types.V1.Inventory.PowerState]::PoweredOff = 0 # [VMware.VimAutomation.ViCore.Types.V1.Inventory.PowerState]::PoweredOn = 1 # [VMware.VimAutomation.ViCore.Types.V1.Inventory.PowerState]::Suspended = 2 { Write-Verbose "$($vm.Name) is starting"; Start-ESXiVM -Server $Server ` -User $User -Password $Password ` -Id (Get-ESXiVMId $vm); $grouper--; if ($grouper -eq 0){ Write-Verbose "Sleeping for $($OperationTimeout) seconds"; sleep -Seconds $OperationTimeout; $grouper = 5; } } } Disconnect-ESXi
PowerShellCorpus/PoshCode/CertMgmt pack_2.ps1
CertMgmt pack_2.ps1
##################################################################### # CertMgmtPack.ps1 # Version 0.51 # # Digital certificate management pack # # Vadims Podans (c) 2009 # http://www.sysadmins.lv/ ##################################################################### #requires -Version 2.0 function Import-Certificate { <# .Synopsis Imports digital certificates to Certificate Store from files .Description Improrts digital certificates to Certificate Store from various types of certificates files, such .CER, .DER, .PFX (password required), .P7B. .Parameter Path Specifies the path to certificate file .Parameter Password Specifies password to PFX/PKCS#12 file only. For other certificate types is not required. Note: this parameter must be passed as SecureString. .Parameter Storage Specifies place in Sertificate Store for certificate. For user certificates (default) you MAY specify 'User' and importing certificate will be stored in CurrentUser Certificate Store. For computer certificates you MUST specify 'Computer' and importing certificates will be stored in LocalMachine Certificate Store. .Parameter Container Specifies container within particular Certificate Store location. Container may be one of AuthRoot/CA/Disallowed/My/REQUEST/Root/SmartCardRoot/Trust/TrustedPeople/ TrustedPublisher/UserDS. These containers represent MMC console containers as follows: AddressBook - AddressBook AuthRoot - Third-Party Root CAs CA - Intermediate CAs Disallowed - Untrused Certificates My - Personal REQUEST - Certificate Enrollment Requests Root - Trusted Root CAs SmartCardRoot - Smart Card Trusted Roots Trust - Enterprise Trust TrustedPeople - Trusted People TrustedPublishers - Trusted Publishers UserDS - Active Directory User Object .Parameter Exportable Marks imported certificates private key as exportable. May be used only for PFX files only. If this switch is not presented for PFX files, after importing you will not be able to export this certificate with private key again. .Parameter StrongProtection Enables private key strong protection that requires user password each time when certificate private key is used. Not available for computer certificates, because computers certificates are used under LocalSystem account and here is no UI for user to type password. .Outputs This command provide a simple message if the export is successful. #> [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)] [string]$Path, [Parameter(Position = 1)] [System.Security.SecureString]$Password, [Parameter(Position = 2)] [string][ValidateSet("CurrentUser", "LocalMachine")]$Storage = "CurrentUser", [string][ValidateSet("AddressBook", "AuthRoot", "CA", "Disallowed", "My", "REQUEST", "Root", "SmartCardRoot", "Trust", "TrustedPeople", "TrustedPublisher", "UserDS")]$Container = "My", [switch]$Exportable, [switch]$StrongProtection ) if (!(Resolve-Path $Path)) {throw "Looks like your specified certificate file doesn't exist"} $file = gi $Path -Force -ErrorAction Stop $certs = New-Object system.security.cryptography.x509certificates.x509certificate2 switch ($Storage) { "CurrentUser" {$flags = "UserKeySet"} "LocalMachine" {$flags = "MachineKeySet"} } switch -regex ($file.Extension) { ".CER|.DER" {$certs.Import($file.FullName, $null, $flags)} ".PFX" { if (!$password) {throw "For PFX files password is required."} if ($StrongProtection -and $Storage -eq "Computer") { throw "You cannot use Private Key Strong Protection for computer certificates!" } if ($Exportable) {$flags = $flags + ", Exportable"} if ($StrongProtection) {$flags = $flags + ", UserProtected"} $certs.Import($file.FullName, $password, $flags) } ".P7B|.SST" { $certs = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection $certs.Import([System.IO.File]::ReadAllBytes($file.FullName)) } default {throw "Looks like your specified file is not a certificate file"} } $store = New-Object system.security.cryptography.X509Certificates.X509Store $Container, $Storage $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) $certs | %{$store.Add($_)} if ($?) {Write-Host -ForegroundColor Green Certificate file`: $file.fullname was successfully added to $Container container} $store.Close() } function Export-Certificate { <# .Synopsis Exports digital certificates to file Certificate Store. .Description Exports digital certificates from Certificate Store to various types of certificate file such .CER, .DER, .PFX (password required), .P7B or .SST (serializd store). .Parameter Path Specifies the path to certificate storing folder .Parameter Type Specifies type of imported certificate. May be one of CERT/PFX/PKCS#12/P7B/PKCS#7. .Parameter Password Specifies a password for PFX files and used only if type is specified as PFX/PKCS#12. Note: password must be supplied as SecureString. .Parameter Storage Specifies place in Sertificate Store for certificate. For user certificates (default) you MAY specify 'User' to export certificates from CurrentUser Certificate Store. For computer certificates you MUST specify 'Computer' to export certificates from LocalMachine Certificate Store. .Parameter Container Specifies container within particular Certificate Store location. Container may be one of AuthRoot/CA/Disallowed/My/REQUEST/Root/SmartCardRoot/Trust/TrustedPeople/ TrustedPublisher/UserDS. These containers represent MMC console containers as follows: AddressBook - AddressBook AuthRoot - Third-Party Root CAs CA - Intermediate CAs Disallowed - Untrused Certificates My - Personal REQUEST - Certificate Enrollment Requests Root - Trusted Root CAs SmartCardRoot - Smart Card Trusted Roots Trust - Enterprise Trust TrustedPeople - Trusted People TrustedPublishers - Trusted Publishers UserDS - Active Directory User Object .EXAMPLE .Outputs This command doesn't provide any output, except errors. .Link #> [CmdletBinding()] param ( [Parameter(Position = 0)] [string]$Path, [Parameter(Mandatory = $true, Position = 1)] [string][ValidatePattern("Cert|Pfx|pkcs12|pkcs7|SST")]$Type, [Parameter(Position = 2)] [System.Security.SecureString]$Password, [Parameter(Position = 3)] [string][ValidateSet("CurrentUser", "LocalMachine")]$Storage = "CurrentUser", [Parameter(ValueFromPipeline = $true, Position = 4)] [string][ValidateSet("AddressBook", "AuthRoot", "CA", "Disallowed", "My", "REQUEST", "Root", "SmartCardRoot", "Trust", "TrustedPeople", "TrustedPublisher", "UserDS")]$Container = "My", [string]$Thumbprint, [string]$Subject, [string]$Issuer, [string]$SerialNumber, [string]$NotAfter, [string]$NotBefore, [switch]$DeleteKey, [switch]$Recurse ) if (!(Test-Path $Path)) { New-Item -ItemType directory -Path $Path -Force -ErrorAction Stop } if ((Resolve-Path $Path).Provider.Name -ne "FileSystem") { throw "Spicifed path is not recognized as filesystem path. Try again" } if ($Recurse) { function dirx ($Storage) { dir cert:\\$Storage -Recurse | ?{!$_.PsIsContainer} } } else { function dirx ($Storage, $Container) { dir cert:\\$Storage\\$Container } } if ($Type -eq 'pkcs12') {$Type = "PFX"} if ($Type -eq 'SST') {$Type = "SerializedStore"} if ($Type -eq "PFX" -and !$Password) {throw "For PFX files password is required."} $Type = [System.Security.Cryptography.X509Certificates.X509ContentType]::$Type if ($NotAfter) {$NotAfter = [datetime]::ParseExact($NotAfter, "dd.MM.yyy", $null)} if ($NotBefore) {$NotBefore = [datetime]::ParseExact($NotBefore, "dd.MM.yyy", $null)} if ($Thumbprint) {$certs = @(dirx | ?{$_.Thumbprint -like "*$Thumbprint*"})} elseif ($Subject) {$certs = @(dirx | ?{$_.Subject -like "*$Subject*"})} elseif ($Issuer) {$certs = @(dirx | ?{$_.Issuer -like "*$Issuer*"})} elseif ($SerialNumber) {$certs = @(dirx | ?{$_.SerialNumber -like "*$SerialNumber*"})} elseif ($NotAfter -and !$NotBefore) {$certs = @(dirx | ?{$_.NotAfter -lt $NotAfter})} elseif (!$NotAfter -and $NotBefore) {$certs = @(dirx | ?{$_.NotBefore -gt $NotBefore})} elseif ($NotAfter -and $NotBefore) {$certs = @(dirx | ?{$_.NotAfter -lt $NotAfter ` -and $_.NotBefore -gt $NotBefore})} else {$certs = @(dirx)} if ($certs.Count -eq 0) {Write-Warning "Sorry, we unable to find certificates that correspond your filter :("; return} switch -regex ($Type) { "Cert" { foreach ($cert in $certs) { [void]($cert.Subject -match 'CN=([^,]+)') $CN = $matches[1] -replace '[\\\\/:\\*?`"<>|]', '' $bytes = $cert.Export($type) $base64Data = [System.Convert]::ToBase64String($bytes) Set-Content -LiteralPath $(Join-Path $Path ($CN + "_" + $cert.Thumbprint + ".cer")) -Value $base64Data } } "PFX" { foreach ($cert in $certs) { [void]($cert.Subject -match 'CN=([^,]+)') $CN = $matches[1] -replace '[\\\\/:\\*?`"<>|]', '' $bytes = $cert.Export($Type, $Password) [System.IO.File]::WriteAllBytes($(Join-Path $Path ($CN + "_" + $cert.Thumbprint + ".pfx")), $bytes) if ($DeleteKey) { $tempcert = $cert.Export("Cert") $store = New-Object system.security.cryptography.X509Certificates.X509Store $container, $Storage $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) $store.Remove($cert) $store.Add($tempcert) $store.Close() } } } "Pkcs7|SerializedStore" { $certcol = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection $certs | %{[void]$certcol.Add($_)} $bytes = $certcol.Export($Type) if ($Type -eq "Pkcs7") {$ext = ".p7b"} else {$ext = ".sst"} [System.IO.File]::WriteAllBytes($("ExportedCertificates" + $ext, $bytes)) } } }
PowerShellCorpus/PoshCode/WriteFileName_3.ps1
WriteFileName_3.ps1
# functions to print overwriting multi-line messages. Test script will accept a file/filespec/dir and iterate through all files in all subdirs printing a test message + file name to demostrate. # e.g. PS>.\\writefilename.ps1 c:\\ # call WriteFileName [string] # after done writing series of overwriting messages, call WriteFileNameEnd function WriteFileName ( [string]$writestr ) # this function prints multiline messages on top of each other, good for iterating through filenames without filling { # the console with a huge wall of text. Call this function to print each of the filename messages, then call WriteFileNameEnd when done # before printing anything else, so that you are not printing into a long file name with extra characters from it visible. if ($Host.Name -match 'ise') { write-host $writestr; return } if ($global:wfnlastlen -eq $null) {$global:wfnlastlen=0} $ctop=[console]::cursortop $cleft=[console]::cursorleft $oldwritestrlen=$writestr.length $rem=$null $writelines = [math]::divrem($writestr.length+$cleft, [console]::bufferwidth, [ref]$rem) #if ($rem -ne 0) {$writelines+=1} $cwe = ($writelines-(([console]::bufferheight-1)-$ctop)) # calculate where text has scroll back to. if ($cwe -gt 0) {$ctop-=($cwe)} write-host "$writestr" -nonewline $global:wfnoldctop=[console]::cursortop $global:wfnoldcleft=[console]::cursorleft if ($global:wfnlastlen -gt $writestr.length) { write-host (" " * ($global:wfnlastlen-$writestr.length)) -nonewline # this only overwrites previously written text if needed, so no need to compute buffer movement on this } $global:wfnlastlen = $oldwritestrlen [console]::cursortop=$ctop [console]::cursorleft=$cleft } function WriteFileNameEnd ( $switch=$true) # call this function when you are done overwriting messages on top of each other { # and before printing something else. Default switch=$true, which prints a newline, $false restores cursor position same line. if ($Host.Name -match 'ise') { return } if ($global:wfnoldctop -ne $null -and $global:wfnoldcleft -ne $null) { [console]::cursortop=$global:wfnoldctop [console]::cursorleft=$wfnoldcleft if ($global:wfnoldcleft -ne 0 -and $switch) { write-host "" } } $global:wfnoldctop=$null $global:wfnlastlen=$null $global:wfnoldcleft=$null } write-host "Checking: " -nonewline dir $args -recurse -ea 0 -force | %{WriteFileName ("$($_.fullname)"*(get-random -min 1 -max 100));sleep -seconds 1} #WriteFileName "Final Test String." WriteFileNameEnd write-host "Done! exiting."
PowerShellCorpus/PoshCode/Searching Word.ps1
Searching Word.ps1
$word=New-Object -COM "Word.Application" $errorlog="c:\\missing.csv" Set-Content $errorlog "Chapter,Script" Get-ChildItem c:\\test\\*.doc | foreach { $file=$_.fullname Write-Host $file $doc=$word.Documents.Open($file) $style=$word.ActiveDocument.Styles | where {$_.namelocal -eq "code Title"} $word.Selection.Find.Style = $style while ($word.Selection.Find.Execute()) { $text=($word.selection.sentences | select Text).text $script=(Join-Path "C:\\scripts\\posh" $text).Trim() if ((Get-Item $script -ea "silentlycontinue").exists) { Write-Host "verified $script" Move-Item $script -destination "c:\\scripts\\posh\\ad" } else { $msg="{0},{1}" -f $file,$script Add-Content $errorlog $msg } } $doc.close() } $word.quit()
PowerShellCorpus/PoshCode/A Compare-Object Bug.ps1
A Compare-Object Bug.ps1
# I want do demonstrate a Compare-object bug # Bernd Kriszio - http://pauerschell.blogspot.com/ 1, 2, 3, 4, 5 > .\\textfile_a.txt 1, 2, 4, 5, 6 > .\\textfile_b.txt cat .\\textfile_a.txt cat .\\textfile_b.txt compare-object (gc .\\textfile_a.txt) (gc .\\textfile_b.txt) -inc <#yields InputObject SideIndicator ----------- ------------- 1 == 2 == 4 == 5 == 6 => 3 <= I think it has to be InputObject SideIndicator ----------- ------------- 1 == 2 == 3 <= 4 == 5 == 6 => #>
PowerShellCorpus/PoshCode/Get-Command (which).ps1
Get-Command (which).ps1
## This ought to be the same as Get-Command, except... ## it will output the commands in the actual order they would be used by the shell function which( [string]$command ) { $Script:ErrorActionPreference = "SilentlyContinue" Get-Command $command -commandType Alias Get-Command $command -commandType Function Get-Command $command -commandType Cmdlet Get-Command $command -commandType Script Get-Command $command -commandType Application Get-Command $command -commandType ExternalScript }
PowerShellCorpus/PoshCode/Reverse filename sequenc.ps1
Reverse filename sequenc.ps1
# Reverse filename sequence v 0.9 # Author: Sean Wendt # # This script will rename a sequenced set of files in a directory. # For example, you have foobar01.jpg, foobar02.jpg, foobar03.jpg # -- it will reverse the order, so the last file is now 01, the second to last 02, etc.. # # Limitations: -You cannot use the same filename prefix, i.e. foobar must change to foobars. # -It's hardcoded to only support 5 digit numbers right now. # -Similarly, it will only support a file sequence with up to 5 digits. # This is the first script I've written, I know it's not great! ;) # Help to make it better would be appreciated. Thanks. # $file_extension = Read-Host "Enter file extension, i.e. .jpg or .txt" $file_prefix = Read-Host "Enter file prefix, i.e. entering foobar will rename files to foobar001.ext, foobar002.ext, etc.." $files = Get-ChildItem | ?{ $_.PSIsContainer -ne "True"} # Creates array of files in current directory, ignores folders $idx = 0 # Sets index value (0 = filenames start at foobar00000.jpg, modify to 1 to start at foobar00001.jpg) for ($ctr=$files.count; $ctr -gt 0 ; --$ctr) { if (($idx -ge 0) -and ($idx -le 9)) { Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '00000' + $idx++ + $file_extension) } elseif (($idx -ge 10) -and ($idx -le 99)) { Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '0000' + $idx++ + $file_extension) } elseif (($idx -ge 100) -and ($idx -le 999)) { Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '000' + $idx++ + $file_extension) } elseif (($idx -ge 1000) -and ($idx -le 9999)) { Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '00' + $idx++ + $file_extension) } elseif (($idx -ge 10000) -and ($idx -le 99999)) { Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '0' + $idx++ + $file_extension) } $idx #prints the index # it just completed }
PowerShellCorpus/PoshCode/h20 - Hashtables to obje.ps1
h20 - Hashtables to obje.ps1
#hashtable to object function. #used to be able to make custom objects with math inside the pipeline #e.g. 1..10 | h20 { @{karl = $_;dude = $_+1} } # gps | h20 { @{name = $_.processname; mem = $_.workingset / 1MB} } function h20([scriptblock]$sb ) { begin {} process{ if ($sb -ne $null) { $ht = &$sb; if ($ht -is [hashtable]) { New-Object PSObject -Property $ht} } } end{} }
PowerShellCorpus/PoshCode/Set-OCSUser.ps1
Set-OCSUser.ps1
###########################################################################" # # NAME: Set-OCSUser.ps1 # # AUTHOR: Jan Egil Ring # EMAIL: jan.egil.ring@powershell.no # # COMMENT: Requires Quest AD cmdlets. This oneliner sets Active Directory user attributes for Microsoft Office Communications Server 2007. # For more info: http://janegilring.wordpress.com/2009/07/23/manage-ocs-users-with-windows-powershell # # You have a royalty-free right to use, modify, reproduce, and # distribute this script file in any way you find useful, provided that # you agree that the creator, owner above has no warranty, obligations, # or liability for such use. # # VERSION HISTORY: # 1.0 23.07.2009 - Initial release # ###########################################################################" $Username="demo.user" $Fullname="Demo User" $serverpool="pool01.ourdomain.com" $oa = @{'msRTCSIP-ArchivingEnabled'=0; 'msRTCSIP-FederationEnabled'=$true; 'msRTCSIP-InternetAccessEnabled'=$true; 'msRTCSIP-OptionFlags'=257; 'msRTCSIP-PrimaryHomeServer'=$serverpool; 'msRTCSIP-PrimaryUserAddress'=("sip:$Username@ourdomain.com"); 'msRTCSIP-UserEnabled'=$true } Set-QADUser $Fullname -oa $oa
PowerShellCorpus/PoshCode/Highlight-Syntax _2.0.ps1
Highlight-Syntax _2.0.ps1
#requires -version 2.0 # Highlight-Syntax.ps1 # version 2.0 # by Jeff Hillman # # this script uses the System.Management.Automation.PsParser class # to highlight PowerShell syntax with HTML. param( [string] $code, [switch] $LineNumbers ) if ( Test-Path $code -ErrorAction SilentlyContinue ) { $code = Get-Content $code | Out-String } $backgroundColor = "#DDDDDD" $foregroundColor = "#000000" $lineNumberColor = "#404040" $PSTokenType = [System.Management.Automation.PSTokenType] $colorHash = @{ # $PSTokenType::Unknown = $foregroundColor; $PSTokenType::Command = "#C86400"; # $PSTokenType::CommandParameter = $foregroundColor; # $PSTokenType::CommandArgument = $foregroundColor; $PSTokenType::Number = "#800000"; $PSTokenType::String = "#800000"; $PSTokenType::Variable = "#000080"; # $PSTokenType::Member = $foregroundColor; # $PSTokenType::LoopLabel = $foregroundColor; # $PSTokenType::Attribute = $foregroundColor; $PSTokenType::Type = "#404040"; $PSTokenType::Operator = "#C86400"; # $PSTokenType::GroupStart = $foregroundColor; # $PSTokenType::GroupEnd = $foregroundColor; $PSTokenType::Keyword = "#C86400"; $PSTokenType::Comment = "#008000"; $PSTokenType::StatementSeparator = "#C86400"; # $PSTokenType::NewLine = $foregroundColor; $PSTokenType::LineContinuation = "#C86400"; # $PSTokenType::Position = $foregroundColor; } filter Html-Encode { $_ = $_ -replace "&", "&amp;" $_ = $_ -replace " ", "&nbsp;" $_ = $_ -replace "<", "&lt;" $_ = $_ -replace ">", "&gt;" $_ } # replace the tabs with spaces $code = $code -replace "\\t", ( " " * 4 ) if ( $LineNumbers ) { $highlightedCode = "<li style='color: $lineNumberColor; padding-left: 5px'>" } else { $highlightedCode = "" } $parser = [System.Management.Automation.PsParser] $lastColumn = 1 $lineCount = 1 foreach ( $token in $parser::Tokenize( $code, [ref] $null ) | Sort-Object StartLine, StartColumn ) { # get the color based on the type of the token $color = $colorHash[ $token.Type ] if ( $color -eq $null ) { $color = $foregroundColor } # add whitespace if ( $lastColumn -lt $token.StartColumn ) { $highlightedCode += ( "&nbsp;" * ( $token.StartColumn - $lastColumn ) ) } @@ $lastColumn = $token.EndColumn switch ( $token.Type ) { $PSTokenType::String { $string = "<span style='color: {0}'>{1}</span>" -f $color, ( $code.SubString( $token.Start, $token.Length ) | Html-Encode ) # we have to highlight each piece of multi-line strings if ( $string -match "\\r\\n" ) { # highlight any line continuation characters as operators $string = $string -replace "(``)(?=\\r\\n)", ( "<span style='color: {0}'>``</span>" -f $colorHash[ $PSTokenType::Operator ] ) $stringHtml = "</span><br />`r`n" if ( $LineNumbers ) { $stringHtml += "<li style='color: $lineNumberColor; padding-left: 5px'>" } $stringHtml += "<span style='color: $color'>" $string = $string -replace "\\r\\n", $stringHtml } $highlightedCode += $string break } $PSTokenType::NewLine { $highlightedCode += "<br />`r`n" if ( $LineNumbers ) { $highlightedCode += "<li style='color: $lineNumberColor; padding-left: 5px'>" } $lastColumn = 1 ++$lineCount break } default { if ( $token.Type -eq $PSTokenType::LineContinuation ) { $lastColumn = 1 ++$lineCount } $highlightedCode += "<span style='color: {0}'>{1}</span>" -f $color, ( $code.SubString( $token.Start, $token.Length ) | Html-Encode ) } } @@ #$lastColumn = $token.EndColumn } # put the highlighted code in the pipeline "<div style='width: 100%; " + "/*height: 100%;*/ " + "overflow: auto; " + "font-family: Consolas, `"Courier New`", Courier, mono; " + "font-size: 12px; " + "background-color: $backgroundColor; " + "color: $foregroundColor; " + "padding: 2px 2px 2px 2px; white-space: nowrap'>" if ( $LineNumbers ) { $digitCount = $lineCount.ToString().Length "<ol start='1' style='border-left: " + "solid 1px $lineNumberColor; " + "margin-left: $( ( $digitCount * 10 ) + 15 )px; " + "padding: 0px;'>" } $highlightedCode if ( $LineNumbers ) { "</ol>" } "</div>"
PowerShellCorpus/PoshCode/Get-GroupMembership_1.ps1
Get-GroupMembership_1.ps1
## Get-DistinguishedName -- look up a DN from a user's (login) name function Get-DistinguishedName { Param($UserName) $ads = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'') $ads.filter = "(&(objectClass=Person)(samAccountName=$UserName))" $s = $ads.FindOne() return $s.GetDirectoryEntry().DistinguishedName } ## Get-GroupMembership -- Get AD group membership recursively function Get-GroupMembership { Param($DNName,[int]$RecurseLimit=-1) $groups = ([adsi]"LDAP://$DNName").MemberOf if ($groups -and $RecurseLimit) { Foreach ($gr in $groups) { $groups += @(Get-GroupMembership $gr -RecurseLimit:$($RecurseLimit-1) | ? {$groups -notcontains $_}) } } return $groups } ## Usage: ################################################################################# ## $groups = Get-GroupMembership (Get-DistinguishedName Jaykul) ## # To turn recursion off: ## $groups = Get-GroupMembership (Get-DistinguishedName Jaykul) -RecurseLimit 0
PowerShellCorpus/PoshCode/Xml Module 4.3.ps1
Xml Module 4.3.ps1
#requires -version 2.0 # Improves over the built-in Select-XML by leveraging Remove-XmlNamespace http`://poshcode.org/1492 # to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations # and prefixes are removed from all XML nodes (by an XSL transform) before searching. # IMPORTANT: returned results *will not* have namespaces in them, even if the input XML did. # Also, only raw XmlNodes are returned from this function, so the output isn't completely compatible # with the built in Select-Xml. It's equivalent to using Select-Xml ... | Select-Object -Expand Node # Version History: # Select-Xml 2.0 This was the first script version I wrote. # it didn't function identically to the built-in Select-Xml with regards to parameter parsing # Select-Xml 2.1 Matched the built-in Select-Xml parameter sets, it's now a drop-in replacement # BUT only if you were using the original with: Select-Xml ... | Select-Object -Expand Node # Select-Xml 2.2 Fixes a bug in the -Content parameterset where -RemoveNamespace was *presumed* # Version 3.0 Added New-XDocument and associated generation functions for my XML DSL # Version 3.1 Fixed a really ugly bug in New-XDocument in 3.0 which I should not have released # Version 4.0 Never content to leave well enough alone, I've completely reworked New-XDocument # Version 4.1 Tweaked namespaces again so they don't cascade down when they shouldn't. Got rid of the unnecessary stack. # Version 4.2 Tightened xml: only cmdlet, function, and external scripts, with "-" in their names are exempted from being converted into xml tags. # Fixed some alias error messages caused when PSCX is already loaded (we overwrite their aliases for cvxml and fxml) # Version 4.3 Added a Path parameter set to Format-XML so you can specify xml files for prety printing $xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators") $xlinq = [Reflection.Assembly]::Load("System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") $xlinq.GetTypes() | ? { $_.IsPublic -and !$_.IsSerializable -and $_.Name -ne "Extensions" -and !$xlr8r::Get[$_.Name] } | % { $xlr8r::Add( $_.Name, $_.FullName ) } if(!$xlr8r::Get["Stack"]) { $xlr8r::Add( "Stack", "System.Collections.Generic.Stack``1, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" ) } if(!$xlr8r::Get["Dictionary"]) { $xlr8r::Add( "Dictionary", "System.Collections.Generic.Dictionary``2, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" ) } if(!$xlr8r::Get["PSParser"]) { $xlr8r::Add( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" ) } filter Format-XML { #.Synopsis # Pretty-print formatted XML source #.Description # Runs an XmlDocument through an auto-indenting XmlWriter #.Parameter Xml # The Xml Document #.Parameter Path # The path to an xml document (on disc or any other content provider). #.Parameter Indent # The indent level (defaults to 2 spaces) #.Example # [xml]$xml = get-content Data.xml # C:\\PS>Format-Xml $xml #.Example # get-content Data.xml | Format-Xml #.Example # Format-Xml C:\\PS\\Data.xml #.Example # ls *.xml | Format-Xml # Param( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Document")] [xml]$Xml , [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName="File")] [Alias("PsPath")] [string]$Path , [Parameter(Mandatory=$false)] $Indent=2 ) ## Load from file, if necessary if($Path) { [xml]$xml = Get-Content $Path } $StringWriter = New-Object System.IO.StringWriter $XmlWriter = New-Object System.Xml.XmlTextWriter $StringWriter $xmlWriter.Formatting = "indented" $xmlWriter.Indentation = $Indent $xml.WriteContentTo($XmlWriter) $XmlWriter.Flush() $StringWriter.Flush() Write-Output $StringWriter.ToString() } Set-Alias fxml Format-Xml -EA 0 function Select-Xml { #.Synopsis # The Select-XML cmdlet lets you use XPath queries to search for text in XML strings and documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched. #.Description # Improves over the built-in Select-XML by leveraging Remove-XmlNamespace to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations and prefixes are removed from all XML nodes (by an XSL transform) before searching. # # However, only raw XmlNodes are returned from this function, so the output isn't currently compatible with the built in Select-Xml, but is equivalent to using Select-Xml ... | Select-Object -Expand Node # # Also note that if the -RemoveNamespace switch is supplied the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically. #.Parameter Content # Specifies a string that contains the XML to search. You can also pipe strings to Select-XML. #.Parameter Namespace # Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}. #.Parameter Path # Specifies the path and file names of the XML files to search. Wildcards are permitted. #.Parameter Xml # Specifies one or more XML nodes to search. #.Parameter XPath # Specifies an XPath search query. The query language is case-sensitive. This parameter is required. #.Parameter RemoveNamespace # Allows the execution of XPath queries without namespace qualifiers. # # If you specify the -RemoveNamespace switch, all namespace declarations and prefixes are actually removed from the Xml before the XPath search query is evaluated, and your XPath query should therefore NOT contain any namespace prefixes. # # Note that this means that the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically. [CmdletBinding(DefaultParameterSetName="Xml")] PARAM( [Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("PSPath")] [String[]]$Path , [Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Node")] [System.Xml.XmlNode[]]$Xml , [Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String[]]$Content , [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [Alias("Query")] [String[]]$XPath , [Parameter(Mandatory=$false)] [ValidateNotNullOrEmpty()] [Hashtable]$Namespace , [Switch]$RemoveNamespace ) BEGIN { function Select-Node { PARAM([Xml.XmlNode]$Xml, [String[]]$XPath, $NamespaceManager) BEGIN { foreach($node in $xml) { if($NamespaceManager -is [Hashtable]) { $nsManager = new-object System.Xml.XmlNamespaceManager $node.NameTable foreach($ns in $Namespace.GetEnumerator()) { $nsManager.AddNamespace( $ns.Key, $ns.Value ) } } foreach($path in $xpath) { $node.SelectNodes($path, $NamespaceManager) } } } } [Text.StringBuilder]$XmlContent = [String]::Empty } PROCESS { $NSM = $Null; if($PSBoundParameters.ContainsKey("Namespace")) { $NSM = $Namespace } switch($PSCmdlet.ParameterSetName) { "Content" { $null = $XmlContent.AppendLine( $Content -Join "`n" ) } "Path" { foreach($file in Get-ChildItem $Path) { [Xml]$Xml = Get-Content $file if($RemoveNamespace) { $Xml = Remove-XmlNamespace $Xml } Select-Node $Xml $XPath $NSM } } "Xml" { foreach($node in $Xml) { if($RemoveNamespace) { $node = Remove-XmlNamespace $node } Select-Node $node $XPath $NSM } } } } END { if($PSCmdlet.ParameterSetName -eq "Content") { [Xml]$Xml = $XmlContent.ToString() if($RemoveNamespace) { $Xml = Remove-XmlNamespace $Xml } Select-Node $Xml $XPath $NSM } } } Set-Alias slxml Select-Xml -EA 0 function Convert-Node { #.Synopsis # Convert a single XML Node via XSL stylesheets param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [System.Xml.XmlReader]$XmlReader, [Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)] [System.Xml.Xsl.XslCompiledTransform]$StyleSheet ) PROCESS { $output = New-Object IO.StringWriter $StyleSheet.Transform( $XmlReader, $null, $output ) Write-Output $output.ToString() } } function Convert-Xml { #.Synopsis # The Convert-XML function lets you use Xslt to transform XML strings and documents. #.Description #.Parameter Content # Specifies a string that contains the XML to search. You can also pipe strings to Select-XML. #.Parameter Namespace # Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}. #.Parameter Path # Specifies the path and file names of the XML files to search. Wildcards are permitted. #.Parameter Xml # Specifies one or more XML nodes to search. #.Parameter Xsl # Specifies an Xml StyleSheet to transform with... [CmdletBinding(DefaultParameterSetName="Xml")] PARAM( [Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("PSPath")] [String[]]$Path , [Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Node")] [System.Xml.XmlNode[]]$Xml , [Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String[]]$Content , [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [Alias("StyleSheet")] [String[]]$Xslt ) BEGIN { $StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform if(Test-Path @($Xslt)[0] -EA 0) { Write-Verbose "Loading Stylesheet from $(Resolve-Path @($Xslt)[0])" $StyleSheet.Load( (Resolve-Path @($Xslt)[0]) ) } else { Write-Verbose "$Xslt" $StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader ($Xslt -join "`n"))))) } [Text.StringBuilder]$XmlContent = [String]::Empty } PROCESS { switch($PSCmdlet.ParameterSetName) { "Content" { $null = $XmlContent.AppendLine( $Content -Join "`n" ) } "Path" { foreach($file in Get-ChildItem $Path) { Convert-Node -Xml ([System.Xml.XmlReader]::Create((Resolve-Path $file))) $StyleSheet } } "Xml" { foreach($node in $Xml) { Convert-Node -Xml (New-Object Xml.XmlNodeReader $node) $StyleSheet } } } } END { if($PSCmdlet.ParameterSetName -eq "Content") { [Xml]$Xml = $XmlContent.ToString() Convert-Node -Xml $Xml $StyleSheet } } } Set-Alias cvxml Convert-Xml -EA 0 function Remove-XmlNamespace { #.Synopsis # Removes namespace definitions and prefixes from xml documents #.Description # Runs an xml document through an XSL Transformation to remove namespaces from it if they exist. # Entities are also naturally expanded #.Parameter Content # Specifies a string that contains the XML to transform. #.Parameter Path # Specifies the path and file names of the XML files to transform. Wildcards are permitted. # # There will bne one output document for each matching input file. #.Parameter Xml # Specifies one or more XML documents to transform [CmdletBinding(DefaultParameterSetName="Xml")] PARAM( [Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("PSPath")] [String[]]$Path , [Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullOrEmpty()] [Alias("Node")] [System.Xml.XmlNode[]]$Xml , [Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String[]]$Content , [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)] [ValidateNotNullOrEmpty()] [Alias("StyleSheet")] [String[]]$Xslt ) BEGIN { $StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform $StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader @" <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/|comment()|processing-instruction()"> <xsl:copy> <xsl:apply-templates/> </xsl:copy> </xsl:template> <xsl:template match="*"> <xsl:element name="{local-name()}"> <xsl:apply-templates select="@*|node()"/> </xsl:element> </xsl:template> <xsl:template match="@*"> <xsl:attribute name="{local-name()}"> <xsl:value-of select="."/> </xsl:attribute> </xsl:template> </xsl:stylesheet> "@)))) [Text.StringBuilder]$XmlContent = [String]::Empty } PROCESS { switch($PSCmdlet.ParameterSetName) { "Content" { $null = $XmlContent.AppendLine( $Content -Join "`n" ) } "Path" { foreach($file in Get-ChildItem $Path) { [Xml]$Xml = Get-Content $file Convert-Node -Xml $Xml $StyleSheet } } "Xml" { $Xml | Convert-Node $StyleSheet } } } END { if($PSCmdlet.ParameterSetName -eq "Content") { [Xml]$Xml = $XmlContent.ToString() Convert-Node -Xml $Xml $StyleSheet } } } Set-Alias rmns Remove-XmlNamespace -EA 0 function New-XDocument { #.Synopsis # Creates a new XDocument (the new xml document type) #.Description # This is the root for a new XML mini-dsl, akin to New-BootsWindow for XAML # It creates a new XDocument, and takes scritpblock(s) to define it's contents #.Parameter root # The root node name #.Parameter version # Optional: the XML version. Defaults to 1.0 #.Parameter encoding # Optional: the Encoding. Defaults to UTF-8 #.Parameter standalone # Optional: whether to specify standalone in the xml declaration. Defaults to "yes" #.Parameter args # this is where all the dsl magic happens. Please see the Examples. :) # #.Example # [string]$xml = New-XDocument rss -version "2.0" { # channel { # title {"Test RSS Feed"} # link {"http`://HuddledMasses.org"} # description {"An RSS Feed generated simply to demonstrate my XML DSL"} # item { # title {"The First Item"} # link {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"} # guid -isPermaLink true {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"} # description {"Ema Lazarus' Poem"} # pubDate {(Get-Date 10/31/2003 -f u) -replace " ","T"} # } # } # } # # C:\\PS>$xml.Declaration.ToString() ## I can't find a way to have this included in the $xml.ToString() # C:\\PS>$xml.ToString() # # <?xml version="1.0" encoding="UTF-8" standalone="yes"?> # <rss version="2.0"> # <channel> # <title>Test RSS Feed</title> # <link>http ://HuddledMasses.org</link> # <description>An RSS Feed generated simply to demonstrate my XML DSL</description> # <item> # <title>The First Item</title> # <link>http ://huddledmasses.org/new-site-new-layout-lost-posts/</link> # <guid isPermaLink="true">http ://huddledmasses.org/new-site-new-layout-lost-posts/</guid> # <description>Ema Lazarus' Poem</description> # <pubDate>2003-10-31T00:00:00Z</pubDate> # </item> # </channel> # </rss> # # # Description # ----------- # This example shows the creation of a complete RSS feed with a single item in it. # # NOTE that the backtick in the http`: in the URLs in the input is unecessary, and I added the space after the http: in the URLs in the output -- these are accomodations to PoshCode's spam filter. Backticks are not need in the input, and spaces do not appear in the actual output. # # #.Example # [XNamespace]$atom="http`://www.w3.org/2005/Atom" # C:\\PS>[XNamespace]$dc = "http`://purl.org/dc/elements/1.1" # # C:\\PS>New-XDocument ($atom + "feed") -Encoding "UTF-16" -$([XNamespace]::Xml +'lang') "en-US" -dc $dc { # title {"Test First Entry"} # link {"http`://HuddledMasses.org"} # updated {(Get-Date -f u) -replace " ","T"} # author { # name {"Joel Bennett"} # uri {"http`://HuddledMasses.org"} # } # id {"http`://huddledmasses.org/" } # # entry { # title {"Test First Entry"} # link {"http`://HuddledMasses.org/new-site-new-layout-lost-posts/" } # id {"http`://huddledmasses.org/new-site-new-layout-lost-posts/" } # updated {(Get-Date 10/31/2003 -f u) -replace " ","T"} # summary {"Ema Lazarus' Poem"} # link -rel license -href "http`://creativecommons.org/licenses/by/3.0/" -title "CC By-Attribution" # dc:rights { "Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)" } # category -scheme "http`://huddledmasses.org/tag/" -term "huddled-masses" # } # } | % { $_.Declaration.ToString(); $_.ToString() } # # <?xml version="1.0" encoding="UTF-16" standalone="yes"?> # <feed xml:lang="en-US" xmlns="http ://www.w3.org/2005/Atom"> # <title>Test First Entry</title> # <link>http ://HuddledMasses.org</link> # <updated>2009-07-29T17:25:49Z</updated> # <author> # <name>Joel Bennett</name> # <uri>http ://HuddledMasses.org</uri> # </author> # <id>http ://huddledmasses.org/</id> # <entry> # <title>Test First Entry</title> # <link>http ://HuddledMasses.org/new-site-new-layout-lost-posts/</link> # <id>http ://huddledmasses.org/new-site-new-layout-lost-posts/</id> # <updated>2003-10-31T00:00:00Z</updated> # <summary>Ema Lazarus' Poem</summary> # <link rel="license" href="http ://creativecommons.org/licenses/by/3.0/" title="CC By-Attribution" /> # <dc:rights>Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)</dc:rights> # <category scheme="http ://huddledmasses.org/tag/" term="huddled-masses" /> # </entry> # </feed> # # # Description # ----------- # This example shows the use of a default namespace, as well as additional specific namespaces for the "dc" namespace. It also demonstrates how you can get the <?xml?> declaration which does not appear in a simple .ToString(). # # NOTE that the backtick in the http`: in the URLs in the input is unecessary, and I added the space after the http: in the URLs in the output -- these are accomodations to PoshCode's spam filter. Backticks are not need in the input, and spaces do not appear in the actual output.# # Param( [Parameter(Mandatory = $true, Position = 0)] [System.Xml.Linq.XName]$root , [Parameter(Mandatory = $false)] [string]$Version = "1.0" , [Parameter(Mandatory = $false)] [string]$Encoding = "UTF-8" , [Parameter(Mandatory = $false)] [string]$Standalone = "yes" , [Parameter(Position=99, Mandatory = $false, ValueFromRemainingArguments=$true)] [PSObject[]]$args ) BEGIN { $script:NameSpaceHash = New-Object 'Dictionary[String,XNamespace]' if($root.NamespaceName) { $script:NameSpaceHash.Add("", $root.Namespace) } } PROCESS { New-Object XDocument (New-Object XDeclaration $Version, $Encoding, $standalone),( New-Object XElement $( $root while($args) { $attrib, $value, $args = $args if($attrib -is [ScriptBlock]) { # Write-Verbose "Preparsed DSL: $attrib" $attrib = ConvertFrom-XmlDsl $attrib Write-Verbose "Reparsed DSL: $attrib" &$attrib } elseif ( $value -is [ScriptBlock] -and "-Content".StartsWith($attrib)) { $value = ConvertFrom-XmlDsl $value &$value } elseif ( $value -is [XNamespace]) { New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-")), $value $script:NameSpaceHash.Add($attrib.TrimStart("-"), $value) } else { New-Object XAttribute $attrib.TrimStart("-"), $value } } )) } } Set-Alias xml New-XDocument -EA 0 Set-Alias New-Xml New-XDocument -EA 0 function New-XAttribute { #.Synopsys # Creates a new XAttribute (an xml attribute on an XElement for XDocument) #.Description # This is the work-horse for the XML mini-dsl #.Parameter name # The attribute name #.Parameter value # The attribute value Param([Parameter(Mandatory=$true)]$name,[Parameter(Mandatory=$true)]$value) New-Object XAttribute $name, $value } Set-Alias xa New-XAttribute -EA 0 Set-Alias New-XmlAttribute New-XAttribute -EA 0 function New-XElement { #.Synopsys # Creates a new XElement (an xml tag for XDocument) #.Description # This is the work-horse for the XML mini-dsl #.Parameter tag # The name of the xml tag #.Parameter args # this is where all the dsl magic happens. Please see the Examples. :) Param( [Parameter(Mandatory = $true, Position = 0)] [System.Xml.Linq.XName]$tag , [Parameter(Position=99, Mandatory = $false, ValueFromRemainingArguments=$true)] [PSObject[]]$args ) # BEGIN { # if([string]::IsNullOrEmpty( $tag.NamespaceName )) { # $tag = $($script:NameSpaceStack.Peek()) + $tag # if( $script:NameSpaceStack.Count -gt 0 ) { # $script:NameSpaceStack.Push( $script:NameSpaceStack.Peek() ) # } else { # $script:NameSpaceStack.Push( $null ) # } # } else { # $script:NameSpaceStack.Push( $tag.Namespace ) # } # } PROCESS { New-Object XElement $( $tag while($args) { $attrib, $value, $args = $args if($attrib -is [ScriptBlock]) { # then it's content &$attrib } elseif ( $value -is [ScriptBlock] -and "-Content".StartsWith($attrib)) { # then it's content &$value } elseif ( $value -is [XNamespace]) { New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-")), $value $script:NameSpaceHash.Add($attrib.TrimStart("-"), $value) } else { New-Object XAttribute $attrib.TrimStart("-"), $value } } ) } # END { # $null = $script:NameSpaceStack.Pop() # } } Set-Alias xe New-XElement Set-Alias New-XmlElement New-XElement function ConvertFrom-XmlDsl { Param([ScriptBlock]$script) $parserrors = $null $global:tokens = [PSParser]::Tokenize( $script, [ref]$parserrors ) $duds = $global:tokens | Where-Object { $_.Type -eq "Command" -and !$_.Content.Contains('-') -and ($(Get-Command $_.Content -Type Cmdlet,Function,ExternalScript -EA 0) -eq $Null) } [Array]::Reverse( $duds ) [string[]]$ScriptText = "$script" -split "`n" ForEach($token in $duds ) { # replace : notation with namespace notation if( $token.Content.Contains(":") ) { $key, $localname = $token.Content -split ":" $ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Remove( $token.StartColumn -1, $token.Length ).Insert( $token.StartColumn -1, "'" + $($script:NameSpaceHash[$key] + $localname) + "'" ) } else { $ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Remove( $token.StartColumn -1, $token.Length ).Insert( $token.StartColumn -1, "'" + $($script:NameSpaceHash[''] + $token.Content) + "'" ) } # insert 'xe' before everything (unless it's a valid command) $ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Insert( $token.StartColumn -1, "xe " ) } Write-Output ([ScriptBlock]::Create( ($ScriptText -join "`n") )) } Export-ModuleMember -alias * -function New-XDocument, New-XAttribute, New-XElement, Remove-XmlNamespace, Convert-Xml, Select-Xml, Format-Xml
PowerShellCorpus/PoshCode/Get-WebFile 3.7.1.ps1
Get-WebFile 3.7.1.ps1
## Get-WebFile (aka wget for PowerShell) ############################################################################################################## ## Downloads a file or page from the web ## History: ## v3.7.1 - Puts a try-catch statement around the $req.GetResponse() call to prevent further execution if ## the page does not exist, cannot connect to server, can't resolve host, etc. ## v3.7 - [int] to [long] to support files larger than 2.0 GB ## v3.6 - Add -Passthru switch to output TEXT files ## v3.5 - Add -Quiet switch to turn off the progress reports ... ## v3.4 - Add progress report for files which don't report size ## v3.3 - Add progress report for files which report their size ## v3.2 - Use the pure Stream object because StreamWriter is based on TextWriter: ## it was messing up binary files, and making mistakes with extended characters in text ## 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 Get-WebFile { param( $url = (Read-Host "The URL to download"), $fileName = $null, [switch]$Passthru, [switch]$quiet ) $req = [System.Net.HttpWebRequest]::Create($url); # http://stackoverflow.com/questions/518181/too-many-automatic-redirections-were-attempted-error-message-when-using-a-httpw $req.CookieContainer = New-Object System.Net.CookieContainer try{ $res = $req.GetResponse(); } catch { Write-Error $error[0].Exception.InnerException.Message; return; } if($fileName -and !(Split-Path $fileName)) { $fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName } elseif((!$Passthru -and ($fileName -eq $null)) -or (($fileName -ne $null) -and (Test-Path -PathType "Container" $fileName))) { [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($Passthru) { $encoding = [System.Text.Encoding]::GetEncoding( $res.CharacterSet ) [string]$output = "" } if($res.StatusCode -eq 200) { [long]$goal = $res.ContentLength $reader = $res.GetResponseStream() if($fileName) { $writer = new-object System.IO.FileStream $fileName, "Create" } [byte[]]$buffer = new-object byte[] 4096 [long]$total = [long]$count = 0 do { $count = $reader.Read($buffer, 0, $buffer.Length); if($fileName) { $writer.Write($buffer, 0, $count); } if($Passthru){ $output += $encoding.GetString($buffer,0,$count) } elseif(!$quiet) { $total += $count if($goal -gt 0) { Write-Progress "Downloading $url" "Saving $total of $goal" -id 0 -percentComplete (($total/$goal)*100) } else { Write-Progress "Downloading $url" "Saving $total bytes..." -id 0 } } } while ($count -gt 0) $reader.Close() if($fileName) { $writer.Flush() $writer.Close() } if($Passthru){ $output } } $res.Close(); if($fileName) { ls $fileName } }
PowerShellCorpus/PoshCode/Get-CInfo.ps1
Get-CInfo.ps1
function Get-CInfo { param($Comp) Function PC-Name{ param ($compname) $ADS = Get-ADComputer -Filter {name -eq $compname} -Properties * | Select-Object -Property name If($ads -eq $null) {$false} ELSE{$True} } $ping = PC-Name $COMP if ($ping -eq $true) { Write-Host -ForegroundColor Green ("Computer Info For: $COMP") $a= @{Expression={$_.Name};Label="Comp. Name";width=25}, @{Expression={$_.ipv4address};Label="IP Address";width=25}, @{Expression={$_.operatingsystem};Label="Operating System";width=25}, @{Expression={$_.Created};Label="Created";width=25}, @{Expression={$_.lastlogondate};Label="Last Logon";width=25}, @{Expression={$_.logoncount};Label="# of Logins";width=25} Get-ADComputer -f {name -eq $comp} -Properties * | select-object -property name,ipv4address,operatingsystem,created,lastlogondate,logoncount | format-table -Wrap -AutoSize $A } ELSEIF ($ping -eq $false) { do { Write-Host -ForegroundColor yellow "No Match Found, Below Is An AD Search, Try Again (CTRL-C to Exit):" $SEARCH = "*$COMP*" Get-ADComputer -Filter {name -like $SEARCH} | Select-Object -property name,enabled | Format-Table -AutoSize $comp = (read-host "What is the Computer Name? (EX. demersm-l7567)").ToLower() function Ping-Server { Param([string]$srv) $pingresult = Get-WmiObject Win32_PingStatus -Filter "Address='$srv'" if($pingresult.StatusCode -eq 0) {$true} else {$false} } $PING2 = PC-Name $COMP } While ($PING2 -eq $false) } If($ping2 -eq $true){ Write-Host -ForegroundColor Green ("Computer Info For: $COMP") $a= @{Expression={$_.Name};Label="Comp. Name";width=25}, @{Expression={$_.ipv4address};Label="IP Address";width=25}, @{Expression={$_.operatingsystem};Label="Operating System";width=25}, @{Expression={$_.Created};Label="Created";width=25}, @{Expression={$_.lastlogondate};Label="Last Logon";width=25}, @{Expression={$_.logoncount};Label="# of Logins";width=25} Get-ADComputer -f {name -eq $comp} -Properties * | select-object -property name,ipv4address,operatingsystem,created,lastlogondate,logoncount | format-table -Wrap -AutoSize $A } }
PowerShellCorpus/PoshCode/Import-Certificate.ps1
Import-Certificate.ps1
function Import-Certificate { param ( [IO.FileInfo] $CertFile = $(throw "Paramerter -CertFile [System.IO.FileInfo] is required."), [string[]] $StoreNames = $(throw "Paramerter -StoreName [System.String] is required."), [switch] $LocalMachine, [switch] $CurrentUser, [string] $CertPassword, [switch] $Verbose ) begin { [void][System.Reflection.Assembly]::LoadWithPartialName("System.Security") } process { if (-not $LocalMachine -and -not $CurrentUser) { Write-Warning "One or both of the following parameters are required: '-LocalMachine' '-CurrentUser'. Skipping certificate '$CertFile'." } try { $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $certfile,$CertPassword } catch { Write-Error ("Error importing '$certfile': $_ .") -ErrorAction:Continue } if ($cert -and $LocalMachine) { $StoreScope = "LocalMachine" $StoreNames | ForEach-Object { $StoreName = $_ if (Test-Path "cert:\\$StoreScope\\$StoreName") { try { $store = New-Object System.Security.Cryptography.X509Certificates.X509Store $StoreName, $StoreScope $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) $store.Add($cert) $store.Close() if ($Verbose -or $VerbosePreference -ne 'SilentlyContinue') { Write-Verbose "Successfully added '$certfile' to 'cert:\\$StoreScope\\$StoreName'." } } catch { Write-Error ("Error adding '$certfile' to 'cert:\\$StoreScope\\$StoreName': $_ .") -ErrorAction:Continue } } else { Write-Warning "Certificate store '$StoreName' does not exist. Skipping..." } } } if ($cert -and $CurrentUser) { $StoreScope = "CurrentUser" $StoreNames | ForEach-Object { $StoreName = $_ if (Test-Path "cert:\\$StoreScope\\$StoreName") { try { $store = New-Object System.Security.Cryptography.X509Certificates.X509Store $StoreName, $StoreScope $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) $store.Add($cert) $store.Close() if ($Verbose -or $VerbosePreference -ne 'SilentlyContinue') { Write-Verbose "Successfully added '$certfile' to 'cert:\\$StoreScope\\$StoreName'." } } catch { Write-Error ("Error adding '$certfile' to 'cert:\\$StoreScope\\$StoreName': $_ .") -ErrorAction:Continue } } else { Write-Warning "Certificate store '$StoreName' does not exist. Skipping..." } } } } end { } }
PowerShellCorpus/PoshCode/Get-StaticMethodDefin_1.ps1
Get-StaticMethodDefin_1.ps1
#Steven Murawski #http://blog.usepowershell.com #03/20/2009 #Examples: # get-staticmethoddefinition max math # [math] | get-staticmethoddefinition max function Get-StaticMethodDefinition() { param ([string[]]$Method, [Type]$Type=$null) BEGIN { if ($Type -ne $null) { $Type | Get-StaticMethodDefinition $Method } } PROCESS { if ($_ -ne $null) { $_ | Get-Member -Name $Method -Static -MemberType Method | ForEach-Object {$_.Definition -replace '\\), ', "), `n"} } } }
PowerShellCorpus/PoshCode/Create a VIAccount.ps1
Create a VIAccount.ps1
function New-VIAccount($principal) { $flags = ` [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Public -bor [System.Reflection.BindingFlags]::DeclaredOnly -bor [System.Reflection.BindingFlags]::Instance $method = $defaultviserver.GetType().GetMethods($flags) | where { $_.Name -eq "VMware.VimAutomation.Types.VIObjectCore.get_Client" } $client = $method.Invoke($global:DefaultVIServer, $null) Write-Output ` (New-Object VMware.VimAutomation.Client20.PermissionManagement.VCUserAccountImpl ` -ArgumentList $principal, "", $client) }
PowerShellCorpus/PoshCode/Get-InstalledApps.ps1
Get-InstalledApps.ps1
Param([string]$server) Begin{ function CheckRegKey{ param([string]$srv) $key = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall" $type = [Microsoft.Win32.RegistryHive]::LocalMachine $regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($type, $Srv) $regKey = $regKey.OpenSubKey($key) foreach($sub in $regKey.GetSubKeyNames()) { if($regKey.OpenSubKey($sub).GetValue("DisplayName")) { $regKey.OpenSubKey($sub).GetValue("DisplayName") } else { $sub } } } $process = @() } Process{ if($_) { $process += $_ } } End{ if($Server) { $process += $Server } foreach($s in $process) { CheckRegKey $s } }
PowerShellCorpus/PoshCode/HuddledTricks.ps1
HuddledTricks.ps1
## Stupid PowerShell Tricks ################################################################################################### ## Usage: ## ps Notepad | Hide-App ## Hide-App -Name PowerShell; Wiggle-Mouse 75 100 ################################################################################################### add-type @" using System; using System.Runtime.InteropServices; public class Tricks { [DllImport("user32.dll")] private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); public static void ShowWindow(IntPtr hWnd) { ShowWindowAsync(hWnd,5); } public static void HideWindow(IntPtr hWnd) { ShowWindowAsync(hWnd,0); } } "@ $dictionary = [System.Collections.Generic.Dictionary``2] $list = [System.Collections.Generic.List``1] $string = [String] $intPtr = [IntPtr] $intPtrList = $list.AssemblyQualifiedName -replace "1,","1[[$($intPtr.AssemblyQualifiedName)]]," $windows = new-object ($dictionary.AssemblyQualifiedName -replace "2,","2[[$($string.AssemblyQualifiedName)],[$intPtrList]],") function Hide-Window { <# .SYNOPSIS Hide a window .DESCRIPTION Hide a window by handle or by process name. Hidden windows are gone: they don't show up in alt+tab, or on the taskbar, and they're invisible. The only way to get them back is with ShowWindow. Windows hidden by Hide-Window are pushed onto a stack so they can be retrieved by Show-Window. Since they're invisible, they're very hard to find otherwise. .NOTES See also Show-Window .PARAMETER WindowHandle The window handle to a specific window we want to hide. .PARAMETER Name The name of a running process whos windows you want to hide. .EXAMPLE Get-Process PowerShell | Hide-Window; Sleep 5; Show-Window Hides the PowerShell window(s) for 5 seconds .LINK http://HuddledMasses.org/stupid-powershell-tricks #> [CmdletBinding()] PARAM ( [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)] [Alias("MainWindowHandle","Handle")] [IntPtr]$WindowHandle=[IntPtr]::Zero , [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)] [Alias("ProcessName")] [String]$Name ) PROCESS { (Push-Window $WindowHandle $Name) | ForEach-Object { [Tricks]::HideWindow( $_ ) } } } function Show-Window { <# .SYNOPSIS Show a window .DESCRIPTION Show a window by handle or by process name. If you call it without any parameters, will show all hidden windows. .NOTES See also Hide-Window .PARAMETER WindowHandle The window handle to a specific window we want to show. .PARAMETER Name The name of a running process whos windows you want to show. .EXAMPLE Get-Process PowerShell | Hide-Window; Sleep 5; Show-Window Hides the PowerShell window(s) for 5 seconds .LINK http://HuddledMasses.org/stupid-powershell-tricks #> [CmdletBinding()] PARAM ( [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)] [Alias("MainWindowHandle","Handle")] [IntPtr]$WindowHandle=[IntPtr]::Zero , [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)] [Alias("ProcessName")] [String]$Name ) PROCESS { (Pop-Window $WindowHandle $Name) | ForEach-Object { [Tricks]::ShowWindow( $_ ) } } } ## PRIVATE FUNCTION Push-Window { [CmdletBinding()] PARAM ([IntPtr]$Handle,[String]$ProcessName) [IntPtr[]]$Handles = @($Handle) if(!$ProcessName) { $ProcessName = "--Unknown--" } if(!$Windows.ContainsKey($ProcessName)) { $windows.Add($ProcessName, (New-Object $intPtrList)) } if($Handle -eq [IntPtr]::Zero) { [IntPtr[]]$Handles = @(Get-Process $ProcessName | % { $_.MainWindowHandle } ) } $windows[$ProcessName].AddRange($Handles) write-output $Handles } ## PRIVATE FUNCTION Pop-Window { [CmdletBinding()] PARAM ([IntPtr]$Handle,[String]$ProcessName) [IntPtr[]]$Handles = @($Handle) if(!$ProcessName) { $ProcessName = "--Unknown--" } if(($Handle -eq [IntPtr]::Zero) -and $windows[$ProcessName] ) { write-output $windows[$ProcessName] $Null = $windows[$ProcessName].Clear() } elseif($Handle -ne [IntPtr]::Zero){ $Null = $windows[$ProcessName].Remove( $Handle ) } write-output $Handles } Add-Type -Assembly System.Windows.Forms function Wiggle-Mouse { <# .SYNOPSIS Wiggle the mouse until you Ctrl+Break to stop the script. .DESCRIPTION Wiggle-Mouse randomly moves the mouse by a few pixels every few milliseconds until you stop the script. .PARAMETER Variation The maximum distance to move the mosue in any direction. Values that are too small aren't noticeable, and values that are too big make the user "loose" the mouse and they have no idea what happened. .PARAMETER Name The name of a running process whos windows you want to hide. .EXAMPLE Get-Process PowerShell | Hide-Window; Wiggle-Mouse -Duration 5; Get-Process PowerShell | Show-Window Hides the PowerShell window and wiggle the mouse for five seconds ... :D .LINK http://HuddledMasses.org/stupid-powershell-tricks #> [CmdletBinding()] PARAM ( [Parameter(Position=0)][Int]$Variation=80, [Parameter(Position=1)][Int]$Sleep=400, [Parameter(Position=2)][Int]$Duration=0 ) if(!$Duration) { Write-Host "Ctrl+C to stop wiggling :)" } $screen = [System.Windows.Forms.SystemInformation]::VirtualScreen $random = new-object Random $Duration *= -1000 While($Duration -le 0) { [Windows.Forms.Cursor]::Position ="$( $random.Next( [Math]::Max( $screen.Left, ([System.Windows.Forms.Cursor]::Position.X - $Variation) ), [Math]::Min( $screen.Right, ([System.Windows.Forms.Cursor]::Position.X + $Variation) ) ) ),$( $random.Next( [Math]::Max( $screen.Top, ([System.Windows.Forms.Cursor]::Position.Y - $Variation) ), [Math]::Min( $screen.Bottom, ([System.Windows.Forms.Cursor]::Position.Y + $Variation) ) ) )" sleep -milli $Sleep $Duration += $Sleep } } Export-ModuleMember Show-Window, Hide-Window, Wiggle-Mouse
PowerShellCorpus/PoshCode/Test-Help_1.ps1
Test-Help_1.ps1
function Test-Help { <# .Synopsis Test-Help -Function Get-USB .Description Test-Help was written to get information why that !@##$%#$%# help is not working ;) Should work fine both with v1 and v2 comments. Using fancy regex that probably could be shorter, more elegant and so long and so forth... ;) .Example Test-Help -Function Test-Help If you want to find mistakes made by other - try to find yours first. ;) .Link Not yet implemented .Parameter Function Name of the function to be tested. .Notes Ver 0.2 - not yet implemented - testing of position in definition of function (has to be at the or at the bottom...) Ver 0.1 - added testing for v1 comments Ver 0.0 - simple test for v2 comment based help #> param ([string]$Function) try { $Definition = (Get-Command -CommandType function -Name $function -ErrorAction Stop).definition -split '\\n' $regKey = [regex]'^\\s*\\.(?<KEY>\\w+)($|\\s*($|(?<PARAM>[\\w-]+))($|\\s*(?<ERROR>\\S*)$))' $regV1Comment = [regex]'^\\s*#(.*)' $regComStart = [regex]'^\\s*<#\\s*$' $regComEnd = [regex]'^\\s*#>\\s*$' $IsComment = $false $KEYS = @('SYNOPSIS','DESCRIPTION','EXAMPLE','INPUTS','OUTPUTS','NOTES','LINK','COMPONENT','ROLE','FUNCTIONALITY') $EXTKEYS = @('PARAMETER','FORWARDHELPTARGETNAME','FORWARDHELPCATEGORY','REMOTEHELPRUNSPACE','EXTERNALHELP') foreach ($line in $Definition) { $line = $line -replace '\\r', '' $invocation = "Line : $line Function : $function" if (($IsComment) -or ($regV1Comment.IsMatch($line))) { # just in case - we get rid of # at the line beg $line = $regV1Comment.Replace($line,'$1') if ($RegKey.IsMatch($line)) { # should contain keyword $RegKey.Match($line) | ForEach-Object { $Key = $_.Groups['KEY'].Value $Par = $_.Groups['PARAM'].Value $Err = $_.Groups['ERROR'].Value } if (![string]::IsNullOrEmpty($Err)) { Write-Host -ForegroundColor Cyan "Unexpected token - not more than two: $Err $invocation" continue } if ($KEYS -contains $Key) { if (![string]::IsNullOrEmpty($Par)) { Write-Host -ForegroundColor Yellow "Unexpected token - keyword without additional parameters: $Par $invocation" continue } } else { if ($EXTKEYS -contains $Key) { if ([string]::IsNullOrEmpty($Par)) { Write-Host -ForegroundColor Magenta "Missing token - $Key should be followed by something, $invocation" } } else { # Looks like spelling mistake... Write-Host -ForegroundColor Green "Key probably with spelling mistake: $Key $invocation" } } } else { if ($RegComEnd.IsMatch($line)) { $IsComment = $false } } } else { if ($RegComStart.IsMatch($line)) { $IsComment = $true } } } } catch { Write-Host -ForegroundColor Red "Error: $_ " } }
PowerShellCorpus/PoshCode/VB MsgBox Powershell.ps1
VB MsgBox Powershell.ps1
<# .SYNOPSIS Shows a graphical message box, with various prompt types available. .DESCRIPTION Emulates the Visual Basic MsgBox function. It takes four parameters, of which only the prompt is mandatory .INPUTS The parameters are:- Prompt (mandatory): Text string that you wish to display Title (optional): The title that appears on the message box Icon (optional). Available options are: Information, Question, Critical, Exclamation (not case sensitive) BoxType (optional). Available options are: OKOnly, OkCancel, AbortRetryIgnore, YesNoCancel, YesNo, RetryCancel (not case sensitive) DefaultButton (optional). Available options are: 1, 2, 3 .OUTPUTS Microsoft.VisualBasic.MsgBoxResult .EXAMPLE C:\\PS> Show-MsgBox Hello Shows a popup message with the text "Hello", and the default box, icon and defaultbutton settings. .EXAMPLE C:\\PS> Show-MsgBox -Prompt "This is the prompt" -Title "This Is The Title" -Icon Critical -BoxType YesNo -DefaultButton 2 Shows a popup with the parameter as supplied. .LINK http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.msgboxresult.aspx .LINK http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.msgboxstyle.aspx #> # By BigTeddy August 24, 2011 # http://social.technet.microsoft.com/profile/bigteddy/. function Show-MsgBox { [CmdletBinding()] param( [Parameter(Position=0, Mandatory=$true)] [string]$Prompt, [Parameter(Position=1, Mandatory=$false)] [string]$Title ="", [Parameter(Position=2, Mandatory=$false)] [ValidateSet("Information", "Question", "Critical", "Exclamation")] [string]$Icon ="Information", [Parameter(Position=3, Mandatory=$false)] [ValidateSet("OKOnly", "OKCancel", "AbortRetryIgnore", "YesNoCancel", "YesNo", "RetryCancel")] [string]$BoxType ="OkOnly", [Parameter(Position=4, Mandatory=$false)] [ValidateSet(1,2,3)] [int]$DefaultButton = 1 ) [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.VisualBasic") | Out-Null switch ($Icon) { "Question" {$vb_icon = [microsoft.visualbasic.msgboxstyle]::Question } "Critical" {$vb_icon = [microsoft.visualbasic.msgboxstyle]::Critical} "Exclamation" {$vb_icon = [microsoft.visualbasic.msgboxstyle]::Exclamation} "Information" {$vb_icon = [microsoft.visualbasic.msgboxstyle]::Information}} switch ($BoxType) { "OKOnly" {$vb_box = [microsoft.visualbasic.msgboxstyle]::OKOnly} "OKCancel" {$vb_box = [microsoft.visualbasic.msgboxstyle]::OkCancel} "AbortRetryIgnore" {$vb_box = [microsoft.visualbasic.msgboxstyle]::AbortRetryIgnore} "YesNoCancel" {$vb_box = [microsoft.visualbasic.msgboxstyle]::YesNoCancel} "YesNo" {$vb_box = [microsoft.visualbasic.msgboxstyle]::YesNo} "RetryCancel" {$vb_box = [microsoft.visualbasic.msgboxstyle]::RetryCancel}} switch ($Defaultbutton) { 1 {$vb_defaultbutton = [microsoft.visualbasic.msgboxstyle]::DefaultButton1} 2 {$vb_defaultbutton = [microsoft.visualbasic.msgboxstyle]::DefaultButton2} 3 {$vb_defaultbutton = [microsoft.visualbasic.msgboxstyle]::DefaultButton3}} $popuptype = $vb_icon -bor $vb_box -bor $vb_defaultbutton $ans = [Microsoft.VisualBasic.Interaction]::MsgBox($prompt,$popuptype,$title) return $ans } #end function
PowerShellCorpus/PoshCode/Determine Computer Uptim.ps1
Determine Computer Uptim.ps1
<# .SYNOPSIS Demonstrates uptime using WMI .DESCRIPTION This script used Win32_ComputerSystem to determine how long your system has been running. This is a rewrite/improvement of sample 3 at http://msdn.microsoft.com/en-us/library/aa394591(VS.85).aspx. .NOTES File Name : Get-UpTime.ps1 Author : Thomas Lee - tfl@psp.co.uk Requires : PowerShell V2 CTP3 .LINK Script Posted to: http://www.pshscripts.blogspot.com Original sample posted at: http://msdn.microsoft.com/en-us/library/aa394591(VS.85).aspx .EXAMPLE PS c:\\foo> .\\Get-UpTime.Ps1 System Up for: 1 days, 8 hours, 40.781 minutes #> ## # Start of script ## # Helper Function - convert WMI date to TimeDate object function WMIDateStringToDate($Bootup) { [System.Management.ManagementDateTimeconverter]::ToDateTime($Bootup) } # Main script $Computer = "." # adjust as needed $computers = Get-WMIObject -class Win32_OperatingSystem -computer $computer # There had better only be one object returned, but... foreach ($system in $computers) { # work out uptime $Bootup = $system.LastBootUpTime $LastBootUpTime = WMIDateStringToDate($Bootup) $now = Get-Date $Uptime = $now - $lastBootUpTime $d = $Uptime.Days $h = $Uptime.Hours $m = $uptime.Minutes $ms= $uptime.Milliseconds # Display uptime "System Up for: {0} days, {1} hours, {2}.{3} minutes" -f $d,$h,$m,$ms } # End script
PowerShellCorpus/PoshCode/Automount new PSDrives.ps1
Automount new PSDrives.ps1
# AutoMount.psm1 v1.0 # Oisin "x0n" Grehan (MVP) $query = new-object System.Management.WqlEventQuery $query.EventClassName = "__InstanceOperationEvent" # default to every 2 seconds $query.WithinInterval = new-object System.TimeSpan 0,0,2 @@# this WMI is only available with Windows 2003 and Vista (not XP it appears). # this could be rewritten to use different WMI queries to support 2000/NT/XP also. $query.QueryString = "Select * from Win32_VolumeChangeEvent" # attach a watcher $watcher = new-object System.Management.ManagementEventWatcher $query # here we use -SupportEvent instead of -SourceIdentifier # this prevents this event from being generally visible # also note the use of the call operator to invoke a # function in the scope of the module since this action # occurs outside of module scope. Register-ObjectEvent $watcher -EventName "EventArrived" ` -SupportEvent "WMI.VolumeChange" -Action { & (get-module automount) VolumeChangeCallback @args } # New PSEvents: # # PowerShell.DeviceConfigurationChanged # PowerShell.DeviceArrived # PowerShell.DeviceRemoved # PowerShell.DeviceDocking # win32_volumechangeevent event types $eventTypes = @{ 1 = "ConfigurationChanged"; 2 = "Arrived"; 3 = "Removed"; 4 = "Docking"; } # private module level callback function function VolumeChangeCallback ($sender, $eventargs) { trap { write-warning $_ } $driveName = $eventArgs.NewEvent.DriveName.TrimEnd(":") $eventType = [int]$eventArgs.NewEvent.EventType # was uint16 $forwardedEvent = "Device$($eventTypes[$eventType])" # forward a new simpler event specific to device event type [void]( New-PSEvent "PowerShell.$forwardedEvent" -Sender $driveName ` -EventArguments $eventargs ) } # hook up our psdrive mount / unmount events # and start the WMI watcher function Enable-AutoMount { Register-PSEvent -SourceIdentifier "PowerShell.DeviceArrived" ` -Action { new-psdrive -name $args[0] -psprovider ` filesystem -root "$args[0]:"; } Register-PSEvent -SourceIdentifier "PowerShell.DeviceRemoved" ` -Action { remove-psdrive -name $args[0] -ea 0; # may not exist } $watcher.Start() } # tear down our psdrive mount / unmount events # and stop the WMI watcher function Disable-AutoMount { Unregister-PSEvent -SourceIdentifier "PowerShell.DeviceArrived" Unregister-PSEvent -SourceIdentifier "PowerShell.DeviceRemoved" $watcher.Stop() } # export functions to control automount Export-ModuleMember Enable-AutoMount, Disable-AutoMount # start watching and (un)mounting Enable-AutoMount
PowerShellCorpus/PoshCode/Update-DeptGPOs.ps1
Update-DeptGPOs.ps1
<# .SYNOPSIS Update permissions on Departmental GPO's .DESCRIPTION This script will backup all existing GPO's in the domain prior to making any changes. After the backup has been made Departmental GPOs will be updated based on their Dept Code. .PARAMETER DeptCode A code that uniquely identifies the GPOs for your department, this is used as a filter against the name of the GPO in question. .PARAMETER TargetName The name of the user/group to assign permissions to .PARAMETER TargetType The default for this parameter is User, but if TargetName is a group, then this should be set to Group. .PARAMETER PermissionLevel Valid permission levels are GpoRead GpoApply GpoEdit GpoEditDeleteModifySecurity None .PARAMETER BackupLocation A valid location either local or UNC to store the GPO backups. .PARAMETER Test Set to $False in order to update security and perform backup. .EXAMPLE .\\Update-DeptGPOs.ps1 -DeptCode "Admin" -TargetName "MyUser" -BackupLocation "c:\\temp" Description ----------- This example shows basic usage, and assumes the default permissionlevel of None. .EXAMPLE .\\Update-DeptGPOs.ps1 -DeptCode "Admin" -TargetName "MyUser" -PermissionLevel "GpoEditDeleteModifySecurity" -BackupLocation "c:\\temp" Description ----------- This example assigns GpoEditDeleteModifySecurity to the MyUser account for all GPOs tagged as Admin .NOTES ScriptName: Update-DeptGPOs Created By: Jeff Patton Date Coded: June 7, 2011 ScriptName is used to register events for this script LogName is used to determine which classic log to write to This script depends on PowerShell GroupPolicy modules to functino properly, the linked in cmdlets are used in this script. If a backup cannot be made the script terminates. .LINK http://scripts.patton-tech.com/wiki/PowerShell/Production/Update-DeptGPOs .LINK http://technet.microsoft.com/en-us/library/ee461059.aspx .LINK http://technet.microsoft.com/en-us/library/ee461038.aspx .LINK http://technet.microsoft.com/en-us/library/ee461052.aspx #> Param ( $DeptCode, $TargetName, $TargetType = "User", [ValidateSet("GpoRead", "GpoApply", "GpoEdit", "GpoEditDeleteModifySecurity","None")] $PermissionLevel = "None", $BackupLocation, $Test = $True ) Begin { $ScriptName = $MyInvocation.MyCommand.ToString() $LogName = "Application" $ScriptPath = $MyInvocation.MyCommand.Path $Username = $env:USERDOMAIN + "\\" + $env:USERNAME New-EventLog -Source $ScriptName -LogName $LogName -ErrorAction SilentlyContinue $Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nStarted: " + (Get-Date).toString() Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message $ErrorActionPreference = "Stop" Try { Import-Module GroupPolicy $DeptGPOs = Get-GPO -All |Where-Object {$_.DisplayName -like "*$($DeptCode)*"} Foreach ($DeptGPO in $DeptGPOs) { If ($Test -eq $False) { Backup-GPO -Guid $DeptGPO.Id -Path $BackupLocation -Comment "Updating Security on $($DeptCode) GPOs" $Message = "Backed up $($DeptGPO.DisplayName) to $($BackupLocation)" Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message } Else { Write-Host "Backed up $($DeptGPO.Displayname) to $($BackupLocation)" } } } Catch { $Message = $Error[0].Exception.InnerException.Message.ToString().Trim() Write-EventLog -LogName $LogName -Source $ScriptName -EventId "102" -EntryType "Error" -Message $Message Write-Error $Message Break } } Process { foreach ($DeptGPO in $DeptGPOs) { Try { If ($Test -eq $False) { Set-GPPermissions -Guid $DeptGPO.Id -TargetName $TargetName -PermissionLevel $PermissionLevel -TargetType $TargetType $Message = "Adding $($TargetName) to $($DeptGPO.DisplayName) with permission level $($PermissionLevel)" Write-EventLog -LogName $LogName -Source $ScriptName -EventId "101" -EntryType "Information" -Message $Message } Else { Set-GPPermissions -Guid $DeptGPO.Id -TargetName $TargetName -PermissionLevel $PermissionLevel -TargetType $TargetType -WhatIf } } Catch { $Message = $Error[0].Exception.InnerException.Message.ToString().Trim() Write-EventLog -LogName $LogName -Source $ScriptName -EventId "102" -EntryType "Error" -Message $Message Return $Error[0].Exception.InnerException.Message.ToString().Trim() } } } End { $Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nFinished: " + (Get-Date).toString() Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message Return $? }
PowerShellCorpus/PoshCode/Get-Tree_1.ps1
Get-Tree_1.ps1
#.Synopsis # Creates a fir tree in your console! #.Description # A simple christmas tree simulation with (optional) flashing lights. # Requires your font be set to a True Type font (best results with Consolas). #.Parameter Trim # Whether or not to trim the tree. NOTE: In violation of convention, this switch to true! # To disable the tree lights, use Get-Tree -Trim:$false #.Example # Get-Tree -Trim:$false #.Example # Get-tree Red, Cyan, Blue, Gray, Green # # Description # ----------- # Creates a tree with multi-colored lights in the five colors that work best... param( [switch]$Trim=$true , [ValidateSet("Red","Blue","Cyan","Yellow","Green","Gray","Magenta","All")] [Parameter(Position=0)] [String[]]$LightColor = @("Red") ) if($LightColor -contains "All") { $LightColor = "Red","Yellow","Green","Gray","Magenta","Cyan","Blue" } Clear-Host $OFS = "`n" $center = [Math]::Min( $Host.UI.RawUI.WindowSize.Width, $Host.UI.RawUI.WindowSize.Height ) - 10 $Sparkle = [string][char]0x0489 $DkShade = [string][char]0x2593 $Needles = [string][char]0x0416 $Width = 2 [string[]]$Tree = $( "$(" " * $Center) " "$(" " * $Center)$([char]0x039B)" "$(" " * ($Center - 1))$($Needles * 3)" for($i = 3; $i -lt $center; $i++) { (" " * ($Center - $i)) + (Get-Random $Needles, " ") + ($Needles * (($Width * 2) + 1)) + (Get-Random $Needles, " ") $Width++ } for($i = 0; $i -lt 4; $i++) { " " * ($Center + 2) } ) $TreeOn = $Host.UI.RawUI.NewBufferCellArray( $Tree, "DarkGreen", "DarkMagenta" ) $TreeOff = $Host.UI.RawUI.NewBufferCellArray( $Tree, "DarkGreen", "DarkMagenta" ) # Make the tree trunk black for($x=-2;$x -le 2;$x++) { for($y=0;$y -lt 4;$y++) { $TreeOn[($center+$y),($center+$x)] = $TreeOff[($center+$y),($center+$x)] = New-Object System.Management.Automation.Host.BufferCell $DkShade, "Black", "darkMagenta", "Complete" } } if($trim) { $ChanceOfLight = 50 $LightIndex = 0 for($y=0;$y -le $TreeOn.GetUpperBound(0);$y++) { for($x=0;$x -le $TreeOn.GetUpperBound(1);$x++) { # only put lights on the tree ... if($TreeOn[$y,$x].Character -eq $Needles) { $LightIndex += 1 if($LightIndex -ge $LightColor.Count) { $LightIndex = 0 } # distribute the lights randomly, but not next to each other if($ChanceOfLight -gt (Get-Random -Max 100)) { # Red for on and DarkRed for off. $Light = $LightColor[$LightIndex] $TreeOn[$y,$x] = New-Object System.Management.Automation.Host.BufferCell $Sparkle, $Light, "darkMagenta", "Complete" $TreeOff[$y,$x] = New-Object System.Management.Automation.Host.BufferCell $Sparkle, "Dark$Light", "darkMagenta", "Complete" $ChanceOfLight = 0 # Make sure the next spot won't have a light } else { # Increase the chance of a light every time we don't have one $ChanceOfLight += 3 } } } } # Set the star on top $TreeOn[0,$Center] = $TreeOff[0,$Center] = New-Object System.Management.Automation.Host.BufferCell $Sparkle, "Yellow", "darkMagenta", "Complete" } # Figure out where to put the tree $Coord = New-Object System.Management.Automation.Host.Coordinates (($Host.UI.RawUI.WindowSize.Width - ($Center*2))/2), 2 $Host.UI.RawUI.SetBufferContents( $Coord, $TreeOff ) while($trim) { # flash the lights on and off once per second, if we trimmed the tree sleep -milli 500 $Host.UI.RawUI.SetBufferContents( $Coord, $TreeOn ) sleep -milli 500 $Host.UI.RawUI.SetBufferContents( $Coord, $TreeOff ) }
PowerShellCorpus/PoshCode/Get-InstalledProgram_v_2.ps1
Get-InstalledProgram_v_2.ps1
function Get-InstalledProgram() { param ( [String[]]$Computer, $User ) if ($User -is [String]) { $Connection = Get-Credential -Credential $User } if ($Connection -eq $null){ foreach ($Comp in $Computer){ $Install_soft = gwmi win32_product -ComputerName $Comp | where {$_.vendor -notlike "*Microsoft*" -and` $_.vendor -notlike "*PGP*" -and $_.vendor -notlike "*Intel*" -and $_.vendor -notlike "*Corel*" -and $_.vendor -notlike "*Adobe*" -and $_.vendor -notlike "*ABBYY*" -and $_.vendor -notlike "*Sun*" -and $_.vendor -ne "SAP" -and $_.vendor -ne "Marvell" -and $_.vendor -ne "Hewlett-Packard" } | select __SERVER,Name,Version,InstallDate $Install_soft } } else { foreach ($Comp in $Computer){ $Install_soft = gwmi win32_product -ComputerName $Comp -Credential $Connection | where {$_.vendor -notlike "*Microsoft*" -and` $_.vendor -notlike "*PGP*" -and $_.vendor -notlike "*Intel*" -and $_.vendor -notlike "*Corel*" -and $_.vendor -notlike "*Adobe*" -and $_.vendor -notlike "*ABBYY*" -and $_.vendor -notlike "*Sun*" -and $_.vendor -ne "SAP" -and $_.vendor -ne "Marvell" -and $_.vendor -ne "Hewlett-Packard" } | select __SERVER,Name,Version,InstallDate $Install_soft } } }
PowerShellCorpus/PoshCode/New-ZipFile.ps1
New-ZipFile.ps1
##############################################################################\n##\n## New-ZipFile\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\nCreate a Zip file from any files piped in. Requires that\nyou have the SharpZipLib installed, which is available from\nhttp://www.icsharpcode.net/OpenSource/SharpZipLib/\n\n.EXAMPLE\n\ndir *.ps1 | New-ZipFile scripts.zip d:\\bin\\ICSharpCode.SharpZipLib.dll\nCopies all PS1 files in the current directory to scripts.zip\n\n.EXAMPLE\n\n"readme.txt" | New-ZipFile docs.zip d:\\bin\\ICSharpCode.SharpZipLib.dll\nCopies readme.txt to docs.zip\n\n#>\n\nparam(\n ## The name of the zip archive to create\n $ZipName = $(throw "Specify a zip file name"),\n\n ## The path to ICSharpCode.SharpZipLib.dll\n $LibPath = $(throw "Specify the path to SharpZipLib.dll")\n)\n\nSet-StrictMode -Version Latest\n\n## Load the Zip library\n[void] [Reflection.Assembly]::LoadFile($libPath)\n$namespace = "ICSharpCode.SharpZipLib.Zip.{0}"\n\n## Create the Zip File\n$zipName = $executionContext.SessionState.`\n Path.GetUnresolvedProviderPathFromPSPath($zipName)\n$zipFile =\n New-Object ($namespace -f "ZipOutputStream") ([IO.File]::Create($zipName))\n$zipFullName = (Resolve-Path $zipName).Path\n\n[byte[]] $buffer = New-Object byte[] 4096\n\n## Go through each file in the input, adding it to the Zip file\n## specified\nforeach($file in $input)\n{\n ## Skip the current file if it is the zip file itself\n if($file.FullName -eq $zipFullName)\n {\n continue\n }\n\n ## Convert the path to a relative path, if it is under the\n ## current location\n $replacePath = [Regex]::Escape( (Get-Location).Path + "\\" )\n $zipName = ([string] $file) -replace $replacePath,""\n\n ## Create the zip entry, and add it to the file\n $zipEntry = New-Object ($namespace -f "ZipEntry") $zipName\n $zipFile.PutNextEntry($zipEntry)\n\n $fileStream = [IO.File]::OpenRead($file.FullName)\n [ICSharpCode.SharpZipLib.Core.StreamUtils]::Copy(\n $fileStream, $zipFile, $buffer)\n $fileStream.Close()\n}\n\n## Close the file\n$zipFile.Close()
PowerShellCorpus/PoshCode/Set-PrimaryDnsSuffix_1.ps1
Set-PrimaryDnsSuffix_1.ps1
function Set-PrimaryDnsSuffix { param ([string] $Suffix) # http://msdn.microsoft.com/en-us/library/ms724224(v=vs.85).aspx $ComputerNamePhysicalDnsDomain = 6 Add-Type -TypeDefinition @" using System; using System.Runtime.InteropServices; namespace ComputerSystem { public class Identification { [DllImport("kernel32.dll", CharSet = CharSet.Auto)] static extern bool SetComputerNameEx(int NameType, string lpBuffer); public static bool SetPrimaryDnsSuffix(string suffix) { try { return SetComputerNameEx($ComputerNamePhysicalDnsDomain, suffix); } catch (Exception) { return false; } } } } "@ [ComputerSystem.Identification]::SetPrimaryDnsSuffix($Suffix) }
PowerShellCorpus/PoshCode/Get-RelativePath.ps1
Get-RelativePath.ps1
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 { Write-Verbose "Resolving paths relative to '$Folder'" $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 } }
PowerShellCorpus/PoshCode/VM Performance Report_4.ps1
VM Performance Report_4.ps1
<# .SYNOPSIS The script creates an HTML report for given vSphere VM's, that contains VM performance data over a given period. The script then emails the report to a given address. .DESCRIPTION The script requires an input file, supplied as an argument to the script. The first line of this file contains an email address, subsequent lines contain VM names, one per line. The script connects to vCenter, queries for given performance stats (get-stat) and then generates a HTML report, which is then emailed to the recipient. The script can be scheduled via scheduled tasks (when supplied with a credential file for vCenter created with http://poshcode.org/3491) or run interactively. .NOTES File Name : Get-VMPeformanceReport.ps1 Author : Samuel Mulhearn Version History: Version 1.0 28 Jun 2012. Release .LINK http://poshcode.org/3494 .EXAMPLE Call the script with a single argument which should be the path to the input file .\\Get-VMPeformanceReport.ps1 <path\\datafile.txt> #> #Change These Values $VC = "vc.domain.local" #VirtualCenter $SMTPServer = "192.168.1.100" #SMTP Server $SendersAddress = "noreply@domain.com" #The report comes from this address $SavedCredentialsFile = "C:\\path\\file.txt" #Make this file using http://poshcode.org/3491 $CompanyLogo = "http://placehold.it/150x50" function Out-LogFile { #Log File Function http://poshcode.org/3232 [CmdletBinding(DefaultParameterSetName='Message')] param( [Parameter(ParameterSetName='Message', Position=0, ValueFromPipeline=$true)] [object[]]$Message, [Parameter(ParameterSetName='Message')] [string]$LogFile = $global:DefaultLogPath, [Parameter(ParameterSetName='Message')] [int]$BlankLine = 0, [switch]$WriteHost = $global:WriteHostPreference, [string]$Severity = "I", [Parameter(ParameterSetName='Message')] [switch]$DontFormat, [Parameter(ParameterSetName='Message')] [string]$DateFormat = "dd-MM-yyyy HH:mm:ss", #[Parameter(ParameterSetName='Title',Position=0,Mandatory=$true)] [string]$Title, [System.ConsoleColor]$ForegroundColor = $host.UI.RawUI.ForegroundColor, [System.ConsoleColor]$BackgroundColor = $host.UI.RawUI.BackgroundColor, [ValidateSet('unicode', 'utf7', 'utf8', 'utf32', 'ascii', 'bigendianunicode', 'default', 'oem')] [string]$Encoding = 'Unicode', [switch]$Force ) begin { Write-Verbose "Log File: $LogFile" if ( -not $LogFile ) { Write-Error "The -LogFile parameter must be defined or $global:LogFile must be set."; break} if ( -not (Test-Path $LogFile) ) { New-Item -Path $LogFile -ItemType File -Force | Out-Null } if ( -not (Test-Path $LogFile) ) { Write-Error "Log file can not be found: $LogFile."; break} if ( $Title ) { $text = $Title $Title = $null Out-LogFile -BlankLine 1 -LogFile $LogFile -WriteHost:$WriteHost -Force:$Force -Encoding $Encoding Out-LogFile -Message $text -BlankLine 1 -DontFormat -LogFile $LogFile -WriteHost:$WriteHost -Force:$Force -Encoding $Encoding } } process { if ( $Message ) { $text = $Message foreach ( $text in $Message ) { if ( -not $DontFormat ) { $text = "$(($Severity).ToUpper()): $(Get-Date -Format `"$DateFormat`")" + ": $text" } if ($WriteHost) { Write-Host $text -BackgroundColor $BackgroundColor -ForegroundColor $ForegroundColor} $text | Out-File -FilePath $LogFile -Force:$Force -Encoding $Encoding -Append } } if ( $BlankLine -gt 0 ){ for ($i = 0; $i -lt $BlankLine; $i++ ) { "" | Out-File -FilePath $LogFile -Force:$Force -Encoding $Encoding -Append if ($WriteHost) { Write-Host "" -BackgroundColor $BackgroundColor -ForegroundColor $ForegroundColor } } } } end { } } #end of logfile function #New Line Variable $nl = [Environment]::NewLine #INTERACTIVE: (Prompt for password) Replace code below with: $VCCred = (Get-Credential) #NONE-INTERACTIVE: Store password in a file (using http://poshcode.org/3491), and retrive as below $key = [byte]57,86,59,11,72,75,18,52,73,46,0,21,56,76,47,12 #Must match key used to save password (http://poshcode.org/3491) $VCCred = Import-Csv $SavedCredentialsFile #Make this file using http://poshcode.org/3491 $VCCred.Password = ($VCCred.Password| ConvertTo-SecureString -Key $key) $VCCred = (New-Object -typename System.Management.Automation.PSCredential -ArgumentList $VCCred.Username,$VCCred.Password) #Get Datafile, this wil contain VM's to report on, and an email address to send the report to #Datafile format: first line is email address, subsequent lines are VM's, one per line) if ($args[0] -eq $null) #Test Datafile was supplied as argument to the script, if not error! { Throw "No datafile supplied, supply path to datafile as an argument to the script! e.g .\\SCRIPT.ps1 DATAFILE.txt $nl To create a datafile, the first line of the datafile should be an email address, each subseqenet line should be a VM (one per line)" #$Datafile = "C:\\Path\\datain.txt" #If debugging uncomment this line and comment above to supply a fixed input file } else { $Datafile = $args[0] } #From Datafile, get a log file, and a $LogFile = (($DataFile).SubString(0,(($Datafile).length - 3))) + "log" $Outfile = (($DataFile).SubString(0,(($Datafile).length - 3))) + "htm" $global:WriteHostPreference = $true $global:DefaultLogPath = $LogFile Out-LogFile -Message "Starting script with $datafile" #Load PowerCLI if ( (Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null ) { Add-PsSnapin VMware.VimAutomation.Core } If (!(Get-PSSnapin -Name VMware.VimAutomation.Core)) {Out-LogFile -Message "Failed to load PowerCLI Snap-in. Check PowerCLI is installed." -Severity "E" Exit(1) } #Static HTML $HTMLPreString=@" <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="http://current.bootstrapcdn.com/bootstrap-v204/css/bootstrap-combined.min.css"> <style type="text/css"> body { padding: 20px; } h2 { color: #3A87AD; } .mytable { width: 776px; margin: 12px; } .alert-info { color: #3A87AD; background-color: #D9EDF7; border-color: #BCE8F1; padding: 8px 8px 8px 14px; margin-top: 12px; margin-left: 12px; margin-right: 12px; margin-bottom: 12px; border: 1px solid; border-radius: 4px; } .chart_wrap { width: 800px; border-style:solid; border-width:1px; border-color: #DDDDDD; margin: 0px 0px 10px 0px; } .chart { text-align: center; width: 800px; height: 400px; } </style> <title> Virtual Machine Performance statistics </title> <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript"> google.load('visualization', '1', {packages: ['corechart']}); </script> "@ $HTMLPreString += "$nl" $HTMLBodyBegin ="<body style=`"font-family: Arial;border: 0 none;`"> $nl" $HTMLBodyBegin += "<img src=`"$CompanyLogo`" alt=`"Company Logo`" /> $nl" $HTMLBodyBegin += "<h2>Performance Statistics</h2>$nl" $HTMLPostString=@" <script src= "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script src="http://current.bootstrapcdn.com/bootstrap-v204/js/bootstrap.min.js"</script> <script src="http://current.bootstrapcdn.com/bootstrap-v204/js/bootstrap-tab.js"</script> </body> </html> "@ #Functions for dynamic HTML Function Get-DataTable ($Statistics, $UID, $Summation = $false, $Title) { #https://developers.google.com/chart/interactive/docs/examples#custom_table_example $mystring = "<script type=`"text/javascript`">$nl" $mystring += "function drawVisualization$UID() {$nl" $mystring += "// Create and populate the data table. $nl" $mystring += "var " + "$UID" + "data = new google.visualization.DataTable();$nl" $mystring += "$UID" + "data.addColumn('datetime', 'Time');$nl" $VMs | % {$mystring += "$UID" + "data.addColumn('number', '$_');$nl"} $mystring += "$UID" + "data.addRows(" + $Statistics.Count + ");$nl" $ColumnCount = 0 $RowCount = 0 $Statistics | % { $ColumnCount = 0 $formatteddate = [datetime]::ParseExact(([string]$_.Name),"dd/MM/yyyy H:mm:ss",$null) $JSMonth = (($formatteddate.ToString("MM"))-1) #Javascript Months are base 0 (Jan = 0) $formatteddate = $formatteddate.ToString("yyyy, $JSMonth, dd, HH, mm") $formatteddate = "new Date($formatteddate)" $mystring += "$UID" + "data.setCell($RowCount, $ColumnCount, $formatteddate);$nl" $_.Group | % { $ColumnCount = 0 foreach ($VM in $VMs) { $ColumnCount += 1 If ($_.Entity.Name -eq $VM ) { if ($Summation -eq $true) { $strPercent = (( $_.Value / ( $_.IntervalSecs * 1000)) * 100) #http://kb.vmware.com/kb/2002181 $strPercent = [system.math]::round($strPercent,2) $mystring += "$UID" + "data.setCell($RowCount, $ColumnCount, " + $strPercent + ");$nl" } else { $mystring += "$UID" + "data.setCell($RowCount, $ColumnCount, " + $_.Value + ");$nl" } } } } $RowCount += 1 } $mystring += "$nl new google.visualization.LineChart(document.getElementById('visualization" + "$UID" +"')).$nl" $VisParam = "` { ` legend: {position: 'in',alignment:`"center`"}, ` lineWidth:`"2`", ` curveType: `"none`",` chartArea:{left:60,top:40,width:`"90%`",height:`"75%`"},` focusTarget:`"category`", ` hAxis: {slantedText:`"true`", format:`"E, d MMM`"},` vAxis: {textPosition:`"out`"},` width: 800, ` height: 400, ` title:`"$Title`"}" $mystring += "draw(" + "$UID" + "data, $VisParam);$nl" $mystring +="}$nl" $mystring += "google.setOnLoadCallback(drawVisualization" + "$UID" + ");$nl</script>$nl" return $mystring } function Get-DivHTML ($UID, $Notes) { $tempHTML = "<div class=`"tab-pane fade`" id=`"$UID`">$nl" $tempHTML += " <div class=`"chart_wrap`">$nl" $tempHTML += " <div id=`"visualization" + "$UID" + "`" class=`"chart`"></div>$nl" $tempHTML += " <div class=`"alert alert-info`"><strong>Information: </strong>$Notes</div>$nl" $tempHTML += " </div>$nl" $tempHTML += "</div>$nl" return $tempHTML } #Main Code #Process datafile, get VM's to report on, and an email address to send the report to $DataTable = @(Get-Content $Datafile) $email = $DataTable[0] $VMs = @($DataTable[1..($DataTable.Count)]) #Connect to VC Set-PowerCLIConfiguration -InvalidCertificateAction:Ignore -DefaultVIServerMode:Single -Confirm:$false|Out-Null if ((Connect-VIServer $VC -Credential $VCCred) -eq $null) #Connect to vCenter, exit if fails. { Out-LogFile -Message "Failed to connect to vCenter ($VC)" -Severity "E" -WriteHost Exit (1) } else {Out-LogFile -Message "Connected to vCenter ($VC)"} #Validate VM's exist $VCVMs = (get-vm -name $VMs -ErrorAction SilentlyContinue) $VMs | % { $tmpvm = $_ $Exists = $false $VCVMs | % { if ($_.Name -eq $tmpvm) {$Exists = $true}} If ($Exists){ Out-LogFile -Message "$_ found in vCenter inventory" } Else { Out-LogFile -Message "$_ not found in vCenter inventory" -Severity "W" $VMs = $VMs |? {$_ -ne $tmpvm} } } #To add new Stat #1. Add stat to $metrics (use Get-VM | GetStatType to find new metrics) #2. Create a Variable To hold new stats, $MyVariabe = ($Stats | Where-Object {$_.MetricId -eq $metrics[X]} | Sort-Object TimeStamp |Group-Object -Property Timestamp) #3. Invent a new UID - MyUID ? #4. Build Datatable, add code: $HTMLOut += (Get-DataTable -Statistics $MyVariable -UID "MyUID" -Title "Graph Title") #5. Edit static Tabs HTML below, within <ul class="nav nav-tabs"> add a new <li> - eg: <li><a href="#MyUID" data-toggle="tab">Tab Title</a></li> #6. Add a new Get-DivHTML - eg. $HTMLOut += (Get-DivHTML -UID "MyUID" -Notes "Some notes below the chart") #Start and Finish times $todayMidnight = (Get-Date -Hour 0 -Minute 0 -Second 0).AddMinutes(-1) $metrics = "cpu.usagemhz.average","mem.usage.average","disk.usage.average","net.usage.average","cpu.ready.summation","mem.vmmemctl.average" $start = $todayMidnight.AddDays(-7) #If changed consider changing hAxis.format in $VisParam to include the time. https://developers.google.com/chart/interactive/docs/gallery/linechart $finish = $todayMidnight $startstring = $start.ToString("dddd, dd MMMM yyyy HH:mm") $finishstring = $finish.ToString("dddd, dd MMMM yyyy HH:mm") Out-LogFile -Message "Getting stats from vCenter" #Variable for all stats combined $Stats = Get-Stat -Entity $vms -Stat $metrics -Start $start -Instance "" -Finish $finish -IntervalSecs "1800" #Instance "" accounts for machines with multiple CPU's or NICS, gets machine average Out-LogFile -Message "Got stats from vCenter" Out-LogFile -Message "Sorting and filtering stats" #Split stats out by each indivial metric into individual variable $CPU = ($Stats | Where-Object {$_.MetricId -eq $metrics[0]} | Sort-Object TimeStamp |Group-Object -Property Timestamp) $Memory = ($Stats | Where-Object {$_.MetricId -eq $metrics[1]} | Sort-Object TimeStamp |Group-Object -Property Timestamp) $Disk = ($Stats | Where-Object {$_.MetricId -eq $metrics[2]} | Sort-Object TimeStamp |Group-Object -Property Timestamp) $Net = ($Stats | Where-Object {$_.MetricId -eq $metrics[3]} | Sort-Object TimeStamp |Group-Object -Property Timestamp) $Ready = ($Stats | Where-Object {$_.MetricId -eq $metrics[4]} | Sort-Object TimeStamp |Group-Object -Property Timestamp) $Balloon = ($Stats | Where-Object {$_.MetricId -eq $metrics[5]} | Sort-Object TimeStamp |Group-Object -Property Timestamp) #Creates HTML inside of <head> for javascript for the charts Out-LogFile -Message "Creating HTML" $HTMLOut = $HTMLPreString + (Get-DataTable -Statistics $CPU -UID "CPU" -Title "CPU (MHz)") $HTMLOut += (Get-DataTable -Statistics $Memory -UID "Memory" -Title "Memory (%)") $HTMLOut += (Get-DataTable -Statistics $Disk -UID "Disk" -Title "Disk Activity (KBps)") $HTMLOut += (Get-DataTable -Statistics $Net -UID "Net" -Title "Network I/O (KBps)") $HTMLOut += (Get-DataTable -Statistics $Ready -UID "Ready" -Summation $true -Title "CPU Wait Time (%)") $HTMLOut += (Get-DataTable -Statistics $Balloon -UID "Balloon" -Summation $true -Title "Memory allocated to the balloon driver (KB)") $HTMLOut += "</head>$nl" $HTMLOut += $HTMLBodyBegin + $nl #Navigation Tabs... #Edit below to add a tab, when adding a new metric $HTMLOut += @" <div id="content"> <ul class="nav nav-tabs"> <li class="active"><a href="#Info" data-toggle="tab">Information</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">CPU<b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="#CPU" data-toggle="tab">CPU Usage</a></li> <li><a href="#Ready" data-toggle="tab">CPU Wait Time</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Memory<b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="#Memory" data-toggle="tab">Memory Usage</a></li> <li><a href="#Balloon" data-toggle="tab">Memory Balloon</a></li> </ul> <li> <li><a href="#Disk" data-toggle="tab">Disk</a></li> <li><a href="#Net" data-toggle="tab">Network</a></li> </ul> <div id="my-tab-content" class="tab-content"> <div class="tab-pane fade in active" id="Info"> <div class="chart_wrap"> <div class="alert alert-info"> <strong>Information: </strong> "@ #Info for fist tab $HTMLOut += "Each datapoint represents resource consumption since the last datapoint ` and its value is either an average, maximum, or summation of all usage in that interval. ` Any values that are zero may actually be zero, or may indicate statistics were not ` collected over that period (for example, if a virtual machine was powered off). $nl ` The statistics displayed are from $startstring to $finishstring</div>$nl" #Table that contains VM resource config & limits. $HTMLOut += "<table class=`"mytable table table-striped table-bordered`"><thead><tr><td>VM Name</td><td>Number of CPU's</td><td>Memory (MB)</td><td>CPU Limit</td><td>Memory Limit</td></tr></thead>$nl<tbody>$nl" $VCVMs | % { $tmpname =$_.Name $tmpNumCpu = $_.NumCpu $TmpMemoryMB = $_.MemoryMB $tmpCPULimit = $_.VMResourceConfiguration.CPULimitMhz.ToString().Replace("-1","None") $tmpMemLimit = $_.VMResourceConfiguration.MemLimitMB.ToString().Replace("-1","None") $HTMLOut += " <tr><td>$tmpname</td><td>$tmpNumCpu</td><td>$TmpMemoryMB</td><td>$tmpMemLimit</td><td>$tmpCPULimit</td></tr>$nl" } $HTMLOut += "</tbody></table>$nl" $HTMLOut +=@" </div> </div> "@ #Div elements that contain each chart $HTMLOut += (Get-DivHTML -UID "CPU" -Notes "Average CPU usage, as measured in megahertz, during the interval") $HTMLOut += (Get-DivHTML -UID "Memory" -Notes "Average memory usage as percentage of total configured or available memory") $HTMLOut += (Get-DivHTML -UID "Disk" -Notes "Average disk activity (combinded read & write) in KBps") $HTMLOut += (Get-DivHTML -UID "Net" -Notes "Average network utilization (combined transmit and receive rates) during the interval") $HTMLOut += (Get-DivHTML -UID "Ready" -Notes "The percentage of time that the virtual machine was ready, but could not get scheduled to run on the physical CPU. Values of less than 10% are considered normal") $HTMLOut += (Get-DivHTML -UID "Balloon" -Notes "Amount of memory allocated by the virtual machine memory control driver (vmmemctl), which is installed with VMware Tools. This value should remain at 0 or close to 0") $HTMLOut += @" </div> </div> </div> "@ $datenow = Get-Date -Format "F" $HTMLOut += "<h6>Report generated at $datenow<h6>$nl" $HTMLOut += $HTMLPostString #Finished HTML Out-LogFile -Message "Finished building HTML, writing to $Outfile" $HTMLOut | Out-File -FilePath $Outfile -Encoding "UTF8" #Build Email $body =@" <P>Performance statistics for the Virtual Machines listed below are attached</p> "@ $body += "<p>Statistics are from $startstring to $finishstring<p>" $VMs | % {$body+= "<li>$_</li>" } Out-LogFile -Message "Sending email. Email:$email. SMTP Server:$SMTPServer" #Send email Send-MailMessage -Attachments $Outfile -Body "$body" -BodyAsHtml:$true -Subject "Performance Statistics" -To $email -From $SendersAddress -SmtpServer $SMTPServer Disconnect-VIServer -Confirm:$false Out-LogFile -Message "Disconnected from vCenter" Out-LogFile -Message "Finished"
PowerShellCorpus/PoshCode/Find-GeoCode.ps1
Find-GeoCode.ps1
$mappoint = New-WebServiceProxy http://staging.mappoint.net/standard-30/mappoint.wsdl -Namespace MapPoint $FindService = new-object MapPoint.FindServiceSoap # You need an account, sign up here: https://mappoint-css.live.com/mwssignup $FindService.Credentials = Get-Credential function Find-ReverseGeoCode( [double]$Latitude, [double]$longitude, [switch]$force ) { $Coords = new-object MapPoint.LatLong $Coords.Latitude = $Latitude $Coords.Longitude = $longitude $Locations = $FindService.GetLocationInfo( $Coords, "MapPoint.NA", $null) if($force) { return $Locations } elseif($Locations[0].Address) { return $Locations[0].Address # .FormattedAddress + " - " + $Locations[0].Address.CountryRegion } else { return $Locations | ?{ $_.Entity.TypeName -eq "PopulatedPlace" } # | %{ $_.Entity.DisplayName } } } function Find-GeoCode( $address, $country = "US" ) { $spec = new-object MapPoint.FindAddressSpecification $spec.DataSourceName = "MapPoint.NA" $spec.InputAddress = $FindService.ParseAddress( $address, $country ) $Found = $FindService.FindAddress( $spec ) if($Found.NumberFound) { $found.Results | Select -expand FoundLocation | Select -Expand LatLong } # if($Found.NumberFound -gt 1) { # $found.Results| Select -expand FoundLocation | Select -Expand Address # } } ## This is how non-geography geeks think of them: Set-Alias Find-Address Find-ReverseGeoCode Set-Alias Find-Coordinates Find-GeoCode
PowerShellCorpus/PoshCode/Invoke-ScriptBlock.ps1
Invoke-ScriptBlock.ps1
##############################################################################\n##\n## Invoke-ScriptBlock\n##\n## From Windows PowerShell, The Definitive Guide (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nApply the given mapping command to each element of the input. (Note that\nPowerShell includes this command natively, and calls it Foreach-Object)\n\n.EXAMPLE\n\n1,2,3 | Invoke-ScriptBlock { $_ * 2 }\n\n#>\n\nparam(\n ## The scriptblock to apply to each incoming element\n [ScriptBlock] $MapCommand\n)\n\nbegin\n{\n Set-StrictMode -Version Latest\n}\nprocess\n{\n & $mapCommand\n}
PowerShellCorpus/PoshCode/Exch07 Quota Report.ps1
Exch07 Quota Report.ps1
#Get information on everybodies inbox and spit it out with total sizes #in MB. Sorts the list by StorageLimitStatus #NOTE THAT I HAD TO USE ASCII WITH OUT-FILE AS NO OTHER ENCODING WOULD #PROPERLY IMPORT CSV INTO EXCEL #create a date var to stick in the filename $date = get-date -Format MM-dd-yyyy #create a outfile var so we only have to update it in one spot $OUTFILE = "C:\\Net_Admin_Stuff\\usage_reports\\daily_storage_limits\\Daily_Storage_Limits-$date.csv" #Create the default db send/receive quota divided by 1024 to convert KB to MB. $DEFAULTSENDQUOTA = 510000/1024 #Create a header to display at the top. $HEADER = "Display Name,Storage Limit Status,Item Count,Total Item Size (MB),Deleted Item Count,Total Deleted Item Size (MB),Prohibit Send/Receive Quota (MB),Quota Source" $HEADER | Out-File $OUTFILE -Append -Encoding Ascii #Get mailbox stats for all users, sort by Storage Limit Status and go through each users objects Get-MailboxStatistics | where {$_.ObjectClass -eq 'Mailbox'} | Sort-Object StorageLimitStatus | ForEach-Object { #Get the current user so we can grab some information from the get-mailbox command $CURUSER = get-mailbox -Identity $_.Identity #if the current user is using db defaults it will show a value of unlimited, which can't be calculated. #Push the default value into the field when this happens #Label where the source of the quota came from If ($CURUSER.UseDatabaseQuotaDefaults -eq $true) { $QUOTASRC = $CURUSER.Database $SENDQUOTA = $DEFAULTSENDQUOTA } else { $QUOTASRC = "User Profile" $SENDQUOTA = $CURUSER.ProhibitSendReceiveQuota.Value.ToMB() } #Generate useable vars for each of the objects that we're going to work with. $DNAME = $_.DisplayName; $SLSTATUS = $_.StorageLimitStatus; $ICOUNT = $_.ItemCount; $TISIZE = $_.TotalItemSize.Value.ToMB(); $DICOUNT = $_.DeletedItemCount; $TDISIZE = $_.TotalDeletedItemSize.Value.ToMB(); #spit out our information into a single row "$DNAME,$SLSTATUS,$ICOUNT,$TISIZE,$DICOUNT,$TDISIZE,$SENDQUOTA,$QUOTASRC" } | Out-File $OUTFILE -Append -Encoding Ascii
PowerShellCorpus/PoshCode/Write-FileInfoToSQL.ps1
Write-FileInfoToSQL.ps1
# --------------------------------------------------------------------------- ### <Script> ### <Author> ### Chad Miller ### </Author> ### <Description> ### Reports data model directories and bool value as to whether they have ### an htm file of the same name as the project directory. ### </Description> ### <Usage> ### ./Write-FileInfoToSQL.ps1 ### </Usage> ### </Script> # --------------------------------------------------------------------------- $sqlserver = 'SQL1' $dbname = 'DataAdmin' $tblname = 'data_model_fill' ####################### function Clear-Fill { $connString = "Server=$sqlserver;Database=$dbname;Integrated Security=SSPI;" $conn = new-object System.Data.SqlClient.SqlConnection $connString $conn.Open() $cmd = new-object System.Data.SqlClient.SqlCommand("TRUNCATE TABLE $tblname", $conn) $cmd.ExecuteNonQuery() $conn.Close() } #Clear-Fill ####################### function Out-DataTable { param($Properties="*") Begin { $dt = new-object Data.datatable $First = $true } Process { $DR = $DT.NewRow() foreach ($item in $_ | Get-Member -type *Property $Properties ) { $name = $item.Name if ($first) { $Col = new-object Data.DataColumn $Col.ColumnName = $name $DT.Columns.Add($Col) } $DR.Item($name) = $_.$name } $DT.Rows.Add($DR) $First = $false } End { return @(,($dt)) } }# Out-DataTable ####################### function Write-DataTableToDatabase { param($destServer,$destDb,$destTbl) process { $connectionString = "Data Source=$destServer;Integrated Security=true;Initial Catalog=$destdb;" $bulkCopy = new-object ("Data.SqlClient.SqlBulkCopy") $connectionString $bulkCopy.DestinationTableName = "$destTbl" $bulkCopy.WriteToServer($_) } }# Write-DataTableToDatabase ####################### Clear-Fill get-childitem "\\\\z001.contoso.com\\wwwroot`$\\Playbook\\Databases\\DataModels" | where {$_.PSIsContainer -eq $true} | select name, @{name='htm';Expression={test-path "\\\\z001.contoso.com\\wwwroot`$\\Playbook\\Databases\\DataModels\\$($_.Name)\\$($_.Name).htm"}}, @{name='lastWrite';Expression={if (test-path "\\\\z001.contoso.com\\wwwroot`$\\Playbook\\Databases\\DataModels\\$($_.Name)\\$($_.Name).htm") {$last = Get-Item "\\\\z001.contoso.com\\wwwroot`$\\Playbook\\Databases\\DataModels\\$($_.Name)\\$($_.Name).htm" | Select LastWriteTime;$last.LastWriteTime}}} | Out-DataTable | Write-DataTableToDatabase $sqlserver $dbname $tblname
PowerShellCorpus/PoshCode/CreateVDS_1.ps1
CreateVDS_1.ps1
function CreateVDS( $vdsName, $datacenter, $vmHost, $physicalNic, $portGroupType = "earlyBinding", ` [array]$portGroupNameList = @(),[array]$uplinkList = @() ) { # ------- Create vDS ------- # $vdsCreateSpec = New-Object VMware.Vim.DVSCreateSpec $vdsCreateSpec.configSpec = New-Object VMware.Vim.DVSConfigSpec $vdsCreateSpec.configSpec.name = $vdsName $vdsCreateSpec.configSpec.uplinkPortPolicy = New-Object VMware.Vim.DVSNameArrayUplinkPortPolicy if ($uplinkList.Count -eq 0) { $vdsCreateSpec.configSpec.uplinkPortPolicy.uplinkPortName = New-Object System.String[] (2) $vdsCreateSpec.configSpec.uplinkPortPolicy.uplinkPortName[0] = "dvUplink1" $vdsCreateSpec.configSpec.uplinkPortPolicy.uplinkPortName[1] = "dvUplink2" } else { $vdsCreateSpec.configSpec.uplinkPortPolicy.uplinkPortName = New-Object System.String[] ($uplinkList.Count) for ($i = 0; $i -lt $uplinkList.Count; $i++){ $vdsCreateSpec.configSpec.uplinkPortPolicy.uplinkPortName[$i] = $uplinkList[$i] } } $hostIdValue = ($vmHost.Id.Split('-', 2))[1] $vdsCreateSpec.configSpec.host = New-Object VMware.Vim.DistributedVirtualSwitchHostMemberConfigSpec[] (1) $vdsCreateSpec.configSpec.host[0] = New-Object VMware.Vim.DistributedVirtualSwitchHostMemberConfigSpec $vdsCreateSpec.configSpec.host[0].operation = "add" $vdsCreateSpec.configSpec.host[0].host = New-Object VMware.Vim.ManagedObjectReference $vdsCreateSpec.configSpec.host[0].host.type = "HostSystem" $vdsCreateSpec.configSpec.host[0].host.value = $hostIdValue $vdsCreateSpec.configSpec.host[0].backing = New-Object VMware.Vim.DistributedVirtualSwitchHostMemberPnicBacking $vdsCreateSpec.configSpec.host[0].backing = New-Object VMware.Vim.DistributedVirtualSwitchHostMemberPnicBacking $vdsCreateSpec.configSpec.host[0].backing.pnicSpec = New-Object VMware.Vim.DistributedVirtualSwitchHostMemberPnicSpec[] (1) $vdsCreateSpec.configSpec.host[0].backing.pnicSpec[0] = New-Object VMware.Vim.DistributedVirtualSwitchHostMemberPnicSpec $vdsCreateSpec.configSpec.host[0].backing.pnicSpec[0].pnicDevice = $physicalNic.DeviceName $networkFolderView = Get-View -Id (($datacenter | Get-View).NetworkFolder) $dvsMoRef = $networkFolderView.CreateDVS($vdsCreateSpec) # ------- Add vDPortGroup ------- # if ($portGroupNameList.Count -eq 0){ $portGroupNameList += "dvPortGroup" } $vdProtGroupSpec = New-Object VMware.Vim.DVPortgroupConfigSpec[] ($portGroupNameList.Length) for ($i = 0; $i -lt $portGroupNameList.Length; $i++){ $vdProtGroupSpec[$i] = New-Object VMware.Vim.DVPortgroupConfigSpec $vdProtGroupSpec[$i].name = $portGroupNameList[$i] $vdProtGroupSpec[$i].numPorts = 128 $vdProtGroupSpec[$i].defaultPortConfig = New-Object VMware.Vim.VMwareDVSPortSetting $vdProtGroupSpec[$i].defaultPortConfig.vlan = New-Object VMware.Vim.VmwareDistributedVirtualSwitchVlanIdSpec $vdProtGroupSpec[$i].defaultPortConfig.vlan.inherited = $false $vdProtGroupSpec[$i].defaultPortConfig.vlan.vlanId = 0 $vdProtGroupSpec[$i].type = $portGroupType } $vdsView = Get-View -Id $vdsMoRef.ToString() $vdsView.AddDVPortgroup($vdProtGroupSpec) return $vdsMoRef }
PowerShellCorpus/PoshCode/GeSHi PowerShell Syntax .ps1
GeSHi PowerShell Syntax .ps1
<?php /************************************************************************************* * posh.php * --------------------------------- * Author: Joel Bennett (Jaykul@HuddledMasses.org) * Copyright: (c) 2007 Joel Bennett (http://HuddledMasses.org/) * Release Version: 1.1.0 * Date Started: 2007-06-08 * Last Modified: 2008-12-27 * * PowerShell language file for GeSHi. * * The lists of Nouns, Verbs, and Parameters are based on my personal install * with PowerShell Community Extensions installed. The really bad news is the * fact that aliases are left out almost completely, along with anything from * .Net or COM objects ... * ## You need to define this function before using any of the generation scripts below.... function Join-String { param ( [string]$separator="', '", [string]$append, [string]$prepend, [string]$prefix="'", [string]$postfix="'") begin { [string[]]$items = @($prepend.split($separator)) } process { $items += $_ } end { $ofs = $separator; $items += @($append.split($separator)); return "$prefix$($items -ne '')$postfix" } } * CHANGES * ------- * 2007-06-08 (0.1.0) * - First Release * 2007-06-09 (1.0.0) * - Changed to use regular expressions for: * verbs, nouns, and -parameters (was already using them for $variables) * 2007-06-10 (1.0.1) * - Ditched the specific list of parameters in favor of just assuming that * anything that starts with a "-" is a parameter. Otherwise it won't * highlight anything that you shorten. * - Improved the lists by *adding* the "deffinitive" list of verbs from the * MS CLI spec to my personal verb list. I didn't remove anything because * ultimately I don't care if it's an official verb if it's a command on my * computer. You should still consider adding your personal verbs too! * - I improved the 4th Keyword list by exporting my personal list of aliases * and functions ... (and showing the command, so you can generate your own) * and removing the variables entirely (they're already highlighted anyway). * 2008-12-27 (1.1.0) * - Updated for CTP3 with powershell scripts * * TODO (last updated 2007-06-09) * ------------------------- * - I would like to create a script which can dump this whole file out based * on an individual user's personal particular set of snapins, cmdlets and * functions. After all, for YOUR personal site, the cmdlets and functions * which you have available are the only ones that actually matter :D * HOWEVER: I don't think it's that important, because * ************************************************************************************* * * This file is part of GeSHi. * * GeSHi is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * GeSHi is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GeSHi; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ************************************************************************************/ $language_data = array ( 'LANG_NAME' => 'Posh', 'COMMENT_SINGLE' => array(1 => '#'), 'COMMENT_MULTI' => array('<#'=>'#>'), 'CASE_KEYWORDS' => GESHI_CAPS_NO_CHANGE, 'QUOTEMARKS' => array('"', "'"), 'HARDQUOTE' => array('@"$','^"@'), // An optional 2-element array defining the beginning and end of a hard-quoted string 'HARDESCAPE' => array(), // Things that must still be escaped inside a hard-quoted string // If HARDQUOTE is defined, HARDESCAPE must be defined // This will not work unless the first character of each element is either in the // QUOTEMARKS array or is the ESCAPE_CHAR 'ESCAPE_CHAR' => '`', 'KEYWORDS' => array( 1 => array( # PoSH keywords/reserved words # [type]::gettype("System.Management.Automation.KeywordTokenReader").InvokeMember("_keywordTokens", "NonPublic,Static,GetField", $null, $_, @() ).GetEnumerator()|%{$_.Name.Trim("-")}|?{$_ -match "^[A-z]"}|Sort -Desc|Join-String 'while', 'until', 'try', 'trap', 'throw', 'switch', 'return', 'process', 'param', 'in', 'if', 'function', 'from', 'foreach', 'for', 'finally', 'filter', 'exit', 'end', 'elseif', 'else', 'dynamicparam', 'do', 'data', 'continue', 'catch', 'break', 'begin' ), 2 => array( # Operators # [type]::gettype("System.Management.Automation.OperatorTokenReader").InvokeMember("_expressionOperatorTokens", "NonPublic,Static,GetField", $null, $_, @() ).GetEnumerator()|%{$_.Name.Trim("-")}|?{$_ -match "^[A-z]"}|Sort -Desc|Join-String 'xor', 'split', 'replace', 'or', 'notmatch', 'notlike', 'notcontains', 'not', 'ne', 'match', 'lt', 'like', 'le', 'join', 'isplit', 'isnot', 'is', 'ireplace', 'inotmatch', 'inotlike', 'inotcontains', 'ine', 'imatch', 'ilt', 'ilike', 'ile', 'igt', 'ige', 'ieq', 'icontains', 'gt', 'ge', 'f', 'eq', 'csplit', 'creplace', 'contains', 'cnotmatch', 'cnotlike', 'cnotcontains', 'cne', 'cmatch', 'clt', 'clike', 'cle', 'cgt', 'cge', 'ceq', 'ccontains', 'bxor', 'bor', 'bnot', 'band', 'as', 'and' ), # built in language type shorcuts, plus a couple of .Net base types... # [type]::gettype("System.Management.Automation.TypeAccelerators")::get.GetEnumerator()|%{$_.Key}|Sort -Desc|Join-String|Out-Clipboard 3 => array( 'xml', 'wmisearcher', 'wmiclass', 'wmi', 'type', 'system', 'switch', 'string', 'single', 'scriptblock', 'runspacefactory', 'runspace', 'regex', 'ref', 'psobject', 'psmoduleinfo', 'pscustomobject', 'powershell', 'microsoft', 'long', 'ipaddress', 'int', 'hashtable', 'float', 'double', 'decimal', 'char', 'byte', 'bool', 'array', 'adsisearcher', 'adsi' ), 4 => array( # MY list of aliases and functions (filtered to remove verb-noun functions which will already be highlighted, and to remove drive letter functions) # Combined list generated with: # gcm -type "Alias,Function,Filter" | Select -Expand Name | ?{$_ -match "[A-z]" -and $_ -notmatch "[A-z]-|:"}|Sort -Unique -Desc | %{[regex]::escape($_) -replace '.ps1$',''} | Join-String 'write', 'wjb', 'which', 'where', 'type', 'tee', 'TabExpansion', 'swmi', 'sv', 'Start', 'spsv', 'spps', 'spjb', 'sp', 'sort', 'sleep', 'sl', 'sign', 'si', 'set', 'select', 'sc', 'sbp', 'say', 'sasv', 'sas', 'sal', 'sajb', 'rwmi', 'rvpa', 'rv', 'rsnp', 'rsn', 'rp', 'rnp', 'rni', 'rmdir', 'rm', 'rjb', 'ri', 'ren', 'rdr', 'rd', 'rcjb', 'rbp', 'RandomLine', 'rand', 'r', 'pwd', 'pushd', 'ps', 'prompt', 'popd', 'oh', 'ogv', 'nv', 'nsn', 'nmo', 'ni', 'ndr', 'nal', 'mv', 'mp', 'move', 'mount', 'more', 'mkdir', 'mi', 'measure', 'md', 'man', 'ls', 'lp', 'kill', 'join', 'iwmi', 'IPSN', 'ipcsv', 'ipal', 'imo', 'ii', 'ihy', 'iex', 'icm', 'history', 'help', 'h', 'gwmi', 'gv', 'gu', 'gsv', 'gsnp', 'gsn', 'group', 'grid', 'gq', 'gps', 'gph', 'gp', 'gmo', 'gm', 'gl', 'gjb', 'gi', 'ghy', 'gdr', 'gcs', 'gcm', 'gci', 'gc', 'gbp', 'gas', 'gal', 'fw', 'ft', 'foreach', 'fl', 'fc', 'EXSN', 'exec', 'ETSN', 'erase', 'EPSN', 'epcsv', 'epal', 'emm', 'edit', 'echo', 'ebp', 'dir', 'diff', 'del', 'dbp', 'cvpa', 'cpp', 'cpi', 'cp', 'copy', 'compare', 'clv', 'cls', 'clp', 'cli', 'clhy', 'clear', 'clc', 'chdir', 'cd\\\\', 'cd\\.\\.', 'cd', 'cat', 'asnp', 'ac' ), ), 'SYMBOLS' => array( '(', ')', '[', ']', '{', '}', "-", "+", "=", '!', '%', '&', '*', '|', '/', '<', '>', ), 'CASE_SENSITIVE' => array( GESHI_COMMENTS => true, 1 => false, 2 => false, 3 => false, 4 => false, 5 => false, 6 => false, ), 'STYLES' => array( 'KEYWORDS' => array( 1 => 'color: #666699; font-weight: bold;', 2 => 'color: #333399; font-weight: bold; font-style: italic;', 3 => 'color: #003366; font-weight: bold;', 4 => 'color: #660033;', //~ 5 => 'color: #006600; font-style: italic;', //~ 6 => 'color: #000000; font-style: italic;', ), 'COMMENTS' => array( 1 => 'color: #666666; font-style: italic;', 'MULTI' => 'color: #666666; font-style: italic;' ), 'ESCAPE_CHAR' => array( 0 => 'color: #000099; font-weight: bold;' ), 'BRACKETS' => array( 0 => 'color: #333;' ), 'STRINGS' => array( 0 => 'color: #009900;' ), 'NUMBERS' => array( 0 => 'color: #cc66cc;' ), 'METHODS' => array( 1 => 'color: #003366;', 2 => 'color: #003366;', // 3 => 'color: #666;' ), 'SYMBOLS' => array( 0 => 'color: #66cc66;' ), 'REGEXPS' => array( 0 => 'color: #0066cc; font-style: italic;', # verb-noun 1 => 'font-style: normal;', # noun 2 => 'color: #000066;', # parameters 3 => 'color: #660033; font-weight: bold;', # variables 4 => 'color: #003366; font-weight: bold;', # types ), 'SCRIPT' => array( ) ), 'URLS' => array( ), 'OOLANG' => true, 'OBJECT_SPLITTERS' => array( 1 => '.', 2 => '::', ), 'REGEXPS' => array( # Verbs. Full SEARCH pattern GENERATED with this: # get-command | %{$_.verb} | sort -unique -descending | Join-String -prefix "((?:" -Separator "|" -postfix ")-[a-zA-Z_][a-zA-Z0-9_]*)" # NOTE: THIS HIGHLIGHTS THE WHOLE COMMAND 0 => array ( GESHI_SEARCH => '((?:Write|Where|Wait|Use|Update|Unregister|Undo|Trace|Test|Tee|Suspend|Stop|Start|Split|Sort|Show|Set|Send|Select|Resume|Restore|Restart|Resolve|Reset|Rename|Remove|Register|Receive|Read|Push|Pop|Out|New|Move|Measure|Limit|Join|Invoke|Import|Group|Get|Format|ForEach|Export|Exit|Enter|Enable|Disconnect|Disable|Debug|Copy|ConvertTo|ConvertFrom|Convert|Connect|Complete|Compare|Clear|Checkpoint|Add)-[a-zA-Z_][a-zA-Z0-9_]*)', GESHI_REPLACE => '\\\\1', GESHI_MODIFIERS => 'i', GESHI_BEFORE => '', GESHI_AFTER => '' ), # Nouns come after a Verb and a dash. It's basically the same as above, GENERATE YOUR OWN with this: # get-command | foreach-object{$_.verb} | sort-object -unique -descending | Join-String -Separator "|" -prefix "((?:" -postfix ")-)([a-zA-Z_][a-zA-Z0-9_]*)" # HYPOTHETICALLY, if you wanted a list of nouns on your system: # get-command | foreach-object{$_.noun} | sort-object -unique -descending | Join-String -Separator "|" -prefix "((?:" -postfix "))" # NOTE: THIS HIGHLIGHTS JUST THE NOUN 1 => array ( GESHI_SEARCH => '((?:Write|Where|Wait|Use|Update|Unregister|Undo|Trace|Test|Tee|Suspend|Stop|Start|Split|Sort|Show|Set|Send|Select|Resume|Restore|Restart|Resolve|Reset|Rename|Remove|Register|Receive|Read|Push|Pop|Out|New|Move|Measure|Limit|Join|Invoke|Import|Group|Get|Format|ForEach|Export|Exit|Enter|Enable|Disconnect|Disable|Debug|Copy|ConvertTo|ConvertFrom|Convert|Connect|Complete|Compare|Clear|Checkpoint|Add)-)([a-zA-Z_][a-zA-Z0-9_]*)', GESHI_REPLACE => '\\\\2', GESHI_MODIFIERS => 'i', GESHI_BEFORE => '\\\\1', GESHI_AFTER => '' ), # Parameters come after a " -" ... and although I can generate a list using: # "(-(?:"+(get-command | foreach-object{$_.parametersets} | foreach-object {$_.parameters} | foreach-object {$_.name} | sort-object -unique -descending | Join-String -Separator "|")+"))" | Set-Clipboard ############### (?:Year|XsltPath|XPath|Write|Wrap|WorkingDirectory|Word|WindowStyle|Width|WhatIf|Warning|WaitTimeout|Wait|Volume|View|Version|Verify|Verbose|Verb|Variable|ValueOnly|Value|Validate|Utc|UseTimeFromFile|UserName|URL|Update|Unique|UFormat|TypeName|TTL|TrustLevel|Trusted|Truncate|Trace|TotalCount|To|Title|TimestampServer|TimeStamp|Timeout|Time|TID|Text|Temp|TargetObject|Target|Syntax|SyncWindow|Sum|Subject|Strings|StringEncoding|String|Strict|Stream|Step|Status|Statistic|Static|State|StartupType|Start|StackName|Stack|Speed|SourceId|SortBy|SmtpHost|Size|SingleLine|SimpleMatch|SID|ShowError|Shortname|SetModifiedTime|SetCreatedTime|SetAccessedTime|Server|Separator|Select|SecureString|SecureKey|SecondValue|SecondsRemaining|Seconds|Second|ScriptBlock|Scope|SchemaPath|SaveCred|Rtf|Root|Role|Retry|Resolve|ReplyTo|Repair|RemoveOriginal|RemoveListener|RemoveFileListener|RemoveEmptyStrings|Registered|RegexSeparator|Regex|ReferenceObject|Recurse|RecommendedAction|Reason|ReadOnly|ReadCount|Raw|Quiet|Query|Quality|Qualifier|PSSnapin|PSProvider|PSHost|PSDrive|PropertyType|Property|Prompt|Process|Privileges|Privilege|Priority|PrinterName|PrincipalName|PrependPath|PortNumber|PortName|PercentComplete|Percent|Pattern|PathType|Path|Password|PassThru|ParentID|Parent|Parameter|Paging|Owner|Overwrite|OutVariable|OutputPath|Output|OutBuffer|Option|Operation|OnType|OmitXmlDeclaration|Offset|Off|Object|NoWindow|Noun|NoTypeInformation|NoTrimEnd|Notify|NoShellExecute|NoQualifier|NoProfile|NoNewLine|NoLineBreak|NoHeader|NoElement|NoClobber|NoAscii|NoAddress|NewName|NewLine|Newest|Namespace|Name|MultiLine|Most|Month|Modified|Minutes|Minute|Minimum|Min|Milliseconds|Migrate|Message|MemberType|Maximum|Max|MacName|LogName|Log|Location|LocalizedHelpPath|LoadUserProfile|LiteralPath|LiteralName|ListenerOption|List|LineCount|Line|Level|Leaf|LastWord|Last|Label|KeyLength|KeyContainerName|KeyAlgorithm|Key|KeepAspectRatio|JobName|ItemType|IsValid|IsAbsolute|IpAddress|Interval|InterfaceName|Interactive|Insert|InputObject|Input|IndentString|Incremental|IncludeEqual|IncludeEmptyDirectories|IncludeChain|Include|Import|Image|IgnoreWhiteSpace|Ignore|Identity|Id|HtmlBody|Html|Hours|Hour|HostName|HideTableHeaders|Height|Head|Handle|GroupBy|Group|GlobalCatalog|Functionality|Full|From|FragmentOnly|Format|ForegroundColor|Force|Follow|FlattenPaths|First|FilterScript|Filter|Files|FilePath|FileName|Fast|Expression|ExpandProperty|Expand|ExecutionPolicy|ExcludeProperty|ExcludeDifferent|Exclude|Exception|Examples|Exact|EventName|ErrorVariable|ErrorRecord|ErrorLimit|ErrorLevel|ErrorId|ErrorAction|Erase|End|Encrypt|Encoding|EnableScript|Elapsed|DriveName|Drain|DomainName|Domain|DistinguishedName|DisplayName|DisplayHint|DisplayError|DirectoryName|DifferenceObject|Detailed|Destination|Description|Descending|Depth|DependsOn|Delimiter|Delete|Default|Debugger|Debug|Days|Day|Date|CurrentOperation|Culture|Csv|CSPType|CSPName|CryptoRng|Credential|Created|Create|Count|Continuous|Container|ConformanceLevel|Confirm|ComputerName|Compress|Component|Completed|Compatible|ComObject|CommandType|Command|Columns|Column|ClusterName|ClassName|Class|ChildPath|Character|Char|CertUsage|CertSubjectName|CertStoreLocation|CertSerialNumber|CertRequestFileName|CertIssuerName|Certificate|CertFile|Cc|CategoryTargetType|CategoryTargetName|CategoryReason|CategoryActivity|Category|CaseSensitive|Cache|BufferSize|Boost|Body|BlockCount|Bitmap|BinaryPathName|Binary|Begin|Before|Bcc|Base64Text|BackgroundColor|Average|AutoSize|Audit|Audio|AttributesOnNewLine|AttributeName|AttachmentPath|AttachmentLiteralPath|Asynchronous|AsString|AssemblyName|AsSecureString|AsPlainText|Ascending|As|Arguments|ArgumentList|ApplicationName|AppendPath|Append|Anonymous|Allocation|AllAddresses|All|Algorithm|After|Adjust|Activity|AclObject|ACL|Accessed) # Since you can abbreviate a parameter to it's shortest representation, it seems like the best thing is to just match any word starting with - # This *MIGHT* affect your math, but I think it'll be better than otherwise 2 => array ( GESHI_SEARCH => ' (-[a-zA-Z_][a-zA-Z0-9_]*)', GESHI_REPLACE => '\\\\1', GESHI_MODIFIERS => 'i', GESHI_BEFORE => ' ', GESHI_AFTER => '' ), # Variables always start with $ and they can be pretty much whatever ... 3 => array ( GESHI_SEARCH => '(\\\\$[a-zA-Z_][a-zA-Z0-9_]*)', GESHI_REPLACE => '\\\\1', GESHI_MODIFIERS => '', GESHI_BEFORE => '', GESHI_AFTER => '' ), 4 => array ( GESHI_SEARCH => '(\\[[a-z][a-z0-9_\\.\\]\\[]+\\])', GESHI_REPLACE => '\\\\1', GESHI_MODIFIERS => 'i', GESHI_BEFORE => '', GESHI_AFTER => '' ), ), 'STRICT_MODE_APPLIES' => GESHI_NEVER, 'SCRIPT_DELIMITERS' => array( ), 'HIGHLIGHT_STRICT_BLOCK' => array( ) ); ?>
PowerShellCorpus/PoshCode/Help Differ 10000 v_1.01.ps1
Help Differ 10000 v_1.01.ps1
# These functions are meant to help generate a table that shows differences between # cmdlets among different versions of a module. # You will need a MoinMoin wiki to render the output. # If you don't have a MoinMoin wiki you might be able to use the sandbox at http://moinmo.in/WikiSandBox # Extracts some data from a module's help for use with Diff-HelpXml function Get-HelpXml { param ($module) get-command -module $module | % { $allParams = $_.parametersets | % { $_.parameters | select -unique Name } $obj = new-object psobject $obj | add-member -type noteproperty -name name -value $_.Name $obj | add-member -type noteproperty -name parameters -value $allParams # Pull some things out of help. $h = $_ | get-help $obj | add-member -type noteproperty -name description -value $h.Description $obj | add-member -type noteproperty -name paramDescriptions -value $h.parameters $obj } } # Diff a help XML and output the results in Moinmoin wiki format. # You can then copy to a MoinMoin wiki to do HTML rendering. function Diff-HelpXml { param ($beforeFile, $afterFile) # The XML files should be generated with makexml.ps1 $before = import-clixml $beforeFile $after = import-clixml $afterFile $titleColor = "<bgcolor=`"#72AEC0`">" $color1 = "<bgcolor=`"#C2DEF0`">" $color2 = "<bgcolor=`"#ffffff`">" echo "= New cmdlets in this release =" echo " ||$titleColor Name ||$titleColor Description ||" foreach ($a in $after) { $match = $before | where { $_.Name -eq $a.Name } if ($match -eq $null) { $name = $a.Name $desc = $a.Description[0].Text echo " || $name || $desc ||" } } echo "" echo "= New cmdlet parameters in this release =" $color = $color1 echo " ||$titleColor Cmdlet Name ||$titleColor Parameter Name ||$titleColor Description ||" foreach ($a in $after) { $match = $before | where { $_.Name -eq $a.Name } if ($match) { $noMatches = $true foreach ($p in $a.parameters) { $matchPar = $match.parameters | where { $_.Name -eq $p.Name } if ($matchPar -eq $null) { $cmdletName = "" $pName = $p.Name if ($noMatches) { $cmdletName = $a.Name $noMatches = $false if ($color -eq $color1) { $color = $color2 } else { $color = $color1 } } # Find the help for this switch. $matchDesc = $a.paramDescriptions.parameter | where { $_.Name -eq $pName } $pDesc = $matchDesc.description[0].text $pDesc = $pDesc -replace "[^A-Za-z1-9\\.`"``, ]", " " echo " ||$color $cmdletName ||$color $pName ||$color $pDesc ||" } } } } } # Sample usage: ## Install VI Toolkit 1.0 # Get-HelpXml -module vmware.vimautomation.core | export-clixml before.xml ## Install VI Toolkit 1.5 # Get-HelpXml -module vmware.vimautomation.core | export-clixml after.xml # Diff-HelpXml -before before.xml -after after.xml | set-content diffsInMoinMoin.txt
PowerShellCorpus/PoshCode/Reset-Tray.ps1
Reset-Tray.ps1
function Reset-Tray { Add-Type -Assembly UIAutomationClient $Window = Add-Type -Name ([char[]](65..90 | Get-Random -count 10) -join "") -Member @" [DllImport("user32")] public static extern IntPtr PostMessage(IntPtr hWnd, UInt32 Msg, Int32 wParam, Int32 lParam); public static void SendMouseMove(IntPtr hWnd, ushort x, ushort y) { int point = (y << 16) + x; PostMessage(hWnd, 0x200, 0, point); } "@ -Passthru $tray1 = [System.Windows.Automation.AutomationElement]::RootElement.FindAll( "Descendants" , [System.Windows.Automation.Condition]::TrueCondition ) | Where { $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ClassNameProperty) -like "SysPager" } # On Windows7 and Vista there's this, like, sub-tray thing $tray2 = $tray1.FindAll( "Children" , [System.Windows.Automation.Condition]::TrueCondition ) | Where { $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::NameProperty) -eq "User Promoted Notification Area" } $tray = $(if($tray2) { $tray2 } else { $tray1 }) $handle = $tray.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::NativeWindowHandleProperty) $rect = $tray.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::BoundingRectangleProperty) $y = $rect.Height/2 for ( $x = 0; $x -lt $rect.Width; $x += 8) { $Window::SendMouseMove( $handle, $x, $y ) } }
PowerShellCorpus/PoshCode/Get-FileEncoding_1.ps1
Get-FileEncoding_1.ps1
function Get-FileEncoding { <# .SYNOPSIS Gets file encoding. .DESCRIPTION The Get-FileEncoding function determines encoding by looking at Byte Order Mark (BOM). Based on port of C# code from http://www.west-wind.com/Weblog/posts/197245.aspx .EXAMPLE Get-ChildItem *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {$_.Encoding -ne 'ASCII'} This command gets ps1 files in current directory where encoding is not ASCII .EXAMPLE Get-ChildItem *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {$_.Encoding -ne 'ASCII'} | foreach {(get-content $_.FullName) | set-content $_.FullName -Encoding ASCII} Same as previous example but fixes encoding using set-content .NOTES Version History v1.0 - 2010/08/10, Chad Miller - Initial release v1.1 - 2010/08/16, Jason Archer - Improved pipeline support and added detection of little endian BOMs. #> [CmdletBinding()] param ( [Alias("PSPath")] [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] [String]$Path ) process { $Encoding = "ASCII" [Byte[]]$byte = Get-Content -Encoding Byte -ReadCount 4 -TotalCount 4 -Path $Path if ($byte[0] -eq 0xEF -and $byte[1] -eq 0xBB -and $byte[2] -eq 0xBF) { $Encoding = "UTF8" } elseif ($byte[0] -eq 0 -and $byte[1] -eq 0 -and $byte[2] -eq 0xFE -and $byte[3] -eq 0xFF) { ## UTF-32 Big-Endian $Encoding = "UTF32" } elseif ($byte[0] -eq 0xFF -and $byte[1] -eq 0xFE -and $byte[2] -eq 0 -and $byte[3] -eq 0) { ## UTF-32 Little-Endian $Encoding = "UTF32" } elseif ($byte[0] -eq 0xFE -and $byte[1] -eq 0xFF) { ## 1201 UTF-16 Big-Endian $Encoding = "Unicode" } elseif ($byte[0] -eq 0xFF -and $byte[1] -eq 0xFE) { ## 1200 UTF-16 Little-Endian $Encoding = "Unicode" } elseif ($byte[0] -eq 0x2B -and $byte[1] -eq 0x2F -and $byte[2] -eq 0x76) { $Encoding = "UTF7" } $Encoding } }
PowerShellCorpus/PoshCode/Query-VeeamBackupDB.ps1
Query-VeeamBackupDB.ps1
$dbServer = "servername\\instance" $db = "VeeamBackup" $veeamJob = "VeeamJobName" $Query = "SELECT [job_name],CONVERT(char(10),[creation_time], 101) AS start_date ` ,CONVERT(varchar, [creation_time], 108) AS job_start,CONVERT(char(10), [end_time], 101) AS end_date ` ,CONVERT(varchar, [end_time], 108) AS job_end, ` LEFT(CONVERT(VARCHAR,CAST([end_time] AS DATETIME)-CAST([creation_time] AS DATETIME), 108),5) AS total_time ` FROM [VeeamBackup].[dbo].[BSessions] WHERE [job_name] = '$veeamJob' ORDER BY start_date" $SqlConnection = New-Object System.Data.SqlClient.SqlConnection $SqlConnection.ConnectionString = "Server=$dbServer;Database=$db;Integrated Security=True" $SqlCmd = New-Object System.Data.SqlClient.SqlCommand $SqlCmd.CommandText = $Query $SqlCmd.Connection = $SqlConnection $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter $SqlAdapter.SelectCommand = $SqlCmd $DataSet = New-Object System.Data.DataSet $SqlAdapter.Fill($DataSet) $SqlConnection.Close() $DataSet.Tables[0] | Format-Table -AutoSize
PowerShellCorpus/PoshCode/chkhash_13.ps1
chkhash_13.ps1
# calculate SHA512 of file. function Get-SHA512([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]')) { $stream = $null; $cryptoServiceProvider = [System.Security.Cryptography.SHA512CryptoServiceProvider]; $hashAlgorithm = new-object $cryptoServiceProvider $stream = $file.OpenRead(); $hashByteArray = $hashAlgorithm.ComputeHash($stream); $stream.Close(); ## We have to be sure that we close the file stream if any exceptions are thrown. trap { if ($stream -ne $null) { $stream.Close(); } break; } foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }} return [string]$result; } function noequal ( $first, $second) { if (!($second) -or $second -eq "") {return $true} $first+="\\" foreach($s in $second) { if ($first.tolower().startswith($s.tolower())) {return $false} } return $true } # chkhash.ps1 [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #3] [-u] [-h [path of .xml database]] # -u updates the XML file database and exits # otherwise, all files are checked against the XML file database. # -h specifies location of xml hash database $hashespath=".\\hashes.xml" del variable:\\args3 -ea 0 del variable:\\args2 -ea 0 del variable:\\xfiles -ea 0 del variable:\\files -ea 0 del variable:\\exclude -ea 0 $args3=@() $args2=@($args) $nu = 0 $errs = 0 $fc = 0 $fm = 0 $upd = $false $create = $false 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} $e=$args2[$i] if (!($e.endswith("\\"))) {$e+="\\"} # add "\\" to end if not present $exclude+=@($e) # 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 $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|?{noequal $_.directoryname $exclude}) # Load database } else { if (!(test-path $hashespath)) {"No database found or specified, exiting."; exit} $xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database and check it if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit} $files=$xfiles } "Loaded $($xfiles.count) file hash(es) 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) { if ((get-item -ea 0 $f.fullname) -eq $null) {continue} # skip if file no longer exists. $n=($hash.($f.fullname)) if ($n -eq $null) { $nu++ # increment needs/needed updating count if ($upd -eq $false) {"Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue "Hashing `"$($f.fullname)`" ..." # Create SHA512 hash of file $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force} $xfiles+=@($f) # then add file + hash to list continue } $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force} # Update and continue is specified. $fc++ # File checked increment. if ($xfiles[$n].SHA512 -eq $f.SHA512) # Check SHA512 for mixmatch. {$fm++;continue} # if matched, increment file matches and continue loop $errs++ # increment mixmatches if ($upd -eq $true) { $xfiles[$n]=$f; "Updated `"$($f.fullname)`"";continue} "Bad SHA-512 found: `"$($f.fullname)`"" } if ($upd -eq $true) # if database updated { $xfiles|export-clixml $hashespath # write xml database "Updated $hashespath" "$nu file hash(es) added to database." "$errs file hash(es) updated in database." exit } "$errs SHA-512 mixmatch(es) found." "$fm file(s) SHA512 matched." "$fc file(s) checked total." if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
PowerShellCorpus/PoshCode/Get_Set Signature (CTP3).ps1
Get_Set Signature (CTP3).ps1
#Requires -version 2.0 ## Authenticode.psm1 updated for CTP 3 #################################################################################################### ## Wrappers for the Get-AuthenticodeSignature and Set-AuthenticodeSignature cmdlets ## These properly parse paths, so they don't kill your pipeline and script if you include a folder ## ## Usage: ## ls | Get-AuthenticodeSignature ## Get all the signatures ## ## ls | Select-Signed -Mine -Broken | Set-AuthenticodeSignature ## Re-sign anything you signed before that has changed ## ## ls | Select-Signed -NotMine -TrustedOnly | Set-AuthenticodeSignature ## Re-sign scripts that are hash-correct but not signed by me or by someone trusted ## #################################################################################################### ## History: ## 1.6 - Converted to work with CTP 3, and added function help comments ## 1.5 - Moved the default certificate setting into the module info Authenticode.psd1 file ## Note: If you get this off PoshCode, you'll have to create it yourself, see below: ## 1.4 - Moved the default certificate setting into an external psd1 file. ## 1.3 - Fixed some bugs in If-Signed and renamed it to Select-Signed ## - Added -MineOnly and -NotMineOnly switches to Select-Signed ## 1.2 - Added a hack workaround to make it appear as though we can sign and check PSM1 files ## It's important to remember that the signatures are NOT checked by PowerShell yet... ## 1.1 - Added a filter "If-Signed" that can be used like: ls | If-Signed ## - With optional switches: ValidOnly, InvalidOnly, BrokenOnly, TrustedOnly, UnsignedOnly ## - commented out the default Certificate which won't work for "you" ## 1.0 - first working version, includes wrappers for Get and Set ## #################################################################################################### ## README! README! README! README! ################################################################# ## README! README! README! README! ################################################################# ## ## You should set the location to your default signing certificate. The permanent way to do that is ## to modify (or create) the .psd1 file to set the PrivateData member variable. Otherwise you'll be ## prompted to provide a cert path whenever you try to sign a script without passing a certificate. ## ## The PrivateData variable should point at your code-signing certificate either with a full path ## or with the THUMBPRINT of a certificate you have available in your Cert:\\CurrentUser\\My\\ provider ## ## EG: ## F05F583BB5EA4C90E3B9BF1BDD0B657701245BD5 ## OR: ## "Cert:\\CurrentUser\\My\\F05F583BB5EA4C90E3B9BF1BDD0B657701245BD5" ## OR a file name: ## "C:\\Users\\Joel\\Documents\\WindowsPowerShell\\PoshCerts\\Joel-Bennett_Code-Signing.pfx" ## ## The simplest thing is to just create a new PSD1 ## ## New-ModuleManifest .\\Authenticode.psd1 -Nested .\\Authenticode.psm1 ` ## -Author "" -COmpany "" -Copy "" -Desc "" ` ## -Types @() -Formats @() -RequiredMod @() -RequiredAs @() -Other @() ` ## -PrivateData F05F583BB5EA4C90E3B9BF1BDD0B657701245BD5 ## #################################################################################################### #################################################################################################### function Get-UserCertificate { <#.SYNOPSIS Gets the user's default signing certificate so we don't have to ask them over and over... .DESCRIPTION The Get-UserCertificate function retrieves and returns a certificate from the user. It also stores the certificate so it can bereused without re-querying for the location and/or password ... .RETURNVALUE An X509Certificate2 suitable for code-signing ###################################################################################################> [CmdletBinding()] PARAM () PROCESS { trap { Write-Host "The authenticode script module requires configuration to function fully!" Write-Host Write-Host "You must put the path to your default signing certificate in the module metadata"` "file before you can use the module's Set-Authenticode cmdlet or to the 'mine'"` "feature of the Select-Signed or Test-Signature. To set it up, you can do this:" Write-Host Write-Host "PrivateData = 'C:\\Users\\${Env:UserName}\\Documents\\WindowsPowerShell\\PoshCerts\\Code-Signing.pfx'" Write-Host Write-Host "If you load your certificate into your 'CurrentUser\\My' store, or put the .pfx file"` "into the folder with the Authenthenticode module script, you can just specify it's"` "thumprint or filename, respectively. Otherwise, it should be a full path." Write-Error $_ return } # Import-LocalizedData -bindingVariable CertificatePath -EA "STOP" if(!$ExecutionContext.SessionState.Module.PrivateData) { $certs = ls cert:\\CurrentUser\\My if($certs.Count) { Write-Host "You have ${certs.Count} certs in your local cert storage which you can specify by Thumbprint:" -fore cyan $certs | Out-Host } $ExecutionContext.SessionState.Module.PrivateData = $(Read-Host "Please specify a user certificate") } if($ExecutionContext.SessionState.Module.PrivateData -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2]) { # Write-Host "CertificatePath: $ExecutionContext.SessionState.Module.PrivateData" -fore cyan $ResolvedPath = $Null $ResolvedPath = Resolve-Path $ExecutionContext.SessionState.Module.PrivateData -ErrorAction "SilentlyContinue" if(!$ResolvedPath -or !(Test-Path $ResolvedPath -ErrorAction "SilentlyContinue")) { # Write-Host "ResolvedPath: $ResolvedPath" -fore green $ResolvedPath = Resolve-Path (Join-Path $PsScriptRoot $ExecutionContext.SessionState.Module.PrivateData -ErrorAction "SilentlyContinue") -ErrorAction "SilentlyContinue" } if(!$ResolvedPath -or !(Test-Path $ResolvedPath -ErrorAction "SilentlyContinue")) { # Write-Host "ResolvedPath: $ResolvedPath" -fore yellow $ResolvedPath = Resolve-Path (Join-Path "Cert:\\CurrentUser\\My" $ExecutionContext.SessionState.Module.PrivateData -ErrorAction "SilentlyContinue") -ErrorAction "SilentlyContinue" } $Certificate = get-item $ResolvedPath -ErrorAction "SilentlyContinue" if($Certificate -is [System.IO.FileInfo]) { $Certificate = Get-PfxCertificate $Certificate -ErrorAction "SilentlyContinue" } Write-Verbose "Certificate: $($Certificate | Out-String)" $ExecutionContext.SessionState.Module.PrivateData = $Certificate } return $ExecutionContext.SessionState.Module.PrivateData } } #################################################################################################### function Test-Signature { <#.SYNOPSIS Tests a script signature to see if it is valid, or at least unaltered. .DESCRIPTION The Test-Signature function processes the output of Get-AuthenticodeSignature to determine if it is Valid, OR **unaltered** and signed by the user's certificate .NOTES Test-Signature returns TRUE even if the root CA certificate can't be verified, as long as the signing certificate's thumbnail matches the one specified by Get-UserCertificate. .EXAMPLE ls *.ps1 | Get-AuthenticodeSignature | Where {Test-Signature $_} To get the signature reports for all the scripts that we consider safely signed. .EXAMPLE ls | ? { gas $_ | test-signature } List all the valid signed scripts (or scripts signed by our cert) .INPUTTYPE System.Management.Automation.Signature .PARAMETER Signature Specifies the signature object to test. This should be the output of Get-AuthenticodeSignature. .PARAMETER ForceValid Switch parameter, forces the signature to be valid (otherwise, even if the certificate chain can't be verified, we will accept the cert which matches the "user" certificate (see Get-UserCertificate). Aliases Valid .RETURNVALUE Boolean value representing whether the script's signature is valid, or YOUR certificate ###################################################################################################> [CmdletBinding()] PARAM ( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)] # The signature to test. $Signature , [Alias("Valid")] [Switch]$ForceValid ) return ( $Signature.Status -eq "Valid" -or ( !$ForceValid -and ($Signature.Status -eq "UnknownError") -and ($_.SignerCertificate.Thumbprint -eq $(Get-UserCertificate).Thumbprint) ) ) } #################################################################################################### function Set-AuthenticodeSignature { <#.SYNOPSIS Adds an Authenticode signature to a Windows PowerShell script or other file. .DESCRIPTION The Set-AuthenticodeSignature function adds an Authenticode signature to any file that supports Subject Interface Package (SIP). In a Windows PowerShell script file, the signature takes the form of a block of text that indicates the end of the instructions that are executed in the script. If there is a signature in the file when this cmdlet runs, that signature is removed. .NOTES After the certificate has been validated, but before a signature is added to the file, the function checks the value of the $SigningApproved preference variable. If this variable is not set, or has a value other than TRUE, you are prompted to confirm the signing of the script. When specifying multiple values for a parameter, use commas to separate the values. For example, "<parameter-name> <value1>, <value2>". .EXAMPLE ls *.ps1 | Set-AuthenticodeSignature -Certificate $Certificate To sign all of the files with the specified certificate .EXAMPLE ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature | Where {!(Test-Signature $_ -Valid)} | gci | Set-AuthenticodeSignature List all the script files, and get and test their signatures, and then sign all of the ones that are not valid, using the user's default certificate. .INPUTTYPE String. You can pipe a file path to Set-AuthenticodeSignature. .PARAMETER FilePath Specifies the path to a file that is being signed. Aliases Path, FullName .PARAMETER Certificate Specifies the certificate that will be used to sign the script or file. Enter a variable that stores an object representing the certificate or an expression that gets the certificate. To find a certificate, use Get-PfxCertificate or use the Get-ChildItem cmdlet in the Certificate (Cert:) drive. If the certificate is not valid or does not have code-signing authority, the command fails. .RETURNVALUE System.Management.Automation.Signature ###################################################################################################> [CmdletBinding()] PARAM ( [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName","Path")] [ValidateScript({ if((resolve-path $_).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } if(!(Test-Path -PathType Leaf $_)) { throw "Specified Path is not a File: '$_'" } return $true })] [string[]] $FilePath , [Parameter(Position=2, Mandatory=$false)] $Certificate = $(Get-UserCertificate) ) PROCESS { Write-Verbose "Set Authenticode Signature on $FilePath with $($Certificate | Out-String)" Microsoft.PowerShell.Security\\Set-AuthenticodeSignature -Certificate $Certificate -FilePath $FilePath } } New-Alias sign Set-AuthenticodeSignature -EA "SilentlyContinue" #################################################################################################### function Get-AuthenticodeSignature { <#.SYNOPSIS Gets information about the Authenticode signature in a file. .DESCRIPTION The Get-AuthenticodeSignature function gets information about the Authenticode signature in a file. If the file is not signed, the information is retrieved, but the fields are blank. .NOTES For information about Authenticode signatures in Windows PowerShell, type "get-help About_Signing". When specifying multiple values for a parameter, use commas to separate the values. For example, "-<parameter-name> <value1>, <value2>". .EXAMPLE Get-AuthenticodeSignature script.ps1 To get the signature information about the script.ps1 script file. .EXAMPLE ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature Get the signature information for all the script and data files .EXAMPLE ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature | Where {!(Test-Signature $_ -Valid)} | gci | Set-AuthenticodeSignature This command gets information about the Authenticode signature in all of the script and module files, and tests the signatures, then signs all of the ones that are not valid. .INPUTTYPE String. You can pipe the path to a file to Get-AuthenticodeSignature. .PARAMETER FilePath The path to the file being examined. Wildcards are permitted, but they must lead to a single file. The parameter name ("-FilePath") is optional. Aliases Path, FullName .RETURNVALUE System.Management.Automation.Signature ###################################################################################################> [CmdletBinding()] PARAM ( [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName","Path")] [ValidateScript({ if((resolve-path $_).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } if(!(Test-Path -PathType Leaf $_)) { throw "Specified Path is not a File: '$_'" } return $true })] [string[]] $FilePath ) PROCESS { Microsoft.PowerShell.Security\\Get-AuthenticodeSignature -FilePath $FilePath } } #################################################################################################### function Select-Signed { <#.SYNOPSIS Select files based on the status of their Authenticode Signature. .DESCRIPTION The Select-Signed function filters files on the pipeline based on the state of their authenticode signature. .NOTES For information about Authenticode signatures in Windows PowerShell, type "get-help About_Signing". When specifying multiple values for a parameter, use commas to separate the values. For example, "-<parameter-name> <value1>, <value2>". .EXAMPLE ls *.ps1,*.ps[dm]1 | Select-Signed To get the signature information about the script.ps1 script file. .EXAMPLE ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature Get the signature information for all the script and data files .EXAMPLE ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature | Where {!(Test-Signature $_ -Valid)} | gci | Set-AuthenticodeSignature This command gets information about the Authenticode signature in all of the script and module files, and tests the signatures, then signs all of the ones that are not valid. .INPUTTYPE String. You can pipe the path to a file to Get-AuthenticodeSignature. .PARAMETER FilePath The path to the file being examined. Wildcards are permitted, but they must lead to a single file. The parameter name ("-FilePath") is optional. Aliases Path, FullName .RETURNVALUE System.Management.Automation.Signature ###################################################################################################> [CmdletBinding()] PARAM ( [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [ValidateScript({ if((resolve-path $_).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } return $true })] [string[]] $FilePath , [Parameter()] # Return only files that are signed with the users' certificate (as returned by Get-UserCertificate). [switch]$MineOnly , [Parameter()] # Return only files that are NOT signed with the users' certificate (as returned by Get-UserCertificate). [switch]$NotMineOnly , [Parameter()] [Alias("HashMismatch")] # Return only files with signatures that are broken (where the file has been edited, and the hash doesn't match). [switch]$BrokenOnly , [Parameter()] # Returns the files that are Valid OR signed with the users' certificate (as returned by Get-UserCertificate). # # That is, TrustedOnly returns files returned by -ValidOnly OR -MineOnly (if you specify both parameters, you get only files that are BOTH -ValidOnly AND -MineOnly) [switch]$TrustedOnly , [Parameter()] # Return only files that are "Valid": This means signed with any cert where the certificate chain is verifiable to a trusted root certificate. This may or may not include files signed with the user's certificate. [switch]$ValidOnly , [Parameter()] # Return only files that doesn't have a "Valid" signature, which includes files that aren't signed, or that have a hash mismatch, or are signed by untrusted certs (possibly including the user's certificate). [switch]$InvalidOnly , [Parameter()] # Return only signable files that aren't signed at all. That is, only files that support Subject Interface Package (SIP) but aren't signed. [switch]$UnsignedOnly ) PROCESS { if(!(Test-Path -PathType Leaf $FilePath)) { # if($ErrorAction -ne "SilentlyContinue") { # Write-Error "Specified Path is not a File: '$FilePath'" # } } else { foreach($sig in Get-AuthenticodeSignature -FilePath $FilePath) { # Broken only returns ONLY things which are HashMismatch if($BrokenOnly -and $sig.Status -ne "HashMismatch") { Write-Debug "$($sig.Status) - Not Broken: $FilePath" return } # Trusted only returns ONLY things which are Valid if($ValidOnly -and $sig.Status -ne "Valid") { Write-Debug "$($sig.Status) - Not Trusted: $FilePath" return } # AllValid returns only things that are SIGNED and not HashMismatch if($TrustedOnly -and (($sig.Status -ne "HashMismatch") -or !$sig.SignerCertificate) ) { Write-Debug "$($sig.Status) - Not Valid: $FilePath" return } # NOTValid returns only things that are SIGNED and Valid if($InvalidOnly -and ($sig.Status -eq "Valid")) { Write-Debug "$($sig.Status) - Valid: $FilePath" return } # Unsigned returns only things that aren't signed # NOTE: we don't test using NotSigned, because that's only set for .ps1 or .exe files?? if($UnsignedOnly -and $sig.SignerCertificate ) { Write-Debug "$($sig.Status) - Signed: $FilePath" return } # Mine returns only things that were signed by MY CertificateThumbprint if($MineOnly -and (!($sig.SignerCertificate) -or ($sig.SignerCertificate.Thumbprint -ne $((Get-UserCertificate).Thumbprint)))) { Write-Debug "Originally signed by someone else, thumbprint: $($sig.SignerCertificate.Thumbprint)" Write-Debug "Does not match your default certificate print: $((Get-UserCertificate).Thumbprint)" Write-Debug " $FilePath" return } # NotMine returns only things that were signed by MY CertificateThumbprint if($NotMineOnly -and (!($sig.SignerCertificate) -or ($sig.SignerCertificate.Thumbprint -eq $((Get-UserCertificate).Thumbprint)))) { if($sig.SignerCertificate) { Write-Debug "Originally signed by you, thumbprint: $($sig.SignerCertificate.Thumbprint)" Write-Debug "Matches your default certificate print: $((Get-UserCertificate).Thumbprint)" Write-Debug " $FilePath" } return } if(!$BrokenOnly -and !$TrustedOnly -and !$ValidOnly -and !$InvalidOnly -and !$UnsignedOnly -and !($sig.SignerCertificate) ) { Write-Debug "$($sig.Status) - Not Signed: $FilePath" return } get-childItem $sig.Path }} } } Export-ModuleMember Set-AuthenticodeSignature, Get-AuthenticodeSignature, Test-Signature, Select-Signed, Get-UserCertificate
PowerShellCorpus/PoshCode/Sith Remote logon mon.ps1
Sith Remote logon mon.ps1
' Script: Process_Monitor.vbs ' Purpose: Live process monitoring script that will trigger an e-mail to a recipient if a certain process is started ' Author: Paperclips (The Dark Lord) ' Email: magiconion_M@hotmail.com ' Date: Feb 2011 ' Comments: This particular monitor monitors the LogonUI process on Win7 ' Notes: - strComputer = "." 'you can type any remote computername here Set objNetwork = CreateObject("WScript.Network") Set objWMIService = GetObject("winmgmts:" & _ "{impersonationLevel=Impersonate}!\\\\" & _ strComputer & "\\root\\cimv2") '---------------------------------------------------------------------------------------LogonUI process------------------------------------------------------------------------------------------------ Set colMonitoredProcesses = objWMIService.ExecNotificationQuery("SELECT * FROM __InstanceCreationEvent Within 5 WHERE TargetInstance Isa ""Win32_Process"" And TargetInstance.Name = 'LogonUI.exe'") Do While True Set objProcess = colMonitoredProcesses.NextEvent Set Items = objWMIService.ExecQuery("select * from win32_process where Name = 'LogonUI.exe'") For Each objProcess in Items colProperties = objProcess.GetOwner(strNameOfUser) Next ' Email variables: strServer = "xxx.xxx.xxx.xxx" strTo = "aa@bb.com" strFrom = "cc@dd.com" strSubject = "LogonUI.exe detected on " & StrComputer & ". Process owner is: " & strNameOfUser & ". Processes monitored by "& objNetwork.Username strBody = StrComputer & " locked OK. This is a live monitor notification. A process 'LogonUI.exe' has triggered this notification signaling that this computer is in the process of being unlocked." & VbCrLf SendEmail strServer, strTo, strFrom, strSubject, strBody, "" Loop '---------------------------------------------------------------------------------------Mail Sub------------------------------------------------------------------------------------------------ Sub SendEmail(strServer, strTo, strFrom, strSubject, strBody, strAttachment) Dim objMessage Set objMessage = CreateObject("CDO.Message") objMessage.To = strTo objMessage.From = strFrom objMessage.Subject = strSubject objMessage.TextBody = strBody If strAttachment <> "" Then objMessage.AddAttachment strAttachment '==This section provides the configuration information for the remote SMTP server. objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'Name or IP of Remote SMTP Server objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = strServer 'Server port (typically 25) objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 objMessage.Configuration.Fields.Update '==End remote SMTP server configuration section== objMessage.Send Set objMessage = Nothing End Sub
PowerShellCorpus/PoshCode/Write-Output_1.ps1
Write-Output_1.ps1
######################################################################## ## Copyright (c) Joel Bennett, 2010 ## Free for use under MS-PL, MS-RL, GPL 2, or BSD license. Your choice. function Write-Output { [CmdletBinding()] param( [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)] [AllowEmptyCollection()] [AllowNull()] [System.Management.Automation.PSObject] ${InputObject} , [Parameter()] [Switch] [Alias("PreventUnrolling")] $AsCollection ) begin { $Collection = New-Object System.Collections.Generic.List[PSObject] } process { if($InputObject) { if($AsCollection) { $Collection.AddRange( ([PSObject[]]@($InputObject)) ) } else { $PSCmdlet.WriteObject( $InputObject, $true ) } } } end { if($AsCollection) { $PSCmdlet.WriteObject( $Collection, $false ) } } <# .SYNOPSIS Sends the specified objects to the next command in the pipeline. If the command is the last command in the pipeline, the objects are displayed in the console. .DESCRIPTION The Write-Output function sends the specified object down the pipeline to the next command. If the command is the last command in the pipeline, the object is displayed in the console. Write-Output sends objects down the primary pipeline, also known as the "output stream" or the "success pipeline." To send error objects down the error pipeline, use Write-Error. This function provides a pair of enhancements to the built-in Write-Output. First, it offers the option of Passthru, which causes collections to be output without unrolling (that is, output as collections to the pipeline), and second, it includes an option to collect input from the pipeline and output it all at once at the end. .PARAMETER InputObject Specifies the objects to send down the pipeline. Enter a variable that contains the objects, or type a command or expression that gets the objects. .PARAMETER AsCollection Specifies that pipeline input should be collected and output all at once at the end. This effectively allows you to take streaming input and turn it into a collection, or output an array from your function without unrolling. Note that this causes the output to be a List[PSObject]. .EXAMPLE $p = get-process C:\\PS>write-output $p Description ----------- These commands get objects representing the processes running on the computer and display the objects on the console. .EXAMPLE $p = get-process | Select-Object -First 10 C:\\PS>write-output $p | ForEach-Object { $_.GetType() } IsPublic IsSerial Name BaseType -------- -------- ---- -------- True False Process System.ComponentModel.Component True False Process System.ComponentModel.Component True False Process System.ComponentModel.Component True False Process System.ComponentModel.Component True False Process System.ComponentModel.Component True False Process System.ComponentModel.Component True False Process System.ComponentModel.Component True False Process System.ComponentModel.Component True False Process System.ComponentModel.Component True False Process System.ComponentModel.Component C:\\PS>write-output $p -AsCollection | ForEach-Object { $_.GetType() } IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True List`1 System.Array Description ----------- These commands demonstrate the difference between using and not using -AsCollection. Without it, each object passes through the ForEach and it's type is output. With -AsCollection, only a single object is output, with a collection type of List`1 .EXAMPLE Get-Process | Select-Object -First 10 | Write-Output -AsCollection | ForEach-Object { $_.GetType() } Description ----------- This command pipes the first ten processes to the ForEach-Object, demonstrating that -AsCollection will force the output to be a collection. .EXAMPLE Get-Process | Write-Output -AsCollection | ForEach-Object { $_.GetType() } Description ----------- This command collects all of the processes before outputting them to the ForEach-Object as a List[PSObject] #> }
PowerShellCorpus/PoshCode/Get-Credential++.ps1
Get-Credential++.ps1
## Get-Credential ## An improvement over the default cmdlet which has no options ... ################################################################################################### ## History ## v 2.0 Rewrite for v2 to replace the default Get-Credential ## v 1.2 Refactor ShellIds key out to a variable, and wrap lines a bit ## v 1.1 Add -Console switch and set registry values accordingly (ouch) ## v 1.0 Add Title, Message, Domain, and UserName options to the Get-Credential cmdlet ################################################################################################### function Get-Credential { ## .Synopsis ## Gets a credential object based on a user name and password. ## .Description ## The Get-Credential function creates a credential object for a specified username and password, with an optional domain. You can use the credential object in security operations. ## ## The function accepts more parameters to customize the security prompt than the default Get-Credential cmdlet (including forcing the call through the console if you're in the native PowerShell.exe CMD console), but otherwise functions identically. ## ## .Parameter Credential ## For compatability reasons only, we accept a credential (and pass it right back out) the way the built-in Get-Credential does. ## .Parameter UserName ## A default user name for the credential prompt ## .Parameter Title ## Allows you to override the default window title of the credential dialog/prompt ## ## You should use this to allow users to differentiate one credential prompt from another. In particular, if you're prompting for, say, Twitter credentials, you should put "Twitter" in the title somewhere. If you're prompting for domain credentials. Being specific not only helps users differentiate and know what credentials to provide, but also allows tools like KeePass to automatically determine it. ## .Parameter Message ## Allows you to override the text displayed inside the credential dialog/prompt. ## ## You can use this for things like presenting an explanation of what you need the credentials for. ## .Parameter Domain ## Specifies the default domain to use if the user doesn't provide one (by default, this is null) ## .Parameter GenericCredentials ## The Get-Credential cmdlet forces you to always return DOMAIN credentials (so even if the user provides just a plain user name, it prepends "\\" to the user name). This switch allows you to override that behavior and allow generic credentials without any domain name or the leading "\\". ## .Parameter Inline ## Forces the credential prompt to occur inline in the console/host using Read-Host -AsSecureString (not implemented properly in PowerShell ISE) ## [CmdletBinding(DefaultParameterSetName="Better")] PARAM( [Parameter(Position=1,Mandatory=$false)] [Alias("Credential")] [PSObject]$UserName=$null, [Parameter(Position=2,Mandatory=$false)] [string]$Title=$null, [Parameter(Position=3,Mandatory=$false)] [string]$Message=$null, [Parameter(Position=4,Mandatory=$false)] [string]$Domain=$null, [Parameter(Mandatory=$false)] [switch]$GenericCredentials, [Parameter(Mandatory=$false)] [switch]$Console ) PROCESS { if( $UserName -is [System.Management.Automation.PSCredential]) { return $UserName } else { $UserName = $UserName.ToString() } if($Console) { if($Title) { Write-Host $Title } if($Message) { Write-Host $Message } if($Domain) { if($UserName -and $UserName -notmatch "[@\\\\]") { $UserName = "${Domain}\\${UserName}" } } if(!$UserName) { $UserName = Read-Host "User" if(($Domain -OR !$GenericCredentials) -and $UserName -notmatch "[@\\\\]") { $UserName = "${Domain}\\${UserName}" } } return New-Object System.Management.Automation.PSCredential $UserName,$(Read-Host "Password for user $UserName" -AsSecureString) } if($GenericCredentials) { $Credential = "Generic" } else { $Credential = "Domain" } ## Now call the Host.UI method ... if they don't have one, we'll die, yay. ## BugBug? PowerShell.exe disregards the last parameter $Host.UI.PromptForCredential($Title, $Message, $UserName, $Domain, $Credential,"Default") } }
PowerShellCorpus/PoshCode/SetDefaultPrinter.ps1
SetDefaultPrinter.ps1
<# .SYNOPSIS Sets the Default Printer for any user on any machine in active directory. .DESCRIPTION Search AD for Computername; Select UserAccount and Printer and make that printer the default printer for that user on that computer. .PARAMETER Hostnme This parameter is required and should reflect the computer name (or names) you wish to inventory. This is basically a search criteria because the first thing the script will do is search Active Directory for computer names matching this input. .EXAMPLE .NOTES Author: Brad Blaylock Version: 3.0 Date: October 3, 2011 Contact: brad.blaylock@gmail.com Details: This Script accepts an AD Query (Computername) in the form of an entire computer name or partial computername as in sbcomp* or *2471wk1 and will find any listed computers that match the criteria in AD. This list will be presented to the user. The user will select the computer they are needing, and click [LOAD]. Load will find all user accounts that have ever had a profile on that computer; Load will also list all printers installed on that computer. The user will then select the user account and printer and click [Set Default]. SetDefault will make the selected printer default for the selected user on the selected computer. If the selected user is not logged into the selected computer at the time, SetDefault will Load the selected user's NTUSER.DAT registry Hive and make the selected changes offline. Issues: None Discovered as of Yet. } #> #~~~~~~~~~~~CUSTOM FUNCTIONS~~~~~~~~~~~~# function Test-Alive($comp) { $ping = new-object System.Net.NetworkInformation.Ping $stat=$ping.Send("$comp") $reply = $stat.status trap { $False continue; } if($reply -eq "Success") {$True} } function Ping-Port([string]$server, [int]$port) { $tcpClient = New-Object System.Net.Sockets.TcpClient trap { $False continue; } $tcpClient.Connect($server,$port) if ($tcpClient.Connected) {$True} } Function ADSearch { $Input = $Args[0] $Search = New-Object DirectoryServices.DirectorySearcher([ADSI]“”) $Search.filter = “(&(objectClass=Computer)(Name=$Input))” $Results = $Search.Findall() foreach ($i in $Results) { $Item = $i.properties $lbxServers.Items.Add("$($Item.cn)") } } function LoadUsers { $hku = 2147483651 $hklm = 2147483650 $UserPath = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList" $UserWMI = [WMIClass]"\\\\$Computer\\root\\default:stdRegProv" $Accounts = $UserWMI.EnumKey($hklm,$UserPath) foreach ($Account in $Accounts.snames) { $User = $UserWMI.GetStringValue($hklm,"$UserPath\\$Account","ProfileImagePath") $UserName = ($User.svalue).split("\\")[2] $cbxUserAccount.Items.Add($Username) } $currentuser = (gwmi win32_ComputerSystem -computername $Computer | select UserName).UserName $tbxCurrentUser.Text = $currentuser } Function LoadPrinters { $hklm = 2147483650 $PrinterPath = "Software\\Microsoft\\Windows NT\\CurrentVersion\\Print\\Printers" $PrinterWMI = [WMIClass]"\\\\$Computer\\root\\default:stdRegProv" $Printers = $PrinterWMI.EnumKey($hklm,$PrinterPath) foreach ($Printer in $Printers.snames) { $Print = $PrinterWMI.GetStringValue($hklm,"$PrinterPath\\$Printer","Name") $PrinterName = $Print.svalue $cbxPrinter.Items.Add($PrinterName) } } Function SetWithLocalRegHive { #<# #Test OS Version (2000, XP or Vista\\7\\8) $ostest = (gwmi win32_operatingsystem -computername $Computer | select Version | %{$_ -replace "@{Version=", ""} | %{$_ -replace "}", ""}) $tbxStatus.ForeColor = [System.Drawing.Color]::FromArgb(255,69,139,0) Switch -wildcard ($ostest) { "5.0*" {$tbxStatus.Text = "Windows 2000"; $profileroot = "Documents and Settings"} "5.1*" {$tbxStatus.Text = "Windows XP"; $profileroot = "Documents and Settings"} "6.0*" {$tbxStatus.Text = "Windows Vista"; $profileroot = "Users" } "6.1*" {$tbxStatus.Text = "Windows 7"; $profileroot = "Users"} } Reg Load HKLM\\TemporaryHive \\\\$Computer\\C$\\$profileroot\\$UserName\\NTUSER.DAT $LocalDefPrinter = (New-Object -ComObject Wscript.shell).RegRead("HKLM\\TemporaryHive\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows\\Device") $LocalDefPrinterDetails = (New-Object -ComObject Wscript.Shell).RegRead("HKLM\\TemporaryHive\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Devices\\$PrinterName") $LocalDefaultPrinter = ($LocalDefPrinter).split(",")[0] $Localspool = ($LocalDefPrinterDetails).split(",")[0] $LocalPort = ($LocalDefPrinterDetails).split(",")[1] $LocalNewDefPrinter = $PrinterName + "," + $Localspool + "," + $LocalPort (New-Object -comobject Wscript.Shell).regWrite("HKLM\\TemporaryHive\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows\\Device", "$LocalNewDefPrinter", "REG_SZ") Reg Unload HKLM\\TemporaryHive $tbxStatus.Text = "Default Printer Changed!" } Function SetDefaultPrinter { Get-service -ComputerName $Computer -Include 'RemoteRegistry' | Start-Service $domain = $env:USERDOMAIN $hklm = 2147483650 $hku = 2147483651 $ntAccount = new-object System.Security.Principal.NTAccount($domain, $UserName) $sid = $ntAccount.Translate([System.Security.Principal.SecurityIdentifier]) $ActionPath = "$sid\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows" $DevicesPath = "$sid\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Devices" $ActionWMI = [WMIClass]"\\\\$Computer\\root\\default:stdRegProv" $DefPrinter = $ActionWMI.GetStringValue($hku,"$ActionPath","Device") $DefPrinterDetails = $ActionWMI.GetStringValue($hku,"$DevicesPath","$PrinterName") $testRegKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($hku,$Computer) $testReg = $testRegKey.OpenSubKey("$sid") If (!$testReg) { SetWithLocalRegHive } Else { $DefaultPrinter = ($DefPrinter.svalue).split(",")[0] $spool = ($DefPrinterDetails.svalue).split(",")[0] $Port = ($DefPrinterDetails.svalue).split(",")[1] $NewDefPrinter = $PrinterName + "," + $spool + "," + $Port $ActionWMI.SetStringValue($HKU,"$ActionPath","Device","$NewDefPrinter") #SET THE DEFAULT PRINTER# $tbxStatus.ForeColor = [System.Drawing.Color]::FromArgb(255,69,139,0) $tbxStatus.Text = "Default Printer Changed!" } $cbxUserAccount.ResetText() $cbxPrinter.ResetText() } #Generated Form Function function GenerateForm { ######################################################################## # Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.8.0 # Generated On: 2/28/2011 11:35 AM # Generated By: bwblaylock ######################################################################## #region Import the Assemblies [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null [reflection.assembly]::loadwithpartialname("System.Windows.Forms.VisualStyles") | Out-Null [System.Windows.Forms.Application]::EnableVisualStyles() #endregion #region Generated Form Objects $FrmMain = New-Object System.Windows.Forms.Form $pgbProgress = New-Object System.Windows.Forms.ProgressBar $lblPrinter = New-Object System.Windows.Forms.Label $lblUserAccount = New-Object System.Windows.Forms.Label $lblSearch = New-Object System.Windows.Forms.Label $btnSearch = New-Object System.Windows.Forms.Button $tbxSearch = New-Object System.Windows.Forms.TextBox $btnClose = New-Object System.Windows.Forms.Button $btnLoad = New-Object System.Windows.Forms.Button $tbxServer = New-Object System.Windows.Forms.TextBox $tbxStatus = New-Object System.Windows.Forms.TextBox $tbxCurrentUser = New-Object System.Windows.Forms.TextBox $lbxServers = New-Object System.Windows.Forms.ListBox $btnSetDefault = New-Object System.Windows.Forms.Button $cbxPrinter = New-Object System.Windows.Forms.ComboBox $cbxUserAccount = New-Object System.Windows.Forms.ComboBox $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState #endregion Generated Form Objects #---------------------------------------------- #Generated Event Script Blocks #---------------------------------------------- #Provide Custom Code for events specified in PrimalForms. $btnClose_OnClick= { $FrmMain.Close() } $lbxServers.add_SelectedIndexChanged({ $tbxStatus.Text = $Null $tbxStatus.Refresh() $tbxServer.Text = $lbxServers.SelectedItem $tbxServer.Refresh() $tbxCurrentUser.Text = $null $tbxCurrentUser.Refresh() $cbxPrinter.Items.clear() $cbxPrinter.Text = $null $cbxPrinter.Refresh() $cbxUserAccount.Items.clear() $cbxUserAccount.Text = $null $cbxUserAccount.Refresh() }) $btnLoad_OnClick= { $tbxStatus.ForeColor = [System.Drawing.Color]::FromArgb(255,255,255,0) $tbxStatus.Text = "Loading..." $tbxStatus.Refresh() $Computer = $tbxServer.Text If (Test-Alive $Computer) { if ( (ping-port $Computer 135) -and (ping-port $Computer 445) ) { LoadUsers $Computer LoadPrinters $Computer $tbxStatus.ForeColor = [System.Drawing.Color]::FromArgb(255,69,139,0) $tbxStatus.Text = "Ready..." } Else { $tbxStatus.ForeColor = [System.Drawing.Color]::FromArgb(255,255,64,64) $tbxStatus.Text = "RPC Server Not Available" } } Else { $tbxStatus.ForeColor = [System.Drawing.Color]::FromArgb(255,255,64,64) $tbxStatus.Text = "Server Offline" } $pgbProgress.Visible = $False } $btnSetDefault_OnClick= { $Script:Computer = $tbxServer.Text $Script:UserName = $cbxUserAccount.SelectedItem $Script:PrinterName = $cbxPrinter.SelectedItem SetDefaultPrinter } $btnSearch_OnClick= { $lbxServers.Items.Clear() $Criteria = $tbxSearch.Text ADSearch $Criteria } $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $FrmMain.WindowState = $InitialFormWindowState } #---------------------------------------------- #region Generated Form Code #Main Form $FrmMain.CancelButton = $btnClose $FrmMain.BackColor = [System.Drawing.Color]::FromArgb(255,166,202,240) $FrmMain.Text = "Set Default Printer" $FrmMain.Name = "FrmMain" $FrmMain.KeyPreview = $True $FrmMain.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 439 $System_Drawing_Size.Height = 272 $FrmMain.ClientSize = $System_Drawing_Size $FrmMain.AcceptButton = $btnSearch $FrmMain.FormBorderStyle = 2 #Search Label $lblSearch.TabIndex = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 14 $lblSearch.Size = $System_Drawing_Size $lblSearch.Text = "Search" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 9 $lblSearch.Location = $System_Drawing_Point $lblSearch.DataBindings.DefaultDataSourceUpdateMode = 0 $lblSearch.Name = "lblSearch" $FrmMain.Controls.Add($lblSearch) #Printer Label $lblPrinter.TabIndex = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 12 $lblPrinter.Size = $System_Drawing_Size $lblPrinter.Text = "Printer:" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 258 $System_Drawing_Point.Y = 185 $lblPrinter.Location = $System_Drawing_Point $lblPrinter.DataBindings.DefaultDataSourceUpdateMode = 0 $lblPrinter.Name = "lblPrinter" $FrmMain.Controls.Add($lblPrinter) #UserAccount Label $lblUserAccount.TabIndex = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 13 $lblUserAccount.Size = $System_Drawing_Size $lblUserAccount.Text = "User Account:" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 259 $System_Drawing_Point.Y = 145 $lblUserAccount.Location = $System_Drawing_Point $lblUserAccount.DataBindings.DefaultDataSourceUpdateMode = 0 $lblUserAccount.Name = "lblUserAccount" $FrmMain.Controls.Add($lblUserAccount) #Progress Bar $pgbProgress.DataBindings.DefaultDataSourceUpdateMode = 0 $pgbProgress.BackColor = [System.Drawing.Color]::FromArgb(255,166,202,240) $pgbProgress.ForeColor = [System.Drawing.Color]::FromArgb(255,0,255,0) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 191 $System_Drawing_Size.Height = 8 $pgbProgress.Size = $System_Drawing_Size $pgbProgress.Step = 1 $pgbProgress.TabIndex = 0 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 246 $System_Drawing_Point.Y = 105 $pgbProgress.Location = $System_Drawing_Point $pgbProgress.Style = [System.Windows.Forms.ProgressBarStyle]::Marquee #2 $pgbProgress.MarqueeAnimationSpeed = 50 $pgbProgress.Visible = $False $pgbProgress.Name = "pgbProgress" $FrmMain.Controls.Add($pgbProgress) #Status Textbox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 168 $System_Drawing_Size.Height = 17 $tbxStatus.Size = $System_Drawing_Size $tbxStatus.DataBindings.DefaultDataSourceUpdateMode = 0 $tbxStatus.TextAlign = 2 $tbxStatus.BorderStyle = 0 $tbxStatus.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",10,1,3,0) $tbxStatus.Name = "tbxStatus" $tbxStatus.BackColor = [System.Drawing.Color]::FromArgb(255,166,202,240) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 259 $System_Drawing_Point.Y = 88 $tbxStatus.Location = $System_Drawing_Point $tbxStatus.TabIndex = 20 $FrmMain.Controls.Add($tbxStatus) #Server Textbox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 168 $System_Drawing_Size.Height = 17 $tbxServer.Size = $System_Drawing_Size $tbxServer.DataBindings.DefaultDataSourceUpdateMode = 0 $tbxServer.TextAlign = 2 $tbxServer.BorderStyle = 0 $tbxServer.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",10,1,3,1) $tbxServer.Name = "tbxServer" $tbxServer.BackColor = [System.Drawing.Color]::FromArgb(255,166,202,240) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 259 $System_Drawing_Point.Y = 32 $tbxServer.Location = $System_Drawing_Point $tbxServer.TabIndex = 19 $FrmMain.Controls.Add($tbxServer) #CurrentUser Textbox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 168 $System_Drawing_Size.Height = 17 $tbxCurrentUser.Size = $System_Drawing_Size $tbxCurrentUser.DataBindings.DefaultDataSourceUpdateMode = 0 $tbxCurrentUser.TextAlign = 2 $tbxCurrentUser.BorderStyle = 0 $tbxCurrentUser.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",8,[Drawing.FontStyle]'Italic') #0,3,1) $tbxCurrentUser.Name = "tbxCurrentUser" $tbxCurrentUser.BackColor = [System.Drawing.Color]::FromArgb(255,166,202,240) $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 259 $System_Drawing_Point.Y = 60 $tbxCurrentUser.Location = $System_Drawing_Point $tbxCurrentUser.TabIndex = 20 $FrmMain.Controls.Add($tbxCurrentUser) #Search Button $btnSearch.TabIndex = 2 $btnSearch.Name = "btnSearch" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 60 $System_Drawing_Size.Height = 23 $btnSearch.Size = $System_Drawing_Size $btnSearch.UseVisualStyleBackColor = $True $btnSearch.Text = "Search" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 180 $System_Drawing_Point.Y = 26 $btnSearch.Location = $System_Drawing_Point $btnSearch.DataBindings.DefaultDataSourceUpdateMode = 0 $btnSearch.add_Click($btnSearch_OnClick) $FrmMain.Controls.Add($btnSearch) #Load Button $btnLoad.TabIndex = 4 $btnLoad.Name = "btnLoad" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 60 $System_Drawing_Size.Height = 23 $btnLoad.Size = $System_Drawing_Size $btnLoad.UseVisualStyleBackColor = $True $btnLoad.Text = "Load" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 310 $System_Drawing_Point.Y = 120 $btnLoad.Location = $System_Drawing_Point $btnLoad.DataBindings.DefaultDataSourceUpdateMode = 0 $btnLoad.add_Click($btnLoad_OnClick) $FrmMain.Controls.Add($btnLoad) #Close Button $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 351 $System_Drawing_Point.Y = 236 $btnClose.Location = $System_Drawing_Point $btnClose.DataBindings.DefaultDataSourceUpdateMode = 0 $btnClose.DialogResult = 2 $btnClose.add_Click($btnClose_OnClick) $FrmMain.Controls.Add($btnClose) #SetDefault Button $btnSetDefault.TabIndex = 7 $btnSetDefault.Name = "btnSetDefault" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 75 $System_Drawing_Size.Height = 23 $btnSetDefault.Size = $System_Drawing_Size $btnSetDefault.UseVisualStyleBackColor = $True $btnSetDefault.Text = "Set Default" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 259 $System_Drawing_Point.Y = 236 $btnSetDefault.Location = $System_Drawing_Point $btnSetDefault.DataBindings.DefaultDataSourceUpdateMode = 0 $btnSetDefault.add_Click($btnSetDefault_OnClick) $FrmMain.Controls.Add($btnSetDefault) #Search Textbox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 161 $System_Drawing_Size.Height = 20 $tbxSearch.Size = $System_Drawing_Size $tbxSearch.DataBindings.DefaultDataSourceUpdateMode = 0 $tbxSearch.Name = "tbxSearch" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 29 $tbxSearch.Location = $System_Drawing_Point $tbxSearch.TabIndex = 1 $FrmMain.Controls.Add($tbxSearch) $btnClose.TabIndex = 8 $btnClose.Name = "btnClose" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 75 $System_Drawing_Size.Height = 23 $btnClose.Size = $System_Drawing_Size $btnClose.UseVisualStyleBackColor = $True $btnClose.Text = "Close" #Servers Listbox #$lbxServers.UseCompatibleStateImageBehavior = $False $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 227 $System_Drawing_Size.Height = 205 $lbxServers.Size = $System_Drawing_Size $lbxServers.DataBindings.DefaultDataSourceUpdateMode = 0 $lbxServers.Name = "lbxServers" #$lbxServers.View = 3 $lbxServers.TabIndex = 3 $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 13 $System_Drawing_Point.Y = 55 $lbxServers.Location = $System_Drawing_Point $FrmMain.Controls.Add($lbxServers) #Printer Combobox $cbxPrinter.FormattingEnabled = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 168 $System_Drawing_Size.Height = 21 $cbxPrinter.Size = $System_Drawing_Size $cbxPrinter.DataBindings.DefaultDataSourceUpdateMode = 0 $cbxPrinter.Name = "cbxPrinter" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 258 $System_Drawing_Point.Y = 200 $cbxPrinter.Location = $System_Drawing_Point $cbxPrinter.TabIndex = 6 $FrmMain.Controls.Add($cbxPrinter) #UserAccount Combobox $cbxUserAccount.FormattingEnabled = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 168 $System_Drawing_Size.Height = 21 $cbxUserAccount.Size = $System_Drawing_Size $cbxUserAccount.DataBindings.DefaultDataSourceUpdateMode = 0 $cbxUserAccount.Name = "cbxUserAccount" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 258 $System_Drawing_Point.Y = 161 $cbxUserAccount.Location = $System_Drawing_Point $cbxUserAccount.TabIndex = 5 $FrmMain.Controls.Add($cbxUserAccount) #endregion Generated Form Code #Save the initial state of the form $InitialFormWindowState = $FrmMain.WindowState #Init the OnLoad event to correct the initial state of the form $FrmMain.add_Load($OnLoadForm_StateCorrection) #Show the Form $FrmMain.ShowDialog()| Out-Null } #End Function #Call the Function GenerateForm
PowerShellCorpus/PoshCode/Get-DiskUsage_3.ps1
Get-DiskUsage_3.ps1
Function Get-DiskUsage { <# .SYNOPSIS A tribute to the excellent Unix command DU. .DESCRIPTION This command will output the full path and the size of any object and it's subobjects. Using just the Get-DiskUsage command without any parameters will result in an output of the directory you are currently placed in and it's subfolders. .PARAMETER Path If desired a path can be specified with the Path parameter. In no path is specified $PWD will be used. .PARAMETER h the -h paramater is the same as -h in Unix. It will list the folders and subfolders in the most appropriate unit depending on the size (i.e. Human Readable). .PARAMETER l The -l paramater will add the largest file to the end of the output. .PARAMETER Sort Allows you to sort by Folder or Size. If none i specified the default of Folder will be used. .PARAMETER Depth Depth will allow you to specify a maximum recursion depth. A depth of 1 would return the immediate subfolders under the root. .PARAMETER Force Works the same way as Get-ChildItem -force. .PARAMETER Descending Works the same way as Sort-Object -descending. .LINK http://www.donthaveasite.nu .NOTES Author: Jonas Hallqvist Developed with Powershell v3 #> [CmdletBinding( SupportsShouldProcess=$True )] param ( [String]$Path=$PWD, [Switch]$h, [Switch]$l, [String]$Sort="Folder", [Int]$Depth, [Switch]$Force, [Switch]$Descending ) $ErrorActionPreference = "silentlycontinue" function HumanReadable { param ($size) switch ($size) { {$_ -ge 1PB}{"{0:#'P'}" -f ($size / 1PB); break} {$_ -ge 1TB}{"{0:#'T'}" -f ($size / 1TB); break} {$_ -ge 1GB}{"{0:#'G'}" -f ($size / 1GB); break} {$_ -ge 1MB}{"{0:#'M'}" -f ($size / 1MB); break} {$_ -ge 1KB}{"{0:#'K'}" -f ($size / 1KB); break} default {"{0}" -f ($size) + "B"} } } function LargestFolder { if ($h) { $large = ($results | Sort-Object -Property Size -Descending)[0] | Format-Table @{Label="Size";Expression={HumanReadable $_.Size};Align="Right"},Folder -AutoSize -HideTableHeaders Write-host "Largest Folder is:" -NoNewline $large } else { $large = ($results | Sort-Object -Property Size -Descending)[0] | Format-Table @{Label="Size";Expression={"$($_.Size)B"};Align="Right"},Folder -AutoSize -HideTableHeaders Write-host "Largest Folder is:" -NoNewline $large } } function Max-Depth { param( [String]$Path = '.', [String]$Filter = '*', [Int]$Level = 0, [Switch]$Force, [Switch]$Descending, [int]$i=0 ) $results=@() $root = (Resolve-Path $Path).Path if ($root -notmatch '\\\\$') {$root += '\\'} if (Test-Path $root -PathType Container) { do { [String[]]$_path += $root + "$Filter" $Filter = '*\\' + $Filter $i++ } until ($i -eq $Level) $dirs=Get-ChildItem -directory $_path -Force:$Force foreach ($dir in $dirs) { $size = 0 $size += (gci $dir.Fullname -recurse | Measure-Object -Property Length -Sum).Sum $results += New-Object psobject -Property @{Folder=$dir.fullname;Size=$size} } if ($h) { $results | Sort-Object $Sort -Descending:$Descending | Format-Table @{Label="Size";Expression={HumanReadable $_.Size};Align="Right"},Folder -AutoSize } if ($l) { LargestFolder } if (($h -eq $false) -and ($l -eq $false)) { $results | Sort-Object $Sort -Descending:$Descending | Format-Table @{Label="Size";Expression={"$($_.Size)B"};Align="Right"},Folder -AutoSize } } } if ($Depth) { Max-Depth -Path $Path -Level $Depth -Force:$Force -Descending:$Descending } else { $results = @() $dirs=Get-ChildItem -directory $Path -Force:$Force -Recurse foreach ($dir in $dirs) { $size = 0 $size += (gci $dir.FullName -Recurse | Measure-Object -Property Length -Sum).Sum $results+= New-Object psobject -Property @{Folder=$dir.FullName;Size=$size} } if ($h) { $results | Sort-Object $Sort -Descending:$Descending | Format-Table @{Label="Size";Expression={HumanReadable $_.Size};Align="Right"},Folder -AutoSize } if ($l) { LargestFolder } if (($h -eq $false) -and ($l -eq $false)) { $results | Sort-Object $Sort -Descending:$Descending | Format-Table @{Label="Size";Expression={"$($_.Size)B"};Align="Right"},Folder -AutoSize } } }
PowerShellCorpus/PoshCode/LibraryLinkedServer.ps1
LibraryLinkedServer.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; $smoVersion = 10} catch {add-type -AssemblyName "Microsoft.SqlServer.Smo"; $smoVersion = 9} try {add-type -AssemblyName "Microsoft.SqlServer.SqlEnum, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop; $smoVersion = 10} catch {add-type -AssemblyName "Microsoft.SqlServer.SqlEnum"; $smoVersion = 9} try { try {add-type -AssemblyName "Microsoft.SqlServer.SMOExtended, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop} catch {add-type -AssemblyName "Microsoft.SqlServer.SMOExtended" -EA Stop} } catch {Write-Warning "SMOExtended not available"} $ErrorActionPreference = 'Stop' $scriptRoot = Split-Path (Resolve-Path $myInvocation.MyCommand.Path) ####################### filter Remove-LinkedServerLogin { param([string[]]$LinkedServerLogins) $ServerInstance = $_ $sqlserver = new-object ("Microsoft.SqlServer.Management.Smo.Server") $ServerInstance #Get the linked server logins in the global group $l = $sqlserver.LinkedServers| % {$_.LinkedServerLogins } | ? {$LinkedServerLogins -contains $_.name} write-host $ServerInstance if ($l) { #Drop the Linked Server Logins $l | %{$_.Drop()} } } #Remove-LinkedServerLogin ####################### filter Backup-LinkedServer { param($LinkedServer,[string[]]$LinkedServerLogins) $ServerInstance = $_ $ServerInstanceFileName = $ServerInstance -replace '\\\\','_' $sqlserver = new-object ("Microsoft.SqlServer.Management.Smo.Server") $ServerInstance #Get the linked servers if ($LinkedServer) { $l = $sqlserver.LinkedServers| ? {$_.Name -eq "$LinkedServer" } } elseif ($LinkedServerLogins) { $l = $sqlserver.LinkedServers| % {$_.LinkedServerLogins } | ? {$LinkedServerLogins -contains $_.name} | %{$_.parent} | select-object -unique } else { throw 'LinkedServer or LinkedServerLogins required.' } write-host $ServerInstance $opts = New-Object Microsoft.SqlServer.Management.Smo.ScriptingOptions $opts.ToFileOnly =$true if ($l) { #Backup Linked Server Before Dropping Linked Server Logins $l | % {$opts.FileName = $("{0}\\{1}_{2}.sql" -f $scriptRoot,$ServerInstanceFileName,$($($_.Name) -replace '\\\\','_')); write-host $opts.FileName; $_.script($opts)} } } #Backup-LinkedServer ####################### filter Remove-LinkedServer { param($LinkedServer) $ServerInstance = $_ $ServerInstanceFileName = $ServerInstance -replace '\\\\','_' $sqlserver = new-object ("Microsoft.SqlServer.Management.Smo.Server") $ServerInstance write-host "$ServerInstance" $l = $sqlserver.LinkedServers| ? {$_.Name -eq "$LinkedServer" } #Backup Linked Server Before Dropping if ($l) { #Drop the Linked Server $l | %{$_.Drop($true)} } } #Remove-LinkedServer ####################### function Get-CMRegisteredServer { param($CMServer,$GroupName) $query = @" SELECT DISTINCT s.name FROM msdb.dbo.sysmanagement_shared_registered_servers s JOIN msdb.dbo.sysmanagement_shared_server_groups g ON s.server_group_id = g.server_group_id WHERE 1 = 1 "@ if ($GroupName) { $query =+ "`nAND g.name = '$GroupName'" } #Write-Host $query Invoke-SqlCmd2 -ServerInstance $CMServer -Database msdb -Query $query | foreach {$_.name} } #Get-CMRegisteredServer ####################### <# .SYNOPSIS Runs a T-SQL script. .DESCRIPTION Runs a T-SQL script. Invoke-Sqlcmd2 only returns message output, such as the output of PRINT statements when -verbose parameter is specified .INPUTS None You cannot pipe objects to Invoke-Sqlcmd2 .OUTPUTS System.Data.DataTable .EXAMPLE Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -Query "SELECT login_time AS 'StartTime' FROM sysprocesses WHERE spid = 1" This example connects to a named instance of the Database Engine on a computer and runs a basic T-SQL query. StartTime ----------- 2010-08-12 21:21:03.593 .EXAMPLE Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -InputFile "C:\\MyFolder\\tsqlscript.sql" | Out-File -filePath "C:\\MyFolder\\tsqlscript.rpt" This example reads a file containing T-SQL statements, runs the file, and writes the output to another file. .EXAMPLE Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -Query "PRINT 'hello world'" -Verbose This example uses the PowerShell -Verbose parameter to return the message output of the PRINT command. VERBOSE: hello world .NOTES Version History v1.0 - Chad Miller - Initial release v1.1 - Chad Miller - Fixed Issue with connection closing v1.2 - Chad Miller - Added inputfile, SQL auth support, connectiontimeout and output message handling. Updated help documentation v1.3 - Chad Miller - Added As parameter to control DataSet, DataTable or array of DataRow Output type #> function Invoke-Sqlcmd2 { [CmdletBinding()] param( [Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance, [Parameter(Position=1, Mandatory=$false)] [string]$Database, [Parameter(Position=2, Mandatory=$false)] [string]$Query, [Parameter(Position=3, Mandatory=$false)] [string]$Username, [Parameter(Position=4, Mandatory=$false)] [string]$Password, [Parameter(Position=5, Mandatory=$false)] [Int32]$QueryTimeout=600, [Parameter(Position=6, Mandatory=$false)] [Int32]$ConnectionTimeout=15, [Parameter(Position=7, Mandatory=$false)] [ValidateScript({test-path $_})] [string]$InputFile, [Parameter(Position=8, Mandatory=$false)] [ValidateSet("DataSet", "DataTable", "DataRow")] [string]$As="DataRow" ) if ($InputFile) { $filePath = $(resolve-path $InputFile).path $Query = [System.IO.File]::ReadAllText("$filePath") } $conn=new-object System.Data.SqlClient.SQLConnection if ($Username) { $ConnectionString = "Server={0};Database={1};User ID={2};Password={3};Trusted_Connection=False;Connect Timeout={4}" -f $ServerInstance,$Database,$Username,$Password,$ConnectionTimeout } else { $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerInstance,$Database,$ConnectionTimeout } $conn.ConnectionString=$ConnectionString #Following EventHandler is used for PRINT and RAISERROR T-SQL statements. Executed when -Verbose parameter specified by caller if ($PSBoundParameters.Verbose) { $conn.FireInfoMessageEventOnUserErrors=$true $handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] {Write-Verbose "$($_)"} $conn.add_InfoMessage($handler) } $conn.Open() $cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn) $cmd.CommandTimeout=$QueryTimeout $ds=New-Object system.Data.DataSet $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd) [void]$da.fill($ds) $conn.Close() switch ($As) { 'DataSet' { Write-Output ($ds) } 'DataTable' { Write-Output ($ds.Tables) } 'DataRow' { Write-Output ($ds.Tables[0]) } } } #Invoke-Sqlcmd2
PowerShellCorpus/PoshCode/Computer Inventory.ps1
Computer Inventory.ps1
# ======================================================== # # Script Information # # Title: Remote Computer Inventory # Author: Assaf Miron # Originally created: 21/06/2008 # Original path: Computer-Inventory.PS1 # Description: Collects Remote Computer Data Using WMI and Registry Access # Outputs all information to a Data Grid Form and to a CSV Log File # # ======================================================== #region Constructor # Import Assembly [void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") [void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") # Log File where the results are Saved $LogFile = "C:\\Monitoring\\Test-Monitor.csv" # Check to see if the Log File Directory exists If((Test-Path ($LogFile.Substring(0,$logFile.LastIndexof("\\")))) -eq $False) { # Create The Directory New-Item ($LogFile.Substring(0,$logFile.LastIndexof("\\"))) -Type Directory } #endregion #region Form Creation #~~< Form1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $Form1 = New-Object System.Windows.Forms.Form $Form1.AutoSize = $TRUE $Form1.ClientSize = New-Object System.Drawing.Size(522, 404) $Form1.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen $Form1.Text = "Computer Inventory" #~~< Panel1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $Panel1 = new-object System.Windows.Forms.Panel $Panel1.Dock = [System.Windows.Forms.DockStyle]::Fill $Panel1.Location = new-object System.Drawing.Point(0, 24) $Panel1.Size = new-object System.Drawing.Size(522, 380) $Panel1.TabIndex = 20 $Panel1.Text = "" #~~< btnRun >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $btnRun = New-Object System.Windows.Forms.Button $btnRun.Enabled = $FALSE $btnRun.Location = New-Object System.Drawing.Point(431, 30) $btnRun.Size = New-Object System.Drawing.Size(75, 23) $btnRun.TabIndex = 2 $btnRun.Text = "Run" $btnRun.UseVisualStyleBackColor = $TRUE $btnRun.add_Click({ RunScript($btnRun) }) #~~< Label1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $Label1 = New-Object System.Windows.Forms.Label $Label1.AutoSize = $False#$TRUE $Label1.Location = New-Object System.Drawing.Point(12, 31) $Label1.Size = New-Object System.Drawing.Size(163, 13) $Label1.TabIndex = 15 $Label1.Text = "File containing Computer Names" #~~< TextBox1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $TextBox1 = New-Object System.Windows.Forms.TextBox $TextBox1.Location = New-Object System.Drawing.Point(177, 30) $TextBox1.Size = New-Object System.Drawing.Size(161, 20) $TextBox1.TabIndex = 0 $TextBox1.Text = "" #~~< btnBrowse >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $btnBrowse = New-Object System.Windows.Forms.Button $btnBrowse.Location = New-Object System.Drawing.Point(347, 30) $btnBrowse.Size = New-Object System.Drawing.Size(75, 23) $btnBrowse.TabIndex = 1 $btnBrowse.Text = "Browse" $btnBrowse.UseVisualStyleBackColor = $TRUE $btnBrowse.add_Click({ BrowseFile($btnBrowse) }) #~~< DataGridView1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $DataGridView1 = new-object System.Windows.Forms.DataGridView $DataGridView1.Anchor = ([System.Windows.Forms.AnchorStyles]([System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right)) $DataGridView1.ColumnHeadersHeightSizeMode = [System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode]::AutoSize $DataGridView1.Location = New-Object System.Drawing.Point(12, 59) $DataGridView1.Size = New-Object System.Drawing.Size(497, 280) $DataGridView1.TabIndex = 4 $DataGridView1.ClipboardCopyMode = [System.Windows.Forms.DataGridViewClipboardCopyMode]::Disable $DataGridView1.Text = "" #~~< ProgressBar1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $ProgressBar1 = New-Object System.Windows.Forms.ProgressBar $ProgressBar1.Anchor = ([System.Windows.Forms.AnchorStyles] ([System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right )) $ProgressBar1.Location = New-Object System.Drawing.Point(12, 345) $ProgressBar1.Size = New-Object System.Drawing.Size(410, 23) $ProgressBar1.TabIndex = 5 $ProgressBar1.Text = "" #~~< btnExit >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $btnExit = New-Object System.Windows.Forms.Button $btnExit.Anchor = ([System.Windows.Forms.AnchorStyles]([System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Right)) $btnExit.DialogResult = [System.Windows.Forms.DialogResult]::Cancel $btnExit.Location = New-Object System.Drawing.Point(431, 345) $btnExit.Size = New-Object System.Drawing.Size(78, 23) $btnExit.TabIndex = 3 $btnExit.Text = "Exit" $btnExit.UseVisualStyleBackColor = $TRUE $btnExit.add_Click({ CloseForm($btnExit) }) #~~< MenuStrip1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $MenuStrip1 = new-object System.Windows.Forms.MenuStrip $MenuStrip1.Location = new-object System.Drawing.Point(0, 0) $MenuStrip1.Size = new-object System.Drawing.Size(292, 24) $MenuStrip1.TabIndex = 6 $MenuStrip1.Text = "MenuStrip1" #~~< FileToolStripMenuItem >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $FileToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem $FileToolStripMenuItem.Size = new-object System.Drawing.Size(35, 20) $FileToolStripMenuItem.Text = "File" #~~< OpenLogFileToolStripMenuItem >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $OpenLogFileToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem $OpenLogFileToolStripMenuItem.Size = new-object System.Drawing.Size(152, 22) $OpenLogFileToolStripMenuItem.Text = "Open Log File" $OpenLogFileToolStripMenuItem.add_Click({Open-file($OpenLogFileToolStripMenuItem)}) #~~< ExitToolStripMenuItem >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $ExitToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem $ExitToolStripMenuItem.Size = new-object System.Drawing.Size(152, 22) $ExitToolStripMenuItem.Text = "Exit" $ExitToolStripMenuItem.add_Click({CloseForm($ExitToolStripMenuItem)}) $FileToolStripMenuItem.DropDownItems.AddRange([System.Windows.Forms.ToolStripItem[]](@($OpenLogFileToolStripMenuItem, $ExitToolStripMenuItem))) #~~< HelpToolStripMenuItem >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $HelpToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem $HelpToolStripMenuItem.Size = new-object System.Drawing.Size(40, 20) $HelpToolStripMenuItem.Text = "Help" #~~< AboutToolStripMenuItem >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $AboutToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem $AboutToolStripMenuItem.Size = new-object System.Drawing.Size(152, 22) $AboutToolStripMenuItem.Text = "About" $AboutToolStripMenuItem.add_Click({Show-About($AboutToolStripMenuItem)}) #~~< HowToToolStripMenuItem >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $HowToToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem $HowToToolStripMenuItem.Size = new-object System.Drawing.Size(152, 22) $HowToToolStripMenuItem.Text = "How To?" $HowToToolStripMenuItem.add_Click({Show-HowTo($HowToToolStripMenuItem)}) $HelpToolStripMenuItem.DropDownItems.AddRange([System.Windows.Forms.ToolStripItem[]](@($AboutToolStripMenuItem, $HowToToolStripMenuItem))) $MenuStrip1.Items.AddRange([System.Windows.Forms.ToolStripItem[]](@($FileToolStripMenuItem, $HelpToolStripMenuItem))) $Panel1.Controls.Add($MenuStrip1) $Panel1.Controls.Add($btnRun) $Panel1.Controls.Add($Label1) $Panel1.Controls.Add($TextBox1) $Panel1.Controls.Add($btnBrowse) $Panel1.Controls.Add($ProgressBar1) $Panel1.Controls.Add($btnExit) $Panel1.Controls.Add($DataGridView1) $Panel1.Controls.Add($Menu) $Form1.Controls.Add($Panel1) #~~< Ping1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $Ping1 = New-Object System.Net.NetworkInformation.Ping #~~< OpenFileDialog1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $OpenFileDialog1 = New-Object System.Windows.Forms.OpenFileDialog $OpenFileDialog1.Filter = "Text Files|*.txt|CSV Files|*.csv|All Files|*.*" $OpenFileDialog1.InitialDirectory = "C:" $OpenFileDialog1.Title = "Open Computers File" #~~< objNotifyIcon >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon # Assign an Icon and Icon Type For the NotifyIcon Object $objNotifyIcon.Icon = "D:\\Assaf\\Scripts\\Icons\\XP\\people15.ico" $objNotifyIcon.BalloonTipIcon = "Info" #endregion #region Functions function out-DataTable # Function Creates a New Data Table that will be set as the Data Source of the Data Grid View # Thanks to /\\/\\o\\/\\/ http:\\\\thePowerShellGuy.com { $dt = New-Object Data.datatable $First = $TRUE foreach ($item in $Input) { $DR = $DT.NewRow() $Item.PsObject.get_properties() | foreach { if ($first) { $Col = New-Object Data.DataColumn $Col.ColumnName = $_.Name.ToString() $DT.Columns.Add($Col) } if ($_.value -eq $null) { $DR.Item($_.Name) = "[empty]" } elseif ($_.IsArray) { $DR.Item($_.Name) = [string]::Join($_.value, ";") } else { $DR.Item($_.Name) = $_.value } } $DT.Rows.Add($DR) $First = $FALSE } return @(, ( $dt )) } function Join-Data # Function Joins arrays and Strings to a Single Object with Members # I Used the same principle of the Out-DataTable and converted it to Join Objects into one # Using the Add-Member cmdlet. the Function writes to a predefiend object named $DataObject { param($objName="") # This parameter is used for objects that don't have member other than Length like Strings foreach ($item in $Input) { $Item.PsObject.get_properties() | foreach{ if ($_.value -eq $null) { $DataObject | Add-Member noteproperty $_.Name "[empty]" } elseif ($_.IsArray) { $DataObject | Add-Member noteproperty $_.Name [string]::Join($_.value, ";") } elseif ($objName -ne "") { $DataObject | Add-Member noteproperty $objName $Item } else { $DataObject | Add-Member noteproperty $_.Name $_.value -Force } } } return @(,$DataObject) } function Get-Reg { # Function Connects to a remote computer Registry using the Parameters it recievs param( $Hive, $Key, $Value, $RemoteComputer="." # If not enterd Local Computer is Selected ) # Connect to Remote Computer Registry $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($Hive, $RemoteComputer) # Open Remote Sub Key $regKey= $reg.OpenSubKey($Key) if($regKey.ValueCount -gt 0) # check if there are Values {$regKey.GetValue($Value)} # Return Value } function Get-WMIItem { # Function Retreives a specific Item from a remote computer's WMI param( $Class, $RemoteComputer=".", # If not enterd Local Computer is Selected $Item, $Query="", # If not enterd an empty WMI SQL Query is Entered $Filter="" # If not enterd an empty Filter is Entered ) if ($Query -eq "") # No Specific WMI SQL Query { # Execute WMI Query, Return only the Requsted Items gwmi -Class $Class -ComputerName $RemoteComputer -Filter $Filter -Property $Item | Select $Item } else # User Entered a WMI SQL Query {gwmi -ComputerName $RemoteComputer -Query $Query | select $Item} } function Show-NotifyIcon { # Function Controls the Notification Icon # Changes its Title and Text param( $Title, $Text ) # Change Notify Icon Title $objNotifyIcon.BalloonTipTitle = $Title # Change Notify Icon Text $objNotifyIcon.BalloonTipText = $Text # Show Notify Icon for 10 Secs $objNotifyIcon.Visible = $TRUE $objNotifyIcon.ShowBalloonTip(10000) } #endregion #region Event Loop function Main # Main Function, Runs the Form { [System.Windows.Forms.Application]::EnableVisualStyles() [System.Windows.Forms.Application]::Run($Form1) } #endregion #region Event Handlers function BrowseFile($object) # Function for Running the OpenFileDialog # Used when Clicking on the Browse Button { $OpenFileDialog1.showdialog() $TextBox1.Text = $OpenFileDialog1.FileName $btnRun.Enabled = $TRUE } function Open-File( $object ){ # Function Open the Log File if(Test-Path $LogFile){ Invoke-Item $LogFile } } function Show-PopUp # Function for Showing Custom Pop up Forms { param( $PopupTitle, $PopupText ) #~~< PopupForm >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $PopupForm = New-Object System.Windows.Forms.Form $PopupForm.ClientSize = New-Object System.Drawing.Size(381, 356) $PopupForm.ControlBox = $false $PopupForm.ShowInTaskbar = $false $PopupForm.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterParent $PopupForm.Text = $PopupTitle #~~< PopupColse >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $PopupColse = New-Object System.Windows.Forms.Button $PopupColse.Anchor = ([System.Windows.Forms.AnchorStyles]([System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right)) $PopupColse.DialogResult = [System.Windows.Forms.DialogResult]::Cancel $PopupColse.Location = New-Object System.Drawing.Point(137, 321) $PopupColse.Size = New-Object System.Drawing.Size(104, 23) $PopupColse.TabIndex = 0 $PopupColse.Text = "Close" $PopupColse.UseVisualStyleBackColor = $true $PopupForm.AcceptButton = $PopupColse $PopupForm.CancelButton = $PopupColse #~~< PopupHeader >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $PopupHeader = New-Object System.Windows.Forms.Label $PopupHeader.Font = New-Object System.Drawing.Font("Calibri", 15.75, ([System.Drawing.FontStyle]([System.Drawing.FontStyle]::Bold -bor [System.Drawing.FontStyle]::Italic)), [System.Drawing.GraphicsUnit]::Point, ([System.Byte](0))) $PopupHeader.Location = New-Object System.Drawing.Point(137, 9) $PopupHeader.Size = New-Object System.Drawing.Size(104, 23) $PopupHeader.TabIndex = 2 $PopupHeader.Text = $PopupTitle $PopupHeader.TextAlign = [System.Drawing.ContentAlignment]::MiddleCenter #~~< PopUpTextArea >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $PopUpTextArea = New-Object System.Windows.Forms.Label $PopUpTextArea.Anchor = ([System.Windows.Forms.AnchorStyles]([System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right)) $PopUpTextArea.Location = New-Object System.Drawing.Point(12, 15) $PopUpTextArea.Size = New-Object System.Drawing.Size(357, 265) $PopUpTextArea.TabIndex = 1 $PopUpTextArea.Text = $PopupText $PopUpTextArea.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft $PopupForm.Controls.Add($PopupHeader) $PopupForm.Controls.Add($PopUpTextArea) $PopupForm.Controls.Add($PopupColse) # Show Form $PopupForm.Add_Shown({$PopupForm.Activate()}) [void]$PopupForm.showdialog() } function Show-About( $object ){ # Function Opens the About Page $AboutText = @(" Script Title: Remote Computer Inventory`n Script Author: Assaf Miron`n Script Description: Collects Remote Computer Data Using WMI and Registry Access Outputs all information to a Data Grid Form and to a CSV Log File.`n Log File Name: $LogFile") Show-Popup -PopupTitle "About" -PopupText $AboutText } function Show-HowTo( $object ){ # Function Opens the Help Page $HowToText = @(" 1. Click on the Browse Button and select a TXT or a CSV File Containing Computer Names`n 2. After File is Selected click on the Run Button.`n 3. You will see a Notify Icon with the Coresponding Text.`n 4. The Script has begon collecting Remote Computer Inventory!`n `nWhen The script is Done you will see a Popup Message and all data will be presented in the DataGrid.`n ** Because Poweshell works only in MTA mode there is no Option Copying the Data off the DataGrid...`n 5. All Data will be Exported to a Log File Located Here: $LogFile") Show-Popup -PopupTitle "How To?" -PopupText $HowToText } function CloseForm($object) # Function End the Program { $Form1.Close() } function RunScript($object) # Function Runs the Program and starts collecting data { # Create an Array of Computers Enterd in the Input File $arrComputers = Get-Content -path $textBox1.Text -encoding UTF8 # Create an Array to Keep all Computers Objects $AllComputers = @() # Init the Progress bar to it's Maximum Value if(($arrComputers -is [array]) -eq $FALSE) { $ProgressBar1.Maximum = 1 } else { $ProgressBar1.Maximum = $arrComputers.Count } $ProgressBar1.Minimum = 0 $ProgressBar1.Value = 0 $ProgressBar1.Step = 1 # Define the Progress bar Step value # Scan all Computers in the Array $arrComputers foreach ($strComputer in $arrComputers) { # Uses the Ping Command to check if the Computer is Alive if($Ping1.Send($strComputer).Status -eq "Success"){ Show-NotifyIcon -Title "Retriving Computer Information" -Text "Scanning $strComputer For Hardware Data" # Collect Computer Details from Win32_computersystem Using WMI $ComputerDet = Get-WMIItem -Class "Win32_computersystem" -RemoteComputer $strComputer -Item Caption,Domain,SystemType,Manufacturer,Model,NumberOfProcessors,TotalPhysicalMemory,UserName if($ComputerDet.Caption.Length -gt 1) # Check to See if Any data was Collected at all { #region Total Memory Formating # Check Total Physical Memory Size and Format it acourdingly if($ComputerDet.TotalPhysicalMemory -ge 1GB){ $ComputerDet.TotalPhysicalMemory = ($ComputerDet.TotalPhysicalMemory/1GB).Tostring("# GB")} # Format to GB else {$ComputerDet.TotalPhysicalMemory = ($ComputerDet.TotalPhysicalMemory/1MB).Tostring("# MB")} # Format to MB #endregion #region CPU Name # Collect CPU Name Using WMI $CPUName = Get-WMIItem -Class "Win32_Processor" -RemoteComputer $strComputer -Item Name # CPU Names Can Contain Multiple Values, in Order to Insert Them into the DataGridView I Divde them to String with ";" Seperators $arrCPUNames = @() foreach($CPU in $CPUName){ $arrCPUNames = $CPU.Name.Trim()+";"+$arrCPUNames # the Sting of the CPU Name has White Space in The Begining - Trim It } #endregion #region Operating System Data # Collect Operating System and Service Pack Information Usin WMI $OS = Get-WMIItem -Class "win32_operatingsystem" -RemoteComputer $strComputer -Item Caption,csdversion #endregion #region Chassis Type # Collect Machine Chassis Using WMI $ChassisType = Get-WMIItem -Class Win32_SystemEnclosure -RemoteComputer $strComputer -Item ChassisTypes # Select Machine Chassis switch ($ChassisType.ChassisTypes) { 1 {$ChassisType = "Other"} 2 {$ChassisType = "Unknown"} 3 {$ChassisType = "Desktop"} 4 {$ChassisType = "Low Profile Desktop"} 5 {$ChassisType = "Pizza Box"} 6 {$ChassisType = "Mini Tower"} 7 {$ChassisType = "Tower"} 8 {$ChassisType = "Portable"} 9 {$ChassisType = "Laptop"} 10 {$ChassisType = "Notebook"} 11 {$ChassisType = "Handheld"} 12 {$ChassisType = "Docking Station"} 13 {$ChassisType = "All-in-One"} 14 {$ChassisType = "Sub-Notebook"} 15 {$ChassisType = "Space Saving"} 16 {$ChassisType = "Lunch Box"} 17 {$ChassisType = "Main System Chassis"} 18 {$ChassisType = "Expansion Chassis"} 19 {$ChassisType = "Sub-Chassis"} 20 {$ChassisType = "Bus Expansion Chassis"} 21 {$ChassisType = "Peripheral Chassis"} 22 {$ChassisType = "Storage Chassis"} 23 {$ChassisType = "Rack Mount Chassis"} 24 {$ChassisType = "Sealed- PC"} default {$ChassisType = "Unknown"} } #endregion #region Automatic Updates # Collect the Automatic Updates Options Using Registry Access $AUOptions = Get-Reg -Hive LocalMachine -Key "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update" -Value "AUOptions" # Collect the Automatic Updates Install Day Using Registry Access $AUDay = Get-Reg -Hive LocalMachine -Key "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update" -Value "ScheduledInstallDay" # Collect the Automatic Updates Install Time Using Registry Access $AUTime = Get-Reg -Hive LocalMachine -Key "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update" -Value "ScheduledInstallTime" if($AUOptions -eq $null){ # Automatic Updates is defined in Group Policy $AUOptions = Get-Reg -Hive LocalMachine -Key "SOFTWARE\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU" -Value "AUOptions" $AUDay = Get-Reg -Hive LocalMachine -Key "SOFTWARE\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU" -Value "ScheduledInstallDay" $AUTime = Get-Reg -Hive LocalMachine -Key "SOFTWARE\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU" -Value "ScheduledInstallTime" } switch ($AUOptions){ # Check Wich Automatic Update Option is Selected 1 {$AUClient = "Automatic Updates is Turnd off."} 2 {$AUClient = "Notify for download and notify for install "} 3 {$AUClient = "Auto download and notify for install "} 4 { switch ($AUDay) # Check on What day the Automatic Update Installs { 0 {$InstDay = "Every Day"} 1 {$InstDay = "Sunday"} 2 {$InstDay = "Monday"} 3 {$InstDay = "Tuesday"} 4 {$InstDay = "Wensday"} 5 {$InstDay = "Thursday"} 6 {$InstDay = "Friday"} 7 {$InstDay = "Saturday"} } # Check on What time the Automatic Update Installs if ($AUTime -le 12) { $AUTime = $AUTime.ToString() + " AM" } else { $AUTime = ($AUTime -12) + " PM" } $AUClient = "Auto download and schedule the install - "+$InstDay+" "+$AUTime} Defualt {"Automatic Updates is not Set."} # No setting Collected } #endregion #region Computer Total Health # Collect Avialable Memory with WMI $AvialableMem = Get-WMIItem -Class "Win32_PerfFormattedData_PerfOS_Memory" -RemoteComputer $strComputer -Item "AvailableMBytes" # Collect Disk Queue,Queue Length, Processor time Data Using WMI $DiskQueue = Get-WMIItem -Class "Win32_PerfFormattedData_PerfDisk_LogicalDisk" -RemoteComputer $strComputer -Item CurrentDiskQueueLength $QueueLength = Get-WMIItem -Class "Win32_PerfFormattedData_PerfNet_ServerWorkQueues" -RemoteComputer $strComputer -Item QueueLength $Processor = Get-WMIItem -Class "Win32_PerfFormattedData_PerfOS_Processor" -RemoteComputer $strComputer -Item PercentProcessorTime $intHealth = 0 # integer for Collecting Computer Total Health # Using the Avialable Memory to Check Computer Totla Health if($AvialableMem.AvailableMBytes -lt 4) { $intHealth += 1; $strHealth += "Low Free Memory;" } # Using Current Disk Queue Length to Check Computer Total Health if($DiskQueue.CurrentDiskQueueLength -gt 2) { $intHealth += 1; $strHealth += "High Disk Queue;" } # Using Queue Length to Check Computer Total Health if($QueueLength.QueueLength -gt 4) { $intHealth += 1; $strHealth += "Long Disk Queue;" } # Using Processor Time(%) to Check Computer Total Health if($Processor.PercentProcessorTime -gt 90) { $intHealth += 1; $strHealth += "Processor Usage Over 90%;" } # If the integer is Bigger than 1 so the computer is Unhealthy, Describe Computer Problems # Else The Computer is Healthy if($intHealth -gt 1) { $ComputerTotalHealth = "UnHealthy, " + $strHealth } else { $ComputerTotalHealth = "Healthy" } #endregion #region Avialable Memory Formating # Format Avialable Memory MB $AvialableMem.AvailableMBytes = $AvialableMem.AvailableMBytes.ToString("# MB") #endregion #region Disk Drive Info # Collect Disk Drive Information Using WMI $DriveInfo = Get-WMIItem -Class "Win32_LogicalDisk" -RemoteComputer $strComputer -Item Caption,Size,FreeSpace # Format Every Drive Size and Free Space foreach($DRSize in $DriveInfo) { # Check Object Size and Format Acourdingly if($DRSize.Size -ge 1GB){ $DRSize.Size = ($DRSize.Size/1GB).ToString("# GB") } # Format to GB else { $DRSize.Size = ($DRSize.Size/1MB).ToString("# MB") } # Format to MB if($DRSize.FreeSpace -ge 1GB){ $DRSize.FreeSpace = ($DRSize.FreeSpace/1GB).ToString("# GB") } # Format to GB else { $DRSize.FreeSpace = ($DRSize.FreeSpace/1MB).ToString("# MB") } # Format to MB } # Disk Drives Can Contain Multiple Values, in Order to Insert Them into the DataGridView I divide them to Strings with ";" Seperators $arrDiskDrives = @() $arrDiskSize = @() $arrDiskFreeSpace = @() foreach($Drive in $DriveInfo){ $arrDiskDrives = $Drive.Caption+";"+$arrDiskDrives $arrDiskSize = $Drive.Size+";"+$arrDiskSize $arrDiskFreeSpace = $Drive.FreeSpace+";"+$arrDiskFreeSpace } #endregion #region IP Addresses # Collect IPAddresses Using WMI, Filter only Enabled IPs $IPAddress = Get-WmiItem -Class "Win32_NetworkAdapterConfiguration" -Filter "IPEnabled = True" -RemoteComputer $strComputer -Item IPAddress # IPAddress Can Contain Multiple Values, in Order to Insert Them into the DataGridView I divide them to Strings with ";" Seperators $arrIPAddress = @() foreach($IP in $IPAddress){ $arrIPAddress = $IP.IPAddress[0]+";"+$arrIPAddress } #endregion #region Time Zone # Collect Time Zone Information Using WMI $TimeZone = Get-WMIItem -Class "Win32_TimeZone" -RemoteComputer $strComputer -Item Bias,StandardName $TimeZone.Bias = $TimeZone.Bias/60 #endregion #region System Restore Status # Collect System Restore Information Using Remote Registry $SysRestoreStatus = Get-Reg -Hive LocalMachine -RemoteComputer $strComputer -Key "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SystemRestore" -Value "DisableSR" if ($SysRestoreStatus -eq 0) { $SysRestoreStatus = "Enabled" } else { $SysRestoreStatus = "Disabled" } #endregion #region Offline Files Status # Collect Offline Files Information Using Remote Registry $OfflineFolStatus = Get-Reg -Hive LocalMachine -RemoteComputer $strComputer -Key "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\NetCache" -Value "Enabled" if ($OfflineFolStatus -eq 1) { $OfflineFolStatus = "Enabled" } else { $OfflineFolStatus = "Disabled" } #endregion #region Printers # Collect Printers Information Using WMI $Printers = Get-WMIItem -Class "Win32_Printer" -RemoteComputer $strComputer -Item Name,PortName,Caption # Printers Contain Multiple Values, in Order to Insert Them into the DataGridView I divide them to Strings with ";" Seperators $arrPrinters = @() foreach($Printer in $Printers){ $arrPrinters = $Printer.Name+"("+$Printer.PortName+");"+$arrPrinters } #endregion #region BIOS Serial Number # Collect BIOS Serial Number Using WMI $BIOSSN = Get-WMIItem -Class "Win32_Bios" -RemoteComputer $strComputer -Item SerialNumber #endregion #region Network Drives # Collect Network Drives Using WMI $NetDrives = Get-WMIItem -Query "Select * From Win32_LogicalDisk Where DriveType = 4" -RemoteComputer $strComputer -Item DeviceID,ProviderName # Network Drives Contain Multiple Values, in Order to Insert Them into the DataGridView I divide them to Strings with ";" Seperators $arrNetDrives = @() foreach($NetDrive in $NetDrives){ $arrNetDrives = $NetDrive.DeviceID+"("+$NetDrive.ProviderName+");"+$arrNetDrives } #endregion #region Anti-Virus Client Data # Collect Anti-Virus Info Using Remote Registry $AVParentServer = Get-Reg -Hive LocalMachine -RemoteComputer $strComputer -Key "SOFTWARE\\Intel\\LANDesk\\VirusProtect6\\CurrentVersion" -Value "Parent" # Read the Anti-Virus Virus Definition File and Format it to an actual Date $VirusDefFile = "C:\\Program Files\\Common Files\\Symantec Shared\\VirusDefs\\definfo.dat" If(Test-Path $VirusDefFile){ $AVDefs = Get-Content $VirusDefFile | where { $_ -match "CurDefs" } $AVDefs = $AVDefs.Substring(8) $AVDefs = [datetime]($AVDefs.Substring(5,1) + "/" + $AVDefs.Substring(6,2) + "/" + $AVDefs.substring(0,4)) } Else { $AVDefs = "" } #endregion #region Operating Systems Hotfixes # Collect all Hotfix Information Using WMI $HotFixes = Get-WMIItem -Class "Win32_QuickFixEngineering" -RemoteComputer $strComputer -Item Description,HotFixID,ServicePackInEffect # HotFixes Contain Multiple Values, in Order to Insert Them into the DataGridView I divide them to Strings with ";" Seperators $arrHotFixes = @() foreach($Fix in $HotFixes){ if($Fix.Description -eq ""){ if($Fix.HotFixID -eq "File 1"){ $arrHotFixes = $Fix.ServicePackInEffect+";"+$arrHotFixes } else { $arrHotFixes =$Fix.HotFixID+";"+$arrHotFixes } } else { $arrHotFixes = $Fix.Description+";"+$arrHotFixes } } #endRegion #region Remote Desktop Status # Collect Remote Desktop Protocol Status Using Remote Registry $RDPStatus = Get-Reg -Hive LocalMachine -remoteComputer $strComputer -Key "SYSTEM\\CurrentControlSet\\Control\\Terminal Server" -Value "fAllowToGetHelp" if($RDPStatus -eq 0) {$RDPStatus = "Enabled" } else {$RDPStatus = "Disabled" } #endregion #region Remote Assistance Status # Collect Remote Assistance Status Using Remote Registry $RAStatus = Get-Reg -Hive LocalMachine -remoteComputer $strComputer -Key "SYSTEM\\CurrentControlSet\\Control\\Terminal Server" -Value "fDenyTSConnections" if($RAStatus -eq 1) {$RAStatus = "Enabled" } else {$RAStatus = "Disabled" } #endregion # Change the Notify Icon to Show Exporting Text Show-NotifyIcon -Text "Exporting $strComputer Information" -Title "Exporting..." #region Check the Null Valued Paramters # If one of the Parameters are Null, Enter Space (looks better in the Table) if($ComputerDet -eq $Null){ $ComputerDet = " " } if($ChassisType -eq $Null){ $ChassisType = " " } if($BIOSSN -eq $Null){ $BIOSSN = " " } if($CPUName -eq $Null){ $CPUName = " " } if($AvialableMem -eq $Null){ $AvialableMem = " " } if($OS -eq $Null){ $OS = " " } if($SP -eq $Null){ $SP = " " } if($IPAddress -eq $Null){ $IPAddress = " " } if($HotFixes -eq $Null){ $HotFixes = " " } if($arrDiskDrives -eq $Null){ $arrDiskDrives=" " } if($arrDiskFreeSpace -eq $Null){ $arrDiskFreeSpace=" " } if($arrDiskSize -eq $Null){ $arrDiskSize=" " } if($RDPStatus -eq $Null){ $RDPStatus = " " } if($RAStatus -eq $Null){ $RAStatus = " " } if($AUClient -eq $Null){ $AUClient = " " } if($AVParentServer -eq $Null){ $AVParentServer = " " } if($AVDefs -eq $Null){ $AVDefs = " " } if($Printers -eq $Null){ $Printers = " " } if($ComputerTotalHealth -eq $Null){ $ComputerTotalHealth = " " } #endregion #region Creating the Data Object - $DataObject # Create an Empty psObject, $DataObjcet - Used by this Name in the Join-Data Function $DataObject = New-Object psobject # Join all the Data to the DataObject $ComputerDet | Join-Data # Contians Multiple Values, No need to Define a Name $ChassisType | Join-Data -objName "Chassis Type" # String with no Values - Define a Name $BIOSSN | Join-Data # Contians Multiple Values, No need to Define a Name $CPUName | Join-Data # Contians Multiple Values, No need to Define a Name $AvialableMem | Join-Data # Contians Multiple Values, No need to Define a Name $OS.Caption | Join-Data -objName "Operating System" # Contians Multiple Values, Caption Value canot be overwritten - Define a Name to a certian Value $OS.CsdVersion | Join-Data -objName "Service Pack" # String with no Values - Define a Name $arrIPAddress | Join-Data -objName "IP Addresses" # String with no Values - Define a Name $arrHotFixes| Join-Data -objName "HotFixes" # String with no Values - Define a Name $arrDiskDrives| Join-Data -objName "Disk Drives" # String with no Values - Define a Name $RDPStatus.ToString() | Join-Data -objName "Remote Desktop" # String with no Values - Define a Name $RAStatus.ToString() | Join-Data -objName "Remote Assistance" # String with no Values - Define a Name $AUClient | Join-Data -objName "Automatic Updates" # String with no Values - Define a Name $AVParentServer | Join-Data -objName "Anti-Virus Server" # String with no Values - Define a Name $AVDefs | Join-Data -objName "Anti-Virus Defs" # String with no Values - Define a Name $arrPrinters | Join-Data -objName "Printers" # String with no Values - Define a Name $ComputerTotalHealth | Join-Data -objName "Computer Totla Health" # String with no Values - Define a Name #endregion $AllComputers += $DataObject #region Exporting data # Export the DataObject to the DataGridView Using the out-DataTable $DataTable = $AllComputers | out-dataTable # Define Data Grid's Data Source to the DataTable we Created $DataGridView1.DataSource = $DataTable.psObject.baseobject $DataGridView1.Refresh() # Refresh the Table View in order to View the new lines # Export all the Data to the Log File $DataObject | Export-Csv -Encoding OEM -Path $LogFile #endregion } } else { # No Ping to Computer $objNotifyIcon.BalloonTipIcon = "Error" Show-NotifyIcon -Title "$strComputer is not avialable" -Text "No Ping to $strComputer.`nNo Data was Collected" $objNotifyIcon.BalloonTipIcon = "Info" } $ProgressBar1.PerformStep() } #region Finishing - Script is Done # Assign an Icon and Icon Type For the NotifyIcon Object $objNotifyIcon.Icon = "D:\\Assaf\\Scripts\\Icons\\XP\\people5.ico" $objNotifyIcon.BalloonTipIcon = "Info" # Pop Up a Message box $MSGObject = new-object -comobject wscript.shell $MSGResult = $MSGObject.popup("Script Has Finished Running!",0,"I'm Done",0) # Show Notify Icon with Finishing Text $objNotifyIcon.BalloonTipText = "Done!`nFile Saved in "+$LogFile $objNotifyIcon.Visible = $TRUE $objNotifyIcon.ShowBalloonTip(10000) $objNotifyIcon.Visible = $FALSE # Set to False so that the Notify Icon will Disapear after the Script is Done #endregion } Main # This call must remain below all other event functions #endregion
PowerShellCorpus/PoshCode/Get VMs on a LUN.ps1
Get VMs on a LUN.ps1
function Get-LunVM { param($Lun) Get-VM | Where { $_ | Get-Stat -stat disk.write.average -realtime -maxsamples 1 ` -erroraction SilentlyContinue | Where { $_.Instance -eq $Lun } } }
PowerShellCorpus/PoshCode/The Letter Diamond Oneli.ps1
The Letter Diamond Oneli.ps1
&{Param([char]$l)$s=66;$z=[int]$l;$o=$z-$s+ 5;$p=-1;$n=&{"$(" "*$o)A";([string[]][char[]]($s..$z))|%{$p+=2;$o--;"$(" "*$o)$_$(" "*$p)$_"}};$n;$n[$($n.Length-2)..0]}L
PowerShellCorpus/PoshCode/LoadModuleConfig_1.ps1
LoadModuleConfig_1.ps1
################################################################################ ## Script Name: LoadModuleConfig ## Created On: 01/21/2010 ## Author: Thell Fowler ## File: LoadModuleConfig.ps1 ## Usage: Called from the NestedModules value from a module manifest. ## Version: 1.0.1.0 ## Purpose: Provides automated loading of local configuration data. ## ## Requirements: PowerShell Version 2 ## Last Updated: 01/23/2010 ## History: ## 1.0.1.0 01/21/2010 - TBF - Made Add-Member calls forceful. ## 1.0.0.0 01/21/2010 - TBF - Initial implementation. ## ## ################################################################################ <# To make use of this script use new-modulemanifest to create a manifest named the with the same name as the manifest you are loading data for but with an extension of 'config.psd1' Enter LoadModuleConfig.ps1 in the NestedModules field. After creating the manifest open it in your editor and edit the PrivateData field to include hashes for LocalUser and Settings. After the Settings key add values as you see fit. Here is an example, as used in the FuncGuard module. # Private data to pass to the module specified in ModuleToProcess PrivateData = @{ "LocalUser" = @{ "Settings"=@{ "ActiveConfiguration" = "PSUnit" "Configurations"=@{ "PSUnit" =@{ "Name"="PSUnit"; "Path"=$(join-path -Path $Env:Temp -ChildPath "FuncGuard.PSUnit"); "Prefix"="PSUNIT" } } } } } After loading the module a global variable will be available with a name convention of $($ModuleName)Settings and the values can be accessed using normal hash retrieval. $config = $FuncGuardSettings["Configurations"].$($FuncGuardSettings["ActiveConfiguration"]) $Path = $config.Path #> #requires -version 2.0 Set-StrictMode -Version 2 $Module = $ExecutionContext.SessionState.Module if (! $Module) { throw ( New-Object System.Management.Automation.SessionStateException ` "An active module was not found! LoadModuleConfig must be run from a module manifest's NestedModules field.") } $ModuleName = $Module.Name.Replace(".config",$null) $AppData = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::LocalApplicationData) $ModuleConfigPath = join-path -Path $AppData ` -ChildPath "WindowsPowerShell\\Modules\\$ModuleName\\$ModuleName.config.xml" $configurations = $null if ( Test-Path $ModuleConfigPath -PathType Leaf ) { $configurations = Import-Clixml -Path $ModuleConfigPath } else { # Generate new default config file. $configurations = $Module.PrivateData.LocalUser.Settings Export-Clixml -InputObject $configurations -Path $ModuleConfigPath } if ($configurations) { Add-Member -InputObject $configurations -Name ModuleName -MemberType NoteProperty -force ` -Value $ModuleName Add-Member -InputObject $configurations -Name Export -MemberType ScriptMethod -force ` -Value { $AppData = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::LocalApplicationData) $ModuleConfigPath = join-path -Path $AppData ` -ChildPath "WindowsPowerShell\\Modules\\$ModuleName\\$($this.ModuleName).config.xml" Export-Clixml -InputObject $this -Path $ModuleConfigPath } Set-Variable -Name "$($ModuleName)Settings" -Value $($configurations) -Scope Global ` -Description "$($ModuleName) module configuration settings." }
PowerShellCorpus/PoshCode/scriptable telnet client_2.ps1
scriptable telnet client_2.ps1
function read-stream ([Parameter(Position=0,Mandatory=$true)][validatenotnull()] [System.Net.Sockets.NetworkStream]$stream, [String]$expect = "") { $buffer = new-object system.byte[] 1024 $enc = new-object system.text.asciiEncoding ## Read all the data available from the stream, writing it to the ## screen when done. ## Allow data to buffer start-sleep -m 100 $output = "" while($stream.DataAvailable -or $output -notmatch $expect) { $read = $stream.Read($buffer, 0, 1024) $output = "$output$($enc.GetString($buffer, 0, $read))" ## Allow data to buffer for a bit start-sleep -m 100 } $output.split("`n") } function send-command ([parameter(position=0,Mandatory=$true)][validatenotnull()] [String]$hostname, [parameter(position=1,Mandatory=$true)][validatenotnull()] [String]$User, [parameter(position=2,Mandatory=$true)][validatenotnull()] [String]$Password, [parameter(position=3,Mandatory=$true,valuefrompipeline=$true)][validatenotnull()] [String]$InputObject, [string]$Expect = "") { begin { $sock = new-object system.net.sockets.tcpclient($hostname,23) $str = $sock.GetStream() $wrt = new-object system.io.streamwriter($str) read-stream($str) $wrt.writeline($user) $wrt.flush() read-stream($str) $wrt.writeline($password) $wrt.flush() read-stream($str, $expect) } process { $wrt.writeline($InputObject) $wrt.flush() read-stream($str, $expect) } end { $wrt.writeline("exit") $wrt.flush() read-stream($str) ## Close the streams $wrt.Close() $str.Close() $sock.close() } }
PowerShellCorpus/PoshCode/Get-MemberBody.ps1
Get-MemberBody.ps1
#Requires ILSpy. #Tested with version 2.1.0.1603 #http://ilspy.net/ Add-Type -Path "Mono.Cecil.dll" Add-Type -Path "ICSharpCode.Decompiler.dll" [void][System.Reflection.Assembly]::LoadFrom("ILSpy.exe") function Get-MemberBody { [CmdletBinding()] param( [Parameter(ParameterSetName="MI")] [System.Reflection.MemberInfo]$memberInfo, [Parameter(ParameterSetName="MD",ValueFromPipeline=$true)] [Microsoft.PowerShell.Commands.MemberDefinition]$memberDefinition) Process { if ($memberDefinition -ne $null) { $type = [AppDomain]::CurrentDomain.GetAssemblies().GetTypes() | ? FullName -eq $memberDefinition.TypeName $declaringTypeName = $type.FullName $assembly = $type.Assembly.CodeBase.Replace("file:///", "").Replace("/", "\\") $memberName = $memberDefinition.Name $memberType = $memberDefinition.MemberType } else { $assembly = $memberInfo.DeclaringType.Assembly.CodeBase.Replace("file:///", "").Replace("/", "\\") $memberName = $memberInfo.Name $declaringTypeName = $memberInfo.DeclaringType.FullName } $AssemblyDefinition = [Mono.Cecil.AssemblyDefinition]::ReadAssembly($assembly) $Context = New-Object ICSharpCode.Decompiler.DecompilerContext -ArgumentList $AssemblyDefinition.MainModule $TextOutput = New-Object ICSharpCode.Decompiler.PlainTextOutput $Opts = New-Object ICSharpCode.ILSpy.DecompilationOptions $Lang = New-Object ICSharpCode.ILSpy.CSharpLanguage try { if ($memberType -eq "Method") { $CecilMethod = $AssemblyDefinition.MainModule.Types | ? FullName -eq $declaringTypeName | Select -ExpandProperty Methods | ? Name -eq $memberName $Lang.DecompileMethod($CecilMethod,$TextOutput,$Opts) } if ($memberType -eq "Property") { $CecilMember = $AssemblyDefinition.MainModule.Types | ? FullName -eq $declaringTypeName | Select -ExpandProperty Properties | ? Name -eq $memberName $Lang.DecompileProperty($CecilMember,$TextOutput,$Opts) } if ($memberType -eq "Event") { $CecilMember = $AssemblyDefinition.MainModule.Types | ? FullName -eq $declaringTypeName | Select -ExpandProperty Events | ? Name -eq $memberName $Lang.DecompileEvent($CecilMember,$TextOutput,$Opts) } if ($memberType -eq "Field") { $CecilMember = $AssemblyDefinition.MainModule.Types | ? FullName -eq $declaringTypeName | Select -ExpandProperty Fields | ? Name -eq $memberName $Lang.DecompileField($CecilMember,$TextOutput,$Opts) } } catch { Write-Error (New-Object -TypeName System.Exception -ArgumentList "Failed to decompile $declaringTypeName.$memberName", $Error[0].Exception) } $TextOutput.ToString() } }