full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PoshCode/Hex dump sample.ps1
|
Hex dump sample.ps1
|
C:\\WINDOWS\\system32
PS > hexdmp wsock32.dll
4d 5a 90 00 03 00 00 00 04 00 MZ........
00 00 ff ff 00 00 b8 00 00 00 ..ˇˇ......
00 00 00 00 40 00 00 00 00 00 ..........
e0 00 00 00 0e 1f ba 0e 00 b4 ‡.....∫...
09 cd 21 b8 01 4c cd 21 54 68 .Õ...LÕ.Th
69 73 20 70 72 6f 67 72 61 6d is.program
20 63 61 6e 6e 6f 74 20 62 65 .cannot.be
20 72 75 6e 20 69 6e 20 44 4f .run.in.DO
53 20 6d 6f 64 65 2e 0d 0d 0a S.mode....
|
PowerShellCorpus/PoshCode/Get-LocalGroupMembership.ps1
|
Get-LocalGroupMembership.ps1
|
# #############################################################################
# NAME: FUNCTION-Get-LocalGroupMembership.ps1
#
# AUTHOR: Francois-Xavier Cat
# DATE: 2012/12/27
# EMAIL: fxcat@lazywinadmin.com
# WEBSITE: LazyWinAdmin.com
# TWiTTER: @lazywinadm
#
# COMMENT: This function get the local group membership on a local or remote
# machine using ADSI/WinNT. By default it will run on the localhost
# and check the group "Administrators".
#
# VERSION HISTORY
# 1.0 2012.12.27 Initial Version.
#
# #############################################################################
Function Get-LocalGroupMembership {
<#
.Synopsis
Get the local group membership.
.Description
Get the local group membership.
.Parameter ComputerName
Name of the Computer to get group members. Default is "localhost".
.Parameter GroupName
Name of the GroupName to get members from. Default is "Administrators".
.Example
Get-LocalGroupMembership
Description
-----------
Get the Administrators group membership for the localhost
.Example
Get-LocalGroupMembership -ComputerName SERVER01 -GroupName "Remote Desktop Users"
Description
-----------
Get the membership for the the group "Remote Desktop Users" on the computer SERVER01
.OUTPUTS
PSCustomObject
.INPUTS
Array
.Link
N/A
.Notes
NAME: Get-LocalGroupMembership
AUTHOR: Francois-Xavier Cat
WEBSITE: www.LazyWinAdmin.com
#>
[Cmdletbinding()]
Param (
[Parameter(ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
[string]$ComputerName = $env:COMPUTERNAME,
[string]$GroupName = "Administrators"
)
# Create the array that will contains all the output of this function
$Output = @()
# Get the members for the group and computer specified
$Group = [ADSI]"WinNT://$ComputerName/$GroupName"
$Members = @($group.psbase.Invoke("Members"))
# Format the Output
$members | foreach {
$name = $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)
$class = $_.GetType().InvokeMember("Class", 'GetProperty', $null, $_, $null)
$path = $_.GetType().InvokeMember("ADsPath", 'GetProperty', $null, $_, $null)
# Find out if this is a local or domain object
if ($path -like "*/$ComputerName/*"){
$Type = "Local"
}
else {$Type = "Domain"
}
$Details = "" | Select ComputerName,Account,Class,Group,Path,Type
$Details.ComputerName = $ComputerName
$Details.Account = $name
$Details.Class = $class
$Details.Group = $GroupName
$details.Path = $path
$details.Type = $type
# Send the current result to the $output variable
$output = $output + $Details
}
# Finally show the Output to the user.
$output
}
|
PowerShellCorpus/PoshCode/ConvertFrom-SDDL.ps1
|
ConvertFrom-SDDL.ps1
|
filter ConvertFrom-SDDL
{
<#
.SYNOPSIS
Convert a raw security descriptor from SDDL form to a parsed security descriptor.
Author: Matthew Graeber (@mattifestation)
.DESCRIPTION
ConvertFrom-SDDL generates a parsed security descriptor based upon any string in raw security descriptor definition language (SDDL) form. ConvertFrom-SDDL will parse the SDDL regardless of the type of object the security descriptor represents.
.PARAMETER RawSDDL
Specifies the security descriptor in raw SDDL form.
.EXAMPLE
ConvertFrom-SDDL -RawSDDL 'D:PAI(A;;0xd01f01ff;;;SY)(A;;0xd01f01ff;;;BA)(A;;0x80120089;;;NS)'
.EXAMPLE
'O:BAG:SYD:(D;;0xf0007;;;AN)(D;;0xf0007;;;BG)(A;;0xf0005;;;SY)(A;;0x5;;;BA)', 'O:BAG:SYD:PAI(D;OICI;FA;;;BG)(A;OICI;FA;;;BA)(A;OICIIO;FA;;;CO)(A;OICI;FA;;;SY)' | ConvertFrom-SDDL
.INPUTS
System.String
ConvertFrom-SDDL accepts SDDL strings from the pipeline
.OUTPUTS
System.Management.Automation.PSObject
.LINK
http://www.exploit-monday.com
#>
Param (
[Parameter( Position = 0, Mandatory = $True, ValueFromPipeline = $True )]
[ValidateNotNullOrEmpty()]
[String[]]
$RawSDDL
)
Set-StrictMode -Version 2
# Get reference to sealed RawSecurityDescriptor class
$RawSecurityDescriptor = [Int].Assembly.GetTypes() | ? { $_.FullName -eq 'System.Security.AccessControl.RawSecurityDescriptor' }
# Create an instance of the RawSecurityDescriptor class based upon the provided raw SDDL
try
{
$Sddl = [Activator]::CreateInstance($RawSecurityDescriptor, [Object[]] @($RawSDDL))
}
catch [Management.Automation.MethodInvocationException]
{
throw $Error[0]
}
if ($Sddl.Group -eq $null)
{
$Group = $null
}
else
{
$SID = $Sddl.Group
$Group = $SID.Translate([Security.Principal.NTAccount]).Value
}
if ($Sddl.Owner -eq $null)
{
$Owner = $null
}
else
{
$SID = $Sddl.Owner
$Owner = $SID.Translate([Security.Principal.NTAccount]).Value
}
$ObjectProperties = @{
Group = $Group
Owner = $Owner
}
if ($Sddl.DiscretionaryAcl -eq $null)
{
$Dacl = $null
}
else
{
$DaclArray = New-Object PSObject[](0)
# System.Security.AccessControl.FileSystemRights contains the most generic forms of access rights.
# Because we don't necessarily know the object type ahead of time,
# this may lead to some false positives due to some overlap in access control types.
$EnumValueStrings = [Enum]::GetNames([System.Security.AccessControl.FileSystemRights])
$EnumValues = $EnumValueStrings | % { [System.Security.AccessControl.FileSystemRights] $_ }
foreach ($DaclEntry in $Sddl.DiscretionaryAcl)
{
$SID = $DaclEntry.SecurityIdentifier
$Account = $SID.Translate([Security.Principal.NTAccount]).Value
$Values = New-Object String[](0)
# Resolve access mask
foreach ($Value in $EnumValues)
{
if (($DaclEntry.Accessmask -band $Value) -eq $Value)
{
$Values += $Value.ToString()
}
}
$Access = [Security.AccessControl.FileSystemRights] "$($Values -join ',')"
$DaclTable = @{
Rights = $Access
IdentityReference = $Account
IsInherited = $DaclEntry.IsInherited
InheritanceFlags = $DaclEntry.InheritanceFlags
PropagationFlags = $DaclEntry.PropagationFlags
}
if ($DaclEntry.AceType.ToString().Contains('Allowed'))
{
$DaclTable['AccessControlType'] = [Security.AccessControl.AccessControlType]::Allow
}
else
{
$DaclTable['AccessControlType'] = [Security.AccessControl.AccessControlType]::Deny
}
$DaclArray += New-Object PSObject -Property $DaclTable
}
$Dacl = $DaclArray
}
$ObjectProperties['Access'] = $Dacl
$SecurityDescriptor = New-Object PSObject -Property $ObjectProperties
Write-Output $SecurityDescriptor
}
|
PowerShellCorpus/PoshCode/Get-UIChildItem.ps1
|
Get-UIChildItem.ps1
|
#requires -version 2.0
[CmdletBinding()]
param($Path)
<#
Quick check to see if we have necessary module...
#>
if (!(Get-Module ShowUI)) {
try {
Import-Module ShowUI
} catch {
Write-Warning "Can't load ShowUI module. I quit! For more details about error use -Verbose parameter."
Write-Verbose $_
}
}
<#
Show UI builds UI structure...
#>
Show-UI -Parameters $Path {
param ($Path)
DockPanel -Height 400 {
ScrollViewer {
ItemsControl {
<#
Hash that will set common button's options and some effects...
#>
$Effect = @{
Effect = {
New-Object Windows.Media.Effects.BlurEffect -Property @{
Radius = 3
}
}
On_MouseEnter = {
$Clear = DoubleAnimation -From 3 -To 1 -Duration '0:0:0.5'
$DependencyRadius = $This.Effect.GetType()::RadiusProperty
$This.Effect.BeginAnimation($DependencyRadius,$Clear)
}
On_MouseLeave = {
$Blur = DoubleAnimation -From 1 -To 3 -Duration '0:0:0.5'
$DependencyRadius = $This.Effect.GetType()::RadiusProperty
$This.Effect.BeginAnimation($DependencyRadius,$Blur)
}
}
<#
Time to read our folder. We ignore folders, only files will be listed.
As you can see it's pretty easy to pass $Path parameter to UI, and it's not global... :)
#>
foreach ($File in Get-ChildItem $Path | where { !$_.PSIsContainer } ) {
Button @Effect -Content $File.Name -On_Click ([scriptblock]::Create(@"
Write-UIOutput $($File.FullName)
`$ShowUI.ActiveWindow.Close()
"@)) -ToolTip "File size: $($File.Length) bytes, Last modified: $($File.LastWriteTime.ToShortDateString())"
}
} # END ItemsControl
} # END ScrollViewer
} # END DockPanel
} # END Show-UI
|
PowerShellCorpus/PoshCode/Run-Query (SharePoint)_4.ps1
|
Run-Query (SharePoint)_4.ps1
|
function Run-Query($siteUrl, $queryText)
{
[reflection.assembly]::loadwithpartialname("microsoft.sharePOint") | out-null
[reflection.assembly]::loadwithpartialname("microsoft.office.server") | out-null
[reflection.assembly]::loadwithpartialname("microsoft.office.server.search") | out-null
$s = [microsoft.sharepoint.spsite]$siteUrl
$q = new-object microsoft.office.server.search.query.fulltextsqlquery -arg $s
$q.querytext = $queryText
$q.RowLimit = 100
$q.ResultTypes = "RelevantResults"
$dt = $q.Execute()
$r = $dt["RelevantResults"]
$output = @()
while ($r.Read()) {
$o = new-object PSObject
0..($r.FieldCount-1) | foreach {
add-member -inputObject $o -memberType "NoteProperty" -name $r.GetName($_) -value $r[$_].ToString()
}
$output += $o
}
return $output
}
@@
@@
@@#Sample usage:
@@#Run-Query -siteUrl "http://dev/" -queryText "SELECT PreferredName, WorkPhone FROM SCOPE() WHERE ""scope""='People' AND PreferredName LIKE '%JIM%'"
@@
@@
|
PowerShellCorpus/PoshCode/ResetOutlookLivePassword.ps1
|
ResetOutlookLivePassword.ps1
|
function Reset-OutlookLivePassword {
<#
.SYNOPSIS
Resets an Outlook Live account password.
.DESCRIPTION
The Reset-OutlookLivePassword function resets an Outlook Live (Live@edu) acccount password.
A remote session is opened to the Outlook Live service. Connecting to the remote service requires administrative credentials to
Outlook Live. The function optionally stores the credential for subsequent use with the SaveCredential parameter.
The stored credential is protected using the Windows Data Protection API (DPAPI).
.PARAMETER Identity
Specifies the identity of the Outlook Live user account. Acceptable values include:
* User principal name (UPN)
.PARAMETER Password
Specifies a new password for the account.
A plain text string may be supplied or by not specifing the parameter a prompt for secure entry will appear.
.PARAMETER ResetPasswordOnNextLogon
Specifies that the user will be forced to reset their password at next logon.
.PARAMETER Credential
Specifies a credential for connecting to the Outlook Live remote session.
.PARAMETER SaveCredential
Specifies that the credential provided to connect to the Outlook Live remote session will be saved for subsequent use.
The Windows Data Protection API (DPAPI) is used to encrypt the password string representation.
.EXAMPLE
Reset-OutlookLivePassword unique.name@mydomain.edu
Resets the Outlook Live password on the account unique.name@mydomain.edu to the password specified in a secure entry prompt.
.EXAMPLE
Reset-OutlookLivePassword unique.name@mydomain.edu -Password HelloDave
Resets the Outlook Live password on the account unique.name@mydomain.edu to the password HelloDave.
.EXAMPLE
Reset-OutlookLivePassword unique.name@mydomain.edu -Password HelloDave -SaveCredential
Resets the Outlook Live password on the account unique.name@mydomain.edu to the password HelloDave and saves the remote session credential.
.INPUTS
System.String, System.Security.SecureString
.OUTPUTS
None
.NOTES
Name: Reset-OutlookLivePassword
Author: Rich Kusak
Created: 2010-07-30
LastEdit: 2011-08-28 16:27
Version: 2.0.0.0
.LINK
http://outlookliveanswers.com/forums/p/10/15.aspx
#>
[CmdletBinding(DefaultParameterSetName='Default', SupportsShouldProcess=$true)]
param (
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
[string]$Identity,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[ValidateScript({
if ($_ -is [System.String] -or $_ -is [System.Security.SecureString]) {$true} else {
throw "The argument '$_' is not of type System.String or System.Security.SecureString."
}
})]
$Password = (Read-Host 'Enter New Password' -AsSecureString),
[Parameter(ValueFromPipelineByPropertyName=$true)]
[switch]$ResetPasswordOnNextLogon,
[Parameter(ParameterSetName='Default', ValueFromPipelineByPropertyName=$true)]
[Parameter(ParameterSetName='Save', Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[System.Management.Automation.PSCredential]$Credential,
[Parameter(ParameterSetName='Save', ValueFromPipelineByPropertyName=$true)]
[switch]$SaveCredential
)
begin {
function Save-Credential {
param ($Path, $Credential)
if (Test-Path $Path) {
$attribs = [IO.FileAttributes]('Normal')
Set-ItemProperty $Path -Name Attributes -Value $attribs -Force
}
New-Object PSObject -Property @{
'UserName' = $Credential.UserName
'Password' = $Credential.Password | ConvertFrom-SecureString
} | Export-Csv $Path -NoTypeInformation -Force
$attribs = [IO.FileAttributes]('Hidden', 'ReadOnly')
Set-ItemProperty $Path -Name Attributes -Value $attribs -Force
} # function Save-Credential
# The location where a credential will be saved
$psFolder = Split-Path $PROFILE
$credFile = Join-Path $psFolder -ChildPath 'b94437da-2522-4bd4-903f-4b3f8ec7132a.csv'
if (Test-Path $credFile) {
if ($Credential -and $SaveCredential) {
Write-Warning 'A saved credential already exists.'
do {
$prompt = Read-Host 'Do you want to overwrite the saved credential? (Y)es or (N)o.'
} until ('^Yes$|^No$' -match $prompt)
}
switch ($prompt) {
{$_ -match 'Y'} {
Write-Debug "Performing operation 'Save-Credential' on target '$credFile'."
Save-Credential -Path $credFile -Credential $Credential
$importedCredFile = Import-Csv $credFile
$liveUserName = $importedCredFile.UserName
$livePassword = $importedCredFile.Password | ConvertTo-SecureString
break
}
{$_ -match 'N'} {
$liveUserName = $Credential.UserName
$livePassword = $Credential.Password
break
}
default {
$importedCredFile = Import-Csv $credFile
$liveUserName = $importedCredFile.UserName
$livePassword = $importedCredFile.Password | ConvertTo-SecureString
}
} # switch
$liveCred = New-Object System.Management.Automation.PSCredential($liveUserName, $livePassword)
} else {
if (-not $Credential) {
try {
$Credential = Get-Credential -ErrorAction Stop
} catch {
throw $_
}
}
$liveCred = New-Object System.Management.Automation.PSCredential($Credential.UserName, $Credential.Password)
if ($SaveCredential) {
if (-not (Test-Path $psFolder)) {
New-Item $psFolder -ItemType Directory -Force | Out-Null
}
Write-Debug "Performing operation 'Save-Credential' on target '$credFile'."
Save-Credential -Path $credFile -Credential $Credential
}
}
# Remote session parameters
$connectionUri = 'https://ps.outlook.com/powershell/'
$newPSSessionParameters = @{
'ConfigurationName' = 'Microsoft.Exchange'
'ConnectionUri' = $connectionUri
'Credential' = $liveCred
'Authentication' = 'Basic'
'AllowRedirection' = $true
}
try {
Write-Debug "Performing operation 'New-PSSession' on target '$connectionUri'."
$session = New-PSSession @newPSSessionParameters -ErrorAction Stop
Write-Verbose "Successfully opened new remote session to '$connectionUri'."
if ($PSBoundParameters['Verbose']) {
$session
Write-Host
}
} catch {
throw $_
}
} # begin
process {
if ($Password -is [System.String]) {
Write-Debug "Performing operation 'ConvertTo-SecureString' on target 'Password'."
$Password = $Password | ConvertTo-SecureString -AsPlainText -Force
}
if ($PSBoundParameters['WarningAction']) {
$WarningAction = $PSBoundParameters['WarningAction']
} else {
$WarningAction = $WarningPreference
}
if ($PSBoundParameters['WhatIf']) {
$WhatIf = $PSBoundParameters['WhatIf']
} else {
$WhatIf = $WhatIfPreference
}
$setMailboxParameters = @{
'Identity' = $Identity
'Password' = $Password
'ResetPasswordOnNextLogon' = $ResetPasswordOnNextLogon
'WarningAction' = $WarningAction
'WhatIf' = $WhatIf
}
try {
Write-Debug "Performing operation 'Invoke-Command' on target '$($session.ComputerName)'."
# Invoke remote command to set a new password
Invoke-Command -Session $session -ArgumentList $setMailboxParameters -ErrorAction Stop -ScriptBlock {
param ($setMailboxParameters)
Set-Mailbox @setMailboxParameters
}
} catch {
return Write-Error $_
}
} # process
end {
Write-Debug "Performing operation 'Remove-PSSession' on target '$($session.ComputerName)'."
# Close the remote session
Remove-PSSession $session -ErrorAction Stop -WhatIf:$false
Write-Verbose "Successfully removed remote session to '$connectionUri'."
} # end
} # function Reset-OutlookLivePassword
|
PowerShellCorpus/PoshCode/copy-data.ps1
|
copy-data.ps1
|
function copy-data {
param($source, $dest)
$counter = 0
$files = Get-ChildItem $source -Force -Recurse
foreach($file in $files)
{
$status = "Copying file {0} of {1}: {2}" -f $counter, $files.count, $file.name
Write-Progress -Activity "Copyng Files" -Status $status -PercentComplete ($counter/$files.count * 100)
Copy-Item $file.pspath $dest -Force
$counter++
}
}
|
PowerShellCorpus/PoshCode/LibraryPrompt.ps1
|
LibraryPrompt.ps1
|
##############################################################################\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\nSet-StrictMode -Version Latest\n\nfunction Prompt\n{\n $id = 1\n $historyItem = Get-History -Count 1\n if($historyItem)\n {\n $id = $historyItem.Id + 1\n }\n\n Write-Host -ForegroundColor DarkGray "`n[$(Get-Location)]"\n Write-Host -NoNewLine "PS:$id > "\n $host.UI.RawUI.WindowTitle = "$(Get-Location)"\n\n "`b"\n}
|
PowerShellCorpus/PoshCode/Get-FSMORoleOwner_2.ps1
|
Get-FSMORoleOwner_2.ps1
|
Function Get-FSMORoleOwner {
<#
.SYNOPSIS
Retrieves the list of FSMO role owners of a forest and domain
.DESCRIPTION
Retrieves the list of FSMO role owners of a forest and domain
.NOTES
Name: Get-FSMORoleOwner
Author: Boe Prox
DateCreated: 06/9/2011
.EXAMPLE
Get-FSMORoleOwner
DomainNamingMaster : dc1.rivendell.com
Domain : rivendell.com
RIDOwner : dc1.rivendell.com
Forest : rivendell.com
InfrastructureOwner : dc1.rivendell.com
SchemaMaster : dc1.rivendell.com
PDCOwner : dc1.rivendell.com
Description
-----------
Retrieves the FSMO role owners each domain in a forest. Also lists the domain and forest.
#>
[cmdletbinding()]
Param ()
Try {
$forest = [system.directoryservices.activedirectory.Forest]::GetCurrentForest()
ForEach ($domain in $forest.domains) {
$forestproperties = @{
Forest = $Forest.name
Domain = $domain.name
SchemaMaster = $forest.SchemaRoleOwner
DomainNamingMaster = $forest.NamingRoleOwner
RIDOwner = $Domain.RidRoleOwner
PDCOwner = $Domain.PdcRoleOwner
InfrastructureOwner = $Domain.InfrastructureRoleOwner
}
$newobject = New-Object PSObject -Property $forestproperties
$newobject.PSTypeNames.Insert(0,"ForestRoles")
$newobject
}
}
Catch {
Write-Warning "$($Error)"
}
}
|
PowerShellCorpus/PoshCode/Set-WebConfig_1.ps1
|
Set-WebConfig_1.ps1
|
function Set-WebConfigSqlConnectionString {
param( [switch]$help,
[string]$configfile = $(read-host "Please enter a web.config file to read"),
[string]$connectionString = $(read-host "Please enter a connection string"),
[switch]$backup = $TRUE
)
$usage = "`$conString = `"Data Source=MyDBname;Initial Catalog=serverName;Integrated Security=True;User Instance=True`"`n"
$usage += "`"Set-WebConfigSqlConnectionString -configfile `"C:\\Inetpub\\wwwroot\\myapp\\web.config`" -connectionString `$conString"
if ($help) {Write-Host $usage}
$webConfigPath = (Resolve-Path $configfile).Path
$backup = $webConfigPath + ".bak"
# Get the content of the config file and cast it to XML and save a backup copy labeled .bak
$xml = [xml](get-content $webConfigPath)
#save a backup copy if requested
if ($backup) {$xml.Save($backup)}
$root = $xml.get_DocumentElement();
$root.connectionStrings.add.connectionString = $connectionString
# Save it
$xml.Save($webConfigPath)
}
|
PowerShellCorpus/PoshCode/PowerShell Template_7.ps1
|
PowerShell Template_7.ps1
|
Function new-script
{
$strName = $env:username
$date = get-date -format d
$name = Read-Host "Filename"
$email = Read-Host "eMail Address"
$file = New-Item -type file "c:\\Scripts\\$name.ps1" -force
add-content $file "#=========================================================================="
add-content $file "#"
add-content $file "# NAME: $name.ps1"
add-content $file "#"
add-content $file "# AUTHOR: $strName"
add-content $file "# EMAIL: $email"
add-content $file "#"
add-content $file "# COMMENT: "
add-content $file "#"
add-content $file "# You have a royalty-free right to use, modify, reproduce, and"
add-content $file "# distribute this script file in any way you find useful, provided that"
add-content $file "# you agree that the creator, owner above has no warranty, obligations,"
add-content $file "# or liability for such use."
add-content $file "#"
add-content $file "# VERSION HISTORY:"
add-content $file "# 1.0 $date - Initial release"
add-content $file "#"
add-content $file "#=========================================================================="
ii $file
}
|
PowerShellCorpus/PoshCode/Import-ADUser.ps1
|
Import-ADUser.ps1
|
#############################################################################\n##\n## Import-AdUser\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 users in Active Directory from the content of a CSV.\n\n.DESCRIPTION\n\nIn the user CSV, One column must be named "CN" for the user name.\nAll other columns represent properties in Active Directory for that user.\n\nFor example:\nCN,userPrincipalName,displayName,manager\nMyerKen,Ken.Myer@fabrikam.com,Ken Myer,\nDoeJane,Jane.Doe@fabrikam.com,Jane Doe,"CN=MyerKen,OU=West,OU=Sales,DC=..."\nSmithRobin,Robin.Smith@fabrikam.com,Robin Smith,"CN=MyerKen,OU=West,OU=..."\n\n.EXAMPLE\n\nPS >$container = "LDAP://localhost:389/ou=West,ou=Sales,dc=Fabrikam,dc=COM"\nPS >Import-ADUser.ps1 $container .\\users.csv\n\n#>\n\nparam(\n ## The container in which to import users\n ## For example:\n ## "LDAP://localhost:389/ou=West,ou=Sales,dc=Fabrikam,dc=COM)")\n [Parameter(Mandatory = $true)]\n $Container,\n\n ## The path to the CSV that contains the user records\n [Parameter(Mandatory = $true)]\n $Path\n)\n\nSet-StrictMode -Off\n\n## Bind to the container\n$userContainer = [adsi] $container\n\n## Ensure that the container was valid\nif(-not $userContainer.Name)\n{\n Write-Error "Could not connect to $container"\n return\n}\n\n## Load the CSV\n$users = @(Import-Csv $Path)\nif($users.Count -eq 0)\n{\n return\n}\n\n## Go through each user from the CSV\nforeach($user in $users)\n{\n ## Pull out the name, and create that user\n $username = $user.CN\n $newUser = $userContainer.Create("User", "CN=$username")\n\n ## Go through each of the properties from the CSV, and set its value\n ## on the user\n foreach($property in $user.PsObject.Properties)\n {\n ## Skip the property if it was the CN property that sets the\n ## user name\n if($property.Name -eq "CN")\n {\n continue\n }\n\n ## Ensure they specified a value for the property\n if(-not $property.Value)\n {\n continue\n }\n\n ## Set the value of the property\n $newUser.Put($property.Name, $property.Value)\n }\n\n ## Finalize the information in Active Directory\n $newUser.SetInfo()\n}
|
PowerShellCorpus/PoshCode/Resolve-Aliases 1.7.ps1
|
Resolve-Aliases 1.7.ps1
|
#requires -version 2.0
## ResolveAliases Module v 1.6
########################################################################################################################
## Sample Use:
## Resolve-Aliases Script.ps1 | Set-Content Script.Resolved.ps1
## ls *.ps1 | Resolve-Aliases -Inplace
########################################################################################################################
## Version History
## 1.0 - First Version. "It worked on my sample script"
## 1.1 - Now it parses the $(...) blocks inside strings
## 1.2 - Some tweaks to spacing and indenting (I really gotta get some more test case scripts)
## 1.3 - I went back to processing the whole script at once (instead of a line at a time)
## Processing a line at a time makes it impossible to handle Here-Strings...
## I'm considering maybe processing the tokens backwards, replacing just the tokens that need it
## That would mean I could get rid of all the normalizing code, and leave the whitespace as-is
## 1.4 - Now resolves parameters too
## 1.5 - Fixed several bugs with command resolution (the ? => ForEach-Object problem)
## - Refactored the Resolve-Line filter right out of existence
## - Created a test script for validation, and
## 1.6 - Added resolving parameter ALIASES instead of just short-forms
## 1.7 - Minor tweak to make it work in CTP3
##
## * *TODO:* Put back the -FullPath option to resolve cmdlets with their snapin path
## * *TODO:* Add an option to put #requires statements at the top for each snapin used
########################################################################################################################
function which {
PARAM( [string]$command )
# aliases, functions, cmdlets, scripts, executables, normal files
$cmds = @(Get-Command $command -EA "SilentlyContinue")
if($cmds.Count -gt 1) {
$cmd = @( $cmds | Where-Object { $_.Name -match "^$([Regex]::Escape($command))" })[0]
} else {
$cmd = $cmds[0]
}
if(!$cmd) {
$cmd = @(Get-Command "Get-$command" -EA "SilentlyContinue" | Where-Object { $_.Name -match "^Get-$([Regex]::Escape($command))" })[0]
}
if( $cmd.CommandType -eq "Alias" ) {
$cmd = which $cmd.Definition
}
return $cmd
}
function Resolve-Aliases
{
[CmdletBinding(ConfirmImpact="low",DefaultParameterSetName="Files")]
Param (
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Text")]
[string]$Line
,
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Files")]
[Alias("FullName","PSChildName","PSPath")]
[IO.FileInfo]$File
,
[Parameter(Position=1, ParameterSetName="Files")]
[Switch]$InPlace
)
BEGIN {
Write-Debug $PSCmdlet.ParameterSetName
}
PROCESS {
if($PSCmdlet.ParameterSetName -eq "Files") {
if($File -is [System.IO.FileInfo]){
$Line = ((Get-Content $File) -join "`n")
} else {
throw "We can't resolve a whole folder at once yet"
}
}
$Tokens = [System.Management.Automation.PSParser]::Tokenize($Line,[ref]$null)
for($t = $Tokens.Count; $t -ge 0; $t--) {
$token = $Tokens[$t]
# DEBUG $token | fl * | out-host
switch($token.Type) {
"Command" {
$cmd = which $token.Content
Write-Debug "Command $($token.Content) => $($cmd.Name)"
#if($cmd.CommandType -eq "Alias") {
$Line = $Line.Remove( $token.Start, $token.Length ).Insert( $token.Start, $cmd.Name )
#}
}
"CommandParameter" {
Write-Debug "Parameter $($token.Content)"
for($c = $t; $c -ge 0; $c--) {
if( $Tokens[$c].Type -eq "Command" ) {
$cmd = which $Tokens[$c].Content
# if($cmd.CommandType -eq "Alias") {
# $cmd = @(which $cmd.Definition)[0]
# }
$short = $token.Content -replace "^-?","^"
Write-Debug "Parameter $short"
$parameters = $cmd.ParameterSets | Select -expand Parameters
$param = @($parameters | Where-Object { $_.Name -match $short -or $_.Aliases -match $short} | Select -Expand Name -Unique)
if($param.Count -eq 1) {
$Line = $Line.Remove( $token.Start, $token.Length ).Insert( $token.Start, "-$($param[0])" )
}
break
}
}
}
}
}
switch($PSCmdlet.ParameterSetName) {
"Text" {
$Line
}
"Files" {
switch($File.GetType()) {
"System.IO.FileInfo" {
if($InPlace) {
$Line | Set-Content $File
} else {
$Line
}
}
default { throw "We can't resolve a whole folder at once yet" }
}
}
default { throw "ParameterSet: $($PSCmdlet.ParameterSetName)" }
}
}
}
|
PowerShellCorpus/PoshCode/New-Struct_1.ps1
|
New-Struct_1.ps1
|
## New-Struct
## Creates a Struct class and emits it into memory
## The Struct includes a constructor which takes the parameters in order...
##
## Usage:
## # Assuming you have a csv file with no header and columns: artist,name,length
## New-Struct Song @{
## Artist=[string];
## Name=[string];
## Length=[TimeSpan];
## }
## $songs = gc C:\\Scripts\\songlist.csv | % { new-object Song @($_ -split ",") }
##
function New-Struct {
param([string]$Name,[HashTable]$Properties)
switch($Properties.Keys){{$_ -isnot [String]}{throw "Invalid Syntax"}}
switch($Properties.Values){{$_ -isnot [type]}{throw "Invalid Syntax"}}
# CODE GENERATION MAGIKS!
$code = @"
using System;
public struct $Name {
$($Properties.Keys | % { " public {0} {1};`n" -f $Properties[$_],($_.ToUpper()[0] + $_.SubString(1)) })
public $Name ($( [String]::join(',',($Properties.Keys | % { "{0} {1}" -f $Properties[$_],($_.ToLower()) })) )) {
$($Properties.Keys | % { " {0} = {1};`n" -f ($_.ToUpper()[0] + $_.SubString(1)),($_.ToLower()) })
}
}
"@
## Obtains an ICodeCompiler from a CodeDomProvider class.
$provider = New-Object Microsoft.CSharp.CSharpCodeProvider
## Get the location for System.Management.Automation DLL
$dllName = [PsObject].Assembly.Location
## Configure the compiler parameters
$compilerParameters = New-Object System.CodeDom.Compiler.CompilerParameters
$assemblies = @("System.dll", $dllName)
$compilerParameters.ReferencedAssemblies.AddRange($assemblies)
$compilerParameters.IncludeDebugInformation = $true
$compilerParameters.GenerateInMemory = $true
$compilerResults = $provider.CompileAssemblyFromSource($compilerParameters, $code)
if($compilerResults.Errors.Count -gt 0) {
$compilerResults.Errors | % { Write-Error $_.Line + ":`t" + $_.ErrorText }
}
}
|
PowerShellCorpus/PoshCode/Move-VMThin SVMotion.ps1
|
Move-VMThin SVMotion.ps1
|
function Move-VMThin {
PARAM(
[Parameter(Mandatory=$true,ValueFromPipeline=$true,HelpMessage="Virtual Machine Objects to Migrate")]
[ValidateNotNullOrEmpty()]
[System.String]$VM
,[Parameter(Mandatory=$true,HelpMessage="Destination Datastore")]
[ValidateNotNullOrEmpty()]
[System.String]$Datastore
)
Begin {
#Nothing Necessary to process
} #Begin
Process {
#Prepare Migration info, uses .NET API to specify a transformation to thin disk
$vmView = Get-View -ViewType VirtualMachine -Filter @{"Name" = "$VM"}
$dsView = Get-View -ViewType Datastore -Filter @{"Name" = "$Datastore"}
#Abort Migration if free space on destination datastore is less than 50GB
if (($dsView.info.freespace / 1GB) -lt 50) {throw "Move-ThinVM ERROR: Destination Datastore $Datastore has less than 50GB of free space. This script requires at least 50GB of free space for safety. Please free up space or use the VMWare Client to perform this Migration"}
#Prepare VM Relocation Specificatoin
$spec = New-Object VMware.Vim.VirtualMachineRelocateSpec
$spec.datastore = $dsView.MoRef
$spec.transform = "sparse"
#Perform Migration
$vmView.RelocateVM($spec, $null)
} #Process
}
|
PowerShellCorpus/PoshCode/Robocopy Wrapper.ps1
|
Robocopy Wrapper.ps1
|
function Copy-Robocopy
{
param
(
[Parameter(Position=0, Mandatory=$true)]
[String] $Source,
[Parameter(Position=1, Mandatory=$true)]
[String] $Target,
[Parameter(Position=2, Mandatory=$false)]
[String[]] $Files = @("*.*"),
[Parameter(Position=3, Mandatory=$false)]
[String] $Options = ""
)
# Result
$Result = @{
"Params" = @{}
"Timing" = @{}
"Result" = @{}
}
# Define Log File
$LogFile = $ENV:TEMP + "\\Robocopy." + (Get-Date -UFormat "%Y%m%d.%H%M%S") + "." + (Get-Random -Minimum 1000 -Maximum 9999) + ".log"
# Remove Wrong Options
$Options = $Options.Replace('/NJH', "")
$Options = $Options.Replace('/NJS', "")
# Start Process
$Duration = Measure-Command { Start-Process -FilePath 'ROBOCOPY' -ArgumentList ('"' + $Source + '" "' + $Target + '" "' + [String]::Join('" "', $Files) + '" ' + $Options) -RedirectStandardOutput $LogFile -NoNewWindow -Wait }
# Import Robocopy Log
$Robocopy = Get-Content -Path $LogFile
# Line Numbers
$LineHeaderFirst = (0..($Robocopy.Count - 1) | Where-Object { $Robocopy[$_] -eq "-------------------------------------------------------------------------------" })[0]
$LineHeaderLast = (0..($Robocopy.Count - 1) | Where-Object { $Robocopy[$_] -eq "------------------------------------------------------------------------------" })[0]
$LineFooterFirst = (($Robocopy.Count - 1)..0 | Where-Object { $Robocopy[$_] -eq "------------------------------------------------------------------------------" })[0]
$LineFooterLast = ($Robocopy.Count - 1)
# Result Params
$Result["Params"]["Source"] = ([String]($Robocopy[$LineHeaderFirst + 5].Split(":", 2)[1].Trim()))
$Result["Params"]["Target"] = ([String]($Robocopy[$LineHeaderFirst + 6].Split(":", 2)[1].Trim()))
$Result["Params"]["Files"] = ([String]::Join(", ", (($LineHeaderFirst + 8)..($LineHeaderLast - 4) | ForEach-Object { $Robocopy[$_].Split(":", 2)[-1].Trim() })))
$Result["Params"]["Options"] = ([String]($Robocopy[$LineHeaderLast - 2].Split(":", 2)[1].Trim()))
# Result Timing
$Result["Timing"]["Duration"] = ([String]($Duration))
$Result["Timing"]["Started"] = ([String](Get-Date -Date $Robocopy[$LineHeaderFirst + 4].Split(":", 2)[1].Trim()))
$Result["Timing"]["Ended"] = ([String](Get-Date -Date $Robocopy[$LineFooterLast - 1].Split(":", 2)[1].Trim()))
# Result Result
for ($Line = ($LineFooterFirst + 3); $Line -le ($LineFooterFirst + 6); $Line++)
{
$Key = $Robocopy[$Line].Substring(02,07).Trim()
$Result["Result"][$Key] = @{}
for ($Col = 10; $Col -le 60; $Col += 10)
{
$Title = $Robocopy[$LineFooterFirst + 2].Substring($Col, 10).Trim()
$Title = $Title.Substring(0,1).ToUpper() + $Title.Substring(1).ToLower()
$Result["Result"][$Key][$Title] = $Robocopy[$Line].Substring($Col, 10).Trim()
}
}
# Return
return $Result
}
|
PowerShellCorpus/PoshCode/5a74e43a-a30a-486b-a5a6-349644cb654a.ps1
|
5a74e43a-a30a-486b-a5a6-349644cb654a.ps1
|
#You'll need admin perms on all the servers to run this...
Write-Host "ComputerName in White, then Local Groups in Green, Local Groups' Members in White"
#This feeds the script a list of server names (ServerList.txt, placed in the same directory)
#for which I want the Local Groups and all those groups' Members.
$x = Get-Content ServerList.txt
# this feeds each servername, one by one, into the process...
foreach ($j in $x) {
#The server name becomes variable $strComputer
$strComputer = "$j"
#The Server name then becomes the variable $strComputer, and its name
#is printed out in all CAPS
$computer = [ADSI]("WinNT://" + $strComputer + ",computer")
$g = $computer.name.ToString()
$g.ToUpper(); " "
#The local security groups on the Server is then found,
#and fed to the array $a
$group = $computer.psbase.children | where{$_.psbase.schemaclassname -eq "group"}
$a = @()
foreach ($member in $group.psbase.syncroot)
{$a += $member.name }
#Each Local Group Member is then printed (in white,and with a space) underneath its Group's name
#(Group name printed in green)
foreach ($i in $a) {
$group =[ADSI]"WinNT://$j/$i"
Write-Host "$i" -fore green
$members = @($group.psbase.Invoke("Members"))
$members | foreach { Write-Host " ",$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}
}
Write-host " "
Write-host " "
Write-host " "
}
|
PowerShellCorpus/PoshCode/ESXiMgmt module sample 3.ps1
|
ESXiMgmt module sample 3.ps1
|
#######################################################################################################################
# File: ESXiMgmt_machines_poweroff_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]$MachinePrefix,
[int]$OperationTimeout
)
# USAGE: .\\ESXiMgmt_machines_poweroff_sample.ps1 192.168.1.1 root 123 datastore3 XPSP2 10
cls
Set-StrictMode -Version Latest
Import-Module ESXiMgmt -Force;
Connect-ESXi -Server $Server -Port 443 `
-Protocol HTTPS -User $User -Password $Password `
-DatastoreName $DatastoreName;
$VerbosePreference = [System.Management.Automation.ActionPreference]::Continue;
$VMs = Get-VM *
foreach($vm in $VMs)
{
if ($vm.Name -like "$($MachinePrefix)*" -and `
$vm.PowerState -eq 1) #PoweredOn
{
Write-Verbose "$($vm.Name) is stopping";
Stop-ESXiVM -Server $Server `
-User $User -Password $Password `
-Id (Get-ESXiVMId $vm);
sleep -Seconds $OperationTimeout;
}
}
Disconnect-ESXi
# to restart virtual machines instead of shutdown them
# simply call the ESXiMgmt_machines_poweron_sample.ps1 script:
# USAGE: .\\ESXiMgmt_machines_poweron_sample.ps1 192.168.1.1 root 123 datastore3 host1ds3 XPSP2 300
|
PowerShellCorpus/PoshCode/Backup Cisco UCS FI.ps1
|
Backup Cisco UCS FI.ps1
|
<#
.Synopsis
Does a backup of a single UCS target.
.Description
Uses the UCS PowerTool cmdlet 'Backup-Ucs' and does all four types of UCS backup.
Filenames include the UCS name, date/time stamp, and backup type.
The backup directory is set by a variable in the script. If it doesn't exist the script will create. Since the backup files are XML I recommend enabling compression on the directory.
.Parameter Ucs
The UCS environment to backup. This can be either an IP address or the DNS name.
.Parameter CredentialFile
The location of the credential file to log on to the UCSM with. Defaults to the current directory.
.Example
Backup-mUcs.ps1 -Ucs ucspoc -CredentialPath C:\\Temp\\credentials.enc.xml
.Notes
NAME: Backup-mUcs.ps1
AUTHOR: Chris Monahan
LASTEDIT: 10/2/2012
KEYWORDS: UCS, PowerTool
.Link
http://batchlife.wordpress.com/2012/11/14/powershell-script-to-backup/
Requires -Powershell Version 2.0
Requires -Cisco PowerTool Version 0.99
Requires -Hal Rottenberg's PsCredential functions: http://poshcode.org/501 & http://halr9000.com/article/531
#>
<# Instructions for one time setup are at the bottom of the script #>
param($Ucs=$null, $CredentialFile=$null)
if ($Ucs -eq $null) { Write-Host "Enter the name/address of the UCS you're backing up" -BackgroundColor DarkYellow -ForegroundColor DarkRed; break }
if ($CredentialFile -eq $null) { Write-Host "Enter path to the credential file." -BackgroundColor DarkYellow -ForegroundColor DarkRed; break }
#-----------------------------
# Prep
#-----------------------------
#Static parameters
Set-Variable -Name ScriptDir -Value "\\\\server\\share" -Scope Local
Set-Variable -Name BackupPath -Value "C:\\Backups\\UCSM_Configuration_Backups" -Scope Local
Set-Variable -Name BackupTypes -Value ('config-system','config-logical','config-all','full-state')
Write-Verbose "`nStatic parameters`n-----------------`nScriptDir = $($ScriptDir)`nBackupPath = $($BackupPath)`nBackupTypes = $($BackupTypes)`n"
$errmailTo = "name@address"
$errmailFrom = "name@address"
$errmailSMTP = "emailserver"
If ( !(Test-Path $BackupPath) ) { mkdir $BackupPath }
. $ScriptDir\\Hals_PSCredentials.ps1
$UcsCred = Import-PsCredential -Path $CredentialFile
#-----------------------------
# Start doing the real work.
#-----------------------------
# Connect to the UCS
Connect-Ucs -Name $Ucs -Credential $UcsCred -ErrorVariable errConnectingUcs| select Ucs,UserName,Version
if ($errConnectingUcs -ne $null) {
$errmailBody = @()
$errmailBody += "$(Get-Now) - Error connecting to UCS`n`n"
$errmailBody += $errConnectingUcs
Send-MailMessage -From $errmailFrom -To $errmailTo -Subject "Backup-mUcs Error-- Failed connecting to $($Ucs)" -Body ($errmailBody | Out-String) -SmtpServer $errmailSMTP
break
}
# Get one of each type of UCS backup.
ForEach ($type in $backuptypes) {
Backup-Ucs -Type $type -PreservePooledValues -PathPattern ($BackupPath + '\\${ucs}_${yyyy}${MM}${dd}_${HH}${mm}_' + $type + '.xml') -ErrorVariable errBackupUcs
if ($errBackupUcs -ne $null) {
$errmailBody = @()
$errmailBody += "$(Get-Now) - Error running backup of type $($type)`n`n"
$errmailBody += $error[0]
Send-MailMessage -From $errmailFrom -To $errmailTo -Subject "Backup-mUcs Error-- On $($Ucs) backup of type $($type) failed" -Body ($errmailBody | Out-String) -SmtpServer $errmailSMTP
}
}
# Don't leave a stale session on the UCS
Disconnect-Ucs
<# One time setup
1- Copy script to SCRIPTHOST server for the datacenter you're working in.
$> copy \\\\server\\share\\Hals_PSCredentials.ps1 C:\\Scripts
2- Log on locally to the SCRIPTHOST with the service account the script will run under in Task Scheduler.
3- If necessary install the Cisco PowerTool module and configure it to load automatically in the PowerShell profile.
a- The PowerTool module can be copied from \\\\server\\share\\Modules to the same directory on the local scripthost.
b- The PowerShell profile may not exist yet. If it doesn't create file in the path specified by the "$profile" variable.
$> notepad $profile
1- Add the line "Import-Module C:\\Ops\\Modules\\CiscoUCSPowerTool\\CiscoUcsPS.psd1"
2- Save and exit the file
4- Create the credential file containing the UCS login credentials to use in the script. The credential file can only opened by the Windows user account that created it. That's why you have to log on with the Windows service account used to run the task in Task Scheduler. The Windows credentials encrypt the file, and inside the file are the UCS login username and password. You can store the credential files in any directory you want. The directory in the example is for demonstration.
$> mkdir C:\\Scripts\\CredentialFiles
$> . \\\\server\\share\\Hals_PSCredentials.ps1
$> $creds = Get-Credential # Username/password to login to the UCS with.
$> Export-PSCredential -Credential $creds -Path C:\\Scripts\\CredentialFiles\\somename.enc.xml
5- Copy \\\\vmscripthost201\\C$\\Scripts\\Run_Backup-mUcs.ps1 to the vmscripthost you're setting up.
a- This is the wrapper script that will be put into Task Scheduler. It will call Backup-mUcs.ps1 for each UCS environment to be backed up.
b- Edit the script so that it has the correct UCS DNS name(s) or IP address(es) for the datacenter you're configuring this for.
6- Test the script interactively first by running Backup-mUcs.ps1 and then by running Run_Backup-mUcs.ps1.
7- Add Run_Backup-mUcs.ps1 into Task Scheduler and test.
a- For now copy the Task Scheduler settings for the job from what's in the \\\\server Task Scheduler. May put the full instructions in later.
8- Verify the scripthost server is getting backed up somehow. Preferably as a normal OS level full backup by the backup group. The size of the backups for our UCS's so far for four UCS environments is 12MB a day.
#>
|
PowerShellCorpus/PoshCode/VMWare Quick Migration.ps1
|
VMWare Quick Migration.ps1
|
#########################################
#Name: VMWare Quick Migration Function
#Author: Justin Grote <jgrote NOSPAMAT enpointe DOT com>
#Credit: Inspired by Mike DiPetrillo's Quick Migration Script: http://www.mikedipetrillo.com/mikedvirtualization/2008/10/quick-migration-for-vmware-the-power-of-powershell.html
#Version: 0.1
#Last Revised: 31 July 2009
#
#Description: Performs the fucntional equivalent of a Hyper-V Quick Migration by suspending a VM,
# moving it to a new host, and resuming it. This does not require vMotion licensing.
# it works by providing required VM objects via the pipeline or the second argument,
# and specifying the Destination host in the first argument.
# The commeand accepts both text strings and VMHost objects for the VMHost Parameter
#
#Prerequisites:
# Powershell v1
# VMWare PowerCLI 4.0 (May work with earlier version but not tested)
#
#Instructions to Install: Save this script and import into your session with, for example, . C:\\temp\\quickmigrate.ps1
# You can also include it in your PowerCLI profile to have it automatically included.
#Command Usage: get-vm MyTestVM | Quick-MigrateVM "MyTestHost2"
#########################################
function QuickMigrate-VM {
PARAM(
$NewVMHost = ""
, [VMware.VimAutomation.Client20.VirtualMachineImpl]$VMsToMigrate = $null
)
BEGIN {
if (!$NewVMHost){
Write-Error "No Destination VMHost Specified. You must specify a host to migrate to. `n Example: Get-VM `"Test`" | QuickMigrate-VM `"Host1`""
break
}
elseif ($VMsToMigrate) {
Write-Output $InputObject | &($MyInvocation.InvocationName) -NewVMHost $newVMHost
}
else {
#If NewVMHost was provided as a String, convert it into a VMHost Object.
if ($NewVMHost.GetType().Name -eq "String") {
set-variable -name destinationVMHost -value (get-vmhost $NewVMHost) -scope 1
}
#Make sure that we have a VMHost object to work with.
if (! $destinationVMHost -or (! $destinationVMHost.GetType().Name -eq "VMHostImpl")) {
write-error "Destination VM Host was not found or you provided the wrong object type. Please provide a VMHostImpl object or specify the fully qualified name of a VM Host"
break
}
write-host -fore white "===Begin Quick Migration==="
}
}
PROCESS {
$step = 0
$skip = $false
#In the Event of an error, output the error, and skip the rest of the current item.
#This is a workaround for the fact that "continue" doesn't work in a function process loop.
trap {
write-host -fore yellow "`tSKIPPED: "$_.Exception.Message
set-variable -name skip -value ($true) -scope 1
continue
}
$vmToMigrate = $_
### Validation Checks
if($_ -is [VMware.VimAutomation.Client20.VirtualMachineImpl]) {
write-host -fore white "Quick Migrating $($vmToMigrate.Name) to $NewVMHost..."
}
else {
throw "Object Passed was not a Virtual Machine object. Object must be of type VMware.VimAutomation.Client20.VirtualMachineImpl."
}
# Check for connected devices
if (! $skip -and (get-cddrive $vmToMigrate).ConnectionState.Connected -ieq "TRUE") {
throw "Connected CD Drive. Please disconnect and try again."
}
if (! $skip -and (get-floppydrive $vmToMigrate).ConnectionState.Connected -ieq "TRUE") {
throw "Connected Floppy Drive. Please disconnect and try again."
}
# Make sure the current VM Host and the Destination Host are different.
$sourceVMHost = get-vmhost -vm $vmToMigrate
if (! $skip -and ($sourceVMHost.Name -eq $destinationVMHost.Name)) {
throw "Source and Destination Hosts are the same."
}
###Validation Complete, begin Migration
if (! $skip) {
$step++
write-host -fore cyan "`t$($step. Suspending" $vmToMigrate.Name"..."
$suspend = Suspend-VM -VM $vmToMigrate -confirm:$false
}
if (! $skip) {
$step++
write-host -fore cyan "`t($step). Moving" $vmToMigrate.Name "to" $destinationVMHost.Name"..."
$migrate = Get-VM $vmToMigrate | Move-VM -Destination $destinationVMHost
}
if (! $skip) {
$step++
write-host -fore cyan "`t($step). Resuming" $vmToMigrate.Name"..."
$resume = Start-VM -VM $vmToMigrate
}
write-host -fore green "`tCOMPLETED"
}
END { write-host -fore white "===END Quick Migration===" }
}
|
PowerShellCorpus/PoshCode/Get-Parameter 2.2.ps1
|
Get-Parameter 2.2.ps1
|
#Requires -version 2.0
#.Synopsis
# Enumerates the parameters of one or more commands
#.Notes
# With many thanks to Hal Rottenberg, Oisin Grehan and Shay Levy
# Version 0.80 - April 2008 - By Hal Rottenberg http://poshcode.org/186
# Version 0.81 - May 2008 - By Hal Rottenberg http://poshcode.org/255
# Version 0.90 - June 2008 - By Hal Rottenberg http://poshcode.org/445
# Version 0.91 - June 2008 - By Oisin Grehan http://poshcode.org/446
# Version 0.92 - April 2008 - By Hal Rottenberg http://poshcode.org/549
# - Added resolving aliases and avoided empty output
# Version 0.93 - Sept 24, 2009 - By Hal Rottenberg http://poshcode.org/1344
# Version 1.0 - Jan 19, 2010 - By Joel Bennett http://poshcode.org/1592
# - Merged Oisin and Hal's code with my own implementation
# - Added calculation of dynamic paramters
# Version 2.0 - July 22, 2010 - By Joel Bennett http://poshcode.org/get/2005
# - Now uses FormatData so the output is objects
# - Added calculation of shortest names to the aliases (idea from Shay Levy http://poshcode.org/1982, but with a correct implementation)
# Version 2.1 - July 22, 2010 - By Joel Bennett http://poshcode.org/2007
# - Fixed Help for SCRIPT file (script help must be separated from #Requires by an emtpy line)
# - Fleshed out and added dates to this version history after Bergle's criticism ;)
# Version 2.2 - July 29, 2010 - By Joel Bennett (This Version)
# - Fixed a major bug which caused Get-Parameters to delete all the parameters from the CommandInfo
#
#.Description
# Lists all the parameters of a command, by ParameterSet, including their aliases, type, etc.
#
# By default, formats the output to tables grouped by command and parameter set
#.Example
# Get-Command Select-Xml | Get-Parameter
#.Example
# Get-Parameter Select-Xml
#.Parameter Name
# The name of the command to get parameters for
#.Parameter ModuleName
# The name of the module which contains the command (this is for scoping)
#.Parameter Force
# Forces including the CommonParameters in the output
[CmdletBinding()]
##This is just script-file nesting stuff, so that you can call the SCRIPT, and after it defines the global function, it will call it.
param (
[Parameter(Position=1,ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
[string[]]$Name
,
[Parameter(Position=2,ValueFromPipelineByPropertyName=$true,Mandatory=$false)]
$ModuleName
,
[switch]$Force
)
Function global:Get-Parameter {
#.Synopsis
# Enumerates the parameters of one or more commands
#.Description
# Lists all the parameters of a command, by ParameterSet, including their aliases, type, etc.
#
# By default, formats the output to tables grouped by command and parameter set
#.Example
# Get-Command Select-Xml | Get-Parameter
#.Example
# Get-Parameter Select-Xml
#.Parameter Name
# The name of the command to get parameters for
#.Parameter ModuleName
# The name of the module which contains the command (this is for scoping)
#.Parameter Force
# Forces including the CommonParameters in the output
[CmdletBinding()]
param (
[Parameter(Position=1,ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
[string[]]$Name
,
[Parameter(Position=2,ValueFromPipelineByPropertyName=$true,Mandatory=$false)]
$ModuleName
,
[switch]$Force
)
begin {
$PropertySet = @( "Name",
@{n="Position";e={if($_.Position -lt 0){"Named"}else{$_.Position}}},
"Aliases",
@{n="Short";e={$_.Name}},
@{n="Type";e={$_.ParameterType.Name}},
@{n="ParameterSet";e={$paramset}},
@{n="Command";e={$command}},
@{n="Mandatory";e={$_.IsMandatory}},
@{n="Provider";e={$_.DynamicProvider}},
@{n="ValueFromPipeline";e={$_.ValueFromPipeline}},
@{n="ValueFromPipelineByPropertyName";e={$_.ValueFromPipelineByPropertyName}}
)
function Join-Object {
Param(
[Parameter(Position=0)]
$First
,
[Parameter(ValueFromPipeline=$true,Position=1)]
$Second
)
begin {
[string[]] $p1 = $First | gm -type Properties | select -expand Name
}
process {
$Output = $First | Select $p1
foreach($p in $Second | gm -type Properties | Where { $p1 -notcontains $_.Name } | select -expand Name) {
Add-Member -in $Output -type NoteProperty -name $p -value $Second."$p"
}
$Output
}
}
}
process{
foreach($cmd in $Name) {
if($ModuleName) { $cmd = "$ModuleName\\$cmd" }
$commands = @(Get-Command $cmd)
foreach($command in $commands) {
# resolve aliases (an alias can point to another alias)
while ($command.CommandType -eq "Alias") {
$command = @(Get-Command ($command.definition))[0]
}
if (-not $command) { continue }
$Parameters = @{}
foreach($provider in Get-PSProvider) {
$drive = "{0}\\{1}::\\" -f $provider.ModuleName, $provider.Name
Write-Verbose ("Get-Command $command -Args $drive | Select -Expand Parameters")
[Array]$MoreParameters = (Get-Command $command -Args $drive).Parameters.Values
[Array]$Dynamic = $MoreParameters | Where { $_.IsDynamic }
foreach($p in $MoreParameters | Where { $Dynamic -notcontains $_ } ){
$Parameters.($p.Name) = $p
}
# Write-Verbose "Drive: $Drive | Parameters: $($Parameters.Count)"
if($dynamic) {
foreach($d in $dynamic) {
if(Get-Member -input $Parameters.($d.Name) -Name DynamicProvider) {
Write-Debug ("ADD:" + $d.Name + " " + $provider.Name)
$Parameters.($d.Name).DynamicProvider += $provider.Name
} else {
Write-Debug ("CREATE:" + $d.Name + " " + $provider.Name)
$Parameters.($d.Name) = $Parameters.($d.Name) | Add-Member NoteProperty DynamicProvider @($provider.Name) -Passthru
}
}
}
}
## Calculate the shortest distinct parameter name -- do this BEFORE removing the common parameters or else.
foreach($p in $($Parameters.Keys))
{
$shortest="^"
foreach($char in [char[]]$p)
{
$shortest += $char
$Matches = ($Parameters.Keys -match $Shortest).Count
Write-Debug "$($shortest.SubString(1)) $Matches"
if($Matches -eq 1)
{
$Parameters.$p = $Parameters.$p | Add-Member NoteProperty Aliases ($Parameters.$p.Aliases + @($shortest.SubString(1).ToLower($PSUICulture))) -Force -Passthru
break
}
}
}
Write-Verbose "Parameters: $($Parameters.Count)`n $($Parameters | ft | out-string)"
foreach ($paramset in @($command.ParameterSets | Select -Expand "Name")){
foreach($parameter in $Parameters.Keys | Sort) {
Write-Verbose "Parameter: $Parameter"
if(!$Force -and ($Parameters.$Parameter.aliases -match "vb|db|ea|wa|ev|wv|ov|ob|wi|cf")) { continue }
if($Parameters.$Parameter.ParameterSets.ContainsKey($paramset) -or $Parameters.$Parameter.ParameterSets.ContainsKey("__AllParameterSets")) {
if($Parameters.$Parameter.ParameterSets.ContainsKey($paramset)) {
$output = Join-Object $Parameters.$Parameter $Parameters.$Parameter.ParameterSets.$paramSet
} else {
$output = Join-Object $Parameters.$Parameter $Parameters.$Parameter.ParameterSets.__AllParameterSets
}
Write-Output $Output | Select-Object $PropertySet | ForEach {
$null = $_.PSTypeNames.Insert(0,"System.Management.Automation.ParameterMetadata")
$null = $_.PSTypeNames.Insert(0,"System.Management.Automation.ParameterMetadataEx")
Write-Verbose "$(($_.PSTypeNames.GetEnumerator()) -join ", ")"
$_
}
}
}
}
}
}
}
}
# Since you can't update format data without a file that has a ps1xml ending, let's make one up...
$tempFile = "$([IO.Path]::GetTempFileName()).ps1xml"
Set-Content $tempFile @'
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<Controls>
<Control>
<Name>ParameterGroupingFormat</Name>
<CustomControl>
<CustomEntries>
<CustomEntry>
<CustomItem>
<Frame>
<LeftIndent>4</LeftIndent>
<CustomItem>
<Text>Command: </Text>
<ExpressionBinding>
<ScriptBlock>"{0}/{1}" -f $(if($_.command.ModuleName){$_.command.ModuleName}else{$_.Command.CommandType.ToString()+":"}),$_.command.Name</ScriptBlock>
</ExpressionBinding>
<NewLine/>
<Text>Set: </Text>
<ExpressionBinding>
<ScriptBlock>if($_.ParameterSet -eq "__AllParameterSets"){"Default"}else{$_.ParameterSet}</ScriptBlock>
</ExpressionBinding>
<NewLine/>
</CustomItem>
</Frame>
</CustomItem>
</CustomEntry>
</CustomEntries>
</CustomControl>
</Control>
</Controls>
<ViewDefinitions>
<View>
<Name>ParameterMetadataEx</Name>
<ViewSelectedBy>
<TypeName>System.Management.Automation.ParameterMetadataEx</TypeName>
</ViewSelectedBy>
<GroupBy>
<PropertyName>ParameterSet</PropertyName>
<CustomControlName>ParameterGroupingFormat</CustomControlName>
</GroupBy>
<TableControl>
<TableHeaders>
<TableColumnHeader>
<Label>Name</Label>
<Width>22</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Aliases</Label>
<Width>12</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Position</Label>
<Width>8</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Mandatory</Label>
<Width>9</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Pipeline</Label>
<Width>8</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>ByName</Label>
<Width>6</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Provider</Label>
<Width>15</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Type</Label>
</TableColumnHeader>
</TableHeaders>
<TableRowEntries>
<TableRowEntry>
<TableColumnItems>
<TableColumnItem>
<PropertyName>Name</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Aliases</PropertyName>
</TableColumnItem>
<TableColumnItem>
<!--PropertyName>Position</PropertyName-->
<ScriptBlock>if($_.Position -lt 0){"Named"}else{$_.Position}</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Mandatory</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>ValueFromPipeline</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>ValueFromPipelineByPropertyName</PropertyName>
</TableColumnItem>
<TableColumnItem>
<!--PropertyName>Provider</PropertyName-->
<ScriptBlock>if($_.Provider){$_.Provider}else{"All"}</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Type</PropertyName>
</TableColumnItem>
</TableColumnItems>
</TableRowEntry>
</TableRowEntries>
</TableControl>
</View>
</ViewDefinitions>
</Configuration>
'@
Update-FormatData -Append $tempFile
# This is nested stuff, so that you can call the SCRIPT, and after it defines the global function, we will call that.
Get-Parameter @PSBoundParameters
|
PowerShellCorpus/PoshCode/Easy Migration Tool v3.1.ps1
|
Easy Migration Tool v3.1.ps1
|
#Generated Form Function
function GenerateForm {
########################################################################
# Code Generated By: Richard Yaw
# Generated On: 09/12/2010
#
# Easy Migration Script for VMware (Version 2.1)
# - Added a "Reload Tasks" feature.
# - Fixed issue with the Undo feature for SVMotions.
# - Added snapshot check before doing SVMotions.
# - Added ability to VMotion VMs between clusters.
########################################################################
#region Import the Assemblies
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
#endregion
#region Generated Form Objects
$MigrationForm = New-Object System.Windows.Forms.Form
$Header = new-object System.Windows.Forms.Label
$MigrateButton = New-Object System.Windows.Forms.Button
$ClusterListBox = New-Object System.Windows.Forms.ListBox
$SourceHostListBox = New-Object System.Windows.Forms.ListBox
$SourceDBListBox = New-Object System.Windows.Forms.CheckedListBox
$SourceVMListBox = New-Object System.Windows.Forms.CheckedListBox
$DestinationListBox = New-Object System.Windows.Forms.ListBox
$vCenterLabel = New-Object System.Windows.Forms.Label
$VCTextBox = New-Object System.Windows.Forms.TextBox
$LoginButton = New-Object System.Windows.Forms.Button
$ClearMsgButton = New-Object System.Windows.Forms.Button
$UndoButton = New-Object System.Windows.Forms.Button
$UndoALLButton = New-Object System.Windows.Forms.Button
$ReloadTaskButton = New-Object System.Windows.Forms.Button
$SaveTaskButton = New-Object System.Windows.Forms.Button
$ClusterLabel = New-Object System.Windows.Forms.Label
$HostToHostButton = New-Object System.Windows.Forms.Button
$VMToHostButton = New-Object System.Windows.Forms.Button
$DBtoDBButton = New-Object System.Windows.Forms.Button
$VMtoDBButton = New-Object System.Windows.Forms.Button
$AllClustersCheckbox = New-Object System.Windows.Forms.CheckBox
$SourceButton = New-Object System.Windows.Forms.Button
$DestinationButton = New-Object System.Windows.Forms.Button
$ResetButton = New-Object System.Windows.Forms.Button
$ChangeVCButton = New-Object System.Windows.Forms.Button
$CloseButton = New-Object System.Windows.Forms.Button
$MessagesLabel = New-Object System.Windows.Forms.Label
$MessagesListBox = New-Object System.Windows.Forms.ListBox
$TaskLabel = New-Object System.Windows.Forms.Label
$TaskListBox = New-Object System.Windows.Forms.ListBox
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects
#----------------------------------------------
#Generated Event Script Blocks
#----------------------------------------------
#Provide Custom Code for events specified in PrimalForms.
$LoginButton_Click=
{
#TODO: Place custom script here
If ((Get-PSSnapin "VMware.VimAutomation.Core" -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin "VMware.VimAutomation.Core"
}
#Connect to vCenter
Connect-VIServer $VCTextBox.Text -ErrorAction SilentlyContinue
If (!$?)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show($($error[0]))
}
Else
{
$ClusterListBox.Enabled = $true
#Get Cluster
Get-Cluster | % { [void]$ClusterListBox.items.add($_.Name) }
If ($ClusterListBox.items -ne $null)
{
$LoginButton.Enabled = $false
$VCTextBox.Enabled = $false
$HostToHostButton.Enabled = $true
$VMToHostButton.Enabled = $true
$DBtoDBButton.Enabled = $true
$VMtoDBButton.Enabled = $true
$ResetButton.Enabled = $true
$ChangeVCButton.Enabled = $true
$ReloadTaskButton.Enabled = $true
#Generate a log file for this session
#$logfile = "C:\\TEMP\\EasyMigrate{0:dd-MM-yyyy_HHmmss}" -f (Get-Date) + ".log"
#$logheader = "Easy Migration Tool v2.1 - Log generated on " + (Get-Date)
#Out-File -InputObject $logheader -FilePath $logfile
#Out-File -InputObject "" -Append -FilePath $logfile
}
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$HostToHostButton_Click=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($ClusterName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Cluster.')
}
Else
{
$SourceHostListBox.Enabled = $true
$SourceHostListBox.Items.Clear()
#Get Hostnames in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | % { [void]$SourceHostListBox.items.add($_.Name) }
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceButton.Text = 'Source - Select One Host'
$DestinationButton.Text = 'Destination Host'
$SourceButton.Enabled = $true
$HostToHostButton.BackColor = [System.Drawing.Color]::lightblue
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$VMToHostButton_Click=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($ClusterName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Cluster.')
}
Else
{
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Add($SourceVMListBox)
$SourceVMListBox.Enabled = $true
$SourceVMListBox.Items.Clear()
#Get VMs in a Cluster
Get-Cluster -Name $ClusterName | Get-VM | % { [void]$SourceVMListBox.items.add($_.Name) }
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceButton.Text = 'Source - Select VMs'
$DestinationButton.Text = 'Destination Host'
$SourceButton.Enabled = $true
$VMToHostButton.BackColor = [System.Drawing.Color]::lightblue
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$DBtoDBButton_Click=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($ClusterName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Cluster.')
}
Else
{
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Add($SourceDBListBox)
$SourceDBListBox.Enabled = $true
$SourceDBListBox.Items.Clear()
#Get Datastores in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | Get-Datastore | Where-Object {$_.Name -notlike "*SCR01"} | Where-Object {$_.Name -notlike "DAS*"} | % { [void]$SourceDBListBox.items.add($_.Name) }
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceButton.Text = 'Source - Select a Datastore'
$DestinationButton.Text = 'Destination Datastore'
$SourceButton.Enabled = $true
$DBtoDBButton.BackColor = [System.Drawing.Color]::lightblue
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$VMToDBButton_Click=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($ClusterName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Cluster.')
}
Else
{
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Add($SourceVMListBox)
$SourceVMListBox.Enabled = $true
$SourceVMListBox.Items.Clear()
#Get VMs in a Cluster
Get-Cluster -Name $ClusterName | Get-VM | % { [void]$SourceVMListBox.items.add($_.Name) }
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceButton.Text = 'Source - Select VMs'
$DestinationButton.Text = 'Destination Datastore'
$SourceButton.Enabled = $true
$VMtoDBButton.BackColor = [System.Drawing.Color]::lightblue
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$SourceButton_OnClick=
{
#TODO: Place custom script here
$ClusterName = $ClusterListBox.SelectedItem
If ($SourceButton.Text -eq "Source - Select One Host")
{
$SourceHostname = $SourceHostListBox.SelectedItem
If ($SourceHostname -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Source Host.')
}
Else
{
#Get Hostnames in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | Where-Object {$_.Name -notlike "$SourceHostname"} | % { [void]$DestinationListBox.items.add($_.Name) }
$SourceHostListBox.Enabled = $false
$SourceButton.Enabled = $false
$AllClustersCheckbox.Enabled = $true
$DestinationListBox.Enabled = $true
$DestinationButton.Enabled = $true
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
If ($SourceButton.Text -eq "Source - Select VMs")
{
$SourceVMname = $SourceVMListBox.SelectedItem
If ($SourceVMname -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select One or More VMs.')
}
Else
{
if ($DestinationButton.Text -like "Destination Host")
{
#Get Hostnames in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | % { [void]$DestinationListBox.items.add($_.Name) }
}
Else
{
#Get Datastores in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | Get-Datastore | Where-Object {$_.Name -notlike "*SCR01"} | Where-Object {$_.Name -notlike "DAS*"} | % { [void]$DestinationListBox.items.add($_.Name) }
}
$DestinationListBox.Enabled = $true
$SourceVMListBox.Enabled = $false
$SourceButton.Enabled = $false
$AllClustersCheckbox.Enabled = $true
$DestinationButton.Enabled = $true
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
If ($SourceButton.Text -like "Source - Select a Datastore")
{
$SourceDBname = $SourceDBListBox.SelectedItem
If ($SourceDBname -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select One Datastore.')
}
Else
{
#Get Datastores in a Cluster
Get-Cluster -Name $ClusterName | Get-VMHost | Get-Datastore | Where-Object {$_.Name -notlike "*SCR01"} | Where-Object {$_.Name -notlike "DAS*"} | Where-Object {$_.Name -notlike "$SourceDBname"} | % { [void]$DestinationListBox.items.add($_.Name) }
$SourceDBListBox.Enabled = $false
$SourceButton.Enabled = $false
$DestinationListBox.Enabled = $true
$DestinationButton.Enabled = $true
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
}
$AllClustersCheckbox_Click=
{
#TODO: Place custom script here
$DestinationListBox.Items.Clear()
#List the hosts in all the clusters
Get-VMHost | % { [void]$DestinationListBox.items.add($_.Name) }
$AllClustersCheckbox.Enabled = $False
}
$DestinationButton_OnClick=
{
#TODO: Place custom script here
$DestinationName = $DestinationListBox.SelectedItem
If ($DestinationName -eq $null)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please Select a Destination.')
}
Else
{
$AllClustersCheckbox.Enabled = $False
$DestinationListBox.Enabled = $False
$DestinationButton.Enabled = $False
$MigrateButton.Enabled = $True
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$MigrationForm.WindowState = $InitialFormWindowState
}
}
}
$MigrateButton_OnClick=
{
#TODO: Place custom script here
If ($SourceButton.Text -eq "Source - Select One Host")
{
$SourceHostname = $SourceHostListBox.SelectedItem
$DestinationName = $DestinationListBox.SelectedItem
$VMs = Get-VMHost $SourceHostname | Get-VM
foreach($VM in $VMs)
{
Get-VM -Name $VM | Move-VM -Destination (Get-VMHost $DestinationName) -ErrorAction SilentlyContinue
If (!$?)
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because an exception occurred. Check the vCenter console for more details."
[void]$MessagesListBox.items.add($MsgLine)
}
Else
{
$d = Get-Date
$TaskLine = "$d - $VM migrated successfully from $SourceHostName to $DestinationName"
[void]$TaskListBox.items.add($TaskLine)
}
}
$SourceVMListBox.enabled = $true
$SourceButton.enabled = $true
$MigrateButton.Enabled = $false
$AllClustersCheckbox.Checked = $false
$DestinationListBox.Items.Clear()
$ClearMsgButton.Enabled = $true
$UndoButton.Enabled = $true
$UndoALLButton.Enabled = $true
$SaveTaskButton.Enabled = $true
}
If ($SourceButton.Text -eq "Source - Select VMs")
{
$DestinationName = $DestinationListBox.SelectedItem
If($DestinationButton.Text -eq "Destination Host")
{
foreach($VM in $SourceVMListBox.CheckedItems)
{
$SourceName = Get-VM -Name $VM | Get-VMHost | % {$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Destination (Get-VMHost $DestinationName) -ErrorAction SilentlyContinue
If (!$?)
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because an exception occurred. Check the vCenter console for more details."
[void]$MessagesListBox.items.add($MsgLine)
}
Else
{
$d = Get-Date
$line = "$d - $VM migrated successfully from $SourceName to $DestinationName."
[void]$TaskListBox.items.add($line)
}
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source host and the destination host are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
}
Else
{
foreach($VM in $SourceVMListBox.CheckedItems)
{
$VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024
$DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB}
$DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2}
$DBAvailableSpace = $DBFreeSpace - $DBReserved
$SnapshotCount = (Get-VM -Name $VM | Get-Snapshot | Measure-Object).Count
If ($VMsize -gt $DBAvailableSpace)
{
$VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024)
$DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024)
$DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024)
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)."
[void]$MessagesListBox.items.add($MsgLine)
}
ElseIf ($SnapshotCount -gt 0)
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because it has one or more snapshots."
[void]$MessagesListBox.items.add($MsgLine)
}
Else
{
$SourceName = Get-VM -Name $VM | Get-Datastore | % {$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Datastore ($DestinationName) -ErrorAction SilentlyContinue
If (!$?)
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because an exception occurred. Check the vCenter console for more details."
[void]$MessagesListBox.items.add($MsgLine)
}
Else
{
$d = Get-Date
$TaskLine = "$d - $VM migrated successfully from $SourceName to $DestinationName"
[void]$TaskListBox.items.add($TaskLine)
}
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source datastore and the destination datastore are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
}
}
$SourceVMListBox.enabled = $true
$SourceButton.enabled = $true
$MigrateButton.Enabled = $false
$AllClustersCheckbox.Checked = $false
$DestinationListBox.Items.Clear()
$ClearMsgButton.Enabled = $true
$UndoButton.Enabled = $true
$UndoALLButton.Enabled = $true
$SaveTaskButton.Enabled = $true
}
If ($SourceButton.Text -eq "Source - Select a Datastore")
{
$SourceDBname = $SourceDBListBox.SelectedItem
$DestinationName = $DestinationListBox.SelectedItem
$VMs = Get-Datastore -Name $SourceDBname | Get-VM
If($VMs.count -gt 0)
{
foreach($VM in $VMs)
{
$VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024
$DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB}
$DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2}
$DBAvailableSpace = $DBFreeSpace - $DBReserved
$SnapshotCount = (Get-VM -Name $VM | Get-Snapshot | Measure-Object).Count
If ($VMsize -gt $DBFreeSpace)
{
$VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024)
$DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024)
$DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024)
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)."
[void]$MessagesListBox.items.add($MsgLine)
}
ElseIf ($SnapshotCount -gt 0)
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because it has one or more snapshots."
[void]$MessagesListBox.items.add($MsgLine)
}
Else
{
Get-VM -Name $VM | Move-VM -Datastore ($DestinationName) -ErrorAction SilentlyContinue
If (!$?)
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because an exception occurred. Check the vCenter console for more details."
[void]$MessagesListBox.items.add($MsgLine)
}
Else
{
$d = Get-Date
$line = "$d - $VM migrated successfully from $SourceDBName to $DestinationName"
[void]$TaskListBox.items.add($line)
}
}
}
}
Else
{
$d = Get-Date
$MsgLine = "$d - No VM is present on the source datastore $SourceDBname."
[void]$MessagesListBox.items.add($MsgLine)
}
$SourceDBListBox.enabled = $true
$SourceButton.enabled = $true
$AllClustersCheckbox.Checked = $false
$DestinationListBox.Items.Clear()
$MigrateButton.Enabled = $false
$ClearMsgButton.Enabled = $true
$UndoButton.Enabled = $true
$UndoALLButton.Enabled = $true
$SaveTaskButton.Enabled = $true
}
}
$RESETButton_OnClick=
{
#TODO: Place custom script here
$ClusterListBox.Enabled = $true
$HostToHostButton.Enabled = $true
$VMToHostButton.Enabled = $true
$DBtoDBButton.Enabled = $true
$VMtoDBButton.Enabled = $true
$SourceHostListBox.Items.Clear()
$SourceDBListBox.Items.Clear()
$SourceVMListBox.Items.Clear()
$SourceButton.Enabled = $false
$SourceButton.Text = 'Source'
$AllClustersCheckbox.Checked = $false
$DestinationListBox.Items.Clear()
$DestinationButton.Enabled = $false
$DestinationButton.Text = 'Destination'
$MigrateButton.Enabled = $false
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Remove($SourceVMListBox)
$MigrationForm.Controls.Remove($SourceDBListBox)
$MigrationForm.Controls.Add($SourceHostListBox)
$HostToHostButton.BackColor = [System.Drawing.Color]::Transparent
$VMToHostButton.BackColor = [System.Drawing.Color]::Transparent
$DBtoDBButton.BackColor = [System.Drawing.Color]::Transparent
$VMtoDBButton.BackColor = [System.Drawing.Color]::Transparent
}
$ChangeVCButton_OnClick=
{
#TODO: Place custom script here
$VCTextBox.Text = ""
$VCTextBox.Enabled = $true
$LoginButton.Enabled = $true
$ClusterListBox.Items.Clear()
$ClusterListBox.Enabled = $false
$HostToHostButton.Enabled = $false
$VMToHostButton.Enabled = $false
$DBtoDBButton.Enabled = $false
$VMtoDBButton.Enabled = $false
$SourceHostListBox.Items.Clear()
$SourceDBListBox.Items.Clear()
$SourceVMListBox.Items.Clear()
$SourceButton.Enabled = $false
$SourceButton.Text = 'Source'
$AllClustersCheckbox.Checked = $false
$DestinationListBox.Items.Clear()
$DestinationButton.Enabled = $false
$DestinationButton.Text = 'Destination'
$MigrateButton.Enabled = $false
$ResetButton.Enabled = $false
$ChangeVCButton.Enabled = $false
$MessagesListBox.Items.Clear()
$TaskListBox.Items.Clear()
$MigrationForm.Controls.Remove($SourceHostListBox)
$MigrationForm.Controls.Remove($SourceVMListBox)
$MigrationForm.Controls.Remove($SourceDBListBox)
$MigrationForm.Controls.Add($SourceHostListBox)
$HostToHostButton.BackColor = [System.Drawing.Color]::Transparent
$VMToHostButton.BackColor = [System.Drawing.Color]::Transparent
$DBtoDBButton.BackColor = [System.Drawing.Color]::Transparent
$VMtoDBButton.BackColor = [System.Drawing.Color]::Transparent
#Disconnect from vCenter server
Disconnect-VIServer -Confirm:$false
}
$CloseButton_OnClick=
{
#TODO: Place custom script here
If ($VCTextBox.Text -ne "")
{
#Disconnect from vCenter server
Disconnect-VIServer -Confirm:$false
}
#Close Form
$MigrationForm.close()
}
$ClearMsgButton_Click=
{
#TODO: Place custom script here
If($MessagesListBox.items.count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('No messages to clear.')
}
Else
{
$MessagesListBox.items.clear()
}
}
$UndoButton_Click=
{
#TODO: Place custom script here
If ($TaskListBox.Items.Count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('The task list is empty.')
}
Else
{
If ($TaskListBox.SelectedItems.Count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Please select one or more tasks.')
}
Else
{
foreach($Task in $TaskListBox.SelectedItems)
{
$Task = $Task.split(" ")
$VM = $Task[3]
$DestinationName = $Task[7]
$a = $DestinationName.indexof("SAN")
If ($a -lt 0) #If Destination is NOT a datastore
{
#Perform VMotion
$SourceName = Get-VM -name $VM | Get-VMHost | %{$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Destination (Get-VMHost $DestinationName)
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source host and the destination host are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
Else
{
#Perform SVMotion
$VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024
$DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB}
$DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2}
$DBAvailableSpace = $DBFreeSpace - $DBReserved
$SnapshotCount = (Get-VM -Name $VM | Get-Snapshot | Measure-Object).Count
If ($VMsize -gt $DBAvailableSpace)
{
$VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024)
$DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024)
$DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024)
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)."
[void]$MessagesListBox.items.add($MsgLine)
}
ElseIf ($SnapshotCount -gt 0)
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because it has one or more snapshots."
[void]$MessagesListBox.items.add($MsgLine)
}
Else
{
$SourceName = Get-VM -Name $VM | Get-Datastore | % {$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Datastore ($DestinationName)
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source datastore and the destination datastore are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
}
}
While($TaskListBox.SelectedItems.Count -gt 0)
{
$TaskListBox.Items.Remove($TaskListBox.SelectedItems[0])
}
}
}
}
$UndoALLButton_Click=
{
#TODO: Place custom script here
If ($TaskListBox.Items.Count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('The task list is empty.')
}
Else
{
foreach($Task in $TaskListBox.Items)
{
$Task = $Task.split(" ")
$VM = $Task[3]
$DestinationName = $Task[7]
$a = $DestinationName.indexof("SAN")
If ($a -lt 0) #If Destination is NOT a datastore
{
#Perform VMotion
$SourceName = Get-VM -name $VM | Get-VMHost | %{$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Destination (Get-VMHost $DestinationName)
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source host and the destination host are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
Else
{
#Perform SVMotion
$VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024
$DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB}
$DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2}
$DBAvailableSpace = $DBFreeSpace - $DBReserved
$SnapshotCount = (Get-VM -Name $VM | Get-Snapshot | Measure-Object).Count
If ($VMsize -gt $DBAvailableSpace)
{
$VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024)
$DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024)
$DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024)
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)."
[void]$MessagesListBox.items.add($MsgLine)
}
ElseIf ($SnapshotCount -gt 0)
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because it has one or more snapshots."
[void]$MessagesListBox.items.add($MsgLine)
}
Else
{
$SourceName = Get-VM -Name $VM | Get-Datastore | % {$_.name}
If($SourceName -ne $DestinationName)
{
Get-VM -Name $VM | Move-VM -Datastore ($DestinationName)
}
Else
{
$d = Get-Date
$MsgLine = "$d - Cannot migrate $VM because the source datastore and the destination datastore are the same."
[void]$MessagesListBox.items.add($MsgLine)
}
}
}
}
$TaskListBox.Items.Clear()
}
}
$SaveTaskButton_Click=
{
#TODO: Place custom script here
If ($TaskListBox.items.count -eq 0)
{
[reflection.assembly]::loadwithpartialname('system.windows.forms')
[system.Windows.Forms.MessageBox]::show('Nothing to save to log file.')
}
Else
{
$SaveFileD = new-object System.Windows.Forms.SaveFileDialog
$SaveFileD.Filter = "Log Files (*.log)|*.log";
$SaveFileD.Title = "Save to a log file";
$SaveFileD.FilterIndex = 2;
$SaveFileD.RestoreDirectory = $true;
if ($SaveFileD.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK)
{
$FileName = $SaveFileD.FileName
$Tasks = $TaskListBox.items
$logheader = "Easy Migration Tool v2.1 - Log generated on " + (Get-Date)
#Save a log file for this session to a location selected by the user
Out-File -InputObject $logheader -FilePath $Filename
Out-File -InputObject "" -Append -FilePath $FileName
Out-File -InputObject $Tasks -Append -FilePath $FileName
}
}
}
$ReloadTaskButton_Click=
{
#TODO: Place custom script here
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
#$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "Log Files (*.log)|*.log"
if ($OpenFileDialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK)
{
$FileName = $OpenFileDialog.FileName
$LinesCount = (Get-Content $FileName).Count
$LogLines = Get-Content $FileName | Select -Last ($LinesCount - 2)
$TaskListBox.Items.Clear()
foreach ($LogLine in $LogLines)
{
[void]$TaskListBox.items.add($LogLine)
}
$ClearMsgButton.Enabled = $true
$UndoButton.Enabled = $true
$UndoALLButton.Enabled = $true
$SaveTaskButton.Enabled = $true
}
}
#----------------------------------------------
#region Generated Form Code
# Start Main Form
$MigrationForm.Text = 'Easy Migration Tool v2.1'
$MigrationForm.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$MigrationForm.Name = 'EasyMigrationForm'
$MigrationForm.StartPosition = "CenterScreen"
$MigrationForm.FormBorderStyle = "FixedDialog"
$MigrationForm.MaximizeBox = $false
$MigrationForm.MinimizeBox = $false
$MigrationForm.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 1030
$System_Drawing_Size.Height = 500
$MigrationForm.ClientSize = $System_Drawing_Size
# End Main Form
#Start Easy_Migration Header
$Header.Font = new-object System.Drawing.Font("Tahoma",10,[System.Drawing.FontStyle]::Bold)
$Header.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft
$Header.Text = 'Easy Migration Tool v2.1'
$Header.Location = new-object System.Drawing.Point(150,15)
$Header.Size = new-object System.Drawing.Size(230, 20)
$MigrationForm.Controls.Add($Header)
#End Easy_Migration Header
# Start vCenter Server Label
$vCenterLabel.TabIndex = 2
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 95
$System_Drawing_Size.Height = 20
$vCenterLabel.Size = $System_Drawing_Size
$vCenterLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$vCenterLabel.Text = 'vCenter Server:'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 15
$System_Drawing_Point.Y = 50
$vCenterLabel.Location = $System_Drawing_Point
$vCenterLabel.DataBindings.DefaultDataSourceUpdateMode = 0
$vCenterLabel.Name = 'vCenterLabel'
$MigrationForm.Controls.Add($vCenterLabel)
# End vCenter Server Label
# Start vCenter Textbox
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 120
$System_Drawing_Size.Height = 20
$VCTextBox.Size = $System_Drawing_Size
$VCTextBox.Font = new-object System.Drawing.Font("Tahoma",8)
$VCTextBox.DataBindings.DefaultDataSourceUpdateMode = 0
$VCTextBox.Name = 'VCTextBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 110
$System_Drawing_Point.Y = 50
$VCTextBox.Location = $System_Drawing_Point
$VCTextBox.TabIndex = 1
$MigrationForm.Controls.Add($VCTextBox)
# End vCenter Textbox
# Start Login Button
$LoginButton.TabIndex = 0
$LoginButton.Name = 'LoginButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 95
$System_Drawing_Size.Height = 25
$LoginButton.Size = $System_Drawing_Size
$LoginButton.Font = new-object System.Drawing.Font("Tahoma",8)
$LoginButton.UseVisualStyleBackColor = $True
$LoginButton.Text = 'Login'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 48
$LoginButton.Location = $System_Drawing_Point
$LoginButton.DataBindings.DefaultDataSourceUpdateMode = 0
$LoginButton.add_Click($LoginButton_Click)
$MigrationForm.Controls.Add($LoginButton)
# End Login Button
# Start Change VC Button
$ChangeVCButton.TabIndex = 19
$ChangeVCButton.Name = 'ChangeVCButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 95
$System_Drawing_Size.Height = 25
$ChangeVCButton.Size = $System_Drawing_Size
$ChangeVCButton.Font = new-object System.Drawing.Font("Tahoma",8)
$ChangeVCButton.UseVisualStyleBackColor = $True
$ChangeVCButton.Text = 'Change vCenter'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 355
$System_Drawing_Point.Y = 48
$ChangeVCButton.Location = $System_Drawing_Point
$ChangeVCButton.DataBindings.DefaultDataSourceUpdateMode = 0
$ChangeVCButton.add_Click($ChangeVCButton_OnClick)
$ChangeVCButton.Enabled = $false
$MigrationForm.Controls.Add($ChangeVCButton)
# End Change VC Button
# Start Cluster Listbox
$ClusterLabel.TabIndex = 5
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 85
$System_Drawing_Size.Height = 20
$ClusterLabel.Size = $System_Drawing_Size
$ClusterLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$ClusterLabel.Text = 'Select Cluster:'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 20
$System_Drawing_Point.Y = 90
$ClusterLabel.Location = $System_Drawing_Point
$ClusterLabel.DataBindings.DefaultDataSourceUpdateMode = 0
$ClusterLabel.Name = 'ClusterLabel'
$MigrationForm.Controls.Add($ClusterLabel)
$ClusterListBox.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 120
$System_Drawing_Size.Height = 100
$ClusterListBox.Size = $System_Drawing_Size
$ClusterListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$ClusterListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$ClusterListBox.Name = 'ClusterListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 110
$System_Drawing_Point.Y = 90
$ClusterListBox.Location = $System_Drawing_Point
$ClusterListBox.MultiColumn = $false
$ClusterListBox.TabIndex = 5
$ClusterListBox.Sorted = $True
$MigrationForm.Controls.Add($ClusterListBox)
# End Cluster Listbox
# Start Host to Host Button
$HostToHostButton.TabIndex = 3
$HostToHostButton.Name = 'HostToHostButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 20
$HostToHostButton.Size = $System_Drawing_Size
$HostToHostButton.Font = new-object System.Drawing.Font("Tahoma",8)
$HostToHostButton.UseVisualStyleBackColor = $True
$HostToHostButton.Text = 'Host to Host'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 90
$HostToHostButton.Location = $System_Drawing_Point
$HostToHostButton.DataBindings.DefaultDataSourceUpdateMode = 0
$HostToHostButton.add_Click($HostToHostButton_Click)
$HostToHostButton.Enabled = $False
$MigrationForm.Controls.Add($HostToHostButton)
# End Host to Host Button
# Start All Clusters Checkbox
$AllClustersCheckbox.TabIndex = 4
$AllClustersCheckbox.Name = 'AllClustersCheckbox'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 150
$System_Drawing_Size.Height = 20
$AllClustersCheckbox.Size = $System_Drawing_Size
$AllClustersCheckbox.Font = new-object System.Drawing.Font("Tahoma",8)
$AllClustersCheckbox.UseVisualStyleBackColor = $True
$AllClustersCheckbox.Text = 'Show Hosts in All Clusters'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 190
$AllClustersCheckbox.Location = $System_Drawing_Point
$AllClustersCheckbox.DataBindings.DefaultDataSourceUpdateMode = 0
$AllClustersCheckbox.add_Click($AllClustersCheckbox_Click)
$AllClustersCheckbox.Enabled = $False
$MigrationForm.Controls.Add($AllClustersCheckbox)
# End All Clusters Checkbox
# Start VM to Host Button
$VMToHostButton.TabIndex = 3
$VMToHostButton.Name = 'VMToHostButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 20
$VMToHostButton.Size = $System_Drawing_Size
$VMToHostButton.Font = new-object System.Drawing.Font("Tahoma",8)
$VMToHostButton.UseVisualStyleBackColor = $True
$VMToHostButton.Text = 'VM to Host'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 115
$VMToHostButton.Location = $System_Drawing_Point
$VMToHostButton.DataBindings.DefaultDataSourceUpdateMode = 0
$VMToHostButton.add_Click($VMToHostButton_Click)
$VMToHostButton.Enabled = $false
$MigrationForm.Controls.Add($VMToHostButton)
# End VM to Host Button
# Start Datastore to Datastore Button
$DBtoDBButton.TabIndex = 3
$DBtoDBButton.Name = 'DBtoDBButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 20
$DBtoDBButton.Size = $System_Drawing_Size
$DBtoDBButton.Font = new-object System.Drawing.Font("Tahoma",8)
$DBtoDBButton.UseVisualStyleBackColor = $True
$DBtoDBButton.Text = 'Datastore to Datastore'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 140
$DBtoDBButton.Location = $System_Drawing_Point
$DBtoDBButton.DataBindings.DefaultDataSourceUpdateMode = 0
$DBtoDBButton.add_Click($DBtoDBButton_Click)
$DBtoDBButton.Enabled = $false
$MigrationForm.Controls.Add($DBtoDBButton)
# End Datastore to Datastore Button
# Start VM to Datastore Button
$VMtoDBButton.TabIndex = 3
$VMtoDBButton.Name = 'VMtoDBButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 20
$VMtoDBButton.Size = $System_Drawing_Size
$VMtoDBButton.Font = new-object System.Drawing.Font("Tahoma",8)
$VMtoDBButton.UseVisualStyleBackColor = $True
$VMtoDBButton.Text = 'VM to Datastore'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 165
$VMtoDBButton.Location = $System_Drawing_Point
$VMtoDBButton.DataBindings.DefaultDataSourceUpdateMode = 0
$VMtoDBButton.add_Click($VMtoDBButton_Click)
$VMtoDBButton.Enabled = $false
$MigrationForm.Controls.Add($VMtoDBButton)
# End VM to Datastore Button
# Start Source Host List Box
$SourceHostListBox.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 200
$SourceHostListBox.Size = $System_Drawing_Size
$SourceHostListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$SourceHostListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$SourceHostListBox.Name = 'SourceHostListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 210
$SourceHostListBox.Location = $System_Drawing_Point
$SourceHostListBox.MultiColumn = $false
$SourceHostListBox.TabIndex = 5
$SourceHostListBox.Sorted = $True
$MigrationForm.Controls.Add($SourceHostListBox)
# End Source Host List Box
# Start Source Datastore List Box
$SourceDBListBox.FormattingEnabled = $True
$SourceDBListBox.CheckOnClick = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 200
$SourceDBListBox.Size = $System_Drawing_Size
$SourceDBListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$SourceDBListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$SourceDBListBox.Name = 'SourceDBListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 210
$SourceDBListBox.Location = $System_Drawing_Point
$SourceDBListBox.MultiColumn = $false
$SourceDBListBox.HorizontalScrollBar = $true
$SourceDBListBox.TabIndex = 5
$SourceDBListBox.Sorted = $True
# End Source Datastore List Box
# Start Source VM List Box
$SourceVMListBox.FormattingEnabled = $True
$SourceVMListBox.CheckOnClick = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 200
$SourceVMListBox.Size = $System_Drawing_Size
$SourceVMListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$SourceVMListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$SourceVMListBox.Name = 'SourceVMListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 210
$SourceVMListBox.Location = $System_Drawing_Point
$SourceVMListBox.MultiColumn = $false
$SourceVMListBox.TabIndex = 5
$SourceVMListBox.Sorted = $True
# End Source VM List Box
# Start Source Button
$SourceButton.TabIndex = 7
$SourceButton.Name = 'Source Button'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 20
$SourceButton.Size = $System_Drawing_Size
$SourceButton.Font = new-object System.Drawing.Font("Tahoma",8)
$SourceButton.UseVisualStyleBackColor = $True
$SourceButton.Text = 'Source'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 415
$SourceButton.Location = $System_Drawing_Point
$SourceButton.DataBindings.DefaultDataSourceUpdateMode = 0
$SourceButton.add_Click($SourceButton_OnClick)
$SourceButton.Enabled = $false
$MigrationForm.Controls.Add($SourceButton)
# End Source Button
# Start Destination List Box
$DestinationListBox.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 200
$DestinationListBox.Size = $System_Drawing_Size
$DestinationListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$DestinationListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$DestinationListBox.Name = 'DestinationListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 210
$DestinationListBox.Location = $System_Drawing_Point
$DestinationListBox.HorizontalScrollBar = $true
$DestinationListBox.MultiColumn = $false
$DestinationListBox.TabIndex = 5
$DestinationListBox.Sorted = $True
$MigrationForm.Controls.Add($DestinationListBox)
# End Destination List Box
# Start Destination Button
$DestinationButton.TabIndex = 7
$DestinationButton.Name = 'Destination Button'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 200
$System_Drawing_Size.Height = 20
$DestinationButton.Size = $System_Drawing_Size
$DestinationButton.Font = new-object System.Drawing.Font("Tahoma",8)
$DestinationButton.UseVisualStyleBackColor = $True
$DestinationButton.Text = 'Destination'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 250
$System_Drawing_Point.Y = 415
$DestinationButton.Location = $System_Drawing_Point
$DestinationButton.DataBindings.DefaultDataSourceUpdateMode = 0
$DestinationButton.add_Click($DestinationButton_OnClick)
$DestinationButton.Enabled = $false
$MigrationForm.Controls.Add($DestinationButton)
# End Destination Button
# Start Migrate Button
$MigrateButton.TabIndex = 7
$MigrateButton.Name = 'MigrateButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 25
$MigrateButton.Size = $System_Drawing_Size
$MigrateButton.Font = new-object System.Drawing.Font("Tahoma",8)
$MigrateButton.UseVisualStyleBackColor = $True
$MigrateButton.Text = 'Migrate'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 30
$System_Drawing_Point.Y = 450
$MigrateButton.Location = $System_Drawing_Point
$MigrateButton.DataBindings.DefaultDataSourceUpdateMode = 0
$MigrateButton.add_Click($MigrateButton_OnClick)
$MigrateButton.Enabled = $false
$MigrationForm.Controls.Add($MigrateButton)
# End Migrate Button
# Start RESET Button
$ResetButton.TabIndex = 19
$ResetButton.Name = 'ResetButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 140
$System_Drawing_Size.Height = 25
$ResetButton.Size = $System_Drawing_Size
$ResetButton.Font = new-object System.Drawing.Font("Tahoma",8)
$ResetButton.UseVisualStyleBackColor = $True
$ResetButton.Text = 'Reset'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 170
$System_Drawing_Point.Y = 450
$ResetButton.Location = $System_Drawing_Point
$ResetButton.DataBindings.DefaultDataSourceUpdateMode = 0
$ResetButton.add_Click($ResetButton_OnClick)
$ResetButton.Enabled = $false
$MigrationForm.Controls.Add($ResetButton)
# End RESET Button
# Start CLOSE Button
$CloseButton.TabIndex = 19
$CloseButton.Name = 'CloseButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 130
$System_Drawing_Size.Height = 25
$CloseButton.Size = $System_Drawing_Size
$CloseButton.Font = new-object System.Drawing.Font("Tahoma",8)
$CloseButton.UseVisualStyleBackColor = $True
$CloseButton.Text = 'Close'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 320
$System_Drawing_Point.Y = 450
$CloseButton.Location = $System_Drawing_Point
$CloseButton.DataBindings.DefaultDataSourceUpdateMode = 0
$CloseButton.add_Click($CloseButton_OnClick)
$MigrationForm.Controls.Add($CloseButton)
# End CLOSE Button
# Start Messages ListBox
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 80
$System_Drawing_Size.Height = 20
$MessagesLabel.Size = $System_Drawing_Size
$MessagesLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$MessagesLabel.Text = 'Messages'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 50
$MessagesLabel.Location = $System_Drawing_Point
$MessagesLabel.DataBindings.DefaultDataSourceUpdateMode = 0
$MessagesLabel.Name = 'MessagesLabel'
$MigrationForm.Controls.Add($MessagesLabel)
$MessagesListBox.FormattingEnabled = $True
$MessagesListBox.SelectionMode = "None"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 525
$System_Drawing_Size.Height = 140
$MessagesListBox.Size = $System_Drawing_Size
$MessagesListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$MessagesListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$MessagesListBox.Name = 'MessagesListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 70
$MessagesListBox.Location = $System_Drawing_Point
$MessagesListBox.MultiColumn = $false
$MessagesListBox.HorizontalScrollbar = $true
$MigrationForm.Controls.Add($MessagesListBox)
# End Messages ListBox
# Start Task ListBox
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 80
$System_Drawing_Size.Height = 20
$TaskLabel.Size = $System_Drawing_Size
$TaskLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold)
$TaskLabel.Text = 'Recent Tasks'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 215
$TaskLabel.Location = $System_Drawing_Point
$TaskLabel.DataBindings.DefaultDataSourceUpdateMode = 0
$TaskLabel.Name = 'TaskLabel'
$MigrationForm.Controls.Add($TaskLabel)
$TaskListBox.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 525
$System_Drawing_Size.Height = 200
$TaskListBox.Size = $System_Drawing_Size
$TaskListBox.Font = new-object System.Drawing.Font("Tahoma",8)
$TaskListBox.DataBindings.DefaultDataSourceUpdateMode = 0
$TaskListBox.Name = 'TaskListBox'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 235
$TaskListBox.Location = $System_Drawing_Point
$TaskListBox.MultiColumn = $false
$TaskListBox.HorizontalScrollbar = $true
$TaskListBox.SelectionMode = "MultiExtended"
$MigrationForm.Controls.Add($TaskListBox)
# End Task ListBox
# Start Clear Messages Button
$ClearMsgButton.TabIndex = 0
$ClearMsgButton.Name = 'ClearMsgButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 93
$System_Drawing_Size.Height = 25
$ClearMsgButton.Size = $System_Drawing_Size
$ClearMsgButton.Font = new-object System.Drawing.Font("Tahoma",8)
$ClearMsgButton.UseVisualStyleBackColor = $True
$ClearMsgButton.Enabled = $false
$ClearMsgButton.Text = 'Clear Messages'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 480
$System_Drawing_Point.Y = 450
$ClearMsgButton.Location = $System_Drawing_Point
$ClearMsgButton.DataBindings.DefaultDataSourceUpdateMode = 0
$ClearMsgButton.add_Click($ClearMsgButton_Click)
$MigrationForm.Controls.Add($ClearMsgButton)
# End Clear Messages Button
# Start Undo Button
$UndoButton.TabIndex = 0
$UndoButton.Name = 'UndoButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 93
$System_Drawing_Size.Height = 25
$UndoButton.Size = $System_Drawing_Size
$UndoButton.Font = new-object System.Drawing.Font("Tahoma",8)
$UndoButton.UseVisualStyleBackColor = $True
$UndoButton.Enabled = $false
$UndoButton.Text = 'Undo'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 588
$System_Drawing_Point.Y = 450
$UndoButton.Location = $System_Drawing_Point
$UndoButton.DataBindings.DefaultDataSourceUpdateMode = 0
$UndoButton.add_Click($UndoButton_Click)
$MigrationForm.Controls.Add($UndoButton)
# End Undo Button
# Start UndoALL Button
$UndoALLButton.TabIndex = 0
$UndoALLButton.Name = 'UndoALLButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 93
$System_Drawing_Size.Height = 25
$UndoALLButton.Size = $System_Drawing_Size
$UndoALLButton.Font = new-object System.Drawing.Font("Tahoma",8)
$UndoALLButton.UseVisualStyleBackColor = $True
$UndoALLButton.Enabled = $false
$UndoALLButton.Text = 'Undo ALL'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 696
$System_Drawing_Point.Y = 450
$UndoALLButton.Location = $System_Drawing_Point
$UndoALLButton.DataBindings.DefaultDataSourceUpdateMode = 0
$UndoALLButton.add_Click($UndoALLButton_Click)
$MigrationForm.Controls.Add($UndoALLButton)
# End UndoALL Button
# Start Save Task Button
$SaveTaskButton.TabIndex = 0
$SaveTaskButton.Name = 'SaveTaskButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 93
$System_Drawing_Size.Height = 25
$SaveTaskButton.Size = $System_Drawing_Size
$SaveTaskButton.Font = new-object System.Drawing.Font("Tahoma",8)
$SaveTaskButton.UseVisualStyleBackColor = $True
$SaveTaskButton.Enabled = $false
$SaveTaskButton.Text = 'Save Tasks'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 804
$System_Drawing_Point.Y = 450
$SaveTaskButton.Location = $System_Drawing_Point
$SaveTaskButton.DataBindings.DefaultDataSourceUpdateMode = 0
$SaveTaskButton.add_Click($SaveTaskButton_Click)
$MigrationForm.Controls.Add($SaveTaskButton)
# End Save Task Button
# Start Load Task Button
$ReloadTaskButton.TabIndex = 0
$ReloadTaskButton.Name = 'ReloadTaskButton'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 93
$System_Drawing_Size.Height = 25
$ReloadTaskButton.Size = $System_Drawing_Size
$ReloadTaskButton.Font = new-object System.Drawing.Font("Tahoma",8)
$ReloadTaskButton.UseVisualStyleBackColor = $True
$ReloadTaskButton.Enabled = $false
$ReloadTaskButton.Text = 'Reload Tasks'
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 912
$System_Drawing_Point.Y = 450
$ReloadTaskButton.Location = $System_Drawing_Point
$ReloadTaskButton.DataBindings.DefaultDataSourceUpdateMode = 0
$ReloadTaskButton.add_Click($ReloadTaskButton_Click)
$MigrationForm.Controls.Add($ReloadTaskButton)
# End Load Task Button
#endregion Generated Form Code
#Save the initial state of the form
$InitialFormWindowState = $MigrationForm.WindowState
#Init the OnLoad event to correct the initial state of the form
$MigrationForm.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$MigrationForm.ShowDialog()| Out-Null
} #End Function
#Call the Function
GenerateForm
|
PowerShellCorpus/PoshCode/Start-MyTranscript.ps1
|
Start-MyTranscript.ps1
|
function Start-MyTranscript
{
Param
(
[Parameter(Mandatory=$true,Position=0)]
[string] $Path
)# of Param
Process
{
$fileextension = "txt"
$filenamePrefix = [System.DateTime]::Now.ToString("yyyy-MM-dd")
$existingFiles = Get-ChildItem (Join-Path $Path "$filenamePrefix.*.Transcript.$fileextension") | Sort-Object Name
if($existingFiles)
{
if($existingFiles.Count -gt 1)
{
$existingFilename = $existingFiles[-1].Name
}# if we have more than one file
else
{
$existingFilename = $existingFiles.Name
}# if we only have one file
$fileNumber = $existingFilename.Substring($filenamePrefix.Length + 1)
$fileNumber = $fileNumber.Substring(0, $fileNumber.IndexOf("."))
[int] $iFileNumber = 9999
if([Int32]::TryParse($fileNumber, [ref] $iFileNumber))
{
$iFileNumber++
}# if we parsed the number
}# if we have files
else
{
$iFileNumber = 1
}# if we don't have files
if($iFileNumber)
{
$fileNumber = $iFileNumber.ToString("0000")
$filename = "$filenamePrefix.$fileNumber.Transcript.$fileextension"
if(!(Test-Path $Path))
{
New-Item $Path -Type Directory -Force
}# create dir if it doesn't exist
try
{
Start-Transcript -Path (Join-Path $Path $fileName) -Append -Force -NoClobber
}# try to start the transcript
catch
{
Write-Host "Unable to start transcript"
}# catch any error
}# if we got a filename
}# of Process
}# of Start-MyTranscript
|
PowerShellCorpus/PoshCode/Compare-ADUserGroups.ps1
|
Compare-ADUserGroups.ps1
|
function Compare-ADUserGroups
{
#requires -pssnapin Quest.ActiveRoles.ADManagement
param (
[string] $FirstUser = $(Throw "SAMAccountName required."),
[string] $SecondUser = $(Throw "SAMAccountName required.")
)
$a = (Get-QADUser $FirstUser).MemberOf
$b = (Get-QADUser $SecondUser).MemberOf
$c = Compare-Object -referenceObject $a -differenceObject $b
$c
}
|
PowerShellCorpus/PoshCode/SQL Log Backup.ps1
|
SQL Log Backup.ps1
|
## log backup
$backuppath = "\\\\server\\sqlbackups\\"
$alertaddress = "jrich@domain.com"
$smtp = "smtp.domain.com"
$hname = (gwmi win32_computersystem).name
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
$dt = get-date -format "MMddyy-hhmm"
$Instances = Get-Item "HKLM:\\software\\microsoft\\microsoft sql server\\instance names\\sql"
foreach($InstanceName in $Instances.property)
{
$body =@()
$errorstate = 0
$InstancePath = $Instances.GetValue($InstanceName)
if(Test-Path ("HKLM:\\software\\microsoft\\microsoft sql server\\" + $InstancePath + "\\cluster"))
{ #is cluster
$ServerName = (gp ("HKLM:\\software\\microsoft\\microsoft sql server\\" + $InstancePath + "\\cluster")).ClusterName
}
else #not cluster
{
$ServerName = $hname
}
if($InstanceName -eq "MSSQLSERVER")
{#default Instance
$InstConn = $ServerName
}
else
{#named instance
$InstConn = $ServerName + "\\" + $InstanceName
}
$sql = New-Object Microsoft.SqlServer.management.Smo.Server $InstConn
$backuppath += $sql.name + "\\"
$backuppath += $sql | ?{$_.instancename -ne "" -or $_.instancename -ne "MSSQLSERVER"} | %{$_.instancename + "\\"}
$dbs = $sql.databases | ? {!$_.isSystemObject -And $_.recoverymodel -eq [microsoft.sqlserver.management.smo.recoverymodel]::full}
foreach ($db in $dbs)
{
$path = $backuppath + $db.name + "\\"
#clean old trans logs
$lwt = (gci $path *.bak |sort lastwritetime | select -Last 1).lastwritetime
gci $path $.trn | where {$_.lastwritetime -le $lwt} | ri -force
if(!(Test-Path $path)){mkdir $path | Out-Null}
$conn = New-Object Microsoft.SqlServer.management.Smo.Server $InstConn
$bk = new-object microsoft.sqlserver.management.smo.backup
$bk.BackupSetDescription = "log backup of $($db.name) at $(get-date)"
$bk.action = [microsoft.SqlServer.management.smo.backupactiontype]::log
$bk.BackupSetName = "log backup"
$bk.database = $db.name
$bk.Devices.AddDevice("$backuppath$($db.name)\\$($db.name)-$dt.trn",'File')
try{
$msg = "$($bk.database) completed successfully"
$bk.sqlbackup($sql)}
catch{$errorstate = 1; $msg = "$($bk.database) Failed : $_"}
$body += $msg
}
if($errorstate -eq 1){$subject = "Log Failure on $hname"} else {$subject = "Log Success on $hname"}
Send-MailMessage -Subject $subject -BodyAsHtml ([string]::join("<br>",$body)) -From $alertaddress -To $alertaddress -SmtpServer $smtp
}
|
PowerShellCorpus/PoshCode/Get-ExchangeDBSizes.ps1
|
Get-ExchangeDBSizes.ps1
|
<#
.SYNOPSIS
Get-ExchangeDBSizes - Gather data on Exchange 2007 / 2010 Mailbox Databases.
.DESCRIPTION
Gathers data from Exchange mailbox servers.
These data include:
Server\\StorageGroup\\Database (2007) or Database (2010),
Total Size (in GB) of the disk,
Size of the .edb file (in GB),
Free disk space,
Percent Disk Free,
Total Mailboxes on the database,
White Space,
Total Free disk space,
Total Percent Free disk space
.EXAMPLE
Get-ExchangeDBSizes
.LINK
http://unlockpowershell.wordpress.com/
#>
Function Get-MountPointInfo($ServerName) {
$Summary = @()
$VolumeHash = @{}
$VolumeCapacityHash = @{}
$DatabaseSizeHash = @{}
$DatabaseFreeHash = @{}
$MountPoints = Get-WmiObject -Class Win32_Mountpoint -ComputerName $ServerName
$MailboxDatabases = Get-MailboxDatabase -Server $ServerName
$Volumes = Get-WmiObject -Class Win32_Volume -ComputerName $ServerName | Where-Object {$_.DriveType -eq 3}| Select-Object Name,FreeSpace,Capacity
$DatabaseLetters = $MailboxDatabases | Select-Object edbfilepath
foreach ($Volume in $Volumes) {
$VolumeHash.Add($Volume.name.TrimEnd("\\"),$Volume.FreeSpace)
$VolumeCapacityHash.Add($Volume.name.TrimEnd("\\"),$Volume.Capacity)
}
foreach ($drive in $DatabaseLetters)
{
$letter = $drive.EdbFilePath.Substring(0,$drive.EdbFilePath.lastIndexOf("\\"))
$DatabaseSizeHash.Add($letter.TrimEnd("\\"),$VolumeCapacityHash[$letter])
$DatabaseFreeHash.Add($letter.TrimEnd("\\"),$VolumeHash[$letter])
}
$VolumeHash.Clear()
$VolumeCapacityHash.Clear()
#Now I have all mailbox databases, along with the OS reported free space and capacity
foreach ($MP in $Mountpoints) {
$MP.directory = $MP.directory.replace("\\\\","\\").Split("=")[1].Replace("`"","")
if($DatabaseSizeHash[$MP.directory])
{
#This mountpoint is a database
$Record = new-Object PSObject
$OSfree = $DatabaseFreeHash[$MP.directory]
$OSCapacity = $DatabaseSizeHash[$MP.directory]
$DestFolder = "\\\\"+$ServerName + "\\" + $MP.directory
$colItems = (Get-ChildItem $destfolder.Replace(":","$") -Recurse| where{$_.length -ne $null} |Measure-Object -property length -sum)
if($colItems.sum -eq $null) {
$fsize = 0
} else {
$fsize = $colItems.sum
}
$TotFolderSize = $fsize + $OSfree
$percFree = "{0:P0}" -f ( $OSfree/$TotFolderSize)
$Record | add-Member -memberType noteProperty -name Server -Value $ServerName
$Record | add-Member -memberType noteProperty -name "Mount Point" -Value $MP.directory
$Record | add-Member -memberType noteProperty -name "Capacity" -Value ("{0:N2}" -f ($OSCapacity /1gb))
$Record | add-Member -memberType noteProperty -name "Used" -Value ("{0:N2}" -f ($fsize / 1gb))
$Record | add-Member -memberType noteProperty -name "Free" -Value ("{0:N2}" -f ($OSfree / 1gb))
$Record | add-Member -memberType noteProperty -name "Percent Free" -Value $percFree
$Summary += $Record
}
}
return $Summary
}
function Get-ExchangeWhiteSpace {
param(
$ComputerName = $(throw "ComputerName cannot be empty.")
)
# Convert Dates to WMI CIM dates
$tc = [System.Management.ManagementDateTimeconverter]
$Start =$tc::ToDmtfDateTime( (Get-Date).AddDays(-1).Date )
$End =$tc::ToDmtfDateTime( (Get-Date).Date)
$whiteSpace = @{}
# Create two claculated properties for InsertionStrings values
$DB = @{Name="DB";Expression={$_.InsertionStrings[1]}}
$FreeMB = @{Name="FreeMB";Expression={[int]$_.InsertionStrings[0]}}
$freespace = Get-WMIObject Win32_NTLogEvent -ComputerName $ComputerName -Filter "LogFile='Application' AND EventCode=1221 AND TimeWritten>='$Start' AND TimeWritten<='$End'" | Select-Object $DB,$FreeMB | Sort-Object DB –Unique –Descending
$freespace | ForEach-Object {$whiteSpace.Add($_.DB,$_.FreeMB)}
#Preceding function from Shay Levy http://blogs.microsoft.co.il/blogs/scriptfanatic/archive/2009/08/13/exchange-white-space.aspx
}
$AllServers = @()
$ServerVersion = @{}
foreach ($server in Get-MailboxServer)
{
$ServerName = $server.name
$version = Get-ExchangeServer -Identity $ServerName | Select-Object AdminDisplayVersion
if($version.admindisplayversion.major)
{
$ServerVersion.Add($ServerName,$version.admindisplayversion.major)
}
else
{
$ServerVersion.Add($ServerName,$version.admindisplayversion.Split()[1].split(".")[0])
}
}
foreach ($server in Get-MailboxServer)
{
$ServerName = $server.Name
if ([int]$ServerVersion[$ServerName] -gt 8)
{ #An Exchange 2010 server, so use Get-MailboxDatabase <database> -Status | Select-Object AvailableNewMailboxSpace
$whiteSpace = @{}
$Free = Get-MailboxDatabase -Server $ServerName -Status | Select-Object Server,Name,AvailableNewMailboxSpace
foreach ($item in $free)
{
$db = $ServerName+"\\"+$item.Name
$whiteSpace.Add($item.Name,[int]$item.AvailableNewMailboxSpace.split("(")[1].Split()[0]/1mb)
}
}
Else
{#not an Exchange 2010 server
. Get-ExchangeWhiteSpace $ServerName
}
$MountPoint = . Get-MountPointInfo $ServerName
foreach ($objItem in Get-MailboxDatabase -Server $ServerName)
{
$edbfilepath = $objItem.edbfilepath
# $path = "`\\`\\" + $ServerName + "`\\" + $objItem.EdbFilePath.DriveName.Remove(1).ToString() + "$"+ $objItem.EdbFilePath.PathName.Remove(0,2)
$path = "`\\`\\" + $ServerName + "`\\" + $objItem.EdbFilePath.Split(":")[0] + "$"+ $objItem.EdbFilePath.Split(":")[1]
$dbsize = Get-ChildItem $path
# $dbpath=(Split-Path $edbfilepath.PathName -Leaf).trimend(".edb")
$dbpath=(Split-Path $edbfilepath.Split(":")[1] -Leaf).trimend(".edb")
if (!$MountPoint)
{
$mailboxpath = $ServerName + $edbfilepath.Split(":")[1].trimend(".edb")
# $size = get-wmiobject -computername $ServerName win32_logicaldisk |where-object {$_.deviceid -eq $objItem.EdbFilePath.DriveName} |select-object deviceID, Freespace, Size
$size = get-wmiobject -computername $ServerName win32_logicaldisk |where-object {$_.deviceid -eq $objItem.EdbFilePath.Split("\\")[0]} |select-object deviceID, Freespace, Size
$freespace = ($size.freespace / 1GB)
$total = ($size.size / 1GB)
}
if ($MountPoint)
{
$mailboxpath = "$ServerName\\$dbpath"
$MPPath = $EdbFilePath.Substring(0,$EdbFilePath.LastIndexOf("\\"))
$freespace = $DatabaseFreeHash[$MPPath ] /1GB
$total = $DatabaseSizeHash[$MPPath] /1GB
}
$PercentFree = "{0:n2}" -f ($freespace / $total *100)
if (!$MountPoint)
{
$mailboxcount = Get-MailboxStatistics -database "$mailboxpath" |Where {$_.DisconnectDate -eq $null -and $_.ObjectClass -eq 'Mailbox'} |measure-object
}
if($MountPoint)
{
$mailboxcount = Get-MailboxStatistics -database $mailboxpath.Split("\\")[1] |Where {$_.DisconnectDate -eq $null -and $_.ObjectClass -eq 'Mailbox'} |measure-object
}
$ReturnedObj = New-Object PSObject
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Server\\StorageGroup\\Database" -Value $objItem.Identity
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Total Size (GB)" -Value ("{0:n2}" -f ($total))
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Used Space (GB)" -Value ("{0:n2}" -f ($dbsize.Length/1024MB))
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Free Space (GB)" -Value ("{0:n2}" -f ($freespace))
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Percent Disk Free" -Value $percentfree
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "User Mailbox Count" -Value $mailboxcount.count
if ($objitem.Identity.Split("\\").Count -eq 3){$dbasename = $objitem.Identity.Substring($objitem.Identity.IndexOf("\\")+1)}
else{$dbasename = $objitem.Identity}
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "White Space (GB)" -Value ("{0:n2}" -f ($whiteSpace[$dbasename]/1024))
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Total Free (GB)" -Value ("{0:n2}" -f ($freespace + $whiteSpace[$dbasename]/1024))
$TotalPercent = ($freespace + $whiteSpace[$dbasename]/1024) / $total *100
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Total Percent Free" -Value ("{0:n2}" -f ($TotalPercent))
$AllServers += $ReturnedObj
}
}
$AllServers |Export-Csv C:\\MailboxDatabaseSizeReport.csv -NoTypeInformation
|
PowerShellCorpus/PoshCode/Remove Disabled AD Users.ps1
|
Remove Disabled AD Users.ps1
|
import-module ActiveDIrectory
search-adaccount -searchbase "ou=UserObjectsPendingDeletion,DC=mydomain,DC=com" -Accountinactive -Timespan 400.00:00:00 | where {$_.objectclass -eq 'user'} | remove-aduser -confirm:$false
|
PowerShellCorpus/PoshCode/ESXi Config BackupScript.ps1
|
ESXi Config BackupScript.ps1
|
###ESXi Configuration Backup Script
#DESCRIPION: This Script takes a CSV file with the hostname, username, and password of a list of ESXi servers, and backs up their configurations to a specified Destination
#USAGE: This script is meant to be run as a regular scheduled task or a pre-script for a backup job. There is no version control, so it is recommended to use an external backup program (Such as Backup Exec) to scan this.
#LAST MODIFIED: 15 Dec 2009 by JGrote <jgrote AT enpointe NOSPAMDOT-com>
#REQUIREMENTS:
#VMWare Remote CLI (Tested with 4.0U1)
### SETTINGS
#Location of the VMWare Remote CLI vicfg-cfgbackup.pl command (will be different for 32-bit systems)
$vSphereCLIPath = "C:\\Program Files (x86)\\VMware\\VMware vSphere CLI\\"
#Backup Destination Folder
$BackupDest = "E:\\Backup\\ESXi"
#Path to ESXi CSV File. APPLY STRICT PERMISSIONS TO THIS FILE SO THAT ONLY THE SCRIPTAND ADMINISTRATORS CAN READ IT!
#Format:
#1st Field - HOSTNAME - ESXi IP Address or Hostname
#2nd Field - USERNAME - Local Username (usually root)
#3rd Field - PASSWORD - Password
#
#Example:
#HOSTNAME,USERNAME,PASSWORD
#server1,root,password
#server2,root,password2
#It is recommended to create and edit this file using Excel (Save as CSV)
$ESXiCSV = "C:\\Scripts\\ESXiBackupList.csv"
### PREPARATION
#Create an ESXi Backup Event Source if it doesn't already exist
$eventsource = "Backup-ESXi"
$eventlog = "Application"
if (!(get-eventlog -logname $eventlog -source $eventsource)) {new-eventlog -logname $eventlog -source $eventsource}
#Write an error and exit the script if an exception is ever thrown
trap {write-eventlog -logname $eventlog -eventID 1 -source $eventsource -EntryType "Error" -Message "An Error occured during $($eventsource): $_ . Script run from $($MyInvocation.MyCommand.Definition)"; exit}
#Verify the Destination Directory Exists:
#Verify that the import XML file was created. If it is not there, it will throw an exception caught by the trap above that will exit the script.
$ESXiCSVIsPresentTest = Get-Item $ESXiCSV
### SCRIPT
#Read Each Host from the File and back up the config to the backup directory
import-csv $ESXiCSV | ForEach-Object {
$BackupResult = invoke-expression "& '$vSphereCLIPath\\perl\\bin\\perl.exe' '$vSphereCLIPath\\bin\\vicfg-cfgbackup.pl' --server $($_.HOSTNAME) --username $($_.USERNAME) --password $($_.PASSWORD) --save $($BackupDest)\\$($_.HOSTNAME)-cfgbackup.tgz"
if ($LastExitCode -ne 0) {throw "An Error occurred while executing $BackupBin for $($_.HOSTNAME): $BackupResult"}
}
#Compose and Write Success Event
$successText = "ESXi Configurations were successfully backed up to $BackupDest. Script run from $($MyInvocation.MyCommand.Definition)"
write-eventlog -logname $eventlog -eventID 1 -source $eventsource -EntryType "Information" -Message $successText
|
PowerShellCorpus/PoshCode/Out-Balloon_2.ps1
|
Out-Balloon_2.ps1
|
<#
.Synopsis
Makes a baloon tip in the notification area
.Description
With just a few arguments, it is easy to make some text appear in a little balloon.
You can specify an icon file (*.ico) with the -icon argument, if you don't then
the first icon of the host is used.
out-balloon accepts pipeline input, strings only please.
It blocks for the duration of the balloon display, 3 seconds by default. Simple
fixes for this are welcome.
timeout should be an integer value.
INSTALLATION:
um, save this text in a file named out-balloon.ps1 in your path
.Parameter BuiltInIcon
Must be one of none, Info, warning, error.
.Parameter TimeoutSeconds
Number of Seconds to display the Tool tip for
.Example
"job done." | out-balloon
.Example
out-balloon "hey, your job is done." -icon "C:\\Program Files\\Microsoft Office\\Office12\\MYSL.ICO"
.Example
out-balloon "hey, your job is done." -title "Printer Server" -BuiltInIcon info
#>
param(
[Parameter(ValueFromPipeline=$true,Position=0,Mandatory=$true)]
[Alias('output')]
[string]$text,
[string]$iconFile,
[string]$title,
[string]$BuiltInIcon,
[int32]$TimeoutSeconds = 3
)
begin
{
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
if( $BuiltInIcon )
{
if( $title -eq $null )
{
write-error "You must supply a title to dislay the BuiltInIcon!"
}
}
if( $iconFile -and $ToolTipIcon)
{
write-error "Cannot supply -IconFile and ToolTipIcon parameters together."
}
$not = new-object System.Windows.Forms.NotifyIcon
if ($icon -eq $null)
{
if ($win32extraciconex -eq $null)
{
$script:ExtractIconEx = Add-Type ¢memberDefinition @"
[DllImport("Shell32", CharSet=CharSet.Auto)]
private static extern int ExtractIconEx (string lpszFile, int nIconIndex,
IntPtr[] phIconLarge,IntPtr[] phIconSmall,int nIcons);
[DllImport("user32.dll", EntryPoint="DestroyIcon", SetLastError=true)]
private static extern int DestroyIcon(IntPtr hIcon);
public static System.Drawing.Icon ExtractIconFromExe(string file, bool large)
{
int readIconCount = 0;
IntPtr[] hDummy = new IntPtr[1] {IntPtr.Zero};
IntPtr[] hIconEx = new IntPtr[1] {IntPtr.Zero};
try
{
if(large)
readIconCount = ExtractIconEx(file,0, hIconEx, hDummy, 1);
else
readIconCount = ExtractIconEx(file,0, hDummy, hIconEx, 1);
if(readIconCount > 0 && hIconEx[0] != IntPtr.Zero)
{
System.Drawing.Icon extractedIcon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(hIconEx[0]).Clone();
return extractedIcon;
}
else // NO ICONS READ
return null;
}
catch(Exception ex)
{
throw new ApplicationException("Failed extracting icon", ex);
}
finally
{
foreach(IntPtr ptr in hIconEx)
if(ptr != IntPtr.Zero)
DestroyIcon(ptr);
foreach(IntPtr ptr in hDummy)
if(ptr != IntPtr.Zero)
DestroyIcon(ptr);
}
}
"@ -name ōWin32ExtractIconExö -namespace win32api ¢passThru -ReferencedAssemblies "System.Drawing"
}
$not.Icon = $extractIconEx::ExtractIconFromExe((get-process -Id $pid).mainmodule.filename, $true)
}
else
{
$not.Icon = new-object System.Drawing.Icon($iconFile)
}
$not.visible = $true
}
process
{
$not.BalloonTipText = $text
$not.BalloonTipTitle = $title
if( $BuiltInIcon) { $not.BalloonTipIcon = $BuiltInIcon }
$not.ShowBalloonTip($timeout)
sleep $timeout
}
end
{
$not.dispose()
}
|
PowerShellCorpus/PoshCode/finddupe_13.ps1
|
finddupe_13.ps1
|
# new version avoids recalculating MD5s, has delete/noprompt options, and by default checks the current directory.
function Get-MD5([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]'))
{
$stream = $null;
$cryptoServiceProvider = [System.Security.Cryptography.MD5CryptoServiceProvider];
$hashAlgorithm = new-object $cryptoServiceProvider
$stream = $file.OpenRead();
$hashByteArray = $hashAlgorithm.ComputeHash($stream);
$stream.Close();
## We have to be sure that we close the file stream if any exceptions are thrown.
trap
{
if ($stream -ne $null)
{
$stream.Close();
}
break;
}
foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }}
return [string]$result;
}
write-host "Usage: finddupe.ps1 <directory/file #1> <directory/file #2> ... <directory/file #N> [-delete] [-noprompt]"
$matches = 0 # initialize number of matches for summary.
$filesdeleted = 0 # number of files deleted.
$bytesrec = 0 # Number of bytes recovered.
$files=@()
$del = $false # delete duplicates
$noprompt = $false # delete without prompting toggle
$currentdir = $true # work on current directory by default
for ($i=0;$i -ne $args.count; $i++)
{
if ($args[$i] -eq "-delete")
{
$del=$true;continue
}
else
{
if ($args[$i] -eq "-noprompt")
{
$noprompt=$true;continue
}
else
{
$files+=(dir $args[$i] -recurse | ? {$_.psiscontainer -ne $true})
$currentdir=$false
}
}
}
if ($currentdir -eq $true) { $files=(dir -recurse | ? {$_.psiscontainer -ne $true})}
if ($files -eq $null) {write-host "No files found."; exit}
for ($i=0;$i -ne $files.count; $i++) # Cycle thru all files
{
if ($files[$i] -eq $null) {continue}
$filecheck = $files[$i]
$files[$i] = $null
for ($c=0;$c -ne $files.count; $c++)
{
if ($files[$c] -eq $null) {continue}
# write-host "Comparing $filecheck and $($files[$c]) `r" -nonewline
if ($filecheck.length -eq $files[$c].length)
{
#write-host "Comparing MD5 of $($filecheck.fullname) and $($files[$c].fullname) `r" -nonewline
if ($filecheck.md5 -eq $null)
{
$md5 = (get-md5 $filecheck.fullname)
$filecheck = $filecheck | %{add-member -inputobject $_ -name MD5 -membertype noteproperty -value $md5 -passthru}
}
if ($files[$c].md5 -eq $null)
{
$md5 = (get-md5 $files[$c].fullname)
$files[$c] = $files[$c] | %{add-member -inputobject $_ -name MD5 -membertype noteproperty -value $md5 -passthru}
}
if ($filecheck.md5 -eq $files[$c].md5)
{
write-host "Size and MD5 match: " -fore red -nonewline
write-host "`"$($filecheck.fullname)`"" -nonewline
write-host " and " -nonewline
write-host "`"$($files[$c].fullname)`""
$matches++
if ($del -eq $true)
{
if ($noprompt -eq $true)
{
del $files[$c].fullname
write-host "Deleted duplicate: " -f red -nonewline
write-host "$($files[$c].fullname)."
}
else
{
del $files[$c].fullname -confirm
}
if ((get-item -ea 0 $files[$c].fullname) -eq $null)
{
$filesdeleted += 1
$bytesrec += $files[$c].length
}
}
$files[$c] = $null
}
}
}
}
write-host ""
write-host "Number of Files checked: $($files.count)." # Display useful info; files checked and matches found.
write-host "Number of matches found: $matches."
Write-host "Number of duplicates deleted: $filesdeleted." # Display number of duplicate files deleted and bytes recovered.
write-host "$bytesrec bytes recovered."
write-host ""
|
PowerShellCorpus/PoshCode/LetterDiamondOneLiner v4.ps1
|
LetterDiamondOneLiner v4.ps1
|
&{($r=,(' '*($p=[char]$args[0]-($s=65))+[char]$s)+($p..1|%{"{0,$_} {1}{0}"-f[char]++$s,(' '*$f++)}));$r[-2..-99]}J
|
PowerShellCorpus/PoshCode/xczxc.ps1
|
xczxc.ps1
|
###########################################################################"
#
# NAME: Create-Printers.ps1
#
# AUTHOR: Jan Egil Ring
# EMAIL: jan.egil.ring@powershell.no
# BLOG: http://blog.powershell.no
#
# COMMENT: Simple script to bulk-create printers on a print-server. Printers are imported from a csv-file.
# Running the script from Windows Server 2003 returns an access denied error, possibly due to the impersonation-model in Windows Server 2003.
# Created and tested from Windows Server 2008 against a remote Windows Server 2003 print-server.
# Should work from Windows Vista, Windows 7, Windows Server 2008 and Windows Server 2008 R2 against remote print-servers (2000/2003/2008/2008 R2)
#
# 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 07.11.2009 - Initial release
#
###########################################################################"
function CreatePrinter {
$server = $args[0]
$print = ([WMICLASS]"\\\\$server\\ROOT\\cimv2:Win32_Printer").createInstance()
$print.drivername = $args[1]
$print.PortName = $args[2]
$print.Shared = $true
$print.Sharename = $args[3]
$print.Location = $args[4]
$print.Comment = $args[5]
$print.DeviceID = $args[6]
$print.Put()
}
function CreatePrinterPort {
$server = $args[0]
$port = ([WMICLASS]"\\\\$server\\ROOT\\cimv2:Win32_TCPIPPrinterPort").createInstance()
$port.Name= $args[1]
$port.SNMPEnabled=$false
$port.Protocol=1
$port.HostAddress= $args[2]
$port.Put()
}
$printers = Import-Csv c:\\printers.csv
foreach ($printer in $printers) {
CreatePrinterPort $printer.Printserver $printer.Portname $printer.IPAddress
CreatePrinter $printer.Printserver $printer.Driver $printer.Portname $printer.Sharename $printer.Location $printer.Comment $printer.Printername
}
|
PowerShellCorpus/PoshCode/Get_Set Signature 2.3.ps1
|
Get_Set Signature 2.3.ps1
|
#Requires -version 2.0
## Authenticode.psm1 updated for PowerShell 2.0 (with time stamping)
####################################################################################################
## 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-AuthenticodeSigned -Mine -Broken | Set-AuthenticodeSignature
## Re-sign anything you signed before that has changed
##
## ls | Select-AuthenticodeSigned -NotMine -ValidOnly | Set-AuthenticodeSignature
## Re-sign scripts that are hash-correct but not signed by me or by someone trusted
##
####################################################################################################
## History:
## 2.3 - Reworked Get-UserCertificate and Get-AuthenticodeCertificate for better behavior
## 2.2 - Added sorting and filtering the displayed certs, and the option to save your choice
## 2.1 - Added some extra exports and aliases, and included my Start-AutoSign script...
## 2.0 - Updated to work with PowerShell 2.0 RTM and add -TimeStampUrl support
## 1.7 - Modified the reading of certs to better support people who only have one :)
## 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-AuthenticodeSigned
## - Added -MineOnly and -NotMineOnly switches to Select-AuthenticodeSigned
## 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
##
####################################################################################################
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 be reused without re-querying for the location and/or password ...
.RETURNVALUE
An X509Certificate2 suitable for code-signing
#>
[CmdletBinding()]
param ( $Name )
begin {
if($Name) {
$Script:UserCertificate = Get-AuthenticodeCertificate $Name
}
}
end {
## If they don't have a cert, or they haven't stored it...
if(!(Test-Path Variable:Script:UserCertificate) -or
$Script:UserCertificate -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2] -or
$Script:UserCertificate.Thumbprint -ne $ExecutionContext.SessionState.Module.PrivateData
) {
## Verbose output
if($VerbosePreference -gt "SilentlyContinue") {
if(!(Test-Path Variable:Script:UserCertificate)) {
Write-Verbose "Loading User Certificate from Module Config: $($ExecutionContext.SessionState.Module.PrivateData)"
} else {
Write-Verbose "Saving User Certificate to Module Config: ($($Script:UserCertificate.Thumbprint) -ne $($ExecutionContext.SessionState.Module.PrivateData))"
}
}
Write-Debug "PrivateData: $($ExecutionContext.SessionState.Module | fl * | Out-String)"
## If they don't have a cert
if(!(Test-Path Variable:Script:UserCertificate) -or $Script:UserCertificate -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2]) {
$Script:UserCertificate = Get-AuthenticodeCertificate $ExecutionContext.SessionState.Module.PrivateData
}
Write-Verbose "Confirming Certificate: $($Script:UserCertificate.Thumbprint)"
## If their cert isn't stored at least temporarily...
if($Script:UserCertificate -and (!$ExecutionContext.SessionState.Module.PrivateData -or
($ExecutionContext.SessionState.Module.PrivateData -ne $Script:UserCertificate.Thumbprint)))
{
## Store it temporarily ...
$ExecutionContext.SessionState.Module.PrivateData = $Script:UserCertificate.Thumbprint
## And ask them if they want to store it permanently
Write-Verbose "Updating Module Metadata"
if($Host.UI -and $Host.UI.PromptForChoice -and (0 -eq
$Host.UI.PromptForChoice("Keep this certificate for future sessions?", $Script:UserCertificate,
[Management.Automation.Host.ChoiceDescription[]]@("&Yes","&No"), 0))
) {
$mVersion = $PSCmdlet.MyInvocation.MyCommand.Module.Version
if($MVersion -le "2.2") { $MVersion = 2.2 }
New-ModuleManifest $PSScriptRoot\\Authenticode.psd1 `
-ModuleToProcess Authenticode.psm1 `
-Author 'Joel Bennett' -Company 'HuddledMasses.org' `
-ModuleVersion $MVersion `
-PowerShellVersion '2.0' `
-Copyright '(c) 2008-2010, Joel Bennett' `
-Desc 'Function wrappers for Authenticode Signing cmdlets' `
-Types @() -Formats @() -RequiredModules @() `
-RequiredAssemblies @() -FileList @() -NestedModules @() `
-PrivateData $Script:UserCertificate.Thumbprint
$null = Sign $PSScriptRoot\\Authenticode.psd1 -Cert $Script:UserCertificate
}
}
}
return $Script:UserCertificate
}
}
function Get-AuthenticodeCertificate {
[CmdletBinding()]
param (
$Name = $(Get-UserCertificate)
)
end {
$Certificate = $Name
# Until they get a cert, or hit ENTER without any input
while($Certificate -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2]) {
trap {
Write-Host "The authenticode module requires a code-signing certificate, and can't find yours!"
Write-Host
Write-Host "If this is the first time you've seen this error, please run Get-AuthenticodeCertificate by hand and specify the full path to your PFX file, or the Thumbprint of a cert in your OS Cert store -- and then answer YES to save that cert in the 'PrivateData' of the Authenticode Module metadata."
Write-Host
Write-Host "If you have seen this error multiple times, you may need to manually create a module manifest for this module with the path to your cert, and/or specify the certificate name each time you use it."
Write-Error $_
continue
}
## If they haven't specified the name, prompt them:
if(!$Name) {
$certs = @(Get-ChildItem Cert:\\ -Recurse -CodeSign | Sort NotAfter)
if($certs.Count) {
Write-Host "You have $($certs.Count) code signing certificates in your local certificate storage which you can specify by partial Thumbprint, or you may specify the path to a .pfx file:" -fore cyan
$certs | Out-Host
}
$Name = $(Read-Host "Please specify a user certificate (wildcards allowed)")
if(!$Name) { return }
}
Write-Verbose "Certificate Path: $Name"
$ResolvedPath = Get-ChildItem Cert:\\ -Recurse -CodeSign | Where {$_.ThumbPrint -like $Name } | Select -Expand PSPath
if(!$ResolvedPath) {
Write-Verbose "Not a Certificate path: $Path"
$ResolvedPath = Resolve-Path $Name -ErrorAction "SilentlyContinue" | Where { Test-Path $_ -PathType Leaf -ErrorAction "SilentlyContinue" }
}
if(!$ResolvedPath) {
Write-Verbose "Not a full or legit relative path Path: $ResolvedPath"
$ResolvedPath = Resolve-Path (Join-Path $PsScriptRoot $Name -ErrorAction "SilentlyContinue") -ErrorAction "SilentlyContinue" | Where { Test-Path $_ -PathType Leaf -ErrorAction "SilentlyContinue" }
Write-Verbose "Resolved File Path: $ResolvedPath"
}
if(@($ResolvedPath).Count -gt 1) {
throw "You need to specify enough of the name to narrow it to a single certificate. '$Name' returned $(@($ResolvedPath).Count):`n$($ResolvedPath|Out-String)"
}
$Certificate = get-item $ResolvedPath -ErrorAction "SilentlyContinue"
if($Certificate -is [System.IO.FileInfo]) {
$Certificate = Get-PfxCertificate $Certificate -ErrorAction "SilentlyContinue"
}
$Name = $Null # Blank it out so we re-prompt them
}
Write-Verbose "Certificate: $($Certificate | Out-String)"
return $Certificate
}
}
function Test-AuthenticodeSignature {
<#
.SYNOPSIS
Tests a script signature to see if it is valid, or at least unaltered.
.DESCRIPTION
The Test-AuthenticodeSignature function processes the output of Get-AuthenticodeSignature to determine if it
is Valid, OR **unaltered** and signed by the user's certificate
.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
.EXAMPLE
ls *.ps1 | Get-AuthenticodeSignature | Where {Test-AuthenticodeSignature $_}
To get the signature reports for all the scripts that we consider safely signed.
.EXAMPLE
ls | ? { gas $_ | Test-AuthenticodeSignature }
List all the valid signed scripts (or scripts signed by our cert)
.NOTES
Test-AuthenticodeSignature 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.
.INPUTTYPE
System.Management.Automation.Signature
.RETURNVALUE
Boolean value representing whether the script's signature is valid, or YOUR certificate
#>
[CmdletBinding()]
param (
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
$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-AuthenticodeSignature $_ -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.
.PARAMETER Force
Allows the cmdlet to append a signature to a read-only file. Even using the Force parameter, the cmdlet cannot override security restrictions.
.Parameter HashAlgorithm
Specifies the hashing algorithm that Windows uses to compute the digital signature for the file. The default is SHA1, which is the Windows default hashing algorithm.
Files that are signed with a different hashing algorithm might not be recognized on other systems.
.PARAMETER IncludeChain
Determines which certificates in the certificate trust chain are included in the digital signature. "NotRoot" is the default.
Valid values are:
-- Signer: Includes only the signer's certificate.
-- NotRoot: Includes all of the certificates in the certificate chain, except for the root authority.
--All: Includes all the certificates in the certificate chain.
.PARAMETER TimestampServer
Uses the specified time stamp server to add a time stamp to the signature. Type the URL of the time stamp server as a string.
Defaults to Verisign's server: http://timestamp.verisign.com/scripts/timstamp.dll
The time stamp represents the exact time that the certificate was added to the file. A time stamp prevents the script from failing if the certificate expires because users and programs can verify that the certificate was valid atthe time of signing.
.RETURNVALUE
System.Management.Automation.Signature
###################################################################################################>
[CmdletBinding()]
param (
[Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ValueFromPipeline=$true)]
[Alias("FullName","Path")]
[ValidateScript({
if((resolve-path $_).Provider.Name -ne "FileSystem") {
throw "Specified Path is not in the FileSystem: '$_'"
}
return $true
})]
[string[]]
$FilePath
,
[Parameter(Position=2, Mandatory=$false)]
$Certificate = $(Get-UserCertificate)
,
[Switch]$Force
,
[ValidateSet("SHA","MD5","SHA1","SHA256","SHA384","SHA512")]
[String]$HashAlgorithm #="SHA1"
,
[ValidateSet("Signer","NotRoot","All")]
[String]$IncludeChain #="NotRoot"
,
[String]$TimestampServer = "http://timestamp.verisign.com/scripts/timstamp.dll"
)
begin {
if($Certificate -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2]) {
$Certificate = Get-AuthenticodeCertificate $Certificate
}
$PSBoundParameters["Certificate"] = $Certificate
}
process {
Write-Verbose "Set Authenticode Signature on $FilePath with $($Certificate | Out-String)"
$PSBoundParameters["FilePath"] = $FilePath = $(Resolve-Path $FilePath)
if(Test-Path $FilePath -Type Leaf) {
Microsoft.PowerShell.Security\\Set-AuthenticodeSignature @PSBoundParameters
} else {
Write-Warning "Cannot sign folders: '$FilePath'"
}
}
}
####################################################################################################
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-AuthenticodeSignature $_ -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-AuthenticodeSigned {
<#.SYNOPSIS
Select files based on the status of their Authenticode Signature.
.DESCRIPTION
The Select-AuthenticodeSigned 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-AuthenticodeSigned
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-AuthenticodeSignature $_ -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
}
# InvalidOnly returns things that are Either NotSigned OR HashMismatch ...
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 NOT 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
}}
}
}
function Start-AutoSign {
# .Synopsis
# Start a FileSystemWatcher to automatically sign scripts when you save them
# .Description
# Create a FileSystemWatcher with a scriptblock that uses the Authenticode script Module to sign anything that changes
# .Parameter Path
# The path to the folder you want to monitor
# .Parameter Filter
# A filter to select only certain files: by default, *.ps* (because we can only sign .ps1, .psm1, .psd1, and .ps1xml
# .Parameter Recurse
# Whether we should also watch autosign files in subdirectories
# .Parameter CertPath
# The path or name of a certain certificate, to override the defaults from the Authenticode Module
# .Parameter NoNotify
# Whether wo should avoid using Growl to notify the user each time we sign something.
# .NOTE
# Don't run this on a location where you're going to be generating dozens or hundreds of files ;)
param($Path=".", $Filter= "*.ps*", [Switch]$Recurse, $CertPath, [Switch]$NoNotify)
if(!$NoNotify -and (Get-Module Growl -ListAvailable -ErrorAction 0)) {
Import-Module Growl
Register-GrowlType AutoSign "Signing File" -ErrorAction 0
} else { $NoNotify = $false }
$realItem = Get-Item $Path -ErrorAction Stop
if (-not $realItem) { return }
$Action = {
## Files that can't be signed show up as "UnknownError" with this message:
$InvalidForm = "The form specified for the subject is not one supported or known by the specified trust provider"
## Files that are signed with a cert we don't trust also show up as UnknownError, but with different messages:
# $UntrustedCert = "A certificate chain could not be built to a trusted root authority"
# $InvalidCert = "A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider"
# $ExpiredCert = "A required certificate is not within its validity period when verifying against the current system clock or the timestamp in the signed file"
ForEach($file in Get-ChildItem $eventArgs.FullPath | Get-AuthenticodeSignature |
Where-Object { $_.Status -ne "Valid" -and $_.StatusMessage -ne $invalidForm } |
Select-Object -ExpandProperty Path )
{
if(!$NoNotify) {
Send-Growl AutoSign "Signing File" "File $($eventArgs.ChangeType), signing:" "$file"
}
if($CertPath) {
Set-AuthenticodeSignature -FilePath $file -Certificate $CertPath
} else {
Set-AuthenticodeSignature -FilePath $file
}
}
}
$watcher = New-Object IO.FileSystemWatcher $realItem.Fullname, $filter -Property @{ IncludeSubdirectories = $Recurse }
Register-ObjectEvent $watcher "Created" "AutoSignCreated$($realItem.Fullname)" -Action $Action > $null
Register-ObjectEvent $watcher "Changed" "AutoSignChanged$($realItem.Fullname)" -Action $Action > $null
Register-ObjectEvent $watcher "Renamed" "AutoSignChanged$($realItem.Fullname)" -Action $Action > $null
}
Set-Alias gas Get-AuthenticodeSignature -Description "Authenticode Module Alias"
Set-Alias sas Set-AuthenticodeSignature -Description "Authenticode Module Alias"
Set-Alias slas Select-AuthenticodeSigned -Description "Authenticode Module Alias"
Set-Alias sign Set-AuthenticodeSignature -Description "Authenticode Module Alias"
Export-ModuleMember -Alias gas,sas,slas,sign -Function Set-AuthenticodeSignature, Get-AuthenticodeSignature, Test-AuthenticodeSignature, Select-AuthenticodeSigned, Get-UserCertificate, Get-AuthenticodeCertificate, Start-AutoSign
# SIG # Begin signature block
# MIIIDQYJKoZIhvcNAQcCoIIH/jCCB/oCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUGfR1YWyjVOMuIfpDUQHcjAv8
# W8OgggUrMIIFJzCCBA+gAwIBAgIQKQm90jYWUDdv7EgFkuELajANBgkqhkiG9w0B
# AQUFADCBlTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0
# IExha2UgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYD
# VQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHTAbBgNVBAMTFFVUTi1VU0VS
# Rmlyc3QtT2JqZWN0MB4XDTEwMDUxNDAwMDAwMFoXDTExMDUxNDIzNTk1OVowgZUx
# CzAJBgNVBAYTAlVTMQ4wDAYDVQQRDAUwNjg1MDEUMBIGA1UECAwLQ29ubmVjdGlj
# dXQxEDAOBgNVBAcMB05vcndhbGsxFjAUBgNVBAkMDTQ1IEdsb3ZlciBBdmUxGjAY
# BgNVBAoMEVhlcm94IENvcnBvcmF0aW9uMRowGAYDVQQDDBFYZXJveCBDb3Jwb3Jh
# dGlvbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMfUdxwiuWDb8zId
# KuMg/jw0HndEcIsP5Mebw56t3+Rb5g4QGMBoa8a/N8EKbj3BnBQDJiY5Z2DGjf1P
# n27g2shrDaNT1MygjYfLDntYzNKMJk4EjbBOlR5QBXPM0ODJDROg53yHcvVaXSMl
# 498SBhXVSzPmgprBJ8FDL00o1IIAAhYUN3vNCKPBXsPETsKtnezfzBg7lOjzmljC
# mEOoBGT1g2NrYTq3XqNo8UbbDR8KYq5G101Vl0jZEnLGdQFyh8EWpeEeksv7V+YD
# /i/iXMSG8HiHY7vl+x8mtBCf0MYxd8u1IWif0kGgkaJeTCVwh1isMrjiUnpWX2NX
# +3PeTmsCAwEAAaOCAW8wggFrMB8GA1UdIwQYMBaAFNrtZHQUnBQ8q92Zqb1bKE2L
# PMnYMB0GA1UdDgQWBBTK0OAaUIi5wvnE8JonXlTXKWENvTAOBgNVHQ8BAf8EBAMC
# B4AwDAYDVR0TAQH/BAIwADATBgNVHSUEDDAKBggrBgEFBQcDAzARBglghkgBhvhC
# AQEEBAMCBBAwRgYDVR0gBD8wPTA7BgwrBgEEAbIxAQIBAwIwKzApBggrBgEFBQcC
# ARYdaHR0cHM6Ly9zZWN1cmUuY29tb2RvLm5ldC9DUFMwQgYDVR0fBDswOTA3oDWg
# M4YxaHR0cDovL2NybC51c2VydHJ1c3QuY29tL1VUTi1VU0VSRmlyc3QtT2JqZWN0
# LmNybDA0BggrBgEFBQcBAQQoMCYwJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmNv
# bW9kb2NhLmNvbTAhBgNVHREEGjAYgRZKb2VsLkJlbm5ldHRAWGVyb3guY29tMA0G
# CSqGSIb3DQEBBQUAA4IBAQAEss8yuj+rZvx2UFAgkz/DueB8gwqUTzFbw2prxqee
# zdCEbnrsGQMNdPMJ6v9g36MRdvAOXqAYnf1RdjNp5L4NlUvEZkcvQUTF90Gh7OA4
# rC4+BjH8BA++qTfg8fgNx0T+MnQuWrMcoLR5ttJaWOGpcppcptdWwMNJ0X6R2WY7
# bBPwa/CdV0CIGRRjtASbGQEadlWoc1wOfR+d3rENDg5FPTAIdeRVIeA6a1ZYDCYb
# 32UxoNGArb70TCpV/mTWeJhZmrPFoJvT+Lx8ttp1bH2/nq6BDAIvu0VGgKGxN4bA
# T3WE6MuMS2fTc1F8PCGO3DAeA9Onks3Ufuy16RhHqeNcMYICTDCCAkgCAQEwgaow
# gZUxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJVVDEXMBUGA1UEBxMOU2FsdCBMYWtl
# IENpdHkxHjAcBgNVBAoTFVRoZSBVU0VSVFJVU1QgTmV0d29yazEhMB8GA1UECxMY
# aHR0cDovL3d3dy51c2VydHJ1c3QuY29tMR0wGwYDVQQDExRVVE4tVVNFUkZpcnN0
# LU9iamVjdAIQKQm90jYWUDdv7EgFkuELajAJBgUrDgMCGgUAoHgwGAYKKwYBBAGC
# NwIBDDEKMAigAoAAoQKAADAZBgkqhkiG9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgor
# BgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQUOIm528+7
# FtEr5g4ZCgKJv41Ba60wDQYJKoZIhvcNAQEBBQAEggEAPDRvxMNIOV6rSJ1ZTHIr
# PYh99AFKfgMDkAfxZn5zwzZBwUAbvyRsXpqLecqVaiYAh50yORfPFCXOzJA7tJUn
# Sc3uDMnBZ5VU4obS5xTn25N7hEp2EWPIvrw2kGgKq5+HUnHWIqyyxOyWFxC32tQ/
# /hWw7U4IpnNlSBVYEWVh6WwS6r091UQlO5SIZ5bTP329+8kUJ4qcJm5a61oFJ8Hr
# O9WgxVQmIzmR/OQNv1pAxyG3p6nB5VlGuJSKPshphAVWT73RmWmY0O8VPiokqzFb
# eVNYquzBTJyK4gEcQw8VE0v3KQi9gzPatoaFAxbzyrseBIb5FRIcsnuBgFGhwT36
# MQ==
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Out-ColorMatchInfo.ps1
|
Out-ColorMatchInfo.ps1
|
<#
.Synopsis
Highlights MatchInfo objects similar to the output from grep.
.Description
Highlights MatchInfo objects similar to the output from grep.
#>
#requires -version 2
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[Microsoft.PowerShell.Commands.MatchInfo] $match
)
begin {}
process {
function Get-RelativePath([string] $path) {
$path = $path.Replace($pwd.Path, '')
if ($path.StartsWith('\\') -and (-not $path.StartsWith('\\\\'))) {
$path = $path.Substring(1)
}
$path
}
function Write-PathAndLine($match) {
Write-Host (Get-RelativePath $match.Path) -foregroundColor DarkMagenta -nonewline
Write-Host ':' -foregroundColor Cyan -nonewline
Write-Host $match.LineNumber -foregroundColor DarkYellow
}
function Write-HighlightedMatch($match) {
$index = 0
foreach ($m in $match.Matches) {
Write-Host $match.Line.SubString($index, $m.Index - $index) -nonewline
Write-Host $m.Value -ForegroundColor Red -nonewline
$index = $m.Index + $m.Length
}
if ($index -lt $match.Line.Length) {
Write-Host $match.Line.SubString($index) -nonewline
}
''
}
Write-PathAndLine $match
$match.Context.DisplayPreContext
Write-HighlightedMatch $match
$match.Context.DisplayPostContext
''
}
end {}
|
PowerShellCorpus/PoshCode/Start-Presentation.ps1
|
Start-Presentation.ps1
|
PARAM(
$presentationTitle = "PowerShell Presentation"
, $background = "C:\\Users\\Joel\\Pictures\\flow\\Flow_2560.jpg"
)
Import-Module PowerBoots
$name = [System.Windows.Navigation.JournalEntry]::NameProperty
function global:Add-Slide {
[CmdletBinding()]
PARAM(
[Parameter(Position=0)]
$Title = "This is the title"
, [Parameter(Position=1, ValueFromPipeline=$true)]
[string[]]$Content = @("Several bullet points", "Which are equally important")
, [Parameter()]
$Window = $presentationTitle
)
BEGIN { [string[]]$Points = @() }
PROCESS { [string[]]$Points += $Content }
END {
Invoke-BootsWindow $Window {
$global:container[0].Content = `
StackPanel -Margin 10 {
TextBlock $Title -FontSize 42 -FontWeight Bold -Foreground "#FF0088"
$Points | % { TextBlock -FontSize 24 -Foreground "White" $_ }
} | Set-AttachedProperty $Name $Title
}
}
}
function global:Set-Slide {
PARAM([int]$index)
Invoke-BootsWindow $presentationTitle {
$count = @($global:container[0].BackStack.GetEnumerator()).Count
for($i=$count;$i -lt $index;$i++) {
$global:container[0].GoForward()
}
for($i=$count;$i -gt $index;$i--) {
$global:container[0].GoBack()
}
}
}
## Finally, make the slide window
Boots -Title $presentationTitle {
Frame -Ov global:container `
-MinWidth 800 -MinHeight 600 `
-Content {
StackPanel {
TextBlock -FontSize 42 $presentationTitle -Foreground "White"
} -ov global:WelcomePage |
Set-AttachedProperty $Name "Welcome"
}
} -Async -Popup -On_SourceInitialized {
$this.Background = ImageBrush -ImageSource $background
} -WindowState Maximized
"Point 1 is cool","Point 2 is also" | Add-Slide "Slide 1"
"This is one point", "And this is another" | Add-Slide "Slide 2"
Add-Slide "Slide 3" "Point 5 is cool","Point 6 is also"
Add-Slide "Slide 4" "This is one point", "And this is the last"
Set-Slide 0
|
PowerShellCorpus/PoshCode/Test-Certificate_2.ps1
|
Test-Certificate_2.ps1
|
#####################################################################
# Test-Certificate.ps1
# Version 0.9
#
# Tests specified certificate for certificate chain and revocation
#
# Vadims Podans (c) 2009
# http://www.sysadmins.lv/
#####################################################################
#requires -Version 2.0
function Test-Certificate {
<#
.Synopsis
Tests specified certificate for certificate chain and revocation
.Description
Tests specified certificate for certificate chain and revocation status for each certificate in chain
exluding Root certificates
.Parameter Certificate
Specifies the certificate to test certificate chain. This parameter may accept
X509Certificate, X509Certificate2 objects or physical file path. this paramter accept
pipeline input
.Parameter Password
Specifies PFX file password. Password must be passed as SecureString.
.Parameter CRLMode
Sets revocation check mode. May contain on of the following values:
Online - perform revocation check downloading CRL from CDP extension ignoring cached CRLs. Default value
Offline - perform revocation check using cached CRLs if they are already downloaded
NoCheck - specified certificate will not checked for revocation status (not recommended)
.Parameter CRLFlag
Sets revocation flags for chain elements. May contain one of the following values:
ExcludeRoot - perform revocation check for each certificate in chain exluding root. Default value
EntireChain - perform revocation check for each certificate in chain including root. (not recommended)
EndCertificateOnly - perform revocation check for specified certificate only.
.Parameter VerificationFlags
Sets verification checks that will bypassed performed during certificate chaining engine
check. You may specify one of the following values:
NoFlag - No flags pertaining to verification are included (default).
IgnoreNotTimeValid - Ignore certificates in the chain that are not valid either because they have expired or they
are not yet in effect when determining certificate validity.
IgnoreCtlNotTimeValid - Ignore that the certificate trust list (CTL) is not valid, for reasons such as the CTL
has expired, when determining certificate verification.
IgnoreNotTimeNested - Ignore that the CA (certificate authority) certificate and the issued certificate have
validity periods that are not nested when verifying the certificate. For example, the CA cert can be valid
from January 1 to December 1 and the issued certificate from January 2 to December 2, which would mean the
validity periods are not nested.
IgnoreInvalidBasicConstraints - Ignore that the basic constraints are not valid when determining certificate
verification.
AllowUnknownCertificateAuthority - Ignore that the chain cannot be verified due to an unknown certificate
authority (CA).
IgnoreWrongUsage - Ignore that the certificate was not issued for the current use when determining
certificate verification.
IgnoreInvalidName - Ignore that the certificate has an invalid name when determining certificate verification.
IgnoreInvalidPolicy - Ignore that the certificate has invalid policy when determining certificate verification.
IgnoreEndRevocationUnknown - Ignore that the end certificate (the user certificate) revocation is unknown when
determining certificate verification.
IgnoreCtlSignerRevocationUnknown - Ignore that the certificate trust list (CTL) signer revocation is unknown
when determining certificate verification.
IgnoreCertificateAuthorityRevocationUnknown - Ignore that the certificate authority revocation is unknown
when determining certificate verification.
IgnoreRootRevocationUnknown - Ignore that the root revocation is unknown when determining certificate verification.
AllFlags - All flags pertaining to verification are included.
.Example
Get-ChilItem cert:\\CurrentUser\\My | Test-Certificate -CRLMode "NoCheck"
Will check certificate chain for each certificate in current user Personal container.
Certificates will not checked for revocation status.
.Example
Test-Certificate C:\\Certs\\certificate.cer -CRLFlag "EndCertificateOnly"
Will check certificate chain for certificate that is located in C:\\Certs and named
as Certificate.cer and revocation checking will be performed for specified certificate only
.Outputs
This script return general info about certificate chain status
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
$Certificate,
[System.Security.SecureString]$Password,
[System.Security.Cryptography.X509Certificates.X509RevocationMode]$CRLMode = "Online",
[System.Security.Cryptography.X509Certificates.X509RevocationFlag]$CRLFlag = "ExcludeRoot",
[System.Security.Cryptography.X509Certificates.X509VerificationFlags]$VerificationFlags = "NoFlag"
)
begin {
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$chain = New-Object System.Security.Cryptography.X509Certificates.X509Chain
$chain.ChainPolicy.RevocationFlag = $CRLFlag
$chain.ChainPolicy.RevocationMode = $CRLMode
$chain.ChainPolicy.VerificationFlags = $VerificationFlags
function _getstatus_ ($status, $chain, $cert) {
if ($status) {
Write-Host Current certificate $cert.SerialNumber chain and revocation status is valid -ForegroundColor Green
} else {
Write-Warning "Current certificate $($cert.SerialNumber) chain is invalid due of the following errors:"
$chain.ChainStatus | %{Write-Host $_.StatusInformation.trim() -ForegroundColor Red}
}
}
}
process {
if ($_ -is [System.Security.Cryptography.X509Certificates.X509Certificate2]) {
$status = $chain.Build($_)
_getstatus_ $status $chain $_
} else {
if (!(Test-Path $Certificate)) {Write-Warning "Specified path is invalid"; return}
else {
if ((Resolve-Path $Certificate).Provider.Name -ne "FileSystem") {
Write-Warning "Spicifed path is not recognized as filesystem path. Try again"; return
} else {
$Certificate = gi $(Resolve-Path $Certificate)
switch -regex ($Certificate.Extension) {
"\\.CER|\\.DER|\\.CRT" {$cert.Import($Certificate.FullName)}
"\\.PFX" {
if (!$Password) {$Password = Read-Host "Enter password for PFX file $certificate" -AsSecureString}
$cert.Import($Certificate.FullName, $password, "UserKeySet")
}
"\\.P7B|\\.SST" {
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
$cert.Import([System.IO.File]::ReadAllBytes($Certificate.FullName))
}
default {Write-Warning "Looks like your specified file is not a certificate file"; return}
}
$cert | %{
$status = $chain.Build($_)
_getstatus_ $status $chain $_
}
$cert.Reset()
$chain.Reset()
}
}
}
}
}
# SIG # Begin signature block
# MIIIPAYJKoZIhvcNAQcCoIIILTCCCCkCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUbRDcSlj31gB3Dj0E/HWIHY/w
# 5IKgggVaMIIFVjCCBD6gAwIBAgIQSX2g7+3+PL1oSJra3tEBIzANBgkqhkiG9w0B
# AQUFADCBlTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0
# IExha2UgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYD
# VQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHTAbBgNVBAMTFFVUTi1VU0VS
# Rmlyc3QtT2JqZWN0MB4XDTA5MTAxNjAwMDAwMFoXDTEwMTAxNjIzNTk1OVowgcQx
# CzAJBgNVBAYTAlVTMQ4wDAYDVQQRDAUxNDYyMzERMA8GA1UECAwITmV3IFlvcmsx
# EjAQBgNVBAcMCVJvY2hlc3RlcjEUMBIGA1UECQwLTVMgMDgwMS0xN0ExGjAYBgNV
# BAkMETEzNTAgSmVmZmVyc29uIFJkMRowGAYDVQQKDBFYZXJveCBDb3Jwb3JhdGlv
# bjEUMBIGA1UECwwLU0VFRFUgVG9vbHMxGjAYBgNVBAMMEVhlcm94IENvcnBvcmF0
# aW9uMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA+BtkDUSRsr9qshYW
# 6mBLwe62RdoKaBiCZh1whKQbAqN58lmbN3fP2Qf6eheR03EyqPXq5gGQO8SpeeOn
# tDmlgR47dKFfawWKLEM4H189FJ6VHKD8Hmk1+/OAv/6F45HvbXOrGmisUgKplmzl
# tmot9uv04nyFlRXMPbHwKxNlWOdSSs1N9Y+q7y3kuSBm4bCqquqEFnm7gAzHt/A1
# 1CkT8f/0UP0ODKj0Cs/hc+b/xOCCL06SALYOYtMdBFwluBs85p2Bv1WcdUIELprz
# jnOjgoF4vk29UIUNkDZ5j2d0W0FCNd61ukm9faJMuU2/yw348sxclSoT18yOeC+Z
# vKc4lQIDAQABo4IBbzCCAWswHwYDVR0jBBgwFoAU2u1kdBScFDyr3ZmpvVsoTYs8
# ydgwHQYDVR0OBBYEFAu07ifjpHK32XeSDsdjIK4/R25LMA4GA1UdDwEB/wQEAwIH
# gDAMBgNVHRMBAf8EAjAAMBMGA1UdJQQMMAoGCCsGAQUFBwMDMBEGCWCGSAGG+EIB
# AQQEAwIEEDBGBgNVHSAEPzA9MDsGDCsGAQQBsjEBAgEDAjArMCkGCCsGAQUFBwIB
# Fh1odHRwczovL3NlY3VyZS5jb21vZG8ubmV0L0NQUzBCBgNVHR8EOzA5MDegNaAz
# hjFodHRwOi8vY3JsLnVzZXJ0cnVzdC5jb20vVVROLVVTRVJGaXJzdC1PYmplY3Qu
# Y3JsMDQGCCsGAQUFBwEBBCgwJjAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AuY29t
# b2RvY2EuY29tMCEGA1UdEQQaMBiBFkpvZWwuQmVubmV0dEBYZXJveC5jb20wDQYJ
# KoZIhvcNAQEFBQADggEBAG5+It5AFsnqx1GDTuHxuExJGtpRYH6OatSs3eV507zz
# 5tyKbtCros6j92rvJOUfefk38saqbk81o5vMvEyQ/lQ7tp06NV0QBdt5WtoOnUZk
# u2lG4NcxiSz5vxQRF4+3mUZ77K3kRu6zY+zrauTTONmRPOdhYMMbKfZ67kePVNNv
# gnueXBxhd+xj5FJUVTW0qlks6+uYMKNM+MLvRxV83WUYwpnfcQyyvVILsVdw56qp
# OzOxIsQDc2flhqYVktPjL80fOXAPWzs88VXxoEkO3fvqHXi3VlWxMVV/861RORzk
# 5aleuMEp/2Ue1dJG279ATD1QDCHiG11Vz34Pdptf3FYxggJMMIICSAIBATCBqjCB
# lTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2Ug
# Q2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExho
# dHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHTAbBgNVBAMTFFVUTi1VU0VSRmlyc3Qt
# T2JqZWN0AhBJfaDv7f48vWhImtre0QEjMAkGBSsOAwIaBQCgeDAYBgorBgEEAYI3
# AgEMMQowCKACgAChAoAAMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3AgEEMBwGCisG
# AQQBgjcCAQsxDjAMBgorBgEEAYI3AgEVMCMGCSqGSIb3DQEJBDEWBBSLcWVsGmEs
# y3aqToxGv4N7GtZKaTANBgkqhkiG9w0BAQEFAASCAQBKs1LvUwZC+0Bs9/3D03/L
# xp9NYjTfnXfeKI73KOnw4RMKY4rnnbEi0eLxsKOyFTDLbvEkO0dPeRa8LVANktgx
# H2zHECjyud949UaU1CnAhJhbx0EHQQatumsBEcaQqO/vJGTTE3F1faxIbQoyxkZC
# bax1ISAF1JeR8avSDgLEEDj1kqTP7a5lNTO0k9CX0kvmF7GXGBwEJJ0XZh1ipCFW
# PEF9xdE3wP3iXs2rVk8LZIKx6Iz14PPhp/004hKKPUolAg9PPJM+fiN6vsluTpoH
# tDe5OXi71/Hpl51E9XNpRz/kUyB5MSxvsl9bf0DTHwWTa4hOrvWUBpkPU10FT7y6
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Get-MIX10Video_1.ps1
|
Get-MIX10Video_1.ps1
|
#requires -version 2.0
PARAM (
[Parameter(Position=1, Mandatory=$true)]
[ValidateSet("wmv","wmvhigh","pptx", "mp4")]
[String]$MediaType,
[string]$Destination = $PWD
)
if( ([System.Environment]::OSVersion.Version.Major -gt 5) -and -not ( # Vista and ...
new-object Security.Principal.WindowsPrincipal (
[Security.Principal.WindowsIdentity]::GetCurrent()) # current user is admin
).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) ) {
Write-Warning @"
On VISTA and above, BITS limits the number of jobs in the queue to 300 jobs and the number of jobs that a non-administrator user can create to 60 jobs.
You MUST run this script from an elevated host if you're on Vista, Windows 7, or Server 2008
"@
}
Import-Module BitsTransfer
Push-Location $Destination
$Extension = $(switch -wildcard($MediaType){"wmv*"{"wmv"} "mp4"{"mp4"} "ppt"{"pptx"}})
$BaseUrl = "http://ecn.channel9.msdn.com/o9/mix/10/{0}/{2}.{1}"
$DownloadSite= 'http://live.visitmix.com/Videos'
[regex]$regex = ('(CL|DS|EX|FTL|KEY|PR|SVC)[0-9][0-9]')
$regex.matches((New-Object system.net.webclient).downloadstring($DownloadSite)) |
Select-Object -ExpandProperty value |
Sort-Object -Unique |
ForEach-Object { Start-BitsTransfer -Source $($BaseUrl -f $MediaType, $Extension, $_) -Async }
Pop-Location
Write-Host "You may now use Get-BitsTransfer to check on the status of the downloads. By default, failed transfers will be retried every 10 minutes for two weeks."
# SIG # Begin signature block
# MIIQpAYJKoZIhvcNAQcCoIIQlTCCEJECAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU1rHbsevByxO2Dg/epgqTER3S
# YH6ggg3ZMIIGyzCCBbOgAwIBAgICAIMwDQYJKoZIhvcNAQEFBQAwgYwxCzAJBgNV
# BAYTAklMMRYwFAYDVQQKEw1TdGFydENvbSBMdGQuMSswKQYDVQQLEyJTZWN1cmUg
# RGlnaXRhbCBDZXJ0aWZpY2F0ZSBTaWduaW5nMTgwNgYDVQQDEy9TdGFydENvbSBD
# bGFzcyAyIFByaW1hcnkgSW50ZXJtZWRpYXRlIE9iamVjdCBDQTAeFw0wOTEyMjIw
# NjAwMTlaFw0xMTEyMjMxMTE2NTdaMIHIMSAwHgYDVQQNExcxMTc2NjEtcTdtZGI4
# Y28zaGhBbXAxMjELMAkGA1UEBhMCVVMxEjAQBgNVBAgTCVdpc2NvbnNpbjESMBAG
# A1UEBxMJR3JlZW5kYWxlMS0wKwYDVQQLEyRTdGFydENvbSBWZXJpZmllZCBDZXJ0
# aWZpY2F0ZSBNZW1iZXIxGDAWBgNVBAMTD1N0ZXZlbiBNdXJhd3NraTEmMCQGCSqG
# SIb3DQEJARYXc3RldmVAdXNlcG93ZXJzaGVsbC5jb20wggEiMA0GCSqGSIb3DQEB
# AQUAA4IBDwAwggEKAoIBAQC94TIYIjVOhj2zKhUQngQ5nxqPCCH6/nsKe49FNqgE
# SPG2PRX9WBNdYIg1QXhpkw16bw+1PItHJi6vjZ7OiYyrS1Sui6iUnQ3Nt40I1H7N
# Hn4i5yn7AcFgUUCBpQgUXEc+10pZUnJ7mY1BqJJGXrDve8I2NxkDPiPwNnm6xqwO
# XkeaWSYpxKv/QXI6J+wnSSvrcMZegMxZ8TbMT7ihNCt8Y+UVlKF7g4jcRjnGzn5h
# F5qJodmgIIuQGkuKspTzqDrIMelJHqZTyvHWBjtA09zkDpMpDlhMP6A4Lu2vpIrc
# 8Ztb9FAFD/+oTLo1cz80QjY2I7rM3oxAWwsdGrCkIn09AgMBAAGjggL3MIIC8zAJ
# BgNVHRMEAjAAMA4GA1UdDwEB/wQEAwIHgDA6BgNVHSUBAf8EMDAuBggrBgEFBQcD
# AwYKKwYBBAGCNwIBFQYKKwYBBAGCNwIBFgYKKwYBBAGCNwoDDTAdBgNVHQ4EFgQU
# nU30uCjZk+GBJq9f25DWwbMRxhQwHwYDVR0jBBgwFoAU0E4PQJlsuEsZbzsouODj
# iAc0qrcwggFCBgNVHSAEggE5MIIBNTCCATEGCysGAQQBgbU3AQIBMIIBIDAuBggr
# BgEFBQcCARYiaHR0cDovL3d3dy5zdGFydHNzbC5jb20vcG9saWN5LnBkZjA0Bggr
# BgEFBQcCARYoaHR0cDovL3d3dy5zdGFydHNzbC5jb20vaW50ZXJtZWRpYXRlLnBk
# ZjCBtwYIKwYBBQUHAgIwgaowFBYNU3RhcnRDb20gTHRkLjADAgEBGoGRTGltaXRl
# ZCBMaWFiaWxpdHksIHNlZSBzZWN0aW9uICpMZWdhbCBMaW1pdGF0aW9ucyogb2Yg
# dGhlIFN0YXJ0Q29tIENlcnRpZmljYXRpb24gQXV0aG9yaXR5IFBvbGljeSBhdmFp
# bGFibGUgYXQgaHR0cDovL3d3dy5zdGFydHNzbC5jb20vcG9saWN5LnBkZjBjBgNV
# HR8EXDBaMCugKaAnhiVodHRwOi8vd3d3LnN0YXJ0c3NsLmNvbS9jcnRjMi1jcmwu
# Y3JsMCugKaAnhiVodHRwOi8vY3JsLnN0YXJ0c3NsLmNvbS9jcnRjMi1jcmwuY3Js
# MIGJBggrBgEFBQcBAQR9MHswNwYIKwYBBQUHMAGGK2h0dHA6Ly9vY3NwLnN0YXJ0
# c3NsLmNvbS9zdWIvY2xhc3MyL2NvZGUvY2EwQAYIKwYBBQUHMAKGNGh0dHA6Ly93
# d3cuc3RhcnRzc2wuY29tL2NlcnRzL3N1Yi5jbGFzczIuY29kZS5jYS5jcnQwIwYD
# VR0SBBwwGoYYaHR0cDovL3d3dy5zdGFydHNzbC5jb20vMA0GCSqGSIb3DQEBBQUA
# A4IBAQDAKxouOZbRGXHT2avNItDoYlnhoLXypJnLUiRX9LXoOSh5Tlj6EQPJuXyG
# pqVDzPfN3YdqmqTSSVay7r7ndOa+VvyPppIc4xE7nMuSPT8HUej96sDJI0QBbQM2
# +OoEVl/ZXcsPbaIGKVKkPFS3nTJ54UNxPKfHUK71IimVyhMQY/KaucD0BuU9Guqi
# 8rh2eYqm2BKkD8RHJxSbTCoMY1g83B/pvaGs2bI7OCwL+sfICFQhoRzY7RLE2Rvy
# maIr9CzN7EBTNYWSr56j/0vuvNFCn0htw2rspyN8ZS+pa3lc/MiWoLVJ09HwJ1pK
# C1soqH5vqdPHHDkw1E5qY8uraRCRMIIHBjCCBO6gAwIBAgIBFTANBgkqhkiG9w0B
# AQUFADB9MQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkG
# A1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UE
# AxMgU3RhcnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDcxMDI0MjIw
# MTQ1WhcNMTIxMDI0MjIwMTQ1WjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0
# YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRl
# IFNpZ25pbmcxODA2BgNVBAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJbnRl
# cm1lZGlhdGUgT2JqZWN0IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
# AQEAyiOLIjUemqAbPJ1J0D8MlzgWKbr4fYlbRVjvhHDtfhFN6RQxq0PjTQxRgWzw
# FQNKJCdU5ftKoM5N4YSjId6ZNavcSa6/McVnhDAQm+8H3HWoD030NVOxbjgD/Ih3
# HaV3/z9159nnvyxQEckRZfpJB2Kfk6aHqW3JnSvRe+XVZSufDVCe/vtxGSEwKCaN
# rsLc9pboUoYIC3oyzWoUTZ65+c0H4paR8c8eK/mC914mBo6N0dQ512/bkSdaeY9Y
# aQpGtW/h/W/FkbQRT3sCpttLVlIjnkuY4r9+zvqhToPjxcfDYEf+XD8VGkAqle8A
# a8hQ+M1qGdQjAye8OzbVuUOw7wIDAQABo4ICfzCCAnswDAYDVR0TBAUwAwEB/zAL
# BgNVHQ8EBAMCAQYwHQYDVR0OBBYEFNBOD0CZbLhLGW87KLjg44gHNKq3MIGoBgNV
# HSMEgaAwgZ2AFE4L7xqkQFulF2mHMMo0aEPQQa7yoYGBpH8wfTELMAkGA1UEBhMC
# SUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdp
# dGFsIENlcnRpZmljYXRlIFNpZ25pbmcxKTAnBgNVBAMTIFN0YXJ0Q29tIENlcnRp
# ZmljYXRpb24gQXV0aG9yaXR5ggEBMAkGA1UdEgQCMAAwPQYIKwYBBQUHAQEEMTAv
# MC0GCCsGAQUFBzAChiFodHRwOi8vd3d3LnN0YXJ0c3NsLmNvbS9zZnNjYS5jcnQw
# YAYDVR0fBFkwVzAsoCqgKIYmaHR0cDovL2NlcnQuc3RhcnRjb20ub3JnL3Nmc2Nh
# LWNybC5jcmwwJ6AloCOGIWh0dHA6Ly9jcmwuc3RhcnRzc2wuY29tL3Nmc2NhLmNy
# bDCBggYDVR0gBHsweTB3BgsrBgEEAYG1NwEBBTBoMC8GCCsGAQUFBwIBFiNodHRw
# Oi8vY2VydC5zdGFydGNvbS5vcmcvcG9saWN5LnBkZjA1BggrBgEFBQcCARYpaHR0
# cDovL2NlcnQuc3RhcnRjb20ub3JnL2ludGVybWVkaWF0ZS5wZGYwEQYJYIZIAYb4
# QgEBBAQDAgABMFAGCWCGSAGG+EIBDQRDFkFTdGFydENvbSBDbGFzcyAyIFByaW1h
# cnkgSW50ZXJtZWRpYXRlIE9iamVjdCBTaWduaW5nIENlcnRpZmljYXRlczANBgkq
# hkiG9w0BAQUFAAOCAgEAUKLQmPRwQHAAtm7slo01fXugNxp/gTJY3+aIhhs8Gog+
# IwIsT75Q1kLsnnfUQfbFpl/UrlB02FQSOZ+4Dn2S9l7ewXQhIXwtuwKiQg3NdD9t
# uA8Ohu3eY1cPl7eOaY4QqvqSj8+Ol7f0Zp6qTGiRZxCv/aNPIbp0v3rD9GdhGtPv
# KLRS0CqKgsH2nweovk4hfXjRQjp5N5PnfBW1X2DCSTqmjweWhlleQ2KDg93W61Tw
# 6M6yGJAGG3GnzbwadF9BUW88WcRsnOWHIu1473bNKBnf1OKxxAQ1/3WwJGZWJ5Ux
# hCpA+wr+l+NbHP5x5XZ58xhhxu7WQ7rwIDj8d/lGU9A6EaeXv3NwwcbIo/aou5v9
# y94+leAYqr8bbBNAFTX1pTxQJylfsKrkB8EOIx+Zrlwa0WE32AgxaKhWAGho/Ph7
# d6UXUSn5bw2+usvhdkW4npUoxAk3RhT3+nupi1fic4NG7iQG84PZ2bbS5YxOmaII
# sIAxclf25FwssWjieMwV0k91nlzUFB1HQMuE6TurAakS7tnIKTJ+ZWJBDduUbcD1
# 094X38OvMO/++H5S45Ki3r/13YTm0AWGOvMFkEAF8LbuEyecKTaJMTiNRfBGMgnq
# GBfqiOnzxxRVNOw2hSQp0B+C9Ij/q375z3iAIYCbKUd/5SSELcmlLl+BuNknXE0x
# ggI1MIICMQIBATCBkzCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29t
# IEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRlIFNpZ25p
# bmcxODA2BgNVBAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJbnRlcm1lZGlh
# dGUgT2JqZWN0IENBAgIAgzAJBgUrDgMCGgUAoHgwGAYKKwYBBAGCNwIBDDEKMAig
# AoAAoQKAADAZBgkqhkiG9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgorBgEEAYI3AgEL
# MQ4wDAYKKwYBBAGCNwIBFjAjBgkqhkiG9w0BCQQxFgQUvCnDmypuBgpyTnsqsizH
# k7dxTZ0wDQYJKoZIhvcNAQEBBQAEggEAKfOmoJWHshLV7kwyeZHtShnB3E1HpxLg
# GTfATRtZFVaomevrDBhFLLkLRLmeTHE6hmLEiRud5C4KOU7GzDG0St3Bb9oggeO/
# dXDrkfUHlk7VJLMz+BiwbANAeiN5BNSuPXDzrYRlYHaGYWbMtrh2z5q9fHT/2IjF
# 40N80PN4KDx2k6M49kPAA49DiLwEuCrjHZSeKgdx6zANNydhkBx8xvkAtpBGP0cX
# lnh22mPL0OAS7vV8Z8Xp9E54eBnjbAVE77QidlRJj9fL7TXuT9bkASiWAFAAYF/J
# fEG7coOCJyr0ZrcIxaOe94HwzR4SMHzU+mpogUXDW6g+lCc9kvJC2w==
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Convert-ToCHexString_2.ps1
|
Convert-ToCHexString_2.ps1
|
function Convert-ToCHexString
{
param ([String] $str)
$ans = ''
[System.Text.Encoding]::ASCII.GetBytes($str) | % { $ans += "0x{0:X2}, " -f $_ }
return $ans.Trim(' ',',')
}
|
PowerShellCorpus/PoshCode/Const.ps1
|
Const.ps1
|
function Set-Constant {
<#
.SYNOPSIS
Creates constants.
.DESCRIPTION
This function can help you to create constants so easy as it possible.
It works as keyword 'const' as such as in C#.
.EXAMPLE
PS C:\\> Set-Constant a = 10
PS C:\\> $a += 13
There is a integer constant declaration, so the second line return
error.
.EXAMPLE
PS C:\\> const str = "this is a constant string"
You also can use word 'const' for constant declaration. There is a
string constant named '$str' in this example.
.LINK
Set-Variable
About_Functions_Advanced_Parameters
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0)]
[string][ValidateNotNullOrEmpty()]$Name,
[Parameter(Mandatory=$true, Position=1)]
[char][ValidateSet("=")]$Link,
[Parameter(Mandatory=$true, Position=2)]
[object][ValidateNotNullOrEmpty()]$Mean,
[Parameter(Mandatory=$false)]
[string]$Surround = "script"
)
Set-Variable -n $name -val $mean -opt Constant -s $surround
}
Set-Alias const Set-Constant
|
PowerShellCorpus/PoshCode/VMWare DS Migration.ps1
|
VMWare DS Migration.ps1
|
#####################################################
# Migrate a VM to new storage and set to Thin Prov #
#####################################################
# Set the VM name you want to move
$Server = 'SERVERNAME'
# Set the location you want to move the VM to
$DataStore = 'DATASTORE'
# Set the vCenter name (should not need to be changed)
$VCName = 'VCENTERSERVER'
# Load VMWare Snapin
asnp VMware.VimAutomation.Core -ErrorAction SilentlyContinue
# Connect to vCenter
Connect-VIServer $VCName -User 'USERNAME' -Password 'PASSWORD'
# Check if server is powered off, if not perform a clean shutdown
$VMPower = Get-VM $Server
If($VMPower.PowerState -eq 'PoweredOn'){
Get-VM $Server | Shutdown-VMGuest
}
# Wait for VM to stop
Start-Sleep -s 30
# Move the server to the new storage and set it to thin provisioned
Move-VM $Server -Datastore $DataStore -DiskStorageFormat Thin
# Power on the VM
#Start-VM $Server
# disconnect from the vCenter CLI
Disconnect-VIServer -Confirm:$False
|
PowerShellCorpus/PoshCode/WSS_MOSS export.ps1
|
WSS_MOSS export.ps1
|
# Export sharepoint web contents with powershell like
# stsadm -o export -url http://localhost:80/wiki -filename export.cab -overwrite -versions 1
#
# http://www.sharepointblogs.com/mossms/default.aspx
# http://msdn2.microsoft.com/en-us/library/microsoft.sharepoint.deployment.aspx
param ( [string] $sitename = "http://localhost:80", [string] $relweburl = "/wiki")
# Load Assembly
[void] [System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
$spsite = new-object Microsoft.SharePoint.SPSite($SiteName)
$webpart = $spsite.openweb($relweburl, $false)
# Check type
if (!$webpart -is [Microsoft.SharePoint.SPWeb]) {
Write-Host "Wrong type to export!" -foregroundcolor red
exit
}
[System.Guid] $webguid = $webpart.ID
# $webguid.toString()
# Select Object to Export
[Microsoft.SharePoint.Deployment.SPExportObject] $exportObject = new-object Microsoft.SharePoint.Deployment.SPExportObject
$exportObject.Id = $webguid
$exportObject.Type = [Microsoft.SharePoint.Deployment.SPDeploymentObjectType]::Web
$exportObject.ExcludeChildren = $FALSE
$exportObject.IncludeDescendants = [Microsoft.SharePoint.Deployment.SPIncludeDescendants]::All
# Export Settings
[Microsoft.SharePoint.Deployment.SPExportSettings] $expSettings = new-object Microsoft.SharePoint.Deployment.SPExportSettings
$expSettings.SiteUrl = $sitename
$expSettings.ExportObjects.Add($exportObject)
$expSettings.ExportMethod = [Microsoft.SharePoint.Deployment.SPExportMethodType]::ExportAll # Or ExportChanges
$expSettings.FileCompression = $TRUE
$expSettings.OverwriteExistingDataFile = $TRUE
$expSettings.BaseFileName = "export.cab"
$expSettings.IncludeSecurity = [Microsoft.SharePoint.Deployment.SPIncludeSecurity]::None # Or All
$expSettings.FileLocation = "."
$expSettings.LogFilePath = "./export.log"
$expSettings.IncludeVersions = [Microsoft.SharePoint.Deployment.SPIncludeVersions]::LastMajor
$expSettings.ExcludeDependencies = $FALSE
$expSettings.Validate()
# Show Settings
$expSettings
# Now Export
[Microsoft.SharePoint.Deployment.SPExport] $export = new-object Microsoft.SharePoint.Deployment.SPExport($expSettings)
$export.Run()
Write-Host "Done!"
trap [Exception] {
write-host $("`tTRAPPED: " + $_.Exception.GetType().FullName)
write-host $("`tTRAPPED: " + $_.Exception.Message)
break
}
|
PowerShellCorpus/PoshCode/Audit Script_2.ps1
|
Audit Script_2.ps1
|
#####################################################
# #
# Audit script by Alan Renouf - Virtu-Al #
# Blog: http://teckinfo.blogspot.com/ #
# #
# Usage: Audit.ps1 'pathtolistofservers' #
# #
# The file is optional and needs to be a #
# plain text list of computers to be audited #
# one on each line. #
# #
#####################################################
param( [string] $auditlist)
if ($auditlist -eq ""){
Write-Host "No list specified, using $env:computername"
$targets = $env:computername
}
else
{
if ((Test-Path $auditlist) -eq $false)
{
Write-Host "Invalid audit path specified: $auditlist"
exit
}
else
{
Write-Host "Using Audit list: $auditlist"
$Targets = Get-Content $auditlist
}
}
$Date = Get-Date
Foreach ($Target in $Targets){
Write-Output "Collating Detail for $Target"
$ComputerSystem = Get-WmiObject -computername $Target Win32_ComputerSystem
switch ($ComputerSystem.DomainRole){
0 { $ComputerRole = "Standalone Workstation" }
1 { $ComputerRole = "Member Workstation" }
2 { $ComputerRole = "Standalone Server" }
3 { $ComputerRole = "Member Server" }
4 { $ComputerRole = "Domain Controller" }
5 { $ComputerRole = "Domain Controller" }
default { $ComputerRole = "Information not available" }
}
$OperatingSystems = Get-WmiObject -computername $Target Win32_OperatingSystem
$TimeZone = Get-WmiObject -computername $Target Win32_Timezone
$Keyboards = Get-WmiObject -computername $Target Win32_Keyboard
$SchedTasks = Get-WmiObject -computername $Target Win32_ScheduledJob
$BootINI = $OperatingSystems.SystemDrive + "boot.ini"
$RecoveryOptions = Get-WmiObject -computername $Target Win32_OSRecoveryConfiguration
switch ($ComputerRole){
"Member Workstation" { $CompType = "Computer Domain"; break }
"Domain Controller" { $CompType = "Computer Domain"; break }
"Member Server" { $CompType = "Computer Domain"; break }
default { $CompType = "Computer Workgroup"; break }
}
$LBTime=$OperatingSystems.ConvertToDateTime($OperatingSystems.Lastbootuptime)
Write-Output "..Hotfix Information"
$colQuickFixes = Get-WmiObject Win32_QuickFixEngineering
Write-Output "..Logical Disks"
$colDisks = Get-WmiObject -ComputerName $Target Win32_LogicalDisk
Write-Output "..Network Configuration"
$NICCount = 0
$colAdapters = Get-WmiObject -ComputerName $Target Win32_NetworkAdapterConfiguration
Write-Output "..Local Shares"
$colShares = Get-wmiobject -ComputerName $Target Win32_Share
Write-Output "..Printers"
$colInstalledPrinters = Get-WmiObject -ComputerName $Target Win32_Printer
Write-Output "..Services"
$colListOfServices = Get-WmiObject -ComputerName $Target Win32_Service
Write-Output "..Regional Options"
$ObjKeyboards = Get-WmiObject -ComputerName $Target Win32_Keyboard
$keyboardmap = @{
"00000402" = "BG"
"00000404" = "CH"
"00000405" = "CZ"
"00000406" = "DK"
"00000407" = "GR"
"00000408" = "GK"
"00000409" = "US"
"0000040A" = "SP"
"0000040B" = "SU"
"0000040C" = "FR"
"0000040E" = "HU"
"0000040F" = "IS"
"00000410" = "IT"
"00000411" = "JP"
"00000412" = "KO"
"00000413" = "NL"
"00000414" = "NO"
"00000415" = "PL"
"00000416" = "BR"
"00000418" = "RO"
"00000419" = "RU"
"0000041A" = "YU"
"0000041B" = "SL"
"0000041C" = "US"
"0000041D" = "SV"
"0000041F" = "TR"
"00000422" = "US"
"00000423" = "US"
"00000424" = "YU"
"00000425" = "ET"
"00000426" = "US"
"00000427" = "US"
"00000804" = "CH"
"00000809" = "UK"
"0000080A" = "LA"
"0000080C" = "BE"
"00000813" = "BE"
"00000816" = "PO"
"00000C0C" = "CF"
"00000C1A" = "US"
"00001009" = "US"
"0000100C" = "SF"
"00001809" = "US"
"00010402" = "US"
"00010405" = "CZ"
"00010407" = "GR"
"00010408" = "GK"
"00010409" = "DV"
"0001040A" = "SP"
"0001040E" = "HU"
"00010410" = "IT"
"00010415" = "PL"
"00010419" = "RU"
"0001041B" = "SL"
"0001041F" = "TR"
"00010426" = "US"
"00010C0C" = "CF"
"00010C1A" = "US"
"00020408" = "GK"
"00020409" = "US"
"00030409" = "USL"
"00040409" = "USR"
"00050408" = "GK"
}
$keyb = $keyboardmap.$($ObjKeyboards.Layout)
if (!$keyb)
{ $keyb = "Unknown"
}
Write-Output "..Event Log Settings"
$colLogFiles = Get-WmiObject -ComputerName $Target Win32_NTEventLogFile
Write-Output "..Event Log Errors"
$WmidtQueryDT = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime([DateTime]::Now.AddDays(-14))
$colLoggedEvents = Get-WmiObject -computer $Target -query ("Select * from Win32_NTLogEvent Where Type='Error' and TimeWritten >='" + $WmidtQueryDT + "'")
Write-Output "..Event Log Warnings"
$WmidtQueryDT = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime([DateTime]::Now.AddDays(-14))
$colLoggedEvents = Get-WmiObject -computer $Target -query ("Select * from Win32_NTLogEvent Where Type='Warning' and TimeWritten >='" + $WmidtQueryDT + "'")
$Filename = ".\\" + $Target + "_" + $date.Hour + $date.Minute + "_" + $Date.Day + "-" + $Date.Month + "-" + $Date.Year + ".htm"
$Report = @"
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html ES_auditInitialized='false'><head><title>Audit</title>
<META http-equiv=Content-Type content='text/html; charset=windows-1252'>
<STYLE type=text/css>
DIV .expando {DISPLAY: block; FONT-WEIGHT: normal; FONT-SIZE: 8pt; RIGHT: 10px; COLOR: #ffffff; FONT-FAMILY: Tahoma; POSITION: absolute; TEXT-DECORATION: underline}
TABLE {TABLE-LAYOUT: fixed; FONT-SIZE: 100%; WIDTH: 100%}
#objshowhide {PADDING-RIGHT: 10px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; Z-INDEX: 2; CURSOR: hand; COLOR: #000000; MARGIN-RIGHT: 0px; FONT-FAMILY: Tahoma; TEXT-ALIGN: right; TEXT-DECORATION: underline; WORD-WRAP: normal}
.heading0_expanded {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 8px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; WIDTH: 100%; CURSOR: hand; COLOR: #FFFFFF; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; BACKGROUND-COLOR: #cc0000}
.heading1 {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 16px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 5px; BORDER-LEFT: #bbbbbb 1px solid; WIDTH: 100%; CURSOR: hand; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; BACKGROUND-COLOR: #7BA7C7}
.heading2 {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 16px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 5px; BORDER-LEFT: #bbbbbb 1px solid; WIDTH: 100%; CURSOR: hand; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; BACKGROUND-COLOR: #A5A5A5}
.tableDetail {BORDER-RIGHT: #bbbbbb 1px solid; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 16px; FONT-SIZE: 8pt;MARGIN-BOTTOM: -1px; PADDING-BOTTOM: 5px; MARGIN-LEFT: 5px; BORDER-LEFT: #bbbbbb 1px solid; WIDTH: 100%; COLOR: #000000; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; BACKGROUND-COLOR: #f9f9f9}
.filler {BORDER-RIGHT: medium none; BORDER-TOP: medium none; DISPLAY: block; BACKGROUND: none transparent scroll repeat 0% 0%; MARGIN-BOTTOM: -1px; FONT: 100%/8px Tahoma; MARGIN-LEFT: 43px; BORDER-LEFT: medium none; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: medium none; POSITION: relative}
.Solidfiller {BORDER-RIGHT: medium none; BORDER-TOP: medium none; DISPLAY: block; BACKGROUND: none transparent scroll repeat 0% 0%; MARGIN-BOTTOM: -1px; FONT: 100%/8px Tahoma; MARGIN-LEFT: 0px; BORDER-LEFT: medium none; COLOR: #000000; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: medium none; POSITION: relative; BACKGROUND-COLOR: #000000}
td {VERTICAL-ALIGN: TOP; FONT-FAMILY: Tahoma}
th {VERTICAL-ALIGN: TOP; COLOR: #cc0000; TEXT-ALIGN: left}
</STYLE>
<SCRIPT language=vbscript>
strShowHide = 1
strShow = "show"
strHide = "hide"
strShowAll = "show all"
strHideAll = "hide all"
Function window_onload()
If UCase(document.documentElement.getAttribute("ES_auditInitialized")) <> "TRUE" Then
Set objBody = document.body.all
For Each obji in objBody
If IsSectionHeader(obji) Then
If IsSectionExpandedByDefault(obji) Then
ShowSection obji
Else
HideSection obji
End If
End If
Next
objshowhide.innerText = strShowAll
document.documentElement.setAttribute "ES_auditInitialized", "true"
End If
End Function
Function IsSectionExpandedByDefault(objHeader)
IsSectionExpandedByDefault = (Right(objHeader.className, Len("_expanded")) = "_expanded")
End Function
Function document_onclick()
Set strsrc = window.event.srcElement
While (strsrc.className = "sectionTitle" or strsrc.className = "expando")
Set strsrc = strsrc.parentElement
Wend
If Not IsSectionHeader(strsrc) Then Exit Function
ToggleSection strsrc
window.event.returnValue = False
End Function
Sub ToggleSection(objHeader)
SetSectionState objHeader, "toggle"
End Sub
Sub SetSectionState(objHeader, strState)
i = objHeader.sourceIndex
Set all = objHeader.parentElement.document.all
While (all(i).className <> "container")
i = i + 1
Wend
Set objContainer = all(i)
If strState = "toggle" Then
If objContainer.style.display = "none" Then
SetSectionState objHeader, "show"
Else
SetSectionState objHeader, "hide"
End If
Else
Set objExpando = objHeader.children.item(1)
If strState = "show" Then
objContainer.style.display = "block"
objExpando.innerText = strHide
ElseIf strState = "hide" Then
objContainer.style.display = "none"
objExpando.innerText = strShow
End If
End If
End Sub
Function objshowhide_onClick()
Set objBody = document.body.all
Select Case strShowHide
Case 0
strShowHide = 1
objshowhide.innerText = strShowAll
For Each obji In objBody
If IsSectionHeader(obji) Then
HideSection obji
End If
Next
Case 1
strShowHide = 0
objshowhide.innerText = strHideAll
For Each obji In objBody
If IsSectionHeader(obji) Then
ShowSection obji
End If
Next
End Select
End Function
Function IsSectionHeader(obj) : IsSectionHeader = (obj.className = "heading0_expanded") Or (obj.className = "heading1_expanded") Or (obj.className = "heading1") Or (obj.className = "heading2"): End Function
Sub HideSection(objHeader) : SetSectionState objHeader, "hide" : End Sub
Sub ShowSection(objHeader) : SetSectionState objHeader, "show": End Sub
</SCRIPT>
</HEAD>
<BODY>
<p><b><font face="Arial" size="5">$Target Audit<hr size="8" color="#CC0000"></font></b>
<font face="Arial" size="1"><b><i>Version 1.1 by Alan Renouf (Virtu-Al)</i></b></font><br>
<font face="Arial" size="1">Report generated on $Date </font></p>
<TABLE cellSpacing=0 cellPadding=0>
<TBODY>
<TR>
<TD>
<DIV id=objshowhide tabIndex=0><FONT face=Arial></FONT></DIV>
</TD>
</TR>
</TBODY>
</TABLE>
<DIV class=heading0_expanded>
<SPAN class=sectionTitle tabIndex=0>$target Details</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=filler></DIV>
<DIV class=container>
<DIV class=heading1>
<SPAN class=sectionTitle tabIndex=0>General</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
<tr>
<th width='25%'><b>Computer Name</b></font></th>
<td width='75%'>$($ComputerSystem.Name)</font></td>
</tr>
<tr>
<th width='25%'><b>Computer Role</b></font></th>
<td width='75%'> $ComputerRole </font></td>
</tr>
<tr>
<th width='25%'><b>$CompType</b></font></th>
<td width='75%'>$($ComputerSystem.Domain)</font></td>
</tr>
<tr>
<th width='25%'><b>Operating System</b></font></th>
<td width='75%'>$($OperatingSystems.Caption)</font></td>
</tr>
<tr>
<th width='25%'><b>Service Pack</b></font></th>
<td width='75%'>$($OperatingSystems.CSDVersion)</font></td>
</tr>
<tr>
<th width='25%'><b>System Root</b></font></th>
<td width='75%'>$($OperatingSystems.SystemDrive)</font></td>
</tr>
<tr>
<th width='25%'><b>Manufacturer</b></font></th>
<td width='75%'>$($ComputerSystem.Manufacturer)</font></td>
</tr>
<tr>
<th width='25%'><b>Model</b></font></th>
<td width='75%'>$($ComputerSystem.Model)</font></td>
</tr>
<tr>
<th width='25%'><b>Number of Processors</b></font></th>
<td width='75%'>$($ComputerSystem.NumberOfProcessors)</font></td>
</tr>
<tr>
<th width='25%'><b>Memory</b></font></th>
<td width='75%'>$($ComputerSystem.TotalPhysicalMemory)</font></td>
</tr>
<tr>
<th width='25%'><b>Registered User</b></font></th>
<td width='75%'>$($ComputerSystem.PrimaryOwnerName)</font></td>
</tr>
<tr>
<th width='25%'><b>Registered Organisation</b></font></th>
<td width='75%'>$($OperatingSystems.Organization)</font></td>
</tr>
<tr>
<th width='25%'><b>Last System Boot</b></font></th>
<td width='75%'>$LBTime</font></td>
</tr>
</TABLE>
</DIV>
</DIV>
<DIV class=filler></DIV>
<DIV class=container>
<DIV class=heading1>
<SPAN class=sectionTitle tabIndex=0>HotFixes</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
<tr>
<th width='25%'><b>HotFix Number</b></font></th>
<th width='75%'><b>Description</b></font></th>
</tr>
"@
ForEach ($objQuickFix in $colQuickFixes)
{
if ($objQuickFix.HotFixID -ne "File 1")
{
$Report+= " <tr>"
$Report+= " <td width='25%'>$($objQuickFix.HotFixID)</font></td>"
$Report+= " <td width='75%'>$($objQuickFix.Description)</font></td>"
$Report+= " </tr>"
}
}
$Report+= @"
</TABLE>
</DIV>
</DIV>
</DIV>
<DIV class=filler></DIV>
<DIV class=container>
<DIV class=heading1>
<SPAN class=sectionTitle tabIndex=0>Logical Disk Configuration</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
<tr>
<th width='15%'><b>Drive Letter</b></font></th>
<th width='20%'><b>Label</b></font></th>
<th width='20%'><b>File System</b></font></th>
<th width='15%'><b>Disk Size</b></font></th>
<th width='15%'><b>Disk Free Space</b></font></th>
<th width='15%'><b>% Free Space</b></font></th>
</tr>
"@
Foreach ($objDisk in $colDisks)
{
if ($objDisk.DriveType -eq 3)
{
$Report+= " <tr>"
$Report+= " <td width='15%'>$($objDisk.DeviceID)</font></td>"
$Report+= " <td width='20%'>$($objDisk.VolumeName)</font></td>"
$Report+= " <td width='20%'>$($objDisk.FileSystem)</font></td>"
$disksize = [math]::round(($objDisk.size / 1048576))
$Report+= " <td width='15%'>$disksize MB</font></td>"
$freespace = [math]::round(($objDisk.FreeSpace / 1048576))
$Report+= " <td width='15%'>$Freespace MB</font></td>"
$percFreespace=[math]::round(((($objDisk.FreeSpace / 1048576)/($objDisk.Size / 1048676)) * 100),0)
$Report+= " <td width='15%'>$percFreespace%</font></td>"
$Report+= " </tr>"
}
}
$Report+= @"
</TABLE>
</DIV>
</DIV>
</DIV>
<DIV class=filler></DIV>
<DIV class=container>
<DIV class=heading1>
<SPAN class=sectionTitle tabIndex=0>NIC Configuration</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
"@
Foreach ($objAdapter in $colAdapters)
{
if ($objAdapter.IPEnabled -eq "True")
{
$NICCount = $NICCount + 1
If ($NICCount -gt 1)
{
$Report+= " </TABLE>"
$Report+= " <DIV class=Solidfiller></DIV>"
$Report+= " <TABLE>"
}
$Report+= " <tr>"
$Report+= " <th width='25%'><b>Description</b></font></th>"
$Report+= " <td width='75%'>$($objAdapter.Description)</font></td>"
$Report+= " </tr>"
$Report+= " <tr>"
$Report+= " <th width='25%'><b>Physical address</b></font></th>"
$Report+= " <td width='75%'>$($objAdapter.MACaddress)</font></td>"
$Report+= " </tr>"
If ($objAdapter.IPAddress -ne $Null)
{
$Report+= " <tr>"
$Report+= " <th width='25%'><b>IP Address / Subnet Mask</b></font></th>"
$Report+= " <td width='75%'>$($objAdapter.IPAddress)/$($objAdapter.IPSubnet)</font></td>"
$Report+= " </tr>"
$Report+= " </tr>"
$Report+= " <tr>"
$Report+= " <th width='25%'><b>Default Gateway</b></font></th>"
$Report+= " <td width='75%'>$($objAdapter.DefaultIPGateway)</font></td>"
$Report+= " </tr>"
}
$Report+= " <tr>"
$Report+= " <th width='25%'><b>DHCP enabled</b></font></th>"
If ($objAdapter.DHCPEnabled -eq "True")
{
$Report+= " <td width='75%'>Yes</font></td>"
}
Else
{
$Report+= " <td width='75%'>No</font></td>"
}
$Report+= " </tr>"
$Report+= " <tr>"
$Report+= " <th width='25%'><b>DNS Servers</b></font></th>"
$Report+= " <td width='75%'>"
If ($objAdapter.DNSServerSearchOrder -ne $Null)
{
$Report+= " $($objAdapter.DNSServerSearchOrder) "
}
$Report+= " </tr>"
$Report+= " <tr>"
$Report+= " <th width='25%'><b>Primary WINS Server</b></font></th>"
$Report+= " <td width='75%'>$($objAdapter.WINSPrimaryServer)</font></td>"
$Report+= " </tr>"
$Report+= " <tr>"
$Report+= " <th width='25%'><b>Secondary WINS Server</b></font></th>"
$Report+= " <td width='75%'>$($objAdapter.WINSSecondaryServer)</font></td>"
$Report+= " </tr>"
$NICCount = $NICCount + 1
}
}
$Report+= @"
</TABLE>
</DIV>
</DIV>
</DIV>
<DIV class=filler></DIV>
"@
if ((get-wmiobject -namespace "root/cimv2" -list) | ? {$_.name -match "Win32_Product"})
{
Write-Output "..Installed Software"
$colShares = get-wmiobject -ComputerName $Target Win32_Product | select Name,Version,Vendor,InstallDate
$Report+= @"
<DIV class=container>
<DIV class=heading1>
<SPAN class=sectionTitle tabIndex=0>Software</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
<tr>
<th width='25%'><b>Name</b></font></th>
<th width='25%'><b>Version</b></font></th>
<th width='25%'><b>Vendor</b></font></th>
<th width='25%'><b>Install Date</b></font></th>
</tr>
"@
Foreach ($objShare in $colShares)
{
$Report+= " <tr>"
$Report+= " <td width='50%'>$($objShare.Name)</font></td>"
$Report+= " <td width='20%'>$($objShare.Version)</font></td>"
$Report+= " <td width='15%'>$($objShare.Vendor)</font></td>"
$Report+= " <td width='15%'>$($objShare.InstallDate)</font></td>"
$Report+= " </tr>"
}
$Report+= " </TABLE>"
$Report+= " </DIV>"
$Report+= " </DIV>"
$Report+= " </DIV>"
$Report+= " <DIV class=filler></DIV>"
}
$Report+= @"
<DIV class=container>
<DIV class=heading1>
<SPAN class=sectionTitle tabIndex=0>Local Shares</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
<tr>
<th width='25%'><b>Share</b></font></th>
<th width='25%'><b>Path</b></font></th>
<th width='50%'><b>Comment</b></font></th>
</tr>
"@
Foreach ($objShare in $colShares)
{
$Report+= " <tr>"
$Report+= " <td width='25%'>$($objShare.Name)</font></td>"
$Report+= " <td width='25%'>$($objShare.Path)</font></td>"
$Report+= " <td width='50%'>$($objShare.Caption)</font></td>"
$Report+= " </tr>"
}
$Report+= @"
</TABLE>
</DIV>
</DIV>
</DIV>
<DIV class=filler></DIV>
<DIV class=container>
<DIV class=heading1>
<SPAN class=sectionTitle tabIndex=0>Printers</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
<tr>
<th width='25%'><b>Printer</b></font></th>
<th width='25%'><b>Location</b></font></th>
<th width='25%'><b>Default Printer</b></font></th>
<th width='25%'><b>Portname</b></font></th>
</tr>
"@
Foreach ($objPrinter in $colInstalledPrinters)
{
If ($objPrinter.Name -eq "")
{
$Report+= " <tr>"
$Report+= " <td width='100%'>No Printers Installed</font></td>"
}
Else
{
$Report+= " <tr>"
$Report+= " <td width='25%'>$($objPrinter.Name)</font></td>"
$Report+= " <td width='25%'>$($objPrinter.Location)</font></td>"
if ($objPrinter.Default -eq "True")
{
$Report+= " <td width='25%'>Yes</font></td>"
}
Else
{
$Report+= " <td width='25%'>No</font></td>"
}
$Report+= " <td width='25%'>$($objPrinter.Portname)</font></td>"
}
$Report+= " </tr>"
}
$Report+= @"
</TABLE>
</DIV>
</DIV>
</DIV>
<DIV class=filler></DIV>
<DIV class=container>
<DIV class=heading1>
<SPAN class=sectionTitle tabIndex=0>Services</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
<tr>
<th width='20%'><b>Name</b></font></th>
<th width='20%'><b>Account</b></font></th>
<th width='20%'><b>Start Mode</b></font></th>
<th width='20%'><b>State</b></font></th>
<th width='20%'><b>Expected State</b></font></th>
</tr>
"@
Foreach ($objService in $colListOfServices)
{
$Report+= " <tr>"
$Report+= " <td width='20%'>$($objService.Caption)</font></td>"
$Report+= " <td width='20%'>$($objService.Startname)</font></td>"
$Report+= " <td width='20%'>$($objService.StartMode)</font></td>"
If ($objService.StartMode -eq "Auto")
{
if ($objService.State -eq "Stopped")
{
$Report+= " <td width='20%'><font color='#FF0000'>$($objService.State)</font></td>"
$Report+= " <td width='25%'><font face='Wingdings'color='#FF0000'>û</font></td>"
}
}
If ($objService.StartMode -eq "Auto")
{
if ($objService.State -eq "Running")
{
$Report+= " <td width='20%'><font color='#009900'>$($objService.State)</font></td>"
$Report+= " <td width='20%'><font face='Wingdings'color='#009900'>ü</font></td>"
}
}
If ($objService.StartMode -eq "Disabled")
{
If ($objService.State -eq "Running")
{
$Report+= " <td width='20%'><font color='#FF0000'>$($objService.State)</font></td>"
$Report+= " <td width='25%'><font face='Wingdings'color='#FF0000'>û</font></td>"
}
}
If ($objService.StartMode -eq "Disabled")
{
if ($objService.State -eq "Stopped")
{
$Report+= " <td width='20%'><font color='#009900'>$($objService.State)</font></td>"
$Report+= " <td width='20%'><font face='Wingdings'color='#009900'>ü</font></td>"
}
}
If ($objService.StartMode -eq "Manual")
{
$Report+= " <td width='20%'><font color='#009900'>$($objService.State)</font></td>"
$Report+= " <td width='20%'><font face='Wingdings'color='#009900'>ü</font></td>"
}
If ($objService.State -eq "Paused")
{
$Report+= " <td width='20%'><font color='#FF9933'>$($objService.State)</font></td>"
$Report+= " <td width='20%'><font face='Wingdings'color='#009900'>ü</font></td>"
}
$Report+= " </tr>"
}
$Report+= @"
</TABLE>
</DIV>
</DIV>
</DIV>
<DIV class=filler></DIV>
<DIV class=container>
<DIV class=heading1>
<SPAN class=sectionTitle tabIndex=0>Regional Settings</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
<tr>
<th width='25%'><b>Time Zone</b></font></th>
<td width='75%'>$($TimeZone.Description)</font></td>
</tr>
<tr>
<th width='25%'><b>Country Code</b></font></th>
<td width='75%'>$($OperatingSystems.Countrycode)</font></td>
</tr>
<tr>
<th width='25%'><b>Locale</b></font></th>
<td width='75%'>$($OperatingSystems.Locale)</font></td>
</tr>
<tr>
<th width='25%'><b>Operating System Language</b></font></th>
<td width='75%'>$($OperatingSystems.OSLanguage)</font></td>
</tr>
<tr>
<th width='25%'><b>Keyboard Layout</b></font></th>
<td width='75%'>$keyb</font></td>
</tr>
</TABLE>
</div>
</DIV>
</DIV>
<DIV class=filler></DIV>
<DIV class=container>
<DIV class=heading1>
<SPAN class=sectionTitle tabIndex=0>Event Logs</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<DIV class=container>
<DIV class=heading2>
<SPAN class=sectionTitle tabIndex=0>Event Log Settings</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
<tr>
<th width='25%'><b>Log Name</b></font></th>
<th width='25%'><b>Overwrite Outdated Records</b></font></th>
<th width='25%'><b>Maximum Size</b></font></th>
<th width='25%'><b>Current Size</b></font></th>
</tr>
"@
ForEach ($objLogFile in $colLogfiles)
{
$Report+= " <tr>"
$Report+= " <td width='25%'>$($objLogFile.LogFileName)</font></td>"
If ($objLogfile.OverWriteOutdated -lt 0)
{
$Report+= " <td width='25%'>Never</font></td>"
}
if ($objLogFile.OverWriteOutdated -eq 0)
{
$Report+= " <td width='25%'>As needed</font></td>"
}
Else
{
$Report+= " <td width='25%'>After $($objLogFile.OverWriteOutdated) days</font></td>"
}
$MaxFileSize = ($objLogfile.MaxFileSize) / 1024
$FileSize = ($objLogfile.FileSize) / 1024
$Report+= " <td width='25%'>$MaxFileSize KB</font></td>"
$Report+= " <td width='25%'>$FileSize KB</font></td>"
$Report+= " </tr>"
}
$Report+= @"
</TABLE>
</DIV>
</DIV>
</DIV>
<DIV class=filler></DIV>
<DIV class=container>
<DIV class=heading2>
<SPAN class=sectionTitle tabIndex=0>ERROR Entries</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
<tr>
<th width='10%'><b>Event Code</b></font></th>
<th width='10%'><b>Source Name</b></font></th>
<th width='15%'><b>Time</b></font></th>
<th width='10%'><b>Log</b></font></th>
<th width='55%'><b>Message</b></font></th>
</tr>
"@
ForEach ($objEvent in $colLoggedEvents)
{
$dtmEventDate = $ObjEvent.ConvertToDateTime($objEvent.TimeWritten)
$Report+= " <tr>"
$Report+= " <td width='10%'>$($objEvent.EventCode)</font></td>"
$Report+= " <td width='10%'>$($objEvent.SourceName)</font></td>"
$Report+= " <td width='15%'>$dtmEventDate</font></td>"
$Report+= " <td width='10%'>$($objEvent.LogFile)</font></td>"
$Report+= " <td width='55%'>$($objEvent.Message)</font></td>"
$Report+= " </tr>"
}
$Report+= @"
</TABLE>
</DIV>
</DIV>
</DIV>
<DIV class=filler></DIV>
<DIV class=container>
<DIV class=heading2>
<SPAN class=sectionTitle tabIndex=0>WARNING Entries</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
<tr>
<th width='10%'><b>Event Code</b></font></th>
<th width='10%'><b>Source Name</b></font></th>
<th width='15%'><b>Time</b></font></th>
<th width='10%'><b>Log</b></font></th>
<th width='55%'><b>Message</b></font></th>
</tr>
"@
ForEach ($objEvent in $colLoggedEvents)
{
$StrWMIDate = $ObjEvent.ConvertToDateTime($objEvent.TimeWritten)
$Report+= " <tr>"
$Report+= " <td width='10%'>$($objEvent.EventCode)</font></td>"
$Report+= " <td width='10%'>$($objEvent.SourceName)</font></td>"
$Report+= " <td width='15%'>$($dtmEventDate)</font></td>"
$Report+= " <td width='10%'>$($objEvent.LogFile)</font></td>"
$Report+= " <td width='55%'>$($objEvent.Message)</font></td>"
$Report+= " </tr>"
}
$Report+= @"
</TABLE>
</DIV>
</DIV>
</DIV>
<DIV class=filler></DIV>
</DIV>
</DIV>
</DIV>
<DIV class=filler></DIV>
</body>
</html>
"@
$Report | out-file -encoding ASCII -filepath $Filename
}
|
PowerShellCorpus/PoshCode/Set-Computername_16.ps1
|
Set-Computername_16.ps1
|
function Set-ComputerName {
param( [switch]$help,
[string]$originalPCName=$(read-host "Please specify the current name of the computer"),
[string]$computerName=$(read-host "Please specify the new name of the computer"))
$usage = "set-ComputerName -originalPCname CurrentName -computername AnewName"
if ($help) {Write-Host $usage;break}
$computer = Get-WmiObject Win32_ComputerSystem -OriginalPCname OriginalName -computername $originalPCName
$computer.Rename($computerName)
}
|
PowerShellCorpus/PoshCode/chkhash_3.ps1
|
chkhash_3.ps1
|
# calculate SHA512 of file.
function Get-SHA512([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]'))
{
$stream = $null;
$cryptoServiceProvider = [System.Security.Cryptography.SHA512CryptoServiceProvider];
$hashAlgorithm = new-object $cryptoServiceProvider
$stream = $file.OpenRead();
$hashByteArray = $hashAlgorithm.ComputeHash($stream);
$stream.Close();
## We have to be sure that we close the file stream if any exceptions are thrown.
trap
{
if ($stream -ne $null)
{
$stream.Close();
}
break;
}
foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }}
return [string]$result;
}
function noequal ( $first, $second)
{
foreach($s in $second)
{
if ($first -eq $s) {return $false}
}
return $true
}
# chkhash.ps1 [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #3] [-u] [-x [path of .xml database]]
# -u updates the XML file database and exits
# otherwise, all files are checked against the XML file database.
# -x specifies location of xml hash database
$hashespath=".\\hashes.xml"
del variable:\\args3 -ea 0
del variable:\\args2 -ea 0
del variable:\\xfiles -ea 0
del variable:\\files -ea 0
del variable:\\exclude -ea 0
$args3=@()
$args2=$args
$nu = 0
$errs = 0
$fc = 0
$upd = $false
$create = $false
for($i=0;$i -lt $args2.count; $i++)
{
if ($args2[$i] -like "-h*") # -help specified?
{
"Usage: .\\chkhash.ps1 [-h] [-u] [-c] [-x <file path of hashes .xml database>] [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #n] [-e <Dirs>]"
"Options: -h - Help display."
" -c - Create hash database. If .xml hash database does not exist, -c will be assumed."
" -u - Update changed files and add new files to existing database."
" -x - specifies .xml database file path to use. Default is .\\hashes.xml"
" -e - exclude dirs. Put this after the files/dirs you want to check with SHA512 and needs to be fullpath (e.g. c:\\users\\bob not ..\\bob)."
""
"Examples: PS>.\\chkhash.ps1 c:\\ d:\\ -c -x c:\\users\\bob\\hashes\\hashes.xml"
" PS>.\\chkhash.ps1 c:\\users\\alice\\pictures\\sunset.jpg -a -x c:\\users\\alice\\hashes\\pictureshashes.xml"
" PS>.\\chkhash.ps1 c:\\users\\eve\\documents d:\\media\\movies -x c:\\users\\eve\\hashes\\private.xml"
" PS>.\\chkhash.ps1 c:\\users\\eve -x c:\\users\\eve\\hashes\\private.xml -e c:\\users\\eve\\hashes"
""
"Note: files in subdirectories of any specified directory are automatically processed."
exit
}
if ($args2[$i] -like "-u*") {$upd=$true;continue} # Update and Add new files to database?
if ($args2[$i] -like "-c*") {$create=$true;continue} # Create database specified?
if ($args2[$i] -like "-x*") {$i++;$hashespath=$args2[$i];continue} # Get hashes xml database path
if ($args2[$i] -like "-e*") # Exclude files, dirs
{
do {
$i++
$exclude+=@($args2[$i])
} while ($args2[$i] -notlike "-*" -and $i -lt $args2.count-1)
continue
}
$args3+=@($args2[$i]) # Add files/dirs
}
"ChkHash.ps1 - .\\chkhash.ps1 -h for usage."
""
if ($args3.count -eq 0) {exit}
# Get list of files and SHA512 hash them.
"Enumerating files from specified locations..."
$files=@(dir -literalpath $args3 -recurse -ea 0 | ?{$_.mode -notmatch "d"} | ?{noequal $_.directoryname $exclude}) # Get list of files
if ($files.count -eq 0) {"No files found. Exiting."; exit}
if ($create -eq $true -or !(test-path $hashespath)) # Create database?
{
# Create SHA512 hashes of files and write to new database
$files = $files | %{write-host "Hashing $($_.fullname) ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
$files |export-clixml $hashespath
"Created $hashespath"
"$($files.count) file hashes saved. Exiting."
exit
}
$xfiles=@(import-clixml $hashespath)
"Loaded $($xfiles.count) file hash(es) from $hashespath"
$hash=@{}
for($x=0;$x -lt $xfiles.count; $x++)
{
if ($hash.contains($xfiles[$x].fullname)) {continue}
$hash.Add($xfiles[$x].fullname,$x)
}
foreach($f in $files)
{
$n=($hash.($f.fullname))
if ($n -eq $null)
{
$nu++ # increment needs/needed updating count
if ($upd -eq $false) {"Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue
"Hashing $($f.fullname) ..."
# Create SHA512 hash of file
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
$xfiles+=@($f) # then add file + hash to list
continue
}
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
# Update and continue is specified.
$fc++ # increment files checked.
if ($xfiles[$n].SHA512 -eq $f.SHA512) # Check SHA512 for mixmatch.
{
continue
}
$errs++ # increment mixmatches
if ($upd -eq $true) { $xfiles[$n]=$f; "Updated `"$($f.fullname)`"";continue}
"Bad SHA-512 found: `"$($f.fullname)`""
}
if ($upd -eq $true) # if database updated
{
$xfiles|export-clixml $hashespath # write xml database
"Updated $hashespath"
"$nu file hash(es) added to database."
"$errs file hash(es) updated in database."
exit
}
"$errs SHA-512 mixmatch(es) found."
"$fc file(s) SHA512 matched."
if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
|
PowerShellCorpus/PoshCode/Get-BogonList.ps1
|
Get-BogonList.ps1
|
<#
.SYNOPSIS
Gets the bogon list.
.DESCRIPTION
The Get-BogonList script retrieves the bogon prefix list maintained by Team Cymru.
A bogon prefix is a route that should never appear in the Internet routing table.
A packet routed over the public Internet (not including over VPNs or other tunnels) should never have a source address in a bogon range.
These are commonly found as the source addresses of DDoS attacks. Bogons are defined as Martians (private and reserved addresses defined by RFC 1918 and RFC 3330) and
netblocks that have not been allocated to a regional internet registry (RIR) by the Internet Assigned Numbers Authority.
.PARAMETER Aggregated
By default the unaggregated bogon list is retrieved. Use this switch parameter to retrieve the aggregated list.
.OUTPUTS
PSObject
.EXAMPLE
Get-BogonList
Retrieves the unaggregated bogon list from Team Cymru.
.EXAMPLE
Get-BogonList -Aggregated
Retrieves the aggregated bogon list from Team Cymru.
.NOTES
Name: Get-BogonList
Author: Rich Kusak (rkusak@cbcag.edu)
Created: 2010-01-31
Version: 1.0.0
#Requires -Version 2.0
.LINK
http://www.team-cymru.org/Services/Bogons/
#>
param (
[switch]$Aggregated
)
$webClient = New-Object System.Net.WebClient
$version = $webClient.DownloadString("http://www.cymru.com/Documents/bogon-list.html") -split "`n" |
Where-Object {$_ -cmatch "TITLE"} | ForEach-Object {$_.Remove(0,7).Replace('</TITLE>',"").Trim()}
if ($Aggregated) {
foreach ($bogon in $webClient.DownloadString("http://www.cymru.com/Documents/bogon-bn-agg.txt") -split "`n" | Where-Object {$_ -notlike $null}) {
New-Object PSObject -Property @{$version = $bogon}
}
} else {
foreach ($bogon in $webClient.DownloadString("http://www.cymru.com/Documents/bogon-bn-nonagg.txt") -split "`n" | Where-Object {$_ -notlike $null}) {
New-Object PSObject -Property @{$version = $bogon}
}
}
|
PowerShellCorpus/PoshCode/Get-Clipboard.ps1
|
Get-Clipboard.ps1
|
#############################################################################\n##\n## Get-Clipboard\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nRetrieve the text contents of the Windows Clipboard.\n\n.EXAMPLE\n\nPS >Get-Clipboard\nHello World\n\n#>\n\nSet-StrictMode -Version Latest\n\nPowerShell -NoProfile -STA -Command {\n Add-Type -Assembly PresentationCore\n [Windows.Clipboard]::GetText()\n}
|
PowerShellCorpus/PoshCode/ModuleWriteError.psm1.ps1
|
ModuleWriteError.psm1.ps1
|
################################################################################
## Script Name: Module Write Error
## Created On: 1/7/2010
## Author: Thell Fowler
## Tribute: Joel 'Jaykul' Bennet
## File: ModuleWriteError.psm1
## Usage: import-module \\Path\\to\\module\\ModuleWriteError.psm1
## Version: 1.0.0
##
## Purpose: Provides a New-ModuleError functions for the creation of an
## error record that is populated and formatted with an
## imported module's advanced function information.
##
## Reasoning: Informational error messages generated from 'Write-Error' do
## not truly represent the current function in some cases and
## do not inform the user of Module specific details.
## Usage of $PSCmdlet.WriteError an error record from
## New-ModuleError can resolve that.
##
## Requirements: PowerShell Version 2
## ModuleWriteError.psd1
## FunctionInfo.types.ps1xml
## Last Updated: 01/13/2010
## History:
## 1.0.0 01/13/2010 - Initial version.
##
##
################################################################################
#requires -version 2.0
Set-StrictMode -Version 2
function New-ModuleExceptionClass{
[CmdletBinding()]
param([string]$exceptionType)
# Generic Default Exception Class for use with WriteError output.
$GenericModuleExceptionSource = @"
using System;
public class $($exceptionType) : System.ApplicationException
{
public $($exceptionType)()
{
}
public $($exceptionType)(string message) : base(message)
{
}
public $($exceptionType)(string message, Exception innerException)
: base(message, innerException)
{
}
}
"@
# Suppresses warning: Generated type defines no public methods of it's own.
Add-Type -TypeDefinition $GenericModuleExceptionSource -IgnoreWarnings -warningaction silentlycontinue
}
function New-ModuleError {
<#
.SYNOPSIS
Create an error record that is populated and formatted to provide data
that is contextual to an imported module's advanced functions.
.DESCRIPTION
Informational error messages generated from 'Write-Error' do not truly
represent the current function in some cases and do not inform the user
of Module specific details. When using $PSCmdlet.WriteError though that
data can be populated into the error record.
.EXAMPLE
$PSCmdlet.WriteError((
New-ModuleError `
"Cannot get `'$Name`' because it does not exist."
))
.OUTPUTs
[ErrorRecord]
#>
[CmdletBinding()]
param(
[Parameter(Position=0, Mandatory=$true)]
[string]$message,
[string]$identifierText = $("ErrorNotSpecified"),
[System.Management.Automation.ErrorCategory]$ErrorCategory = $("NotSpecified"),
[PSObject]$targetObject,
[string]$exceptionType = $($null),
[Exception]$innerException
)
Begin {
# These are used in building the error record.
$MyCommandCaller = ((get-pscallstack)[1].InvocationInfo.MyCommand)
$host.EnterNestedPrompt()
$MyCallersModule = ($MyCommandCaller.ModuleName)
if ( $exceptionType.Length -eq 0 ) {
$exceptionType = "$($MyCallersModule)ModuleException"
} elseif ( ( "$($exceptionType)" -as [type] -eq $null ) -and
( $exceptionType -ne "$($MyCallersModule)ModuleException" ) ) {
$exceptionType = [AppDomain]::CurrentDomain.GetAssemblies() | %{$_.GetExportedTypes()} |
?{ $_.Name -eq "$($exceptionType)" -and $_.IsSubclassOf( [System.Exception] ) }
if ( $exceptionType -as [type] -eq $null ) {
$exceptionType = "$($MyCallersModule)ModuleException"
}
}
if ( ( $exceptionType -eq "$($MyCallersModule)ModuleException" ) -and
( "$($exceptionType)" -as [type] -eq $null) ) {
New-ModuleExceptionClass "$($MyCallersModule)ModuleException"
}
}
Process {
if ($innerException) {
$MyErrorRecord = (new-object System.Management.Automation.ErrorRecord(
(new-object $exceptionType("$($message)", $innerException)),
"$($identifierText), Module : $($MyCommandCaller.ModuleName)\\$($MyCommandCaller.InternalName)",
$ErrorCategory,
$targetObject)
)
} else {
$MyException = new-object $exceptionType $message
$MyErrorRecord = (new-object System.Management.Automation.ErrorRecord(
$MyException,
"$($identifierText), Module : $($MyCommandCaller.ModuleName)\\$($MyCommandCaller.InternalName)",
$ErrorCategory,
$targetObject)
)
}
$MyErrorRecord.CategoryInfo.Activity = "$($MyCommandCaller.Name)"
Write-Output $MyErrorRecord
}
End {
}
}
Export-ModuleMember New-ModuleError
|
PowerShellCorpus/PoshCode/FormsLib.ps1
|
FormsLib.ps1
|
# FormsLib.ps1
# contains some helper functions to create and modify Form controls
# in a PowerShell script used by RoboGUI.ps1
#
# /\\/\\o\\/\\/
# http://thePowerShellGuy.com
Function ConvertTo-HashTable ([string]$StringValue) {
invoke-expression ("@$StringValue".replace(',',';'))
}
Function ConvertTo-Point ([string]$StringValue) {
ConvertTo-HashTable $StringValue |
% {New-Object System.Drawing.Point([int]($_.x),[int]($_.y))}
}
Function ConvertTo-Size ([string]$StringValue) {
ConvertTo-HashTable $StringValue |
% {New-Object System.Drawing.Size([int]($_.Width),[int]($_.Height))}
}
filter get-PropertyList {
$o = $_ ; $_ | gm -MemberType Property |
select name,
@{Name='Type';Expression={$_.definition.split()[0]}},
@{Name='Value';Expression={$o."$($_.name)"}}
}
Function Get-ControlFormat {
Param (
$Control,
$properties = ('Text','Size','Location','Dock','Anchor'),
$ExtraProperties
)
$properties += $ExtraProperties
"Set-ControlFormat `$$($Control.name) ``"
$Control | get-PropertyList |
Where {$Properties -contains $_.name} |
Foreach {
" -$($_.name) '$($_.Value)'``"
}
}
Function Set-ControlFormat {
Param (
$Control
)
foreach ($arg in $args) {
if ($arg.startswith('-')) {
$Property = $arg.trim('-')
[void] $foreach.MoveNext()
Switch ($Property) {
'Location' { $Control.Location = ConvertTo-Point $foreach.current ; break}
'Size' { $Control.Size = ConvertTo-Size $foreach.current ; break}
Default {$Control."$Property" = $foreach.current}
}
}
}
}
Function get-FormControls ($psObject) {
$form = new-object Windows.Forms.Form
$form.Size = new-object Drawing.Size @(600,600)
$controls = @("form")
$psObject.Controls |% {$controls += $_.name}
$CB = new-object Windows.Forms.Combobox
$cb.Size = new-object Drawing.Size @(500,21)
$cb.Items.AddRange($controls)
$PG = new-object Windows.Forms.PropertyGrid
$PG.Size = new-object Drawing.Size @(500,500)
$PG.Location = New-Object System.Drawing.Point(50 , 50)
$form.text = "$psObject"
$PG.selectedobject = $psObject.PsObject.baseobject
$cb.text = 'form'
$cb.add_TextChanged({
if ( $this.SelectedItem -eq 'Form') {
$PG.selectedobject = $psObject.PsObject.baseobject
} Else {
$PG.selectedobject = $psObject.Controls["$($this.SelectedItem)"].PsObject.baseobject
}
})
$form.Controls.Add($PG)
$form.Controls.Add($CB)
$Form.Add_Shown({$form.Activate()})
$form.showdialog()
}
|
PowerShellCorpus/PoshCode/PowerChart 0.5.ps1
|
PowerChart 0.5.ps1
|
function New-PowerChart() {
[CmdletBinding(DefaultParameterSetName='DataTemplate')]
param(
[Parameter(Position=0, Mandatory=$true)]
[ValidateSet("Area","Bar","Bubble","Column","Line","Pie","Scatter")]
[String[]]
${ChartType}
,
[Parameter(Position=1, Mandatory=$true, HelpMessage='The data for the chart ...')]
[System.Management.Automation.ScriptBlock[]]
${ItemsSource}
,
[Parameter(Position=2, Mandatory=$true, HelpMessage='The property name for the independent values ...')]
[String[]]
${IndependentValuePath}
,
[Parameter(Position=3, Mandatory=$true, HelpMessage='The property name for the dependent values ...')]
[String[]]
${DependentValuePath}
,
[Parameter(Position=4, HelpMessage='The property name for the size values ...')]
[String[]]
${SizeValuePath}
,
[TimeSpan]
${Interval}
,
[Switch]
$Show
)
begin
{
Write-Host "Interval: $Interval"
Chart -ControlNale PowerChart -Tag @{Interval=$Interval; ItemsSource=$ItemsSource} -On_Loaded {
$Interval = $this.Tag.Interval
if($Interval) {
Register-PowerShellCommand -ScriptBlock {
$i=0
$Window.Content.Series | ForEach{ $_.ItemsSource = &$($Window.Content.Tag.ItemsSource[$i++]) }
} -in $Interval -run
}
} -Series {
$Series = @()
# Write-Host "Three" -Fore Cyan
for($c=0; $c -lt $ChartType.length; $c++) {
$chartType = $ChartType[$c].ToLower()
if($SizeValuePath -and $ChartType[$c] -eq "Bubble") {
$Series += iex "$($chartType)Series -DependentValuePath $($DependentValuePath[$c]) -IndependentValuePath $($IndependentValuePath[$c]) -SizeValuePath $($SizeValuePath[$c]) -ItemsSource `$(&{$($ItemsSource[$c])})"
#$Series[-1].DataPointStyle = $this.FindResource("$($chartType)DataPointTooltipsFix")
} elseif($ChartType[$c] -eq "Pie") {
$Series += iex "$($chartType)Series -DependentValuePath $($DependentValuePath[$c]) -IndependentValuePath $($IndependentValuePath[$c]) -ItemsSource `$(&{$($ItemsSource[$c])})"
#$Series[-1].StylePalette = $this.FindResource("$($chartType)PaletteTooltipsFix")
} else {
Write-Verbose "$($chartType)Series -DependentValuePath $($DependentValuePath[$c]) -IndependentValuePath $($IndependentValuePath[$c]) -ItemsSource `$(&{$($ItemsSource[$c])})"
$Series += iex "$($chartType)Series -DependentValuePath $($DependentValuePath[$c]) -IndependentValuePath $($IndependentValuePath[$c]) -ItemsSource `$(&{$($ItemsSource[$c])})"
#A$Series[-1].DataPointStyle = $this.FindResource("$($chartType)DataPointTooltipsFix")
}
}
Write-Verbose "There are $($Series.Count) Series!"
$Series
} -Background Transparent -BorderThickness 0 -Show:$Show
}
}
|
PowerShellCorpus/PoshCode/ping check using dotNet _1.ps1
|
ping check using dotNet _1.ps1
|
function dnsref ($computername) {
$ErrorActionPreference = "SilentlyContinue"
$testrun=$Null
trap {
Write-Host "ERROR: $computername does not exist in DNS" -fore Yellow
Throw $_ }
$testrun=[net.dns]::GetHostByName($computername)
if ($testrun -eq $Null){
Write-Host "No DNS Record" }
else {
foreach ($alias in $testrun){
PingX($alias.addresslist)
}
}
}
function PingX($ip) {
$ErrorActionPreference="SilentlyContinue"
$ping = New-Object System.Net.NetworkInformation.ping
#trap {$_.Exception.Message ;$pingres = $_Exception.Message; continue}
if ($_Exception.Message -eq $null) {
$pingres = ($ping.send($ip)).Status | Out-Null
Write-Host $computername - $ip is REACHABLE -background "GREEN" -foreground "BLACk"}
else
{Write-Host $computername - $ip is NOT reachable -background "RED" -foreground "BLACk"}
return $pingres
}
|
PowerShellCorpus/PoshCode/Start-SQL 1.0.ps1
|
Start-SQL 1.0.ps1
|
# Start-Sql.ps1
###################################################################################################
# This is a SCRIPT which emits functions and variables into the global scope
# Most importantly, it uses a variable $SqlConnection which is expected to exist....
#
# On my computer, I set default values for the server and database, but not for the query,
# nor for authentication (I usually use Integrated Security)
###################################################################################################
# By default when you run this script it:
# * creates the functions
# * initializes the connection
# But we don't automatically do a query -- unless you pass one in!
#
# Thus, calling the script with no parameters results in an initialized connection,
# but it doesn't return anything, so it's basically silent if there are no errors.
#
# the default server and database
param(
$Server = $(Read-Host "SQL Server Name"),
$Database = $(Read-Host "Default Database"),
$UserName, $Password, $Query )
## Uncomment the next line to start the SqlServer (or fail miserably but silently)
# Get-Service -include "MSSQLSERVER" | where {$_.Status -like "Stopped"} | Start-Service
#
# change the SqlConnection (it's set to a default when the script it run)
#
function global:Set-SqlConnection( $Server = $(Read-Host "SQL Server Name"), $Database = $(Read-Host "Default Database"), $UserName , $Password ) {
if( ($UserName -gt $null) -and ($Password -gt $null)) {
$login = "User Id = $UserName; Password = $Password"
} else {
$login = "Integrated Security = True"
}
$SqlConnection.ConnectionString = "Server = $Server; Database = $Database; $login"
}
#
# A function to perform a query that returns a table full of data
#
function global:Get-SqlDataTable( $Query = $(Read-Host "Enter SQL Query")) {
if (-not ($SqlConnection.State -like "Open")) { $SqlConnection.Open() }
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand $Query, $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet) | Out-Null
$SqlConnection.Close()
return $DataSet.Tables[0]
}
#
# A function to perform a single-value (series) query. That is, a query that
# returns only a single value per row, which we just output strongly typed.
#
function global:Get-SQLQuery($Query = $(Read-Host "Enter SQL Query"), $type = "string")
{
if (-not ($SqlConnection.State -like "Open")) { $SqlConnection.Open() }
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand $Query, $SqlConnection
# $results = @();
# trap [SqlException]
# {
#LogSqlErrors(e.Errors, sqlQuery);
# throw new DataException("Unable to ExecuteReader(), check EventLog for details.", e);
# }
$dr = $SqlCmd.ExecuteReader()
while($dr.Read())
{
#$results += $dr.GetValue(0) -as $type
$dr.GetValue(0) -as $type # emit the value directly, isn't that more PowerShelly?
}
$dr.Close()
$dr.Dispose()
# return $results
}
# Initialize the SqlConnection variable
Set-Variable SqlConnection (New-Object System.Data.SqlClient.SqlConnection) -Scope Global -Option AllScope -Description "Personal variable for Sql Query functions"
# Initially create the SqlConnection
Set-SqlConnection $Server $Database
# go ahead and run the initial query if we have one...
if( $query -gt $null ) {
Get-SqlDataTable $Query
}
# Some aliases to let you use the functions with less typing
Set-Alias gdt Get-SqlDataTable -Option AllScope -scope Global -Description "Personal Function alias from Get-Sql.ps1"
Set-Alias sql Set-SqlConnection -Option AllScope -scope Global -Description "Personal Function alias from Get-Sql.ps1"
Set-Alias gq Get-SqlQuery -Option AllScope -scope Global -Description "Personal Function alias from Get-Sql.ps1"
|
PowerShellCorpus/PoshCode/SharePoint build script.ps1
|
SharePoint build script.ps1
|
#BASEPATH variable should be explicitly set in every
#build script. It represents the "root"
#of the project folder, underneath which all tools, source, config settings,
#and deployment folder lie.
$global:basepath = (resolve-path ..).path
function Set-BasePath([string]$path)
{
$global:basepath = $path
}
function Clean-DeploymentFolder
{
Clean-Path -dir (Get-FullPath 'deployment')
}
function Compile-Project
{
Run-MSBuild -msBuildArgs @(
((Get-FirstSolutionFile).Fullname),
"/target:Clean",
"/target:Build",
"/p:Configuration=Release")
}
function Create-DeploymentBatchFilesWithSolutionOnly
{
#similar to Create-DeploymentBatchFilesWithFeatureActivation, but WITHOUT Feature activation/deactivation
#Convention: project name == project folder name == Feature name == Solution name
$projectName = (Get-FirstDirectoryUnderneathSrc).name
Create-DeploymentBatchFile -filename (Get-FullPath "deployment\\deploy-any-environment.bat") -solutionName "$($projectName).wsp"
Create-UpgradeBatchFile -filename (Get-FullPath "deployment\\upgrade-any-environment.bat") -solutionName "$($projectName).wsp"
Create-RetractionBatchFile -filename (Get-FullPath "deployment\\z-retract-any-environment.bat") -solutionName "$($projectName).wsp"
}
function Create-DeploymentBatchFilesWithFeatureActivation($siteUrls)
{
#Convention: project name == project folder name == Feature name == Solution name
$projectName = (Get-FirstDirectoryUnderneathSrc).name
$siteUrls.Keys | foreach {
Create-DeploymentBatchFile -url $siteUrls[$_] -filename (Get-FullPath "deployment\\deploy-$($_).bat") -featureName $projectName -solutionName "$($projectName).wsp" -hasFeature
Create-UpgradeBatchFile -url $siteUrls[$_] -filename (Get-FullPath "deployment\\upgrade-$($_).bat") -featureName $projectName -solutionName "$($projectName).wsp" -hasFeature
Create-RetractionBatchFile -url $siteUrls[$_] -filename (Get-FullPath "deployment\\z-retract-$($_).bat") -featureName $projectName -solutionName "$($projectName).wsp" -hasFeature
}
}
function Get-FirstDirectoryUnderneathSrc
{
dir (Get-FullPath "src") | where { $_.PSIsContainer -eq $true } | select -first 1
}
function Get-FirstSolutionFile
{
dir (Get-FullPath "\\*") -include "*.sln" -recurse | select -first 1
}
#BASEPATH variable should be explicitly set in every
#build script. It represents the "root"
#of the project folder, underneath which all tools, source, config settings,
#and deployment folder lie.
$global:basepath = (resolve-path ..).path
function Set-BasePath([string]$path)
{
$global:basepath = $path
}
function Get-FullPath($localPath)
{
return join-path -path $global:basepath -childPath $localPath
}
function Run-DosCommand($program, [string[]]$programArgs)
{
write-host "Running command: $program";
write-host " Args:"
0..($programArgs.Count-1) | foreach { Write-Host " $($_+1): $($programArgs[$_])" }
& $program $programArgs
}
$wspbuilder = Get-FullPath "tools\\WSPBuilder.exe"
function Run-WspBuilder()
{
$rootDirectory = (Get-FirstDirectoryUnderneathSrc).fullname
pushd
cd $rootDirectory
Run-DosCommand -program $WSPBuilder -programArgs @("-BuildWSP",
"true",
"-OutputPath",
(Get-FullPath "deployment"),
"-ExcludePaths",
([string]::Join(";", @(
(Join-Path -path $rootDirectory -childPath "bin\\Debug"),
(Join-Path -path $rootDirectory -childPath "bin\\deploy")
))))
popd
}
$msbuild = "C:\\Windows\\Microsoft.NET\\Framework\\v3.5\\msbuild.exe"
function Run-MSBuild([string[]]$msBuildArgs)
{
Run-DosCommand $msbuild $msBuildArgs
}
function Clean-Path($dir)
{
#I don't like the SilentlyContinue option, but we need to ignore the case
#where there is no directory to delete (in this situation, an error is thrown)
del $dir -recurse -force -erroraction SilentlyContinue
mkdir $dir -erroraction SilentlyContinue | out-null
}
function Create-DeploymentBatchFile($filename, $featureName, $solutionName, $url, [switch]$allcontenturls, [switch]$hasFeature)
{
if ($hasFeature) {
$contents = [string]::Join("`n", @(`
(Emit-FeatureDeactivationBatchScript -featureName $featureName -url $url -allcontenturls:$allcontenturls), `
(Emit-SolutionRetractionBatchScript -solutionName $solutionName -allcontenturls:$allcontenturls), `
(Emit-SolutionDeploymentBatchScript -solutionName $solutionName -allcontenturls:$allcontenturls), `
(Emit-FeatureActivationBatchScript -featureName $featureName -url $url -allcontenturls:$allcontenturls)))
} else {
$contents = [string]::Join("`n", @(`
(Emit-SolutionRetractionBatchScript -solutionName $solutionName -allcontenturls:$allcontenturls), `
(Emit-SolutionDeploymentBatchScript -solutionName $solutionName -allcontenturls:$allcontenturls)))
}
Create-StsadmBatchFile -filename $filename -contents $contents
}
function Create-UpgradeBatchFile($filename, $featureName, $solutionName, $url, [switch]$hasFeature)
{
if ($hasFeature) {
$contents = [string]::Join("`n", @(`
(Emit-FeatureDeactivationBatchScript -featureName $featureName -url $url -allcontenturls:$allcontenturls), `
(Emit-SolutionUpgradeBatchScript -solutionName $solutionName -allcontenturls:$allcontenturls), `
(Emit-FeatureActivationBatchScript -featureName $featureName -url $url -allcontenturls:$allcontenturls)))
} else {
$contents = [string]::Join("`n", @(`
(Emit-SolutionUpgradeBatchScript -solutionName $solutionName -allcontenturls:$allcontenturls)))
}
Create-StsadmBatchFile -filename $filename -contents $contents
}
function Create-RetractionBatchFile($filename, $featureName, $solutionName, $url, [switch]$allcontenturls, [switch]$hasFeature)
{
if ($hasFeature) {
$contents = [string]::Join("`n", @(`
(Emit-EchoMessage -message "RETRACTING solution--press any key to continue, or CTRL+C to cancel"), `
(Emit-FeatureDeactivationBatchScript -featureName $featureName -url $url -allcontenturls:$allcontenturls), `
(Emit-SolutionRetractionBatchScript -solutionName $solutionName -allcontenturls:$allcontenturls)))
} else {
$contents = [string]::Join("`n", @(`
(Emit-EchoMessage -message "RETRACTING solution--press any key to continue, or CTRL+C to cancel"), `
(Emit-SolutionRetractionBatchScript -solutionName $solutionName -allcontenturls:$allcontenturls)))
}
Create-StsadmBatchFile -filename $filename -contents $contents
}
function Emit-EchoMessage($message)
{
return "echo $($message)`npause"
}
function Emit-FeatureDeactivationBatchScript($featureName, $url, [switch]$allcontenturls)
{
$script = @"
%STSADM% -o deactivatefeature -name $featureName -url $url
"@
return $script
}
function Emit-FeatureActivationBatchScript($featureName, $url, [switch]$allcontenturls)
{
$script = @"
%STSADM% -o activatefeature -name $featureName -url $url
"@
return $script
}
function Emit-SolutionRetractionBatchScript($solutionName, [switch]$allcontenturls)
{
$script = @"
%STSADM% -o retractsolution $(if ($allcontenturls) { "-allcontenturls" }) -immediate -name $solutionName
%STSADM% -o execadmsvcjobs
%STSADM% -o deletesolution -name $solutionName -override
%STSADM% -o execadmsvcjobs
"@
return $script
}
function Emit-SolutionDeploymentBatchScript($solutionName, [switch]$allcontenturls)
{
$script = @"
%STSADM% -o addsolution -filename $solutionName
%STSADM% -o deploysolution $(if ($allcontenturls) { "-allcontenturls" }) -immediate -allowgacdeployment -name $solutionName
%STSADM% -o execadmsvcjobs
REM second call to execadmsvcjobs allows for a little more delay. Shouldn't be necessary, but is.
%STSADM% -o execadmsvcjobs
"@
return $script
}
function Emit-SolutionUpgradeBatchScript($solutionName, [switch]$allcontenturls)
{
$script = @"
%STSADM% -o upgradesolution -immediate -allowgacdeployment -name $solutionName -filename $solutionName
%STSADM% -o execadmsvcjobs
REM second call to execadmsvcjobs allows for a little more delay. Shouldn't be necessary, but is.
%STSADM% -o execadmsvcjobs
"@
return $script
}
function Create-StsadmBatchFile($filename, $contents)
{
$header= @"
SET STSADM="%PROGRAMFILES%\\Common Files\\Microsoft Shared\\web server extensions\\12\\BIN\\stsadm.exe"
"@
$footer = @"
echo off
ECHO -------------------------------------------------------------
%STSADM% -o displaysolution -name $solutionName
pause
"@
$wholeFileContents = $header + "`n" + $contents + "`n" + $footer
Out-File -inputObject $wholeFileContents -filePath $filename -encoding ASCII
}
@@#USAGE
@@. ./helper-functions.ps1
@@
@@ Set-BasePath -path ((resolve-path ..).path)
@@ Clean-DeploymentFolder
@@ Compile-Project
@@ Run-WspBuilder
@@ Create-DeploymentBatchFilesWithSolutionOnly
@@#
@@#
@@#
|
PowerShellCorpus/PoshCode/The Letter Diamond_1.ps1
|
The Letter Diamond_1.ps1
|
## Write a program which draws a diamond of the form illustrted
## below. The letter which is to appear at the widest point of the
## figure (E in the example) is to be specified as the input data.
## A
## B B
## C C
## D D
## E E
## D D
## C C
## B B
## A
Param([char]$letter = "E", [int]$padding=5)
$start = [int][char]"B"
$end = [int]$letter
$outerpadding = ($end - $start) + $padding
$innerpadding = -1
$lines = &{
"$(" " * $outerpadding)A"
foreach($char in ([string[]][char[]]($start..$end))) {
$innerpadding += 2; $outerpadding--
"$(" " * $outerpadding)$char$(" " * $innerpadding)$char"
}
}
$lines
$lines[$($lines.Length-2)..0]
|
PowerShellCorpus/PoshCode/Kill-Process_1.ps1
|
Kill-Process_1.ps1
|
function Kill-Process() {
param(
[string[]]$ComputerNames,
[string[]]$ProcessNames,
$User
)
###########################################################################################################
if ($ProcessNames -eq $null) {Write-Error 'The parametre "ProcessNames" cannot be empty';break}
###########################################################################################################
if ($User -is [String]) {
$Connection = Get-Credential -Credential $User
}
###########################################################################################################
foreach ($int1 in $ComputerNames){
foreach ($int2 in $ProcessNames) {
if ($int2 -notlike "*.exe") {$int2 = $int2 + '.exe'}
if ($Connection -eq $null) {$count = 0
$Process_Kill = gwmi "win32_process" -ComputerName $int1 -filter "name='$int2'" |
ForEach-Object {$_.terminate();$count++}
$Process_Kill = "" | select @{e={$int1};n='Computer'},`
@{e={$int2};n='Process'}, @{e={$count};n='Count'}
}
else {$count = 0
$Process_Kill = gwmi "win32_process" -ComputerName $int1 -filter "name='$int2'" |
ForEach-Object {$_.terminate();$count++}
$Process_Kill = "" | select @{e={$int1};n='Computer'},`
@{e={$int2};n='Process'}, @{e={$count};n='Count'}
}
$Process_Kill
}
}
###########################################################################################################
}
|
PowerShellCorpus/PoshCode/Product key.ps1
|
Product key.ps1
|
function Get-SerialNumber {
$regVal = Get-ItemProperty $regDir.PSPath
$arrVal = $regVal.DigitalProductId
$arrBin = $arrVal[52..66]
$arrChr = "B", "C", "D", "F", "G", "H", "J", "K", "M", "P", "Q", "R", `
"T", "V", "W", "X", "Y", "2", "3", "4", "6", "7", "8", "9"
for ($i = 24; $i -ge 0; $i--) {
$k = 0;
for ($j = 14; $j -ge 0; $j--) {
$k = $k * 256 -bxor $arrBin[$j]
$arrBin[$j] = [math]::truncate($k / 24)
$k = $k % 24
}
$strKey = $arrChr[$k] + $strKey
if (($i % 5 -eq 0) -and ($i -ne 0)) {
$strKey = "-" + $strKey
}
}
$strKey
}
#Windows serial key
$regDir = Get-Item "HKLM:\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"
$key_1 = Get-SerialNumber
#MS Office 2007 serial key
$regDir = Get-ChildItem HKLM:\\SOFTWARE\\Microsoft\\Office\\12.0\\Registration
$key_2 = Get-SerialNumber
Write-Output "OS : $key_1"
Write-Output "MS Office: $key_2"
|
PowerShellCorpus/PoshCode/LocalAdminGUI.ps1
|
LocalAdminGUI.ps1
|
Add-Type -AssemblyName PresentationCore
Add-Type -AssemblyName PresentationFramework
[xml]$XAML = @'
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="316" MinWidth="316" MaxWidth="316"
Title="Local Admins Tool" SizeToContent="WidthAndHeight" FontSize="14" FontFamily="Consolas" Name="Window">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition MinWidth="100"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="30"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label Content="Computer: " Grid.Column="0" />
<TextBox Grid.Column="1" Name="TextBoxComputer"/>
<Label Content="Domain: " Grid.Column="0" Grid.Row="1"/>
<ComboBox Grid.Column="1" Grid.Row="1" Name="ComboDomain">
<ComboBox.Items>
<ComboBoxItem Content="FOO"/>
<ComboBoxItem Content="BAR"/>
<ComboBoxItem Content="ALP"/>
<ComboBoxItem Content="BET"/>
<ComboBoxItem Content="GAM"/>
<ComboBoxItem Content="DEL"/>
</ComboBox.Items>
</ComboBox>
<StackPanel Grid.ColumnSpan="2" Grid.Row="2" Orientation="Horizontal">
<Button Name="ButtonList" Content="Check" Width="100"/>
<Button Name="ButtonAdd" Content="Add" Width="100"/>
<Button Name="ButtonCancel" Content="Cancel" Width="100"/>
</StackPanel>
<ListBox Grid.ColumnSpan="3" Grid.Row="3" Name="AdminsList"/>
</Grid>
</Window>
'@
$Reader = New-Object System.Xml.XmlNodeReader $XAML
$Dialog = [Windows.Markup.XamlReader]::Load($Reader)
foreach ($Name in ($XAML | Select-Xml '//*/@Name' | foreach { $_.Node.Value})) {
New-Variable -Name $Name -Value $Dialog.FindName($Name) -Force
}
$AddScriptBlock = {
if ($_.Key) {
if ($_.Key -ne 'Enter') {
return
}
}
$ComputerName = $TextBoxComputer.Text.Trim()
$AdminsList.Items.Clear()
$AdminsList.Items.Add(
(New-Object System.Windows.Controls.ListBoxItem -Property @{
Content = "Adding admin account to: $ComputerName"
FontWeight = 'Bold'
})
)
if ($ComputerName -notmatch '^[a-z]{3}\\d{6}$') {
$AdminsList.Items.Add(
(New-Object System.Windows.Controls.ListBoxItem -Property @{
Content = "Wrong computer name: $ComputerName"
Foreground = 'Red'
}
))
return
}
$DomainName = $ComboDomain.SelectedItem.Content
if (!$PredictDomain) {
$AdminsList.Items.Add(
(New-Object System.Windows.Controls.ListBoxItem -Property @{
Content = "Error: can't find workstation $ComputerName in AD!"
Foreground = 'Red'
}
))
return
}
if (!$DomainName) {
$DomainName = $PredictDomain
}
try {
Invoke-Command -ComputerName Endpoints -ConfigurationName $PredictDomain -ScriptBlock {
param ($Computer, $Domain)
Add-LocalAdmin -ComputerName $Computer -Domain $Domain
} -ArgumentList $ComputerName, $DomainName -ErrorAction Stop
$AdminsList.Items.Add(
(New-Object System.Windows.Controls.ListBoxItem -Property @{
Content = 'Done!'
Foreground = 'Green'
})
)
} catch {
$AdminsList.Items.Add(
(New-Object System.Windows.Controls.ListBoxItem -Property @{
Content = "Error: $_"
Foreground = 'Red'
}
))
}
}
$TextChangedScriptBlock = {
switch -Regex ($this.Text.Trim()) {
'^[a-z]{3}\\d{6}$' {
$this.Background = 'LawnGreen'
# And now we can check domain and try to change ComboBox value...
$Searcher = New-Object ADSISearcher -ArgumentList @(
[ADSI]'GC://DC=domain,DC=local',
"(&(objectClass=computer)(Name=$_))"
)
$Global:PredictDomain = $Searcher.FindOne().Path -replace 'GC.*?,DC=([^,]*),.*', '$1'
$ComboDomain.Items | ForEach-Object {
if ($_.Content -eq $PredictDomain) {
$ComboDomain.SelectedItem = $_
}
}
if (!$Global:PredictDomain) {
$ComboDomain.SelectedItem = $null
}
}
^$ {
$this.Background = 'White'
$Global:PredictDomain = $null
}
default {
$this.Background = 'LightCoral'
$Global:PredictDomain = $null
}
}
}
$ListScriptBlock = {
if ($_.Key) {
if ($_.Key -ne 'Enter') {
return
}
}
$AdminsList.Items.Clear()
$ComputerName = $TextBoxComputer.Text
if ($ComputerName -notmatch '^[a-z]{3}\\d{6}$') {
$AdminsList.Items.Add(
(New-Object System.Windows.Controls.ListBoxItem -Property @{
Content = "Wrong computer name!"
Foreground = 'Red'
}
))
return
}
if (!$PredictDomain) {
$AdminsList.Items.Add(
(New-Object System.Windows.Controls.ListBoxItem -Property @{
Content = "Error: can't find workstation $ComputerName in AD!"
Foreground = 'Red'
}
))
return
}
try {
$AdminsList.Items.Clear()
$AdminsList.Items.Add("Administrators on computer $ComputerName :")
Invoke-Command -ComputerName Endpoints -ConfigurationName $PredictDomain -ScriptBlock {
param ($Computer)
Get-LocalAdmin -ComputerName $Computer
} -ArgumentList $ComputerName -ErrorAction Stop | ForEach-Object {
$AdminsList.Items.Add($_)
}
$AdminsList.Items.Add(
(New-Object System.Windows.Controls.ListBoxItem -Property @{
Content = "Done!"
ForeGround = 'Green'
}
))
} catch {
$AdminsList.Items.Add(
(New-Object System.Windows.Controls.ListBoxItem -Property @{
Content = "Error: $_"
Foreground = 'Red'
}
))
}
}
$TextBoxComputer.Add_KeyDown($ListScriptBlock)
$ButtonAdd.Add_Click($AddScriptBlock)
$ButtonList.Add_Click($ListScriptBlock)
$TextBoxComputer.Add_TextChanged($TextChangedScriptBlock)
$ButtonCancel.Add_Click({$window.Close()})
$Dialog.Add_Loaded( {
$this.TopMost = $true
})
$Dialog.ShowDialog() | Out-Null
# SIG # Begin signature block
# MIIj1wYJKoZIhvcNAQcCoIIjyDCCI8QCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUVgPTlBoK1nvEkL+j1d3tsR3x
# 4o2ggh8FMIIETzCCA7igAwIBAgIEBydYPTANBgkqhkiG9w0BAQUFADB1MQswCQYD
# VQQGEwJVUzEYMBYGA1UEChMPR1RFIENvcnBvcmF0aW9uMScwJQYDVQQLEx5HVEUg
# Q3liZXJUcnVzdCBTb2x1dGlvbnMsIEluYy4xIzAhBgNVBAMTGkdURSBDeWJlclRy
# dXN0IEdsb2JhbCBSb290MB4XDTEwMDExMzE5MjAzMloXDTE1MDkzMDE4MTk0N1ow
# bDELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQ
# d3d3LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFu
# Y2UgRVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM
# 5XPm+9S75S0tMqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT
# 3JTWPNt0OKRKzE0lgvdKpVMSOO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wbl
# CJEMxChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3MRuNs8ckRZqnrG0AFFoEt7oT61EK
# mEFBIk5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQNAQTXKFx01p8Vdte
# ZOE3hzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUeh10a
# UAsgEsxBu24LUTi4S8sCAwEAAaOCAW8wggFrMBIGA1UdEwEB/wQIMAYBAf8CAQEw
# UwYDVR0gBEwwSjBIBgkrBgEEAbE+AQAwOzA5BggrBgEFBQcCARYtaHR0cDovL2N5
# YmVydHJ1c3Qub21uaXJvb3QuY29tL3JlcG9zaXRvcnkuY2ZtMA4GA1UdDwEB/wQE
# AwIBBjCBiQYDVR0jBIGBMH+heaR3MHUxCzAJBgNVBAYTAlVTMRgwFgYDVQQKEw9H
# VEUgQ29ycG9yYXRpb24xJzAlBgNVBAsTHkdURSBDeWJlclRydXN0IFNvbHV0aW9u
# cywgSW5jLjEjMCEGA1UEAxMaR1RFIEN5YmVyVHJ1c3QgR2xvYmFsIFJvb3SCAgGl
# MEUGA1UdHwQ+MDwwOqA4oDaGNGh0dHA6Ly93d3cucHVibGljLXRydXN0LmNvbS9j
# Z2ktYmluL0NSTC8yMDE4L2NkcC5jcmwwHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoI
# Au9jZCvDMA0GCSqGSIb3DQEBBQUAA4GBAC52hdk3lm2vifMGeIIxxEYHH2XJjrPJ
# VHjm0ULfdS4eVer3+psEwHV70Xk8Bex5xFLdpgPXp1CZPwVZ2sZV9IacDWejSQSV
# Mh3Hh+yFr2Ru1cVfCadAfRa6SQ2i/fbfVTBs13jGuc9YKWQWTKMggUexRJKEFhtv
# Srwhxgo97TPKMIIGbzCCBVegAwIBAgIQA4uW8HDZ4h5VpUJnkuHIOjANBgkqhkiG
# 9w0BAQUFADBiMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkw
# FwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSEwHwYDVQQDExhEaWdpQ2VydCBBc3N1
# cmVkIElEIENBLTEwHhcNMTIwNDA0MDAwMDAwWhcNMTMwNDE4MDAwMDAwWjBHMQsw
# CQYDVQQGEwJVUzERMA8GA1UEChMIRGlnaUNlcnQxJTAjBgNVBAMTHERpZ2lDZXJ0
# IFRpbWVzdGFtcCBSZXNwb25kZXIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
# AoIBAQDGf7tj+/F8Q0mIJnRfituiDBM1pYivqtEwyjPdo9B2gRXW1tvhNC0FIG/B
# ofQXZ7dN3iETYE4Jcq1XXniQO7XMLc15uGLZTzHc0cmMCAv8teTgJ+mn7ra9Depw
# 8wXb82jr+D8RM3kkwHsqfFKdphzOZB/GcvgUnE0R2KJDQXK6DqO+r9L9eNxHlRdw
# bJwgwav5YWPmj5mAc7b+njHfTb/hvE+LgfzFqEM7GyQoZ8no89SRywWpFs++42Pf
# 6oKhqIXcBBDsREA0NxnNMHF82j0Ctqh3sH2D3WQIE3ome/SXN8uxb9wuMn3Y07/H
# iIEPkUkd8WPenFhtjzUmWSnGwHTPAgMBAAGjggM6MIIDNjAOBgNVHQ8BAf8EBAMC
# B4AwDAYDVR0TAQH/BAIwADAWBgNVHSUBAf8EDDAKBggrBgEFBQcDCDCCAcQGA1Ud
# IASCAbswggG3MIIBswYJYIZIAYb9bAcBMIIBpDA6BggrBgEFBQcCARYuaHR0cDov
# L3d3dy5kaWdpY2VydC5jb20vc3NsLWNwcy1yZXBvc2l0b3J5Lmh0bTCCAWQGCCsG
# AQUFBwICMIIBVh6CAVIAQQBuAHkAIAB1AHMAZQAgAG8AZgAgAHQAaABpAHMAIABD
# AGUAcgB0AGkAZgBpAGMAYQB0AGUAIABjAG8AbgBzAHQAaQB0AHUAdABlAHMAIABh
# AGMAYwBlAHAAdABhAG4AYwBlACAAbwBmACAAdABoAGUAIABEAGkAZwBpAEMAZQBy
# AHQAIABDAFAALwBDAFAAUwAgAGEAbgBkACAAdABoAGUAIABSAGUAbAB5AGkAbgBn
# ACAAUABhAHIAdAB5ACAAQQBnAHIAZQBlAG0AZQBuAHQAIAB3AGgAaQBjAGgAIABs
# AGkAbQBpAHQAIABsAGkAYQBiAGkAbABpAHQAeQAgAGEAbgBkACAAYQByAGUAIABp
# AG4AYwBvAHIAcABvAHIAYQB0AGUAZAAgAGgAZQByAGUAaQBuACAAYgB5ACAAcgBl
# AGYAZQByAGUAbgBjAGUALjAfBgNVHSMEGDAWgBQVABIrE5iymQftHt+ivlcNK2cC
# zTAdBgNVHQ4EFgQUJqoP9EMNo5gXpV8S9PiSjqnkhDQwdwYIKwYBBQUHAQEEazBp
# MCQGCCsGAQUFBzABhhhodHRwOi8vb2NzcC5kaWdpY2VydC5jb20wQQYIKwYBBQUH
# MAKGNWh0dHA6Ly9jYWNlcnRzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEFzc3VyZWRJ
# RENBLTEuY3J0MH0GA1UdHwR2MHQwOKA2oDSGMmh0dHA6Ly9jcmwzLmRpZ2ljZXJ0
# LmNvbS9EaWdpQ2VydEFzc3VyZWRJRENBLTEuY3JsMDigNqA0hjJodHRwOi8vY3Js
# NC5kaWdpY2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURDQS0xLmNybDANBgkqhkiG
# 9w0BAQUFAAOCAQEAvCT5g9lmKeYy6GdDbzfLaXlHl4tifmnDitXp13GcjqH52v4k
# 498mbK/g0s0vxJ8yYdB2zERcy+WPvXhnhhPiummK15cnfj2EE1YzDr992ekBaoxu
# vz/PMZivhUgRXB+7ycJvKsrFxZUSDFM4GS+1lwp+hrOVPNxBZqWZyZVXrYq0xWzx
# FjObvvA8rWBrH0YPdskbgkNe3R2oNWZtNV8hcTOgHArLRWmJmaX05mCs7ksBKGyR
# lK+/+fLFWOptzeUAtDnjsEWFuzG2wym3BFDg7gbFFOlvzmv8m7wkfR2H3aiObVCU
# NeZ8AB4TB5nkYujEj7p75UsZu62Y9rXC8YkgGDCCBqcwggWPoAMCAQICEAi8iRJ7
# eZMavRDMJtoY/+kwDQYJKoZIhvcNAQEFBQAwczELMAkGA1UEBhMCVVMxFTATBgNV
# BAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEyMDAG
# A1UEAxMpRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2UgQ29kZSBTaWduaW5nIENBLTEw
# HhcNMTIwMzE3MDAwMDAwWhcNMTMwMzIxMTIwMDAwWjB1MQswCQYDVQQGEwJQTDEb
# MBkGA1UECBMSWmFjaG9kbmlvcG9tb3Jza2llMREwDwYDVQQHEwhLb3N6YWxpbjEa
# MBgGA1UEChMRQmFydG9zeiBCaWVsYXdza2kxGjAYBgNVBAMTEUJhcnRvc3ogQmll
# bGF3c2tpMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4lBBMNWpH82J
# 81h5AQn2RPH3hFOYPZHHWI1rDKtrJ+x6fgGb1lsLprr+qzbtDqJ4i3PrdgPtHKV1
# KXhW4i6Xo4X+zmkcKaO9TTEKWt+78JxiITkdsmEoOcS88zH7zHoIODdJ250DFfIL
# ET3gwTf55ZWUi5o9HAnna6D3sl011piFWmmAIg7MjbB2AE9Tb+AB2A8Gxv6Gx7Ma
# 1SDY6KYoKh3BCnc5KQBuLtGmBOteT+11OdsEx0x9rEu/qhOQbhFOw/tEK7tk0har
# MoAyFnWX6C/Q2lnQMcwytYD5T1Ejngen0V6fRPeLX3lfrN6xR+T98n2qOPUEAWjt
# JmQ6e3cH6wIDAQABo4IDMzCCAy8wHwYDVR0jBBgwFoAUl0gD6xUIa7myWCPMlC7x
# xmXSZI4wHQYDVR0OBBYEFIishvEMffoxHqt0SZTyWs37Ck/3MA4GA1UdDwEB/wQE
# AwIHgDATBgNVHSUEDDAKBggrBgEFBQcDAzBpBgNVHR8EYjBgMC6gLKAqhihodHRw
# Oi8vY3JsMy5kaWdpY2VydC5jb20vaGEtY3MtMjAxMWEuY3JsMC6gLKAqhihodHRw
# Oi8vY3JsNC5kaWdpY2VydC5jb20vaGEtY3MtMjAxMWEuY3JsMIIBxAYDVR0gBIIB
# uzCCAbcwggGzBglghkgBhv1sAwEwggGkMDoGCCsGAQUFBwIBFi5odHRwOi8vd3d3
# LmRpZ2ljZXJ0LmNvbS9zc2wtY3BzLXJlcG9zaXRvcnkuaHRtMIIBZAYIKwYBBQUH
# AgIwggFWHoIBUgBBAG4AeQAgAHUAcwBlACAAbwBmACAAdABoAGkAcwAgAEMAZQBy
# AHQAaQBmAGkAYwBhAHQAZQAgAGMAbwBuAHMAdABpAHQAdQB0AGUAcwAgAGEAYwBj
# AGUAcAB0AGEAbgBjAGUAIABvAGYAIAB0AGgAZQAgAEQAaQBnAGkAQwBlAHIAdAAg
# AEMAUAAvAEMAUABTACAAYQBuAGQAIAB0AGgAZQAgAFIAZQBsAHkAaQBuAGcAIABQ
# AGEAcgB0AHkAIABBAGcAcgBlAGUAbQBlAG4AdAAgAHcAaABpAGMAaAAgAGwAaQBt
# AGkAdAAgAGwAaQBhAGIAaQBsAGkAdAB5ACAAYQBuAGQAIABhAHIAZQAgAGkAbgBj
# AG8AcgBwAG8AcgBhAHQAZQBkACAAaABlAHIAZQBpAG4AIABiAHkAIAByAGUAZgBl
# AHIAZQBuAGMAZQAuMIGGBggrBgEFBQcBAQR6MHgwJAYIKwYBBQUHMAGGGGh0dHA6
# Ly9vY3NwLmRpZ2ljZXJ0LmNvbTBQBggrBgEFBQcwAoZEaHR0cDovL2NhY2VydHMu
# ZGlnaWNlcnQuY29tL0RpZ2lDZXJ0SGlnaEFzc3VyYW5jZUNvZGVTaWduaW5nQ0Et
# MS5jcnQwDAYDVR0TAQH/BAIwADANBgkqhkiG9w0BAQUFAAOCAQEArHBrvyCp8Sxm
# oEuhnD4ll2OZK/Ne6HnZeP5Dt7r10/TlUCDWV6L9q9rPSdn5/R8+lvmY2pDV37vX
# k6587Yv7tCsH/6hJYtkMs72aG7ti+yHmGpzYv1syialVgXcY8m/b599k7t710zwv
# hK7bRoT92Esi5xWtks+lkbA5K4WMwu152kXZ4sClolzPcEEUPxf7qk88+mUODDSg
# LbYNdZIL78sWbQEPpQt0RQIzcR28MNd0qD+CyTFhQAKp2S8/Acrwz3WZQqhse+HA
# zg7N1Vi6NHMjgXURzTPO3m2fHb6FIf0uYKlQx3bIhB2RbgtYabs7Ge80eM1YZ5aE
# IWsDUQXZgTCCBr8wggWnoAMCAQICEAgcV+5dcOuboLFSDHKcGwkwDQYJKoZIhvcN
# AQEFBQAwbDELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcG
# A1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBB
# c3N1cmFuY2UgRVYgUm9vdCBDQTAeFw0xMTAyMTAxMjAwMDBaFw0yNjAyMTAxMjAw
# MDBaMHMxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNV
# BAsTEHd3dy5kaWdpY2VydC5jb20xMjAwBgNVBAMTKURpZ2lDZXJ0IEhpZ2ggQXNz
# dXJhbmNlIENvZGUgU2lnbmluZyBDQS0xMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
# MIIBCgKCAQEAxfkj5pQnxIAUpIAyX0CjjW9wwOU2cXE6daSqGpKUiV6sI3HLTmd9
# QT+q40u3e76dwag4j2kvOiTpd1kSx2YEQ8INJoKJQBnyLOrnTOd8BRq4/4gJTyY3
# 7zqk+iJsiMlKG2HyrhBeb7zReZtZGGDl7im1AyqkzvGDGU9pBXMoCfsiEJMioJAZ
# Gkwx8tMr2IRDrzxj/5jbINIJK1TB6v1qg+cQoxJx9dbX4RJ61eBWWs7qAVtoZVvB
# P1hSM6k1YU4iy4HKNqMSywbWzxtNGH65krkSz0Am2Jo2hbMVqkeThGsHu7zVs94l
# ABGJAGjBKTzqPi3uUKvXHDAGeDylECNnkQIDAQABo4IDVDCCA1AwDgYDVR0PAQH/
# BAQDAgEGMBMGA1UdJQQMMAoGCCsGAQUFBwMDMIIBwwYDVR0gBIIBujCCAbYwggGy
# BghghkgBhv1sAzCCAaQwOgYIKwYBBQUHAgEWLmh0dHA6Ly93d3cuZGlnaWNlcnQu
# Y29tL3NzbC1jcHMtcmVwb3NpdG9yeS5odG0wggFkBggrBgEFBQcCAjCCAVYeggFS
# AEEAbgB5ACAAdQBzAGUAIABvAGYAIAB0AGgAaQBzACAAQwBlAHIAdABpAGYAaQBj
# AGEAdABlACAAYwBvAG4AcwB0AGkAdAB1AHQAZQBzACAAYQBjAGMAZQBwAHQAYQBu
# AGMAZQAgAG8AZgAgAHQAaABlACAARABpAGcAaQBDAGUAcgB0ACAARQBWACAAQwBQ
# AFMAIABhAG4AZAAgAHQAaABlACAAUgBlAGwAeQBpAG4AZwAgAFAAYQByAHQAeQAg
# AEEAZwByAGUAZQBtAGUAbgB0ACAAdwBoAGkAYwBoACAAbABpAG0AaQB0ACAAbABp
# AGEAYgBpAGwAaQB0AHkAIABhAG4AZAAgAGEAcgBlACAAaQBuAGMAbwByAHAAbwBy
# AGEAdABlAGQAIABoAGUAcgBlAGkAbgAgAGIAeQAgAHIAZQBmAGUAcgBlAG4AYwBl
# AC4wDwYDVR0TAQH/BAUwAwEB/zB/BggrBgEFBQcBAQRzMHEwJAYIKwYBBQUHMAGG
# GGh0dHA6Ly9vY3NwLmRpZ2ljZXJ0LmNvbTBJBggrBgEFBQcwAoY9aHR0cDovL2Nh
# Y2VydHMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0SGlnaEFzc3VyYW5jZUVWUm9vdENB
# LmNydDCBjwYDVR0fBIGHMIGEMECgPqA8hjpodHRwOi8vY3JsMy5kaWdpY2VydC5j
# b20vRGlnaUNlcnRIaWdoQXNzdXJhbmNlRVZSb290Q0EuY3JsMECgPqA8hjpodHRw
# Oi8vY3JsNC5kaWdpY2VydC5jb20vRGlnaUNlcnRIaWdoQXNzdXJhbmNlRVZSb290
# Q0EuY3JsMB0GA1UdDgQWBBSXSAPrFQhrubJYI8yULvHGZdJkjjAfBgNVHSMEGDAW
# gBSxPsNpA/i/RwHUmCYaCALvY2QrwzANBgkqhkiG9w0BAQUFAAOCAQEAggXpha+n
# TL+vzj2y6mCxaN5nwtLLJuDDL5u1aw5TkIX2m+A1Av/6aYOqtHQyFDwuEEwomwqt
# CAn584QRk4/LYEBW6XcvabKDmVWrRySWy39LsBC0l7/EpZkG/o7sFFAeXleXy0e5
# NNn8OqL/UCnCCmIE7t6WOm+gwoUPb/wI5DJ704SuaWAJRiac6PD//4bZyAk6ZsOn
# No8YT+ixlpIuTr4LpzOQrrxuT/F+jbRGDmT5WQYiIWQAS+J6CAPnvImQnkJPAcC2
# Fn916kaypVQvjJPNETY0aihXzJQ/6XzIGAMDBH5D2vmXoVlH2hKq4G04AF01K8Ui
# hssGyrx6TT0mRjCCBs0wggW1oAMCAQICEAb9+QOWA63qAArrPye7uhswDQYJKoZI
# hvcNAQEFBQAwZTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZ
# MBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEkMCIGA1UEAxMbRGlnaUNlcnQgQXNz
# dXJlZCBJRCBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTIxMTExMDAwMDAwMFow
# YjELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQ
# d3d3LmRpZ2ljZXJ0LmNvbTEhMB8GA1UEAxMYRGlnaUNlcnQgQXNzdXJlZCBJRCBD
# QS0xMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6IItmfnKwkKVpYBz
# QHDSnlZUXKnE0kEGj8kz/E1FkVyBn+0snPgWWd+etSQVwpi5tHdJ3InECtqvy15r
# 7a2wcTHrzzpADEZNk+yLejYIA6sMNP4YSYL+x8cxSIB8HqIPkg5QycaH6zY/2DDD
# /6b3+6LNb3Mj/qxWBZDwMiEWicZwiPkFl32jx0PdAug7Pe2xQaPtP77blUjE7h6z
# 8rwMK5nQxl0SQoHhg26Ccz8mSxSQrllmCsSNvtLOBq6thG9IhJtPQLnxTPKvmPv2
# zkBdXPao8S+v7Iki8msYZbHBc63X8djPHgp0XEK4aH631XcKJ1Z8D2KkPzIUYJX9
# BwSiCQIDAQABo4IDejCCA3YwDgYDVR0PAQH/BAQDAgGGMDsGA1UdJQQ0MDIGCCsG
# AQUFBwMBBggrBgEFBQcDAgYIKwYBBQUHAwMGCCsGAQUFBwMEBggrBgEFBQcDCDCC
# AdIGA1UdIASCAckwggHFMIIBtAYKYIZIAYb9bAABBDCCAaQwOgYIKwYBBQUHAgEW
# Lmh0dHA6Ly93d3cuZGlnaWNlcnQuY29tL3NzbC1jcHMtcmVwb3NpdG9yeS5odG0w
# ggFkBggrBgEFBQcCAjCCAVYeggFSAEEAbgB5ACAAdQBzAGUAIABvAGYAIAB0AGgA
# aQBzACAAQwBlAHIAdABpAGYAaQBjAGEAdABlACAAYwBvAG4AcwB0AGkAdAB1AHQA
# ZQBzACAAYQBjAGMAZQBwAHQAYQBuAGMAZQAgAG8AZgAgAHQAaABlACAARABpAGcA
# aQBDAGUAcgB0ACAAQwBQAC8AQwBQAFMAIABhAG4AZAAgAHQAaABlACAAUgBlAGwA
# eQBpAG4AZwAgAFAAYQByAHQAeQAgAEEAZwByAGUAZQBtAGUAbgB0ACAAdwBoAGkA
# YwBoACAAbABpAG0AaQB0ACAAbABpAGEAYgBpAGwAaQB0AHkAIABhAG4AZAAgAGEA
# cgBlACAAaQBuAGMAbwByAHAAbwByAGEAdABlAGQAIABoAGUAcgBlAGkAbgAgAGIA
# eQAgAHIAZQBmAGUAcgBlAG4AYwBlAC4wCwYJYIZIAYb9bAMVMBIGA1UdEwEB/wQI
# MAYBAf8CAQAweQYIKwYBBQUHAQEEbTBrMCQGCCsGAQUFBzABhhhodHRwOi8vb2Nz
# cC5kaWdpY2VydC5jb20wQwYIKwYBBQUHMAKGN2h0dHA6Ly9jYWNlcnRzLmRpZ2lj
# ZXJ0LmNvbS9EaWdpQ2VydEFzc3VyZWRJRFJvb3RDQS5jcnQwgYEGA1UdHwR6MHgw
# OqA4oDaGNGh0dHA6Ly9jcmwzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEFzc3VyZWRJ
# RFJvb3RDQS5jcmwwOqA4oDaGNGh0dHA6Ly9jcmw0LmRpZ2ljZXJ0LmNvbS9EaWdp
# Q2VydEFzc3VyZWRJRFJvb3RDQS5jcmwwHQYDVR0OBBYEFBUAEisTmLKZB+0e36K+
# Vw0rZwLNMB8GA1UdIwQYMBaAFEXroq/0ksuCMS1Ri6enIZ3zbcgPMA0GCSqGSIb3
# DQEBBQUAA4IBAQBGUD7Jtygkpzgdtlspr1LPUukxR6tWXHvVDQtBs+/sdR90OPKy
# XGGinJXDUOSCuSPRujqGcq04eKx1XRcXNHJHhZRW0eu7NoR3zCSl8wQZVann4+er
# Ys37iy2QwsDStZS9Xk+xBdIOPRqpFFumhjFiqKgz5Js5p8T1zh14dpQlc+Qqq8+c
# dkvtX8JLFuRLcEwAiR78xXm8TBJX/l/hHrwCXaj++wc4Tw3GXZG5D2dFzdaD7eeS
# DY2xaYxP+1ngIw/Sqq4AfO6cQg7PkdcntxbuD8O9fAqg7iwIVYUiuOsYGk38KiGt
# STGDR5V3cdyxG0tLHBCcdxTBnU8vWpUIKRAmMYIEPDCCBDgCAQEwgYcwczELMAkG
# A1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3LmRp
# Z2ljZXJ0LmNvbTEyMDAGA1UEAxMpRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2UgQ29k
# ZSBTaWduaW5nIENBLTECEAi8iRJ7eZMavRDMJtoY/+kwCQYFKw4DAhoFAKB4MBgG
# CisGAQQBgjcCAQwxCjAIoAKAAKECgAAwGQYJKoZIhvcNAQkDMQwGCisGAQQBgjcC
# AQQwHAYKKwYBBAGCNwIBCzEOMAwGCisGAQQBgjcCARUwIwYJKoZIhvcNAQkEMRYE
# FMbqJmtFnnZB2PoOXZkf3M3qjGomMA0GCSqGSIb3DQEBAQUABIIBAF9ziFL78vHk
# 85H10PiuQ5XwMnfuzzK4rQ6s7XjzBjHlRmlJwZNJhh6nGbJoGeKtVm5SM2ZeMvAF
# xBeY1W0ZqLVoaB+b6QTrmxY7ggZaMNeRyM0l5MX4Kw6ZrQdRSiwGrxHS+yQImdxb
# afiGSuBFLXCc4Kyd3ijv3lJ1QdKXOhe+mjvm4cNERg3pQOFJMw82mSaeK1yNMmpL
# +FDv7BNEgwvXBIDzDru8qbgAiE/WyxUEg/6ESL61SZ9zZImRKt242rycNRzs9NvM
# hOO/mUOMm5uzFM2cphVGviCwYMJvuGbqzzFXlfkZrCGD54CuO66Ho1nbNZvQTY6G
# XglCpiknTsahggIPMIICCwYJKoZIhvcNAQkGMYIB/DCCAfgCAQEwdjBiMQswCQYD
# VQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGln
# aWNlcnQuY29tMSEwHwYDVQQDExhEaWdpQ2VydCBBc3N1cmVkIElEIENBLTECEAOL
# lvBw2eIeVaVCZ5LhyDowCQYFKw4DAhoFAKBdMBgGCSqGSIb3DQEJAzELBgkqhkiG
# 9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTEzMDMxNTIxMzU0MVowIwYJKoZIhvcNAQkE
# MRYEFKxkm8oCW6n0kttvDwaGmsrZfe0IMA0GCSqGSIb3DQEBAQUABIIBAJrw872t
# DgvDLC6J0hN2RPBgL2itMtPwxPKOzxSC2iYTsJv8JMrqJBwY1o8P/KipPDZm7tlv
# 7zUO2krH+WdOgYvIZRTYDsDntWog++/6rVf/2yO4/ysNn5gD5ptaNuKpy84/lMzw
# qEc0kDssWBkM9lBzWmqiiXKAGbnhvZvz93SfGZfCBhTJutipNCnJKVoXWbspxEYn
# de7D9ZlOATJ94f8R1W/Kr7oxE377MlRLDofXA7DJscS4mYOXH/o43PlEHRAFiNlO
# KYV3O90ygD2A1Dv4Hni1Agpz0y2xxYIJzd13R1sCEQS64wlApw6d2ucb9TWdEFnk
# vNOfNx11O3z0cR8=
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Veeam backup to OVF.ps1
|
Veeam backup to OVF.ps1
|
# This script runs a different OVF conversion depending on the Day of the week.
$VeeamJob = "JobName"
$server1 = 'ServerName'
asnp VMware.VimAutomation.Core -ErrorAction SilentlyContinue
asnp VeeamPSSnapin -ErrorAction SilentlyContinue
$Dest1 = "R:\\VMWARE\\OVF\\$Server1\\"
$OVFFile1 = "$($Dest1)$($Server1).ovf"
$VmIRName1 = $Server1 + "_ovf"
# Name of vCenter to Export VM From
$VcName = "vCenterServer"
# Name of ESX host for Instant VM Restore
$EsxHost = "SingleESXHost"
# Path to OVF Tool on your system
$OVFTool = "D:\\Program Files\\VMware\\VMware OVF Tool\\ovftool.exe"
# Date
$Date = get-date -Format yy-MM-dd
$TimeStamp = get-date
# Path of Log file
$Log = "D:\\logs\\VMWare\\" + $Date + ' ' + $Server1 + " OVF to AWS.log"
# Email sender address
$EmailTo = 'Address@Domain.com'
$EmailFrom = 'Address@Domain.com'
#############################################################################################
$error.clear()
Add-content -Path $Log -Value "Backup of Server $Server1 Started at $TimeStamp"
# Find most recent restore point for VM
$ExportObj1 = (Get-VBRBackup -name "$VeeamJob").GetLastOibs() | Where-Object {$_.Name -eq $Server1}
# Get ESX Server and Resource Pool and start Instant Recovery with VM powered off
$EsxObj1 = Get-VBRServer -Name "$EsxHost"
$ResourcePoolObj = Find-VBRResourcePool -Server $EsxObj1 -Name "Resources"
Start-VBRInstantRecovery -RestorePoint $ExportObj1 -VMName $VmIRName1 -Server $EsxObj1 -ResourcePool $ResourcePoolObj -PowerUp $false -NICsEnabled $true
if (!$?) {
Add-Content -Path $Log -Value "$server1 InstantRecovery failed with Error (error code:0x00000080): $error"
Add-Content -Path $Log -Value "Stopping the backup of $Server1"
Break}
Else{
Add-Content -Path $Log -Value "$Server1 InstantRecovery Started successfully..."
# Connect to vCenter and get the Instant Recovery VM
Connect-VIServer $VCName -User 'ESXAdminUser' -Password 'Password'
if (!$?) {
Add-Content -Path $Log -Value "$server1 Connection to vCenter failed with Error (error code:0x00000079): $error"
Add-Content -Path $Log -Value "Stopping the backup of $Server1"
Break}
Else{
Add-Content -Path $Log -Value "$Server1 Connection to VI Server was successful..."
$VmIR1 = Get-VM -Name "$VmIRName1"
# Get session and ticket
$Session = Get-View -Id Sessionmanager
$Ticket = $Session.AcquireCloneTicket()
# Call OVFtool to
& $OVFTool "--name=$Server1" "--noSSLVerify" "--targetType=OVF" "--overwrite" "--I:sourceSessionTicket=$($Ticket)" "vi://$($VcName)?moref=vim.VirtualMachine:$($VmIR1.extensiondata.moref.value)" "$($Dest1)$($Server1).ovf"
if (!$?) {
Add-Content -Path $Log -Value "$server1 OVF conversion and transfer failed with Error (error code:0x00000078): $error"
Add-Content -Path $Log -Value "Stopping the backup of $Server1"
Break}
Else{
Add-Content -Path $Log -Value "$Server1 OVF conversion and transfer completed successfully..."
# Remove VM from vCenter Inventory and Stop Instant VM Recovery
$IR1 = Get-VBRInstantRecovery | where-object {$_.VMName -eq "$VMIRName1"}
Stop-VBRInstantRecovery $IR1
if (!$?) {
Add-Content -Path $Log -Value "$server1 Stop InstantRecovery failed with Error (error code:0x0000077): $error"
Add-Content -Path $Log -Value "Stopping the backup of $Server1"
Break}
Else{
Add-Content -Path $Log -Value "$Server1 stopping of the Instant Recovery completed successfully..."
Remove-VM $VmIR1 -Confirm:$false
if (!$?) {
Add-Content -Path $Log -Value "$server1 Removal of Server_OVF Failed with Error (error code:0x00000076): $error"
Add-Content -Path $Log -Value "Stopping the backup of $Server1"
Break}
Else{
Add-Content -Path $Log -Value "$Server1 Removeal of the temp OVF completed successfully..."
# disconnect from vCenter
Disconnect-VIServer $VCName -Confirm:$False
if (!$?) {
Add-Content -Path $Log -Value "$server1 failed to disconnect from the vCenter server with Error (error code:0x00000075): $error"
Add-Content -Path $Log -Value "Stopping backup of $Server1"
Break}
Else{
Add-Content -Path $Log -Value "$Server1 OVF conversion and transfer completed successfully (OK) at $TimeStamp..."
}
}
}
}
}
}
#################################################################
# Check backup status and send notification #
#################################################################
#Check OVF has completed
$Failed = Get-Content $log | Select-String "0x000000" -quiet
$Success = Get-Content $log | Select-String "(OK)" -quiet
# Email server
$PSEmailserver = 'EmailServer'
# Email subject depends on the log file, if there is an error in the log file set subject to failed. if there is an OK in the log set to success, otherwise set to unknown
If ($Failed){$Subject = $Server1 + ' OVF backup failed'}
Elseif ($Success) {$subject = $Server1 + ' OVF backup Success'}
else {$subject = "UNKNOWN OVF backup Result"}
# Send an email with details.
Send-MailMessage -To $EmailTo -From $EmailFrom -Subject $Subject -attachments $log -Body "See the log file for the results of the OVF backup of $Server1"
|
PowerShellCorpus/PoshCode/VI Report.ps1
|
VI Report.ps1
|
param( [string] $VIServer )
if ($VIServer -eq ""){
Write-Host
Write-Host "Please specify a VI Server name eg...."
Write-Host " powershell.exe Report.ps1 MYVISERVER"
Write-Host
Write-Host
exit
}
function PreReq
{
if ((Test-Path REGISTRY::HKEY_CLASSES_ROOT\\Word.Application) -eq $False){
Write-Host "This script directly outputs to Microsoft Word, please install Microsoft Word"
exit
}
Else
{
Write-Host "Microsoft Word Detected"
}
if ((Test-Path REGISTRY::HKEY_CLASSES_ROOT\\OWC11.ChartSpace.11) -eq $False){
Write-Host "This script requires Office Web Components to run correctly, please install these from the following website: http://www.microsoft.com/downloads/details.aspx?FamilyId=7287252C-402E-4F72-97A5-E0FD290D4B76&displaylang=en"
exit
}
Else
{
Write-Host "Office Web Components Detected"
}
$wordrunning = (Get-Process 'WinWord' -ea SilentlyContinue)
if ( $wordrunning -eq ""){
Write-Host "Please close all instances of Microsoft Word before running this report."
exit
}
else
{
}
}
function InsertTitle ($title)
{
# Insert Document Title Information
$objSelection = $msWord.Selection
$objSelection.Style = "Heading 1"
$objSelection.TypeText($Title)
$msword.Selection.EndKey(6) > Null
$objSelection.TypeParagraph()
$msword.Selection.EndKey(6) > Null
}
function InsertText ($text)
{
# Insert Document text
$objSelection = $msWord.Selection
$objSelection.Style = "Normal"
$objSelection.TypeText($text)
$msword.Selection.EndKey(6) > Null
$objSelection.TypeParagraph()
$msword.Selection.EndKey(6) > Null
}
function InsertChart ($Caption, $Stat, $NumToReturn, $Contents)
{
Write-Host "Creating $Caption bar chart...Please Wait"
$categories = @()
$values = @()
$chart = new-object -com OWC11.ChartSpace.11
$chart.Clear()
$c = $chart.charts.Add(0)
# 3D chart type, change the following .Type = 52
$c.Type = 4
$c.HasTitle = "True"
$series = ([array] $chart.charts)[0].SeriesCollection.Add(0)
if ($stat -eq ""){
$contents | foreach-object {
$categories += $_.Name
$values += $_.Value * 1
}
$series.Caption = $Caption
}
else
{
$i = 1
$j = $contents.Length
$myCol = @()
ForEach ($content in $contents)
{
Write-Progress -Activity "Processing Graph Information" -Status "$content ($i of $j)" -PercentComplete (100*$i/$j)
$myObj = "" | Select-Object Name, Value
$myObj.Name = $content.Name
$messtat = Get-Stat -Entity $content -Start ((Get-Date).AddHours(-24)) -Finish (Get-Date) -Stat $stat
$myObj.Value = ($messtat| Measure-Object -Property Value -Average).Average
$myCol += $myObj
$i++
}
$myCol | Sort-Object Value -Descending | Select-Object -First $numtoreturn | foreach-object {
$categories += $_.Name
$values += $_.Value * 1
}
$series.Caption = "$Caption (last 24hrs)"
}
$series.SetData(1, -1, $categories)
$series.SetData(2, -1, $values)
$filename = (resolve-path .).Path + "\\Chart.jpg"
$chart.ExportPicture($filename, "jpg", 900, 600)
$objSelection = $msWord.Selection
$msword.Selection.EndKey(6) > Null
$objSelection.TypeParagraph()
$msWord.Application.Selection.InlineShapes.AddPicture($filename) > Null
Remove-Item $filename
$msword.Selection.EndKey(6) > Null
}
function InsertPie ($Caption, $Contents, $cats)
{
Write-Host "Creating $Caption pie chart...Please Wait"
$categories = @()
$values = @()
$chart = new-object -com OWC11.ChartSpace.11
$chart.Clear()
$c = $chart.charts.Add(0)
# Non 3D pie chart, change the following .Type = 18
$c.Type = 58
$c.HasTitle = "True"
$c.HasLegend = "True"
$series = ([array] $chart.charts)[0].SeriesCollection.Add(0)
$dl = $series.DataLabelsCollection.Add()
$dl.HasValue = "True"
$Contents | foreach-object {
$categories = $cats[0], $cats[1]
$values = [math]::round(($contents[0]), 0), [math]::round(($contents[1]), 0)
}
$series.Caption = $Caption
$series.SetData(1, -1, $categories)
$series.SetData(2, -1, $values)
$filename = (resolve-path .).Path + "\\PIE.jpg"
$chart.ExportPicture($filename, "jpg", 900, 600)
$objSelection = $msWord.Selection
$msword.Selection.EndKey(6) > Null
$objSelection.TypeParagraph()
$msWord.Application.Selection.InlineShapes.AddPicture($filename) > Null
$msword.Selection.EndKey(6) > Null
Remove-Item $filename
}
function TableOutput ($Heading, $columnHeaders, $columnProperties, $contents)
{
Write-Host "Creating $Heading Table...Please Wait"
# Number of columns
$columnCount = $columnHeaders.Count
# Insert Table Heading
$Title = $Heading
InsertTitle $title
# Create a new table
$docTable = $wordDoc.Tables.Add($wordDoc.Application.Selection.Range,$contents.Count,$columnCount)
# Insert the column headers into the table
for ($col = 0; $col -lt $columnCount; $col++) {
$cell = $docTable.Cell(1,$col+1).Range
$cell.Font.Name="Arial"
$cell.Font.Bold=$true
$cell.InsertAfter($columnHeaders[$col])
}
$doctable.Rows.Add() > Null
# Load the data into the table
$i = 1
$j = $contents.Count
for($row = 2; $row -lt ($contents.Count + 2); $row++){
if($row -gt 2){
}
for ($col = 1; $col -le $columnCount; $col++){
Write-Progress -Activity "Processing Table Information" -Status "Adding Row entry $i of $j" -PercentComplete (100*$i/$j)
$cell = $docTable.Cell($row,$col).Range
$cell.Font.Name="Arial"
$cell.Font.Size="10"
$cell.Font.Bold=$FALSE
$cell.Text = $contents[$row-2].($columnProperties[$col-1])
}
$i++
}
# Table style
$doctable.Style = "Table List 4"
$docTable.Columns.AutoFit()
$objSelection = $msWord.Selection
$msword.Selection.EndKey(6) > Null
$objSelection.TypeParagraph()
$msword.Selection.EndKey(6) > Null
}
$date = Get-date
Prereq
# Connect to the VI Server
Write-Host "Connecting to VI Server"
Connect-VIServer $VIServer
# Get Word Ready for Input
# Launch instance of Microsoft Word
Write-Host "Creating New Word Document"
$msWord = New-Object -Com Word.Application
# Create new document
$wordDoc = $msWord.Documents.Add()
# Make word visible (optional)
$msWord.Visible = $false
# Activate the new document
$wordDoc.Activate()
# Insert Document Title
$Title = "VMWare Report produced for $VIServer"
InsertTitle $title
$Title = "Created on " + $date
InsertTitle $title
#Setting common used commands to speed things up
Write-Host "Setting Variables...Please wait"
$VMs = Get-VM
$VMHs = Get-VMHost
$Ds = Get-Datastore
$rp = Get-resourcepool
$clu = Get-Cluster
# Send VM Host Information to Document
$myCol = @()
ForEach ($vmh in $vmhs)
{
$hosts = Get-VMHost $vmh.Name | %{Get-View $_.ID}
$esx = "" | select-Object Name, Version, NumCpuPackages, NumCpuCores, Hz, Memory
$esx.Name = $hosts.Name
$esx.Version = $hosts.Summary.Config.Product.FullName
$esx.NumCpuPackages = $hosts.Hardware.CpuInfo.NumCpuPackages
$esx.NumCpuCores = $hosts.Hardware.CpuInfo.NumCpuCores
$esx.Hz = [math]::round(($hosts.Hardware.CpuInfo.Hz)/10000, 0)
$esx.Memory = [math]::round(($hosts.Hardware.MemorySize)/1024, 0)
$myCol += $esx
}
$contents = $myCol
$columnHeaders = @('Name', 'Version', 'CPU', 'Cores', 'Hz', 'Memory' )
$columnproperties = @('Name', 'Version', 'NumCpuPackages', 'NumCpuCores', 'Hz', 'Memory')
$Heading = "Host Information"
if ($contents[0] -eq $null){
Write-Host "No entries for $Heading found"
}
else
{
Tableoutput $Heading $columnHeaders $columnProperties $contents
}
$totalhosts = $VMhs.Length
$Text = "Total Number of Hosts: $totalhosts"
InsertText $Text
#Insert VM Host CPU Graph
$contents = $VMHs
$Stat = "cpu.usage.average"
$NumToReturn = 5
$Caption = "Top " + $NumToReturn + " Hosts CPU Usage %Average"
if ($contents[0] -eq $null){
Write-Host "No entries for $Heading found"
}
else
{
InsertChart $Caption $Stat $NumToReturn $contents
}
#Insert VM Host MEM Graph
$contents = $VMHs
$Stat = "mem.usage.average"
$NumToReturn = 5
$Caption = "Top " + $NumToReturn + " Hosts MEM Usage %Average"
if ($contents[0] -eq $null){
Write-Host "No entries for $Heading found"
}
else
{
InsertChart $Caption $Stat $NumToReturn $contents
}
# Send VM Information to the document
$contents = @($VMs | Sort-Object Name )
$columnHeaders = @('Name','CPUs','MEM','Power','Description')
$columnProperties = @('Name','NumCPU','MemoryMB','PowerState','Description')
$Heading = "VM Information"
if ($contents[0] -eq $null){
Write-Host "No entries for $Heading found"
}
else
{
Tableoutput $Heading $columnHeaders $columnProperties $contents
}
$totalhosts = $VMs.Length
$Text = "Total Number of Virtual Machines: $totalhosts"
InsertText $Text
#Insert VM CPU Graph
$contents = $VMs
$Stat = "cpu.usage.average"
$NumToReturn = 5
$Caption = "Top " + $NumToReturn + " Virtual Machines CPU Usage %Average"
if ($contents[0] -eq $null){
Write-Host "No entries for $Heading found"
}
else
{
InsertChart $Caption $Stat $NumToReturn $contents
}
#Insert VM MEM Graph
$contents = $VMs
$Stat = "mem.usage.average"
$NumToReturn = 5
$Caption = "Top " + $NumToReturn + " Virtual Machines MEM Usage %Average"
if ($contents[0] -eq $null){
Write-Host "No entries for $Heading found"
}
else
{
InsertChart $Caption $Stat $NumToReturn $contents
}
# Send VM Tools Information to Document
$contents = @($VMs | % { get-view $_.ID } | select Name, @{ Name="ToolsVersion"; Expression={$_.config.tools.toolsVersion}} | Sort-Object Name)
$columnHeaders = @('Name','VM Tools Version')
$columnproperties = @('Name', 'ToolsVersion')
$Heading = "VMWare Tools Version"
if ($contents[0] -eq $null){
Write-Host "No entries for $Heading found"
}
else
{
Tableoutput $Heading $columnHeaders $columnProperties $contents
}
# Datastore report
$contents = @($Ds | Sort-Object Name)
$columnHeaders = @('Name','Storage Type','Total Size','Free Space')
$columnProperties = @('Name','Type','CapacityMB','FreeSpaceMB')
$Heading = "Datastore Information"
if ($contents[0] -eq $null){
Write-Host "No entries for $Heading found"
}
else
{
Tableoutput $Heading $columnHeaders $columnProperties $contents
}
#Insert Datastore Pie Charts
foreach ($contents in $Ds)
{
$UsedSpace = $contents.CapacityMB - $contents.FreespaceMB
$categories = @('Free Space', 'Used Space')
$newcontents = @($contents.FreespaceMB, $usedSpace)
$Caption = $contents.Name + " Space Allocation"
if ($contents -eq $null){
Write-Host "No entries for $Heading found"
}
else
{
InsertPie $Caption $newcontents $categories
}
}
# Send Cluster Information to Document
$contents = @($clu | Sort-Object Name)
$columnHeaders = @('Name','HA Enabled','HA Failover Level','DRS Enabled','DRS Mode')
$columnProperties = @('Name', 'HAEnabled', 'HAFailoverLevel', 'DRSEnabled', 'DrsMode')
$Heading = "Cluster Information"
if ($contents[0] -eq $null){
Write-Host "No entries for $Heading found"
}
else
{
Tableoutput $Heading $columnHeaders $columnProperties $contents
}
# Send ResourcePool Information to Document
$contents = @($rp | select-object Name, MemLimitMB, CpuLimitMhz, NumCPUShares, NumMemShares | Sort-Object Name)
$columnHeaders = @('Name', 'Memory Limit MB', 'CPU Limit Mhz', 'CPU Shares', 'MEM Shares')
$columnProperties = @('Name', 'MemLimitMB', 'CpuLimitMhz', 'NumCPUShares', 'NumMemShares')
$Heading = "Resource Pool Information"
if ($contents[0] -eq $null){
Write-Host "No entries for $Heading found"
}
else
{
Tableoutput $Heading $columnHeaders $columnProperties $contents
}
# Send Snapshot Information to Document
$contents = @($VMs | Get-Snapshot | select-object VM, Name, Description)
$columnHeaders = @('VM', 'Name', 'Description')
$columnProperties = @('VM', 'Name', 'Description')
$Heading = "Snapshot Information"
if ($contents[0] -eq $null){
Write-Host "No entries for $Heading found"
}
else
{
Tableoutput $Heading $columnHeaders $columnProperties $contents
}
# Send Snapshot's over 1 month old to Document
$contents = @($VMs | Get-Snapshot | where { $_.Created -lt (get-date).addmonths(-1)} | select-object VM, Name, Description, Created)
$columnHeaders = @('VM', 'Name', 'Description', 'Created')
$columnProperties = @('VM', 'Name', 'Description', 'Created')
$Heading = "Snapshot's over 1 Month old"
if ($contents[0] -eq $null){
Write-Host "No entries for $Heading found"
}
else
{
Tableoutput $Heading $columnHeaders $columnProperties $contents
}
#Insert Snapshot Graph
$myCol = @()
ForEach ($vm in $vms)
{
$snapshots = Get-Snapshot -VM $vm
$myObj = "" | Select-Object Name, Value
$myObj.Name = $vm.name
$myObj.Value = ($snapshots | measure-object).count
$myCol += $myObj
}
$contents = @($myCol | Where-Object{$_.Value -gt 0} | Sort-Object Name)
$Stat = ""
$NumToReturn = ""
$Caption = "Number of snapshots per VM"
if ($contents[0] -eq $null){
Write-Host "No entries for $Heading found"
}
else
{
InsertChart $Caption $Stat $NumToReturn $contents
}
Write-Host "------------------------------"
Write-Host "Start Date: $date"
$enddate = get-date
Write-Host "End Date: $enddate"
# Show the finished Report
$msword.Selection.HomeKey(6) > Null
$msWord.Visible = $true
# Save the document to disk and close it
$filename = 'C:\\VMReport.doc'
$wordDoc.SaveAs([ref]$filename)
#Close the document if you are using as a scheduled task
#$wordDoc.Close()
# Exit our instance of word
#$msWord.Application.Quit()
#Email options for automated emailed report
#$smtpServer = “localhost”
#
#$msg = new-object Net.Mail.MailMessage
#$att = new-object Net.Mail.Attachment($filename)
#$smtp = new-object Net.Mail.SmtpClient($smtpServer)
#
#$msg.From = “somebody@yourdomain.com”
#$msg.To.Add(”somebody@theirdomain.com”)
#$msg.Subject = “VMware Report”
#$msg.Body = “Please find attached the automated VMware report”
#$msg.Attachments.Add($att)
#
#$smtp.Send($msg)
#Delete file if no longer needed once sent via email
#Remove-Item $filename
Disconnect-VIServer -Confirm:$False
|
PowerShellCorpus/PoshCode/DHCP Backup.ps1
|
DHCP Backup.ps1
|
<#
DHCP Backups Powershell Script
v1.1
2012-06-04
By VulcanX
.SYNOPSIS
This script will automate the backup of DHCP Databases and copy
them into a DFS Store at the following link:
\\\\domain.com\\DHCP
Each location has a seperate folder and once the backup
completes a mail sent out if any errors occur.
***NB*** : This can only be run in AD Environments where there is 1 DHCP Server per site
.USAGE & REQUIREMENTS
1. Open Powershell (Start->Run->Powershell.exe) from the DHCP Server
2. cd %ScriptLocation%
3. .\\DHCPBackup_v1.1
.SCHEDULED TASK CONFIGURATION
If you have your ExecutionPolicy set to RemoteSigned you will need to run the file with the
following, to execute it from a UNC Path unless you sign it yourself.
powershell.exe -ExecutionPolicy Bypass -File "\\\\domain.com\\DHCP\\DHCPBackup_v1.1.ps1"
***RECOVERY***
Please use the following when recovering a failed DHCP Server/Scope:
OPTION A:
netsh dhcp server import "\\\\domain.com\\DHCP\\$SiteName\\$Date\\NetshExport" all
DID NOT WORK IN TESTING!
OPTION B:
netsh exec "\\\\domain.com\\DHCP\\$SiteName\\$Date\\Dump.cfg"
First and foremost always try use OPTION A as this will be able to run on any DHCP Server. OPTION B is a last resort
if OPTION A didnt work.
***NB*** : OPTION B can only be run on the same server as what it was dumped from.
.CHANGELOG
v1.1 - Changed the names in the DHCP DFS Share to reflect the site names
When selecting which share location, it is based on which site the server is in
Found a way to run the script from the DFS DHCP repository
Script now uses dynamic methods allowing it to be more versatile
#>
# Clear Error Variable in case anything carried forward
$Error.Clear()
# Create Temporary DHCP Directory if does not exist
if((Test-Path -Path "C:\\DHCPTemp") -ne $true)
{
New-Item -Verbose "C:\\DHCPTemp" -type directory
}
# Clear any stale Backups that may have been created previously
Remove-Item -Path "C:\\DHCPTemp\\*" -Force -Recurse
# Start logging all the changes to a file in C:\\DHCPTemp\\LogFile.txt
Start-Transcript -Path "C:\\DHCPTemp\\LogFile.txt"
# Store the hostname
$Hostname = hostname
# Get Date and Format correctly
$Date = Get-Date -Format yyyy.MM.dd
# Echo Date for the Transcript
$DateTime = Get-Date
Write-Host "Time and Date Script executed:`r`n$DateTime`r`n`r`n"
# Check if ActiveDirectory Module is Imported, if not Import Module for ActiveDirectory
# This also ensures that the server is a DC and will be able to be checked based on Site
$ADModule = Get-Module -ListAvailable | Where {$_.Name -like "ActiveDirectory"} | Select-Object -ExpandProperty Name
if ($ADModule -eq "ActiveDirectory")
{
Import-Module ActiveDirectory
Write-Host "Active Directory Module Present and Loaded!`r`n"
}
else
{
Write-Host "Active Directory Module Not Available.`r`nExiting Script!`r`n"
Stop-Transcript
Send-MailMessage -From 'sysadm@domain.com' -To 'sysadm@domain.com' -Subject "DHCP Backup Error - $Hostname" `
-Body "Good day Sysadm`r`n`r`nThe following DHCP Backup for $Hostname has run on $Date`r`n`r`nNo AD Module Present!`r`n`r`nThank you`r`nSysAdm" -SmtpServer 'smtp.domain.com'
Exit
}
# Run Netsh Export for the DHCP Server Scopes and Config
Invoke-Command -Scriptblock {netsh dhcp server export "C:\\DHCPTemp\\NetshExport" all}
Write-Host "NetSh Export Completed!`r`n"
# Run NetSh Dump for the DHCP Server Config
Invoke-Command -Scriptblock {netsh dhcp server dump > "C:\\DHCPTemp\\Dump.cfg"}
Write-Host "NetSh Dump Completed!`r`n"
# Selecting correct location based on Site Name
$Site = Get-ADDomainController | Select -ExpandProperty Site
# List of the sites available ***NB*** UPDATE LIST IF NEW SITE IS SETUP
$SitesList = "Site1", "Site2", "Site3", "Site4", "Site5", "Site6", "Site6", "Site7"
# Creating the necessary folder to use with the copying of new Export
if($SitesList -contains "$Site")
{
if((Test-Path -Path "\\\\domain.com\\DHCP\\$Site\\$Date") -ne $true)
{
New-Item "\\\\domain.com\\DHCP\\$Site\\$Date" -type directory
}
Stop-Transcript
Copy -Force "C:\\DHCPTemp\\*" "\\\\domain.com\\DHCP\\$Site\\$Date"
}
# If the Sitename is not detected it will then create a folder using the Hostname
else{
echo "Site selected is not valid for this Domain Controllers DHCP Backup"
if((Test-Path -Path "\\\\domain.com\\DHCP\\$Hostname\\$Date") -ne $true)
{
New-Item "\\\\domain.com\\DHCP\\$Hostname\\$Date" -type directory
}
Stop-Transcript
Copy -Force "C:\\DHCPTemp\\*" "\\\\domain.com\\DHCP\\$Hostname\\$Date"
}
# Echo $Error to a File otherwise its unable to be used correctly as an Array/Variable
$CheckErrors = $Error.Count -ne "0"
if ($CheckErrors -eq "True")
{
echo $Error > "C:\\DHCPTemp\\Errors.txt"
$GCError = Get-Content "C:\\DHCPTemp\\Errors.txt" # Without this there is no way to output the errors in the email correctly
Send-MailMessage -From 'sysadm@domain.com' -To 'sysadm@domain.com' -Subject "DHCP Backup Error - $Hostname" `
-Body "Good day Sysadm`r`n`r`nThe following DHCP Backup Failed for $Hostname $Date`r`n`r`n<ERROR>`r`n`r`n$GCError`r`n`r`n</ERROR>`r`n`r`nThank you`r`nSysAdm" -SmtpServer 'smtp.domain.com'
Exit
}
# If no errors are detected it will proceed and end the powershell session
else
{
Exit
}
|
PowerShellCorpus/PoshCode/HttpRest 1.4.ps1
|
HttpRest 1.4.ps1
|
#requires -version 2.0
## HttpRest module version 1.4
####################################################################################################
## Still only the initial stages of converting to a full v2 module
## Based on the REST api from MindTouch's Dream SDK
##
## INSTALL:
## You need mindtouch.dream.dll (mindtouch.core.dll, SgmlReaderDll.dll, log4net.dll) from the SDK
## Get MindTouch_Dream_1.6.0.zip or greater from http`://sourceforge.net/projects/dekiwiki/files/
##
## Unpack it, and you can find these dlls in the "dist" folder.
## Make sure to put them in the folder with this script module.
##
## For documentation of Dream: http`://wiki.developer.mindtouch.com/Dream
####################################################################################################
## Version History
## 1.0 2008-11-30 First Release
## 1.0.1 2009-01-05 Added Get-WebPageContent
## 1.0.2 2009-05-14 Bug fix for Invoke-Http credential issues
## 1.1.0 2009-05-14 First release of a PowerShell 2.0 (CTP3/Windows7) version....
## 1.1.1 2009-05-15 Added Get-WebPageText and Get-Webfile ... cleaned up options
## 1.2 2009-08-09 Added Hashtable parsing on Get-DreamMessage
## Fixed parsing on Get-DreamPlug so we don't get errors on PowerShell 2
## Added ParameterSet on Invoke-Http to pass in a plug directly (easier to debug)
## 1.3 2010-07-27 Added a few more aliases to make life easier
## 1.4 2010-07-28 Changed Get-WebPageContent and Get-WebPageText to support pipline input
## Started adding help ...
####################################################################################################
## Usage:
## function Get-Google {
## Invoke-Http GET http`://www.google.com/search @{q=$args} |
## Receive-Http Xml "//h3[@class='r']/a" | Select href, InnerText
## }
## #########################################################################
## function Get-WebFile($url,$cred) {
## Invoke-Http GET $url -auth $cred | Receive-Http File
## }
## #########################################################################
## function Send-Paste {
## PARAM($PastebinURI="http`://posh.jaykul.com/p/",[IO.FileInfo]$file)
## PROCESS {
## if($_){[IO.FileInfo]$file=$_}
##
## if($file.Exists) {
## $ofs="`n"
## $result = Invoke-Http POST $PastebinURI @{
## format="posh" # PowerShell
## expiry="d" # (d)ay or (m)onth or (f)orever
## poster=$([Security.Principal.WindowsIdentity]::GetCurrent().Name.Split("\\")[-1])
## code2="$((gc $file) -replace "http`://","http``://")" # To get past the spam filter.
## paste="Send"
## } -Type FORM_URLENCODED -Wait
## $xml = $result.AsDocument().ToXml()
## write-output $xml.SelectSingleNode("//*[@class='highlight']/*").href
## } else { throw "File Not Found" }
## }}
##
####################################################################################################
if(!$PSScriptRoot){
throw "HttpRest is a module, and must be invoked by Import-Module"
}
Write-Debug "PSScriptRoot: '$PSScriptRoot'"
# This Module depends on MindTouch.Dream
$null = Add-Type -Path "$PSScriptRoot\\mindtouch.dream.dll" -ErrorAction Stop
# MindTouch.Dream requires: mindtouch.dream.dll, mindtouch.core.dll, SgmlReaderDll.dll, and log4net.dll)
# This Module also depends on utility functions from System.Web
$null = Add-Type -Assembly System.Web -ErrorAction Stop
## Some utility functions are defined at the bottom
[uri]$global:url = ""
[System.Management.Automation.PSCredential]$global:HttpRestCredential = $null
Function Get-DreamMessage {
PARAM($Content,$Type)
#Write-Verbose "Content: $(if($Content){$Content.GetType()}else{"null"}) $($Content.Length) and Type: $(if($Type){$Type.GetType()}else{"null"})"
if(!$Content) {
Write-Verbose "No Content"
return [MindTouch.Dream.DreamMessage]::Ok()
}
if( $Content -is [System.Xml.XmlDocument]) {
Write-Verbose "Xml Content"
return [MindTouch.Dream.DreamMessage]::Ok( $Content )
}
if($Content -is [Hashtable]) {
$kvp = $Content.GetEnumerator() | %{ new-object "System.Collections.Generic.KeyValuePair[[String],[String]]" $_.Key, $_.Value }
Write-Verbose "Hashtable content: $($kvp | ft -auto | out-string -stream | %{ " $_ ".TrimEnd()} )"
return [MindTouch.Dream.DreamMessage]::Ok( $kvp )
}
if(Test-Path $Content -EA "SilentlyContinue") {
Write-Verbose "File Content"
return [MindTouch.Dream.DreamMessage]::FromFile((Convert-Path (Resolve-Path $Content)));
}
if($Type -is [String]) {
Write-Verbose "Specific Content: $([MindTouch.Dream.MimeType]::$Type)"
$Type = [MindTouch.Dream.MimeType]::$Type
}
if($Type -is [MindTouch.Dream.DreamMessage]) {
Write-Verbose "Specific Content: $([MindTouch.Dream.MimeType]::$Type)"
return [MindTouch.Dream.DreamMessage]::Ok( $Type, $Content )
} else {
Write-Verbose "Unspecified string content"
return [MindTouch.Dream.DreamMessage]::Ok( $([MindTouch.Dream.MimeType]::TEXT), $Content )
}
}
Function Get-DreamPlug {
[CmdletBinding()]
PARAM ( $Url, [hashtable]$With, [hashtable]$Headers )
if($Url -is [array]) {
Write-Verbose "URL is an array of parts"
if($Url[0] -is [hashtable]) {
Write-Verbose "URL is an array of hashtable parts"
$plug = [MindTouch.Dream.Plug]::New($global:url)
foreach($param in $url.GetEnumerator()) {
if($param.Value) {
$plug = $plug.At($param.Key,"=$(Encode-Twice $param.Value)")
} else {
$plug = $plug.At($param.Key)
}
}
}
else
{
[URI]$uri = Join-Url $global:url $url
$plug = [MindTouch.Dream.Plug]::New($uri)
}
}
elseif($url -is [string])
{
Write-Verbose "String URL"
trap { continue }
[URI]$uri = $url
if(!$uri.IsAbsoluteUri) {
$uri = Join-Url $global:url $url
Write-Verbose "Relative URL, appending to $($global:url) to get: $uri"
}
$plug = [MindTouch.Dream.Plug]::New($uri)
}
else {
Write-Verbose "No URL, using default $($global:url)"
$plug = [MindTouch.Dream.Plug]::New($global:url)
}
if($with) {
foreach($w in $with.GetEnumerator()) {
if($w.Value) {
$plug = $plug.With($w.Key,$w.Value)
}
}
Write-Verbose "Added 'with' params: $plug"
}
if($headers) {
foreach($header in $Headers.GetEnumerator()) {
if($header.Value) {
$plug = $plug.WithHeader($header.Key,$header.Value)
}
}
Write-Verbose "Added 'with' params: $plug"
}
return $plug
}
Function Receive-Http {
PARAM(
# [Parameter(Position=1, Mandatory=$false)]
# [ValidateSet("Xml", "File", "Text","Bytes")]
# [Alias("As")]
$Output = "Xml"
,
# [Parameter(Position=2, Mandatory=$false)]
[string]$Path
,
# [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Result")]
# [Alias("IO")]
# [MindTouch.Dream.Result``1[[MindTouch.Dream.DreamMessage]]]
$InputObject
#,
# [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Response")]
# [MindTouch.Dream.DreamMessage]
# $response
)
BEGIN {
if($InputObject) {
Write-Output $inputObject | Receive-Http $Output $Path
} # else they'd better pass it in on the pipeline ...
}
PROCESS {
$response = $null
if($_ -is [MindTouch.Dream.Result``1[[MindTouch.Dream.DreamMessage]]]) {
$response = $_.Wait()
} elseif($_ -is [MindTouch.Dream.DreamMessage]) {
$response = $_
} elseif($_) {
throw "We can only pipeline [MindTouch.Dream.DreamMessage] objects, or [MindTouch.Dream.Result`1[DreamMessage]] objects"
}
if($response) {
Write-Debug $($response | Out-String)
if(!$response.IsSuccessful) {
Write-Error $($response | Out-String)
Write-Verbose $response.AsText()
throw "ERROR: '$($response.Status)' Response Status."
} else {
switch($Output) {
"File" {
## Joel's magic filename guesser ...
if(!$Path) {
[string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $response.Headers["Content-Disposition"] ).Groups[1].Value
$Path = $fileName.trim("\\/""'")
if(!$Path){
if($response.ResponseUri) {
$fileName = $response.ResponseUri.Segments[-1]
$Path = $fileName.trim("\\/")
if(!([IO.FileInfo]$Path).Extension) {
$Path = $Path + "." + $response.ContentType.Split(";")[0].Split("/")[1]
}
}
}
}
if($Path) {
$File = Get-FileName $Path
} else {
$File = Get-FileName
}
$null = [StreamUtil]::CopyToFile( $response.AsStream(), $response.ContentLength, $File )
Get-ChildItem $File
}
"XDoc" {
if($Path) {
$response.AsDocument()[$Path]
} else {
$response.AsDocument()#.ToXml()
}
}
"Xml" {
if($Path) {
$response.AsDocument().ToXml().SelectNodes($Path)
} else {
$response.AsDocument().ToXml()
}
}
"Text" {
if($Path) {
$response.AsDocument()[$Path] | % { $_.AsInnerText }
} else {
$response.AsText()
}
}
"Bytes" {
$response.AsBytes()
}
}
}
}
}
}
Function Invoke-Http {
#.Synopsis
# Invoke an HTTP verb on a URI
#.Description
# This is the core http rest cmdlet, which does most of the work and allows fetching web pages, files, etc.
[CmdletBinding(DefaultParameterSetName="ByPath")]
PARAM(
## http`://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
## Nobody actually uses HEAD or OPTIONS, right?
## And nobody's even heard of TRACE or CONNECT ;)
[Parameter(Position=0, Mandatory=$false)]
[ValidateSet("POST", "GET", "PUT", "DELETE", "HEAD", "OPTIONS")] ## There are other verbs, but we need a list to make sure you don't screw up
[string]$Verb = "GET"
,
[Parameter(Position=1, Mandatory=$true, ValueFromPipeline=$false, ParameterSetName="WithPlug")]
[MindTouch.Dream.Plug]
$Plug
,
[Parameter(Position=1, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="ByPath")]
[string]
$Path
,
[Parameter(Position=2, Mandatory=$false, ParameterSetName="ByPath")]
[hashtable]$With
,
[Parameter(Position=3, Mandatory=$false, ParameterSetName="ByPath")]
[hashtable]$Headers
,
[Parameter(Mandatory=$false)]
$Content
,
[Parameter(Mandatory=$false)]
[System.Collections.Generic.IEnumerable[MindTouch.Dream.DreamCookie]]$Cookies
,
[Parameter(Mandatory=$false)]
$Type # Of Content
,
[Parameter(Mandatory=$false)]
[switch]$authenticate
,
[Parameter(Mandatory=$false)]
$credentials
,
[Parameter(Mandatory=$false)]
[switch]$Persistent ## Note this ALSO causes WaitForResponse
,
[switch]$waitForResponse
)
PROCESS {
if(!$Plug){ #$PSCmdlet.ParameterSetName -eq $ByPath) {
$Plug = Get-DreamPlug $Path $With $Headers
}
## Special Handling for FORM_URLENCODED
if($Type -like "Form*" -and !$Content) {
$dream = [MindTouch.Dream.DreamMessage]::Ok( $Plug.Uri )
$Plug = [MindTouch.Dream.Plug]::New( $Plug.Uri.SchemeHostPortPath )
Write-Verbose "RECREATED Plug: $($Plug.Uri.SchemeHostPortPath)"
} else {
$dream = Get-DreamMessage $Content $Type
Write-Verbose "Created Dream with Content: $($dream.AsText() |out-String)"
}
if(!$plug -or !$dream) {
throw "Can't come up with a request!"
}
if($Persistent -and $global:HttpRestCookies) {
$dream.Cookies.AddRange( $global:HttpRestCookies )
}
if($Cookies) {
$dream.Cookies.AddRange( $Cookies )
}
if($authenticate -or $credentials){
if($credentials -is [System.Management.Automation.PSCredential]) {
Write-Verbose "AUTHENTICATING AS $($credentials.GetNetworkCredential().UserName)"
$plug = $plug.WithCredentials($credentials.GetNetworkCredential())
} elseif($credentials -is [System.Net.ICredentials]) {
Write-Verbose "AUTHENTICATING AS $($credentials.GetNetworkCredential().UserName)"
$plug = $plug.WithCredentials($credentials.GetNetworkCredential())
} else {
if($credentials) {
Write-Error "Credential must be a PSCredential or a System.Net.ICredentials"
}
$null = Get-HttpCredential # Make sure they have global credentials
Write-Verbose "AUTHENTICATING AS $($global:HttpRestCredential.UserName)"
$plug = $plug.WithCredentials($global:HttpRestCredential.GetNetworkCredential())
}
}
Write-Verbose $plug.Uri
## DEBUG:
Write-Debug "URI: $($Plug.Uri)"
Write-Debug "Verb: $($Verb.ToUpper())"
Write-Debug $($dream | gm | Out-String)
$result = $plug.InvokeAsync( $Verb.ToUpper(), $dream )
Write-Debug $($result | Out-String)
# if($DebugPreference -eq "Continue") {
# Write-Debug $($result.Wait() | Out-String)
# }
if($waitForResponse -or $Persistent) {
$result = $result.Wait()
$global:HttpRestCookies = $result.Cookies
}
write-output $result
trap [MindTouch.Dream.DreamResponseException] {
Write-Error @"
TRAPPED DreamResponseException
$($_.Exception.Response | Out-String)
$($_.Exception.Response.Headers | Out-String)
"@
break;
}
}
}
Function Get-WebPageContent {
#.Synopsis
# A wrapper for http get | rcv xml
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$true, ValueFromPipeline=$true)]
[string]$url
,
[Parameter(Mandatory=$false)]
[string]$xpath=""
,
[Parameter(Position=2,Mandatory=$false)]
[hashtable]$with=@{}
,
[Parameter(Mandatory=$false)]
[switch]$Persist
,
[Parameter(Mandatory=$false)]
[switch]$Authenticate
)
PROCESS {
invoke-http get $url $with -Authenticate:$Authenticate -Persist:$Persist | receive-http xml $xpath | select -expand outerxml
}
}
Function Get-WebPageText {
#.Synopsis
# A wrapper for http get | rcv text
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$true, ValueFromPipeline=$true)]
[string]$url
,
[Parameter(Mandatory=$false)]
[string]$xpath=""
,
[Parameter(Position=2,Mandatory=$false)]
[hashtable]$with=@{}
,
[Parameter(Mandatory=$false)]
[switch]$Persist
,
[Parameter(Mandatory=$false)]
[switch]$Authenticate
)
PROCESS {
invoke-http get $url $with -Authenticate:$Authenticate -Persist:$Persist | receive-http text $xpath
}
}
Function Get-WebFile {
#.Synopsis
# Download a file from a URI to the local computer
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$true, ValueFromPipeline=$true)]
[string]$url
,
[Parameter(Mandatory=$false)]
[Alias("output")]
[string]$path=""
,
[Parameter(Position=2,Mandatory=$false)]
[hashtable]$with=@{}
,
[Parameter(Mandatory=$false)]
[switch]$Persist
,
[Parameter(Mandatory=$false)]
[switch]$Authenticate
)
PROCESS {
Invoke-Http GET $url $with -Authenticate:$Authenticate -Persist:$Persist | Receive-Http File $path
}
}
Function Set-HttpDefaultUrl {
#.Synopsis
# Set the base URI for making lots of calls to a single webservice without re-entering the full URL each time
PARAM ([uri]$baseUri=$(Read-Host "Please enter the base Uri for your RESTful web-service"))
$global:url = $baseUri
}
Function Set-HttpCredential {
#.Synopsis
# Set the default credentials for making lots of calls to a single webservice without re-entering credentials
param($Credential=$(Get-CredentialBetter -Title "Http Authentication Request - $($global:url.Host)" `
-Message "Your login for $($global:url.Host)" `
-Domain $($global:url.Host)) )
if($Credential -is [System.Management.Automation.PSCredential]) {
$global:HttpRestCredential = $Credential
} elseif($Credential -is [System.Net.NetworkCredential]) {
$global:HttpRestCredential = new-object System.Management.Automation.PSCredential $Credential.UserName, $(ConvertTo-SecureString $credential.Password)
}
}
Function Get-HttpCredential {
#.Synopsis
# Retrieves the default credentials for making lots of calls to a single webservice without re-entering credentials
if(!$global:url) { Set-HttpDefaultUrl }
if(!$global:HttpRestCredential) { Set-HttpCredential }
if(!$Secure) {
return $global:HttpRestCredential.GetNetworkCredential();
} else {
return $global:HttpRestCredential
}
}
Function ConvertTo-UrlDoubleEncode {
#.Synopsis
# Encode URLs twice for use with mindtouch APIs
param([string]$text)
return [System.Web.HttpUtility]::UrlEncode( [System.Web.HttpUtility]::UrlEncode( $text ) )
}
Function Join-Url {
#.Synopsis
# Like Join-Path, but for URIs
[CmdletBinding()]
param(
[Parameter()]
[uri]$baseUri=$global:url
,
[Parameter(ValueFromRemainingArguments=$true)]
[string[]]$path
)
$ofs="/";$BaseUrl = ""
if($BaseUri -and $baseUri.AbsoluteUri) {
$BaseUrl = "$($baseUri.AbsoluteUri.Trim('/'))/"
}
return [URI]"$BaseUrl$([string]::join("/",@($path)).TrimStart('/'))"
}
Function ConvertTo-SecureString {
#.Synopsis
# Helper function which converts a string to a SecureString
Param([string]$input)
$result = new-object System.Security.SecureString
foreach($c in $input.ToCharArray()) {
$result.AppendChar($c)
}
$result.MakeReadOnly()
return $result
}
Function Get-FileName {
#.Synopsis
# Helper function to get a VALID filesystem path
param($fileName=$([IO.Path]::GetRandomFileName()), $path)
$fileName = $fileName.trim("\\/""'")
## if the $Path has a file name, and it's folder exists:
if($Path -and !(Test-Path $Path -Type Container) -and (Test-Path (Split-Path $path) -Type Container)) {
$path
## if the $Path is just a folder (and it exists)
} elseif($Path -and (Test-Path $path -Type Container)) {
$fileName = Split-Path $fileName -leaf
Join-Path $path $fileName
## If there's no valid $Path, and the $FileName has a folder...
} elseif((Split-Path $fileName) -and (Test-Path (Split-Path $fileName))) {
$fileName
} else {
Join-Path (Get-Location -PSProvider "FileSystem") (Split-Path $fileName -Leaf)
}
}
Function Get-UtcTime {
Param($Format="yyyyMMddhhmmss")
[DateTime]::Now.ToUniversalTime().ToString($Format)
}
Function Get-CredentialBetter {
## .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 UserName
## A default user name for the credential prompt, or a pre-existing credential (would skip all prompting)
## .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]$Inline
)
PROCESS {
if( $UserName -is [System.Management.Automation.PSCredential]) {
return $UserName
} elseif($UserName -ne $null) {
$UserName = $UserName.ToString()
}
if($Inline) {
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")
}
}
New-Alias Encode-Twice ConvertTo-UrlDoubleEncode
new-alias gwpc Get-WebPageContent -EA "SilentlyContinue"
new-alias gwpt Get-WebPageText -EA "SilentlyContinue"
new-alias http Invoke-Http -EA "SilentlyContinue"
new-alias rcv Receive-Http -EA "SilentlyContinue"
Export-ModuleMember -Function Invoke-Http, Receive-Http, ConvertTo-UrlDoubleEncode, Get-WebPageContent, Get-WebPageText, Get-WebFile, Get-HttpCredential, Set-HttpCredential, Set-HttpDefaultUrl -Alias *
# SIG # Begin signature block
# MIIIDQYJKoZIhvcNAQcCoIIH/jCCB/oCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUr09whcNnLQwup5+1zj3w+DcA
# +/agggUrMIIFJzCCBA+gAwIBAgIQKQm90jYWUDdv7EgFkuELajANBgkqhkiG9w0B
# AQUFADCBlTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0
# IExha2UgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYD
# VQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHTAbBgNVBAMTFFVUTi1VU0VS
# Rmlyc3QtT2JqZWN0MB4XDTEwMDUxNDAwMDAwMFoXDTExMDUxNDIzNTk1OVowgZUx
# CzAJBgNVBAYTAlVTMQ4wDAYDVQQRDAUwNjg1MDEUMBIGA1UECAwLQ29ubmVjdGlj
# dXQxEDAOBgNVBAcMB05vcndhbGsxFjAUBgNVBAkMDTQ1IEdsb3ZlciBBdmUxGjAY
# BgNVBAoMEVhlcm94IENvcnBvcmF0aW9uMRowGAYDVQQDDBFYZXJveCBDb3Jwb3Jh
# dGlvbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMfUdxwiuWDb8zId
# KuMg/jw0HndEcIsP5Mebw56t3+Rb5g4QGMBoa8a/N8EKbj3BnBQDJiY5Z2DGjf1P
# n27g2shrDaNT1MygjYfLDntYzNKMJk4EjbBOlR5QBXPM0ODJDROg53yHcvVaXSMl
# 498SBhXVSzPmgprBJ8FDL00o1IIAAhYUN3vNCKPBXsPETsKtnezfzBg7lOjzmljC
# mEOoBGT1g2NrYTq3XqNo8UbbDR8KYq5G101Vl0jZEnLGdQFyh8EWpeEeksv7V+YD
# /i/iXMSG8HiHY7vl+x8mtBCf0MYxd8u1IWif0kGgkaJeTCVwh1isMrjiUnpWX2NX
# +3PeTmsCAwEAAaOCAW8wggFrMB8GA1UdIwQYMBaAFNrtZHQUnBQ8q92Zqb1bKE2L
# PMnYMB0GA1UdDgQWBBTK0OAaUIi5wvnE8JonXlTXKWENvTAOBgNVHQ8BAf8EBAMC
# B4AwDAYDVR0TAQH/BAIwADATBgNVHSUEDDAKBggrBgEFBQcDAzARBglghkgBhvhC
# AQEEBAMCBBAwRgYDVR0gBD8wPTA7BgwrBgEEAbIxAQIBAwIwKzApBggrBgEFBQcC
# ARYdaHR0cHM6Ly9zZWN1cmUuY29tb2RvLm5ldC9DUFMwQgYDVR0fBDswOTA3oDWg
# M4YxaHR0cDovL2NybC51c2VydHJ1c3QuY29tL1VUTi1VU0VSRmlyc3QtT2JqZWN0
# LmNybDA0BggrBgEFBQcBAQQoMCYwJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmNv
# bW9kb2NhLmNvbTAhBgNVHREEGjAYgRZKb2VsLkJlbm5ldHRAWGVyb3guY29tMA0G
# CSqGSIb3DQEBBQUAA4IBAQAEss8yuj+rZvx2UFAgkz/DueB8gwqUTzFbw2prxqee
# zdCEbnrsGQMNdPMJ6v9g36MRdvAOXqAYnf1RdjNp5L4NlUvEZkcvQUTF90Gh7OA4
# rC4+BjH8BA++qTfg8fgNx0T+MnQuWrMcoLR5ttJaWOGpcppcptdWwMNJ0X6R2WY7
# bBPwa/CdV0CIGRRjtASbGQEadlWoc1wOfR+d3rENDg5FPTAIdeRVIeA6a1ZYDCYb
# 32UxoNGArb70TCpV/mTWeJhZmrPFoJvT+Lx8ttp1bH2/nq6BDAIvu0VGgKGxN4bA
# T3WE6MuMS2fTc1F8PCGO3DAeA9Onks3Ufuy16RhHqeNcMYICTDCCAkgCAQEwgaow
# gZUxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJVVDEXMBUGA1UEBxMOU2FsdCBMYWtl
# IENpdHkxHjAcBgNVBAoTFVRoZSBVU0VSVFJVU1QgTmV0d29yazEhMB8GA1UECxMY
# aHR0cDovL3d3dy51c2VydHJ1c3QuY29tMR0wGwYDVQQDExRVVE4tVVNFUkZpcnN0
# LU9iamVjdAIQKQm90jYWUDdv7EgFkuELajAJBgUrDgMCGgUAoHgwGAYKKwYBBAGC
# NwIBDDEKMAigAoAAoQKAADAZBgkqhkiG9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgor
# BgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQUBKVb3pGB
# 1I/RXvlaTjJsduu94KYwDQYJKoZIhvcNAQEBBQAEggEAOUrgnwmYthZZQ7oleYBr
# hy1y4h7DRJ8eNTpjV8wfbJYmriuqWZsbnmZUiMQqXDgQJ7rWx/2KZOtlp5Q4EYdi
# +j8Q3YChnUwVr0Z1zjCj91PtnU5M7IB1eyTqmUgWIX3ldd9AnmCB8Eted487/VuK
# YrAO0gHQVmIX6t/Yv2bG0D3ggvqDmUbuqw7UV526ykVAmbX0tYOXeFBC5sCo9c3L
# lmBO/cgZDXq5C7DC5mnLBYxsvXvSitAE7m/S+v7U2irc2pnGqiIabz/spC+O+YOw
# zWbfdzyHxWNMMQ2ZTfkQ8AVEv+Um1zT81x8Mf2CSznaBawU/7byZdSIObsHTZ2EK
# gg==
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Get-OnlineHelp_3.ps1
|
Get-OnlineHelp_3.ps1
|
#requires -version 2.0
## An update using New-WebServiceProxy to the MSDN ContentService instead of HttpRest
## See: http: //services.msdn.microsoft.com/ContentServices/ContentService.asmx
## YOU MUST SAVE THIS FILE AS Get-OnlineHelp.ps1 in your path, and call it as Get-OnlineHelp
## __OR__ dot-source it -- DO NOT run it twice!
## This is a VERY EARLY prototype of a function that could retrieve cmdlet help from TechNet ...
## and hypothetically, other online help sites which used the same format (none)
## TODO:
## Properly format <pre> in the console
## Properly format the tables at the end of parameters
## Version History
## 0.9 - 2010-07-27 - Added the rest of the parameters, fixed output, support -FULL, etc. THIS VERSION
## 0.3 - 2010-03-25 - Fixed a buggy type check which failed on first run.
## 0.2 - 2010-03-24 - Switched to using the ContentService Web Service. PoshCode.org/1723
## 0.1 - 2010-03-23 - Initial release depended on HttpRest. PoshCode.org/1719
[CmdletBinding(DefaultParameterSetName="Default")]
param(
[Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=0)]
[System.String]
${Name},
[System.String]
${Path},
[System.String[]]
${Category},
[System.String[]]
${Component},
[System.String[]]
${Functionality},
[System.String[]]
${Role},
[Parameter(Mandatory=$true,ParameterSetName='Detailed')]
[Switch]
${Detailed},
[Parameter(Mandatory=$true,ParameterSetName='Full')]
[Switch]
${Full},
[Parameter(Mandatory=$true,ParameterSetName='Examples')]
[Switch]
${Examples},
[Parameter(Mandatory=$true,ParameterSetName='Parameters')]
[System.String]
${Parameter},
[Switch]
${Online}
)
# http://poshcode.org/1718
function Select-Expand {
<#
.Synopsis
Like Select-Object -Expand, but with recursive iteration of a select chain
.Description
Takes a dot-separated series of properties to expand, and recursively iterates the output of each property ...
.Parameter Property
A collection of property names to expand.
Each property can be a dot-separated series of properties, and each one is expanded, iterated, and then evaluated against the next
.Parameter InputObject
The input to be selected from
.Parameter Unique
If set, this becomes a pipeline hold-up, and the total output is checked to ensure uniqueness
.Parameter EmptyToo
If set, Select-Expand will include empty/null values in it's output
.Example
Get-Help Get-Command | Select-Expand relatedLinks.navigationLink.uri -Unique
This will return the online-help link for Get-Command. It's the equivalent of running the following command:
C:\\PS> Get-Help Get-Command | Select-Object -Expand relatedLinks | Select-Object -Expand navigationLink | Select-Object -Expand uri | Where-Object {$_} | Select-Object -Unique
#>
param(
[Parameter(ValueFromPipeline=$false,Position=0)]
[string[]]$Property
,
[Parameter(ValueFromPipeline=$true)]
[Alias("IO")]
[PSObject[]]$InputObject
,
[Switch]$Unique
,
[Switch]$EmptyToo
)
begin {
if($unique) {
$output = @()
}
}
process {
foreach($io in $InputObject) {
foreach($prop in $Property -split "\\.") {
if($io -ne $null) {
$io = $io | Select-Object -Expand $prop
Write-Verbose $($io | out-string)
}
}
if(!$EmptyToo -and ($io -ne $null)) {
$io = $io | Where-Object {$_}
}
if($unique) {
$output += @($io)
}
else {
Write-Output $io
}
}
}
end {
if($unique) {
Write-Output $output | Select-Object -Unique
}
}
}
# New-Alias slep Select-Expand
# http://poshcode.org/1722
function Get-HttpResponseUri {
#.Synopsis
# Fetch the HEAD for a url and return the ResponseUri.
#.Description
# Does a HEAD request for a URL, and returns the ResponseUri. This is useful for resolving (in a service-independent way) shortened urls.
#.Parameter ShortUrl
# A (possibly) shortened URL to be resolved to its redirect location.
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)]
[Alias("Uri","Url")]
[string]$ShortUrl
)
process {
$req = [System.Net.HttpWebRequest]::Create($ShortUrl)
$req.Method = "HEAD"
$response = $req.GetResponse()
Write-Output $response.ResponseUri
$response.Close() # clean up like a good boy
}
}
# New-Alias Resolve-ShortUri Select-Expand
if( -not("Mtps.ContentService" -as [type] -and $global:MtpsWebServiceProxy -as "Mtps.ContentService")) {
$global:MtpsWebServiceProxy = New-WebServiceProxy "http://services.msdn.microsoft.com/ContentServices/ContentService.asmx?wsdl" -Namespace Mtps
}
function global:Get-OnlineHelp {
[CmdletBinding(DefaultParameterSetName="Default")]
param(
[Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=0)]
[System.String]
${Name},
[System.String]
${Path},
[System.String[]]
${Category},
[System.String[]]
${Component},
[System.String[]]
${Functionality},
[System.String[]]
${Role},
[Parameter(Mandatory=$true,ParameterSetName='Detailed')]
[Switch]
${Detailed},
[Parameter(Mandatory=$true,ParameterSetName='Full')]
[Switch]
${Full},
[Parameter(Mandatory=$true,ParameterSetName='Examples')]
[Switch]
${Examples},
[Parameter(Mandatory=$true,ParameterSetName='Parameters')]
[System.String]
${Parameter},
[Switch]
${Online}
)
begin {
$HelpValues = $(
switch($PsCmdlet.ParameterSetName) {
"Default" {"name", "synopsis", "syntax", "description", "related links", "remarks"}
"Full" {"name", "synopsis", "syntax", "description", "parameters", "inputs and outputs", "examples", "notes", "see also"}
"Detailed" {"name", "synopsis", "syntax", "description", "parameters", "examples", "remarks"}
"Examples" {"name", "synopsis", "examples"}
"Parameter" {"name", "synopsis", "parameters"}
}
)
}
process {
### Get the Help ID
$uri = Get-Help @PSBoundParameters | Select-Expand relatedLinks.navigationLink.uri -Unique | Get-HttpResponseUri
if(!$uri) { throw "Couldn't find online help URL for $Name" }
$id = [IO.Path]::GetFileNameWithoutExtension( $uri.segments[-1] )
write-verbose "Content Id: $id"
### Get the Help Content
$content = $MtpsWebServiceProxy.GetContent( (New-Object 'Mtps.getContentRequest' -Property @{locale = $PSUICulture; contentIdentifier = $id; requestedDocuments = (New-Object Mtps.requestedDocument -Property @{Selector="Mtps.Failsafe"}) }) )
$global:OnlineHelpContent = $content.primaryDocuments |?{$_.primaryFormat -eq "Mtps.Failsafe"} | Select -Expand Any
### NAME
$NameNode = $global:OnlineHelpContent.SelectSingleNode("//*[local-name()='div' and @class='topic']/*[local-name()='div' and @class='title']")
$NameNode.SetAttribute("header","NAME")
### Ditch the navigation and stuff
$global:OnlineHelpContent = $global:OnlineHelpContent.SelectSingleNode("//*[local-name()='div' and @id='mainBody']")
### SYNOPSIS
$Synopsis = $global:OnlineHelpContent.SelectSingleNode("*[local-name()='p']")
$Synopsis.SetAttribute("header","SYNOPSIS")
$global:help = @{Name=$NameNode; Synopsis=$Synopsis}
### EVERYTHING ELSE
$headers = $OnlineHelpContent.h2 | ForEach-Object { $_.get_InnerText().Trim() }
$content = $OnlineHelpContent.div | ForEach-Object { $_ }
if($headers.Count -ne $content.Count) {
Write-Warning "Unmatched content"
foreach($header in $headers) {
$help.$header = $OnlineHelpContent.SelectNodes( "//*[preceding-sibling::*[1][local-name()='h2' and normalize-space()='$header']]" )|
ForEach { $_.SetAttribute("header",$header.ToUpper()); $_ }
}
}
else {
for($h=0;$h -lt $headers.Count; $h++){
$help.($headers[$h]) = $content[$h]
$help.($headers[$h]).SetAttribute("header",$headers[$h].ToUpper())
}
}
### PARAMETERS
# $Global:Parameters = $global:OnlineHelpContent.RemoveChild( $global:OnlineHelpContent.SelectSingleNode("//*[local-name()='div' and @id='sectionSection2']") )
# $Parameters.SetAttribute("header","PARAMETERS")
# ## Create the parameters
# $help.Parameters = $Parameters
$parameternames = $help.Parameters.h3 | ForEach-Object { $_.get_InnerText().Trim() }
foreach($header in $parameternames) {
foreach($node in $help.Parameters.SelectNodes( "//*[preceding-sibling::*[1][local-name()='h3' and normalize-space()='$header']]" ) ) {
$node.SetAttribute("header",$header)
}
}
### EXAMPLES
$help.Examples = $Help.Notes.Clone()
$help.Examples.SetAttribute("header","EXAMPLES")
$help.Examples.set_InnerXml('')
ForEach($key in $help.Keys -match "Example \\d+" | sort { [int]($_ -replace "Example ") }) {
$help[$key].Header = $help[$key].Header -creplace "EXAMPLE","Example"
$null = $help.Examples.AppendChild( $help[$key] )
$null = $help.Remove($key)
}
foreach($section in $help[$HelpValues]) {
if($section -isnot [PSObject]) { $section = New-Object PSObject $section }
if($Section.div -and @($Section.div)[0].header) {
$header = New-Object PSObject -Property @{header=$section.Header}
$header.PSTypeNames.Insert(0,"PoshCode.HtmlCommandHelpInfo+Section")
$header
foreach($subsection in $Section.div) {
$null = $subsection.PSTypeNames.Insert(0,"PoshCode.HtmlCommandHelpInfo+Section")
$subsection
}
} else {
$null = $section.PSTypeNames.Insert(0,"PoshCode.HtmlCommandHelpInfo+Section")
$section
}
}
}
}
Get-OnlineHelp @PSBoundParameters
# Since you can't update format data without a file that has a ps1xml ending, let's make one up...
$tempFile = "$([IO.Path]::GetTempFileName()).ps1xml"
Set-Content $tempFile @'
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<ViewDefinitions>
<View>
<Name>HtmlCommandHelpSection</Name>
<ViewSelectedBy>
<TypeName>PoshCode.HtmlCommandHelpInfo+Section</TypeName>
</ViewSelectedBy>
<CustomControl>
<CustomEntries>
<CustomEntry>
<CustomItem>
<Frame>
<LeftIndent>4</LeftIndent>
<CustomItem>
<ExpressionBinding>
<ScriptBlock>
Write-Host $_.Header.Trim() -Fore Cyan -NoNewLine
return " "
</ScriptBlock>
</ExpressionBinding>
<NewLine/>
<ExpressionBinding>
<ScriptBlock>$_.get_InnerText().trim() -replace '^[\\n\\s]*\\n|\\n\\s+$'</ScriptBlock>
</ExpressionBinding>
<NewLine/>
</CustomItem>
</Frame>
</CustomItem>
</CustomEntry>
</CustomEntries>
</CustomControl>
</View>
<!--View>
<Name>HtmlCommandHelpHeader</Name>
<ViewSelectedBy>
<TypeName>PoshCode.HtmlCommandHelpInfo+Header</TypeName>
</ViewSelectedBy>
<CustomControl>
<CustomEntries>
<CustomEntry>
<CustomItem>
<ExpressionBinding>
<ScriptBlock>Write-Host $_ -Fore Cyan; ""</ScriptBlock>
</ExpressionBinding>
</CustomItem>
</CustomEntry>
</CustomEntries>
</CustomControl>
</View-->
</ViewDefinitions>
</Configuration>
'@
Update-FormatData -Append $tempFile
|
PowerShellCorpus/PoshCode/finddupe_21.ps1
|
finddupe_21.ps1
|
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
try
{
$stream = $file.OpenRead()
}
catch { return $null }
$hashByteArray = $hashAlgorithm.ComputeHash($stream)
$stream.Close()
trap
{
if ($stream -ne $null)
{
$stream.Close()
}
return $null
}
foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }}
return [string]$result
}
$starttime=[datetime]::now
write-host "FindDupe.ps1 - find and optionally delete duplicate files. FindDupe.ps1 -help or FindDupe.ps1 -h for usage options."
$m = 0
$args3=$args
$args2=$args3|?{$_ -ne "-delete" -and $_ -ne "-recurse" -and $_ -ne "-hidden" -and $_ -ne "-h" -and $_ -ne "-help"}
if ($args3 -eq "-help" -or $args3 -eq "-h")
{
""
"Usage:"
" PS>.\\FindDupe.ps1 <directory/file #1> <directory/file #2> ... <directory/file #N> [-delete] [-noprompt] [-recurse] [-help]"
"Options:"
" -recurse recurses through all subdirectories of any specified directories."
" -hidden checks hidden files, default is to ignore hidden files."
" -help displays this usage option data, and ignores all other arguments."
""
"Examples:"
" PS>.\\finddupe.ps1 c:\\data d:\\finance -recurse"
" PS>.\\finddupe.ps1 d: -recurse -delete"
" PS>.\\finddupe.ps1 c:\\users\\alice\\pictures\\ -recurse -delete"
exit
}
$files=@(dir -ea 0 $args2 -recurse:$([bool]($args3 -eq "-recurse")) -force:$([bool]($args3 -eq "-hidden")) |?{$_.psiscontainer -eq $false}|sort length)
if ($files.count -lt 2) {exit}
$sizenamehash=@{}
for ($i=0;$i -lt ($files.count-1); $i++)
{
if ($files[$i].length -ne $files[$i+1].length) {continue}
$breakout=$false
while($true)
{
$sha512 = (get-SHA512 $files[$i].fullname)
if ($sha512 -ne $null)
{
if (($sizenamehash.$($files[$i].length)) -ne $null)
{
if ($sizenamehash.$($files[$i].length).$($files[$i].fullname) -eq $null)
{
$sizenamehash.$($files[$i].length)+=@{$($files[$i].fullname)=$sha512}
}
}
else
{
$sizenamehash+=@{$($files[$i].length)=@{$($files[$i].fullname)=$sha512}}
}
}
if ($breakout -eq $true) {break}
$i++
if ($i -eq ($files.count-1)) {$breakout=$true; continue}
$breakout=(($files[$i].length -ne $files[$i+1].length))
}
}
($sizenamehash.getenumerator()|%{$_.name;$sizenamehash.$($_.name).getenumerator()}|group value|?{$_.count -gt 1})|%{write-host "Duplicates:" -fore green;$_.group.name;$m+=$_.group.name.count}
""
write-host "Number of Files checked: $($files.count)."
write-host "Number of duplicate files: $m."
""
write-host "Time to run: $(([datetime]::now)-$starttime|select hours, minutes, seconds, milliseconds)"
""
|
PowerShellCorpus/PoshCode/Get-MemberBody v2.ps1
|
Get-MemberBody v2.ps1
|
<#
Requires ILSpy
Tested with version 2.1.0.1603
http://ilspy.net/
You'll need to adjust this to your ILSpy path
#>
[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()
}
}
Get-Date | Get-Member AddTicks | Get-MemberBody
|
PowerShellCorpus/PoshCode/Get-MailboxesOverSizeLim_1.ps1
|
Get-MailboxesOverSizeLim_1.ps1
|
# -------------------------------------------------------------------------------
# Script: Get-MailboxesOverSizeLimit.ps1
# Author: Chris Brown
# Date: 04/04/2011 10:41:00
# Keywords:
# comments:
#
# Versioning
# 04/04/2011 CJB Initial Script
#
# -------------------------------------------------------------------------------
# ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠
# ~ ~ ~ Variables ~ ~ ~
# ~~ Mail Server Details ~~
$SmtpServer = "mailserver.yourdomain.local"
$FromAddress = "alerts@yourdomain.com"
$ToAddress = "HelpDesk@yourdomain.com"
$Subject = "[Exchange] Mailboxes over size limits"
#
#
# ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠
if ( (Get-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.E2010 -ErrorAction SilentlyContinue) -eq $null) {
Write-Verbose "Exchange 2010 snapin is not loaded. Loading it now."
try { Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010; Write-Verbose "Loaded Exchange 2010 snapin" }
catch { Write-Error "Could not load Exchange 2010 snapins!"; }
}
$overLimit = Get-Mailbox -ResultSize unlimited| Get-MailboxStatistics -WarningAction SilentlyContinue | Where {"ProhibitSend","MailboxDisabled" -contains $_.StorageLimitStatus}
if ($overLimit.Count -gt 0) {
$mailBody = $overLimit | ft DisplayName,TotalItemSize,StorageLimitStatus | Out-String
Send-MailMessage -Body $mailBody.ToString() -From $FromAddress -SmtpServer $SmtpServer -Subject $Subject -To $toAddress
} else {
"No results"
}
|
PowerShellCorpus/PoshCode/Get-Head.ps1
|
Get-Head.ps1
|
function Get-Head {
#.Synopsis
# Read the first few characters of a file, fast.
param(
# The path to the file (no powershell parsing happens here)
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("Path","PSPath")]
[String]$FilePath,
# The number of characters you want to read
[Parameter(Mandatory=$false)]
[Int]$count=512,
# The encoding (UTF8 or ASCII)
[Parameter(Mandatory=$false)]
[ValidateSet("UTF8","ASCII")]
$encoding = "UTF8"
)
begin {
if($encoding -eq "UTF8") {
$decoder = New-Object System.Text.UTF8Encoding $true
} else {
$decoder = New-Object System.Text.AsciiEncoding
}
$buffer = New-Object Byte[] $count
}
process {
$Stream = [System.IO.File]::Open($FilePath, 'Open', 'Read')
$Null = $Stream.Read($buffer,0,$count)
$decoder.GetString($buffer)
$Stream.Close()
}
}
|
PowerShellCorpus/PoshCode/Array-Randomizer.ps1
|
Array-Randomizer.ps1
|
#======================================================================================
# File Name : Array-Randomizer.ps1
# Original Author : Kenneth C. Mazie (kcmjr at kcmjr.com)
# :
# Description : Originally written to regenerate the init.txt file for server
# : based Halo 1 PC multiplayer games. Each run randomizes the
# : list of maps and then randomizes the list of game types so that
# : a new totally random configuration is used each time the game
# : is restarted. You may edit the arrays to add maps or game
# : types as desired. These changes only take affect when the game
# : is (re)started. The script takes into consideration a 32 or 64
# : bit OS and will adjust folders accordingly.
# :
# Notes : Although the script was intended to shuffle Halo maps it may be
# : easily edited and used to randomize any array or group of
# : arrays.
# :
# Warnings : The init.txt file is completely rewritten when this script is
# : run so save a backup first or edit the script to include your
# : custom settings.
# :
# 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 - 07-12-10 - Original
# Change History : v1.1 - 03-10-11 - Changed name and altered description
# :
#=======================================================================================
Clear-Host
#--[ Function to shuffle an array ]-------------------------------
function Shuffle
{
param([Array] $a)
$rnd=(new-object System.Random)
for($i=0;$i -lt $a.Length;$i+=1){
$newpos=$i + $rnd.Next($a.Length - $i);
$tmp=$a[$i];
$a[$i]=$a[$newpos];
$a[$newpos]=$tmp
}
return $a
}
#--[ Check for, and delete any existing init file ]-----------------
if ($env:PROCESSOR_ARCHITECTURE -eq "AMD64"){$path = "C:\\Program Files (x86)\\Microsoft Games\\Halo\\init.txt"}
else
{$path = "C:\\Program Files\\Microsoft Games\\Halo\\init.txt"}
if(!(Test-Path -Path $path))
{new-item -Path $path –itemtype file}
else
{remove-Item -Path $path}
#--[ Please place any file header items here ]-----------------------
$arrHeader =
"sv_name halo",
"sv_public false",
"sv_maxplayers 16",
"sv_mapcycle_timeout 6",
"sv_password halo"
#--[ Place game types here ]--------------------------------
$arrGameType =
"classic_slayer",
"classic_phantoms",
"classic_elimination",
"classic_juggernaut",
"classic_snipers",
"classic_rockets",
"classic_invasion"
#--[ Place your list of maps here ]--------------------------
$arrMapList =
"sv_mapcycle_add dangercanyon",
"sv_mapcycle_add gephyrophobia",
"sv_mapcycle_add deathisland",
"sv_mapcycle_add bloodgulch",
"sv_mapcycle_add beavercreek",
"sv_mapcycle_add boardingaction",
"sv_mapcycle_add carousel",
"sv_mapcycle_add chillout",
"sv_mapcycle_add damnation",
"sv_mapcycle_add hangemhigh",
"sv_mapcycle_add icefields",
"sv_mapcycle_add longest",
"sv_mapcycle_add infinity",
"sv_mapcycle_add prisoner",
"sv_mapcycle_add putput",
"sv_mapcycle_add ratrace",
"sv_mapcycle_add sidewinder",
"sv_mapcycle_add timberland",
"sv_mapcycle_add wizard"
#--[ Randomize the main array ]-------------------------------
shuffle $arrMapList
#--[ Generate the new init file ]-----------------------------
add-content -path $Path -value $arrHeader
foreach ($Map in $arrMapList ) { Add-content -path $Path -value ($Map + " " + $arrGameType[(get-random -min 0 -max ($arrGameType.length))])}
Add-content -path $Path -value "sv_mapcycle_begin"
#--[ Launch the game ]----------------------------------------
if ($env:PROCESSOR_ARCHITECTURE -eq "AMD64"){(new-object -com shell.application).ShellExecute("C:\\Program Files (x86)\\Microsoft Games\\Halo\\haloded108.exe")}
else
{(new-object -com shell.application).ShellExecute("C:\\Program Files\\Microsoft Games\\Halo\\haloded108.exe")}
|
PowerShellCorpus/PoshCode/get-uuid_allHVs.ps1
|
get-uuid_allHVs.ps1
|
#The PowerShell Talk
#Building a HyperVisor Independent Script
#
#This script will take a VM (or host) object from the pipline,
#and from that determine if you're connected to XenServer
#or VMware, and return the apropriate UUID.
Begin {
#VMware VM Host (ESX) UUID
$VMHost_UUID = @{
Name = "VMHost_UUID"
Expression = { $_.Summary.Hardware.Uuid }
}
#XenServer Host UUID
$XenHost_UUID = @{
Name = "XenHost_UUID"
Expression = { $_.Uuid }
}
}
Process {
#Get the type of object we have
$InputTypeName = $_.GetType().Name
#Do something with that object
#is it VMware?
if ( $InputTypeName -eq "VMHostImpl" ) {
$output = $_ | Get-View | Select-Object $VMHost_UUID
#is it Xen?
} elseif ($InputTypeName -eq "Host"){
$output = $_ | get-view | Select-Object $XenHost_UUID
#Otherwise throw an error
} else {
Write-Host "`nPlease pass this script either a VMHost or VM object on the pipeline.`n"
}
}
|
PowerShellCorpus/PoshCode/Filtering hosts.ps1
|
Filtering hosts.ps1
|
set-psdebug -strict
Function Where-Host
{
<#
.SYNOPSIS
Filter hosts according to hostname resolution, ping reachability or WMI capability
.DESCRIPTION
Filter hostnames by hostname resolution, ping reachbility or WMI capabilities.
Filter can be positive or negative. Positive filter includes hosts that can be reached at least at level X (X can be "DNS", "Ping" or "WMI"). Negative filter includes hosts that cannot be reached at level X (X can be the same as above).
.EXAMPLE
Get a list of hosts from Hosts.txt and keep only those who reply to WMI requests:
Get-Content Hosts.txt | Filter-Host -Can WMI
.INPUTTYPE
String
.PARAMETER Hostname
Name of the host we want to know about its level of reachability
.PARAMETER PingTimeout
When pinging hosts, timeout after what we consider the host is unreachable
.PARAMETER PingCount
When pinging hosts, number of packets sent
.PARAMETER Can
Positive Filter. We keep hosts who DO reply to a certain level of request.
"Can" parameter takes an argument that is the MINIMUM capacity we are looking to know about:
- "DNS": the hostname can at least be resolved by DNS
- "Ping": the host at least replies to ping requests
- "WMI": the host at least replies to a WMI "List" request
Only one argument can be given to "Can" parameter. Give the most elevated you want.
.PARAMETER Cannot
Negative Filter. We keep hosts who DO NOT reply to a certain level of request.
"Cannot" parameter takes an argument that is the MAXIMUM capacity we are looking to know about:
- "DNS": the hostname cannot be resolved by DNS
- "Ping": the host doesn't reply to ping requests
- "WMI": the host doesn't reply to a WMI "List" request
Only one argument can be given to "Can" parameter. Give the less elevated you want.
.PARAMETER Credential
A PSCredential object used if you want to do WMI requests and you're not logged with a power user.
See Get-Credential
.RETURNVALUE
For each object in the pipeline, the cmdlet returns the input object if filter matches, nothing if it doesn't.
.EXAMPLE
Get a list of hosts from Hosts.txt and keep only those who doesn't reply to ping requests:
Get-Content Hosts.txt | Filter-Host -Cannot Ping
.NOTES
Author : Rafael Corvalan - rafael <a-t> corvalan [dot] net
.LINK
http://psh-xrt.blogspot.com
#>
[CmdletBinding(DefaultParameterSetName="PositiveFilter")]
Param(
[String]
[Parameter(ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True, Mandatory=$True)]
[Alias("Host","Name")]
$Hostname,
[Alias("Timeout")]
[Int]$PingTimeout = 200,
[Alias("Count")]
[Int]$PingCount = 2,
[ValidateSet("DNS", "Ping", "WMI")]
[Parameter(ParameterSetName="PositiveFilter")]
[String]
$Can = "Ping",
[ValidateSet("DNS", "Ping", "WMI")]
[Parameter(ParameterSetName="NegativeFilter")]
[String]
$Cannot,
[System.Management.Automation.PSCredential]
[Alias("PSCredential")]
$Credential
)
BEGIN
{
if (-not (Test-Path Variable:\\Can)) {$Can = ''}
if (-not (Test-Path Variable:\\Cannot)) {$Cannot = ''}
}
Process
{
Write-Verbose "+ Processing host $Hostname"
Write-Verbose " - Resolving host $Hostname"
$rh = Resolve-Host $Hostname -ErrorAction SilentlyContinue -ErrorVariable err
if ($err -ne $Null)
{
Write-Verbose('Cannot resolve host {0}. Message [{1}]' -f $Hostname, ($err -join '; '))
if ($Cannot -match '^DNS|Ping|WMI$')
{
return $_
}
return
}
if ($Can -ieq 'DNS') {return $_}
if ($Cannot -ieq 'DNS') {return}
Write-Verbose " - Pinging host $Hostname"
$ping = Ping-Host $Hostname -Quiet -Count $PingCount -Timeout $PingTimeout -ErrorAction SilentlyContinue -ErrorVariable err
if ($err -ne $Null)
{
Write-Verbose('Error pinging host {0}. Message [{1}]' -f $Hostname, ($err -join '; '))
}
elseif ($ping.Loss -eq 100)
{
Write-Verbose('Host {0} is unreachable by ping' -f $Hostname)
}
if ($err -ne $null -or $ping.Loss -eq 100)
{
if ($Cannot -match '^Ping|WMI$') {return $_ }
else {return}
}
if ($Can -ieq 'Ping') {return $_}
if ($Cannot -ieq 'Ping') {return}
Write-Verbose " - WMI test on host $Hostname"
if ($Credential -ne $Null) {
Get-WMIObject -List -ComputerName $Hostname -Credential $Credential -ErrorAction SilentlyContinue -ErrorVariable err > $Null
} else {
Get-WMIObject -List -ComputerName $Hostname -ErrorAction SilentlyContinue -ErrorVariable err > $Null
}
if ($err -ne $Null)
{
Write-Verbose('Error querying WMI on host {0}. Message [{1}]' -f $Hostname, ($err -join '; '))
if ($Cannot -ieq 'WMI') {return $_}
else {return}
}
if ($Can -ieq 'WMI') {return $_}
else {return}
}
}
|
PowerShellCorpus/PoshCode/Get-Codecs.ps1
|
Get-Codecs.ps1
|
[string[]]$key = "SOFTWARE\\Classes\\CLSID\\{083863F1-70DE-11d0-BD40-00A0C911CE86}\\Instance",
"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Drivers32"
function ModuleInfo([string]$path) {
$item.SubItems.Add((gci $path).VersionInfo.CompanyName)
$item.SubItems.Add((gci $path).VersionInfo.FileDescription)
}
function ItemsCount {
$sbCount.Text = $lvPage1.Items.Count.ToString() + " item(s)"
}
$mnuScan_Click= {
#clear both ListView before each scan
$lvPage1.Items.Clear()
$lvPage2.Items.Clear()
<#
Do not use Get-ChildItem cmdlet if you want quick scan!
#>
$reg = [Microsoft.Win32.Registry]::LocalMachine
$rk = $reg.OpenSubKey($key[0])
$rk.GetSubKeyNames() | % {
#adding name of filters
$name = $reg.OpenSubKey($($key[0] + "\\" + $_))
$item = $lvPage1.Items.Add($name.GetValue("FriendlyName"))
$name.Close()
#adding its CLSID
$item.SubItems.Add($_)
#adding path and additional info of filters
$path = $reg.OpenSubKey($("SOFTWARE\\Classes\\CLSID\\" + "\\" + $_ + "\\InprocServer32"))
$item.SubItems.Add($path.GetValue(""))
ModuleInfo($path.GetValue(""))
$path.Close()
}
$rk.Close()
$rk = $reg.OpenSubKey($key[1])
$rk.GetValueNames() | % {
$item = $lvPage2.Items.Add($_)
#hypothetical directory
$file = $rk.GetValue($_)
if (-not (Test-Path $file)) {
#another possible directory of driver
$pos = [Environment]::SystemDirectory + "\\" + $file
if (Test-Path $pos) {
$item.SubItems.Add($pos)
ModuleInfo($pos)
}
}
else {
$item.SubItems.Add($file)
ModuleInfo($file)
}
}
$rk.Close()
ItemsCount
}
$tcPage2_Enter= {
$sbCount.Text = $lvPage2.Items.Count.ToString() + " item(s)"
}
#this is about form load function
$frmMain_Load= {
try {
$icon = [Drawing.Icon]::ExtractAssociatedIcon($($pshome + "\\powershell.exe"))
$pbImage.Image = $icon.ToBitmap()
}
catch {}
}
function frmMain_Show {
Add-Type -AssemblyName System.Windows.Forms
[Windows.Forms.Application]::EnableVisualStyles()
$frmMain = New-Object Windows.Forms.Form
$mnuMain = New-Object Windows.Forms.MainMenu
$mnuFile = New-Object Windows.Forms.MenuItem
$mnuScan = New-Object Windows.Forms.MenuItem
$mnuExit = New-Object Windows.Forms.MenuItem
$mnuHelp = New-Object Windows.Forms.MenuItem
$mnuInfo = New-Object Windows.Forms.MenuItem
$tabCtrl = New-Object Windows.Forms.TabControl
$tcPage1 = New-Object Windows.Forms.TabPage
$lvPage1 = New-Object Windows.Forms.ListView
$chFName = New-Object Windows.Forms.ColumnHeader
$chCLSID = New-Object Windows.Forms.ColumnHeader
$chFPath = New-Object Windows.Forms.ColumnHeader
$chFPubl = New-Object Windows.Forms.ColumnHeader
$chFDesc = New-Object Windows.Forms.ColumnHeader
$tcPage2 = New-Object Windows.Forms.TabPage
$lvPage2 = New-Object Windows.Forms.ListView
$chDName = New-Object Windows.Forms.ColumnHeader
$chDPath = New-Object Windows.Forms.ColumnHeader
$chDPubl = New-Object Windows.Forms.ColumnHeader
$chDDesc = New-Object Windows.Forms.ColumnHeader
$sbCount = New-Object Windows.Forms.StatusBar
#
#mnuMain
#
$mnuMain.MenuItems.AddRange(@($mnuFile, $mnuHelp))
#
#mnuFile
#
$mnuFile.MenuItems.AddRange(@($mnuScan, $mnuExit))
$mnuFile.Text = "&File"
#
#mnuScan
#
$mnuScan.Shortcut = "F5"
$mnuScan.Text = "&Scan"
$mnuScan.Add_Click($mnuScan_Click)
#
#mnuExit
#
$mnuExit.Shortcut = "CtrlX"
$mnuExit.Text = "E&xit"
$mnuExit.Add_Click({$frmMain.Close()})
#
#mnuHelp
#
$mnuHelp.MenuItems.AddRange(@($mnuInfo))
$mnuHelp.Text = "&Help"
#
#mnuInfo
#
$mnuInfo.Text = "About"
$mnuInfo.Add_Click({frmAbout_Show})
#
#tabCtrl
#
$tabCtrl.Controls.AddRange(@($tcPage1, $tcPage2))
$tabCtrl.Dock = "Fill"
#
#tcPage1
#
$tcPage1.Controls.AddRange(@($lvPage1))
$tcPage1.Text = "DirectShow"
$tcPage1.UseVisualStyleBackColor = $true
$tcPage1.Add_Enter($tcPage1_Enter)
#
#lvPage1
#
$lvPage1.AllowColumnReorder = $true
$lvPage1.Columns.AddRange(@($chFName, $chCLSID, $chFPath, $chFPubl, $chFDesc))
$lvPage1.Dock = "Fill"
$lvPage1.FullRowSelect = $true
$lvPage1.GridLines = $false
$lvPage1.MultiSelect = $false
$lvPage1.ShowItemToolTips = $true
$lvPage1.Sorting = "Ascending"
$lvPage1.View = "Details"
#
#chFName
#
$chFName.Text = "Name"
$chFName.Width = 110
#
#chCLSID
#
$chCLSID.Text = "CLSID"
$chCLSID.Width = 241
#
#chFPath
#
$chFPath.Text = "Path"
$chFPath.Width = 215
#
#chFPubl
#
$chFPubl.Text = "Publisher"
$chFPubl.Width = 145
#
#chFDesc
#
$chFDesc.Text = "Description"
$chFDesc.Width = 300
#
#tcPage2
#
$tcPage2.Controls.AddRange(@($lvPage2))
$tcPage2.Text = "Drivers"
$tcPage2.UseVisualStyleBackColor = $true
$tcPage2.Add_Enter($tcPage2_Enter)
#
#lvPage2
#
$lvPage2.AllowColumnReorder = $true
$lvPage2.Columns.AddRange(@($chDName, $chDPath, $chDPubl, $chDDesc))
$lvPage2.Dock = "Fill"
$lvPage2.FullRowSelect = $true
$lvPage2.GridLines = $false
$lvPage2.MultiSelect = $false
$lvPage2.ShowItemToolTips = $true
$lvPage2.Sorting = "Ascending"
$lvPage2.View = "Details"
#
#chDName
#
$chDName.Text = "Name"
$chDName.Width = 100
#
#chDPath
#
$chDPath.Text = "Path"
$chDPath.Width = 210
#
#chDPubl
#
$chDPubl.Text = "Publisher"
$chDPubl.Width = 145
#
#chDDesc
#
$chDDesc.Text = "Description"
$chDDesc.Width = 300
#
#sbCount
#
$sbCount.SizingGrip = $false
#
#frmMain
#
$frmMain.ClientSize = New-Object Drawing.Size(573, 217)
$frmMain.Controls.AddRange(@($tabCtrl, $sbCount))
$frmMain.Menu = $mnuMain
$frmMain.StartPosition = "CenterScreen"
$frmMain.Text = "Codecs"
[void]$frmMain.ShowDialog()
}
function frmAbout_Show {
$frmMain = New-Object Windows.Forms.Form
$pbImage = New-Object Windows.Forms.PictureBox
$lblName = New-Object Windows.Forms.Label
$lblCopy = New-Object Windows.Forms.Label
$btnExit = New-Object Windows.Forms.Button
#
#pbImage
#
$pbImage.Location = New-Object Drawing.Point(16, 16)
$pbImage.Size = New-Object Drawing.Size(32, 32)
$pbImage.SizeMode = "StretchImage"
#
#lblName
#
$lblName.Font = New-Object Drawing.Font("Microsoft Sans Serif", 9, [Drawing.FontStyle]::Bold)
$lblName.Location = New-Object Drawing.Size(53, 19)
$lblName.Size = New-Object Drawing.Size(360, 18)
$lblName.Text = "Codecs v1.00"
#
#lblCopy
#
$lblCopy.Location = New-Object Drawing.Point(67, 37)
$lblCopy.Size = New-Object Drawing.Size(360, 23)
$lblCopy.Text = "(C) 2012 Greg Zakharov gregzakh@gmail.com"
#
#btnExit
#
$btnExit.Location = New-Object Drawing.Point(135, 67)
$btnExit.Text = "OK"
#
#frmMain
#
$frmMain.AcceptButton = $btnExit
$frmMain.CancelButton = $btnExit
$frmMain.ClientSize = New-Object Drawing.Size(350, 110)
$frmMain.ControlBox = $false
$frmMain.Controls.AddRange(@($pbImage, $lblName, $lblCopy, $btnExit))
$frmMain.FormBorderStyle = "FixedSingle"
$frmMain.ShowInTaskbar = $false
$frmMain.StartPosition = "CenterScreen"
$frmMain.Text = "About..."
$frmMain.Add_Load($frmMain_Load)
[void]$frmMain.ShowDialog()
}
frmMain_Show
|
PowerShellCorpus/PoshCode/Connect-VMHost_1.ps1
|
Connect-VMHost_1.ps1
|
#requires -version 2
#requires -pssnapin VMware.VimAutomation.Core
Function Connect-VMHost {
<#
.Summary
Used to Connect a disconnected host to vCenter.
.Parameter VMHost
VMHost to reconnect to virtual center
.Example
Get-VMHost | Where-Object {$_.state -eq "Disconnected"} | Connect-VMHost
Will Attempt to reconnect any host that are currently disconnected.
.Example
Connect-VMHost -Name ESX1.get-admin.local
Will reconnect ESX1 to vCenter
#>
[CmdletBinding(
SupportsShouldProcess=$True,
SupportsTransactions=$False,
ConfirmImpact="low",
DefaultParameterSetName="ByString"
)]
Param(
[Parameter(
Mandatory=$True,
Valuefrompipeline=$true,
ParameterSetName="ByObj"
)]
[VMware.VimAutomation.Client20.VMHostImpl[]]
$VMHost,
[Parameter(
Mandatory=$True,
Position=0,
ParameterSetName="ByString"
)]
[string[]]
$Name
)
Begin {
IF ($Name) {
$VMHost = $Name|%{ Get-VMHost -Name $_ }
}
}
process {
Foreach ($VMHostImpl in ($VMHost|Get-View)) {
$ReconnectSpec = New-Object VMware.Vim.HostConnectSpec
$ReconnectSpec.HostName = $VMHostImpl.Summary.Config.Name
$ReconnectSpec.Port = $VMHostImpl.Summary.Config.Port
$ReconnectSpec.Force = $true
if ($pscmdlet.ShouldProcess($VMHostImpl.name)) {
$VMHostImpl.ReconnectHost_Task($ReconnectSpec)
}
}
}
}
|
PowerShellCorpus/PoshCode/ffdb7026-570c-4644-8a9f-b2c8fcdabfd5.ps1
|
ffdb7026-570c-4644-8a9f-b2c8fcdabfd5.ps1
|
# Code to auto update the Address policy, GAL, OAB and storage groups and mailbox databases of an Exchange 2007 server by John McLear
# This code is good for hosting providers or people who wish to use lots of storage groups and mailbox databases.
#
# Thanks to Joel Bennett (Jaykul) for general scripting help and the friendly folks in #powershell - freenode
#
# I rewrote this and didnt test before publishing so there may be some syntax errors.
#
# Created 07/09/2008
#################################################################################################################################
param([string]$fullname, [string]$mail2, [string]$typeofcustomer)
# PRE REQ - Create a container in your address lists called "Generic Address Book" or something similar - this is where we will store address lists!
# - Create a public folder database on your MB server - In $publicfolderDatabase our example is in storage group sg0 called Public Folder.
# We need to set some things manually too!
$yourinternaldomain = "domain.com" # ie contoso.com
$OABDistributionServer = "CASserver" # Your CAS server responsible for OAB distribution
$MailboxServer = "MBserver" # Shortname of your MailboxServer
$PublicFolderDatabase = $MailboxServer + '\\sg0\\Public Folder' # The Path to your public folder used for Address List distribution
$LogFilePath = "d:\\Program Files\\Microsoft\\Exchange Server\\Mailbox\\First Storage Group\\" # Where we will put the log files
$AdminName = "CN=Servers,CN=Exchange Administrative Group (TESTING23TESTY),CN=Administrative Groups,CN=Contoso,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=contoso,DC=com" # This needs to be changed
echo "Fullname: $fullname" # full name of customer - this must be a unique value)
echo "Domain name: $mail2" # customers domain name ie fraggle.com
echo "Type of customer (1 is basic, 2 is standard, 3 is premium): $typeofcustomer" # Basically a premium customer will get their own mailboxdatabase - a basic or standard will share in one big database (know why before you use this!)
echo "Your internal domain: $yourinternaldomain" # The internal domain you set
# Lets go!
######################
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin
# Loads exchange snap ins
new-AcceptedDomain -Name $mail2 -DomainName $mail2 -DomainType 'Authoritative'
# Creates an accepted domain
new-EmailAddressPolicy -Name $fullname -IncludedRecipients 'AllRecipients' -ConditionalCompany $fullname -Priority 'Lowest' -EnabledEmailAddressTemplates SMTP:%m@$mail2,smtp:%g@$mail2,smtp:%1g.%s@$mail2,smtp:%m@$yourinternaldomain
# Creates a new address policy giving - you may wish to modify this to suit
set-EmailAddressPolicy -Identity $fullname -IncludedRecipients 'AllRecipients' -ConditionalCompany $fullname -Priority 'Lowest' -EnabledEmailAddressTemplates SMTP:%m@$mail2,smtp:%g@$mail2,smtp:%1g.%s@$mail2,smtp:%m@$yourinternaldomain
# Modifies the new address policy giving - you may wish to modify this to suit - Why modify? You may wish to update this at some point and its best practice to have a set command imho
new-GlobalAddressList -Name $fullname -IncludedRecipients 'AllRecipients' -ConditionalCompany $fullname
# Create a new GAL
new-AddressList -Name $fullname -IncludedRecipients 'AllRecipients' -ConditionalCompany $fullname -Container '\\Generic Address Book'
# Create a new address list in the Generic Address Book container - Modify your container to suit!
$fullname2 = '\\Generic Address book\\' + $fullname
# You may wish to modify the above to suit
$OABPoint = $OABdistributionServer + '\\OAB (Default Web Site)'
# You may wish to modify the above line to suit but I doubt it.
new-OfflineAddressBook -Name $fullname -Server $pinkyring -AddressLists $fullname2 -PublicFolderDistributionEnabled $false -VirtualDirectories $OABPoint
# Create a new Offline Address Book
Set-OfflineAddressBook -Identity $fullname -versions Version3, Version4 -PublicFolderDistributionEnabled $true -AddressLists $fullname2
# Set the OAB to V3, 4 and Public folder distribution.
Update-EmailAddressPolicy -Identity $fullname
# Update the Email Address Policy
Set-MailboxDatabase -Identity $fullname -OfflineAddressBook $fullname -PublicFolderDatabase $PublicFolderDatabase
# Set the Mailbox database of the customer to use the public folder database you created
$maildb = Get-MailboxDataBase | Select-String $fullname
echo $maildb
if ($maildb -match "sg")
# if there is a database for the fullname value then
{
echo "not making the DB"
}
else
{
if ($typeofcustomer -match "3")
# and if the type of customer is 3 (premium)
{
echo "making the DB" # this customer must be premium! good for them!!
$i = 1
for( $i=0; $i -lt 50; $i++ )
# for each count 1 to 50
{
$maildb = Get-MailboxDataBase | Select-String $fullname
echo $maildb
if ($maildb -match "sg")
# Check for a database
{ echo "database located" } # if database is found then do nothing
else
{
new-storagegroup sg$i
# creating 50 storage groups
new-mailboxdatabase -StorageGroup $MailboxServer\\sg$i -Name $fullname -EdbFilePath $LogFilePath + '\\' + $fullname.edb
# make a database on the server - we need to add incrementation on servername here..
mount-database -Identity "CN=$fullname,CN=sg$i,CN=InformationStore,CN=$MailboxServer,$AdminName"
# mount the database
$i++
# increase the storage group by 1
}
}
Set-MailboxDatabase -Identity $fullname -PublicFolderDatabase $PublicFolderDatabase
# set the public folder
}
else
{
echo "customer is a basic or standard customer so we are going to not create a DB"
Set-MailboxDatabase -Identity $fullname -OfflineAddressBook $fullname -PublicFolderDatabase $PublicFolderDatabase
}
}
|
PowerShellCorpus/PoshCode/Set-Wallpaper (CTP3)_2.ps1
|
Set-Wallpaper (CTP3)_2.ps1
|
#requires -version 2.0
## Set-Wallpaper - set your windows desktop wallpaper
###################################################################################################
## Usage:
## Set-Wallpaper "C:\\Users\\Joel\\Pictures\\Wallpaper\\Dual Monitor\\mandolux-tiger.jpg" "Tile"
## ls *.jpg | get-random | Set-Wallpaper
## ls *.jpg | get-random | Set-Wallpaper -Style "Stretch"
###################################################################################################
## History:
## v0.5 First release (on #PowerShell@irc.freenode.net)
## v1.0 Public release (http://www.poshcode.org/488)
## - Added Style: Tile|Center|Stretch
## v1.1 (http://poshcode.org/491)
## - Added "NoChange" style to just use the style setting already set
## - Made the Style parameter to the cmdlet optional
## v2.0 This Release
## - Updated for CTP3, and made it run as a script instead of a function.
###################################################################################################
[CmdletBinding()]
Param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[string]
$Path
,
[Parameter(Position=1, Mandatory=$false)]
$Style = "NoChange"
)
BEGIN {
try {
$WP = [Wallpaper.Setter]
} catch {
$WP = add-type @"
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace Wallpaper
{
public enum Style : int
{
Tile, Center, Stretch, NoChange
}
public class Setter {
public const int SetDesktopWallpaper = 20;
public const int UpdateIniFile = 0x01;
public const int SendWinIniChange = 0x02;
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int SystemParametersInfo (int uAction, int uParam, string lpvParam, int fuWinIni);
public static void SetWallpaper ( string path, Wallpaper.Style style ) {
SystemParametersInfo( SetDesktopWallpaper, 0, path, UpdateIniFile | SendWinIniChange );
RegistryKey key = Registry.CurrentUser.OpenSubKey("Control Panel\\\\Desktop", true);
switch( style )
{
case Style.Stretch :
key.SetValue(@"WallpaperStyle", "2") ;
key.SetValue(@"TileWallpaper", "0") ;
break;
case Style.Center :
key.SetValue(@"WallpaperStyle", "1") ;
key.SetValue(@"TileWallpaper", "0") ;
break;
case Style.Tile :
key.SetValue(@"WallpaperStyle", "1") ;
key.SetValue(@"TileWallpaper", "1") ;
break;
case Style.NoChange :
break;
}
key.Close();
}
}
}
"@ -Passthru
}
}
PROCESS {
Write-Verbose "Setting Wallpaper ($Style) to $(Convert-Path $Path)"
$WP::SetWallpaper( (Convert-Path $Path), $Style )
}
|
PowerShellCorpus/PoshCode/ConvertFrom-Hashtable.ps1
|
ConvertFrom-Hashtable.ps1
|
# function ConvertFrom-Hashtable {
PARAM([[HashTable]$hashtable,[switch]$combine)
BEGIN { $output = New-Object PSObject }
PROCESS {
if($_) {
$hashtable = $_;
if(!$combine) {
$output = New-Object PSObject
}
}
$hashtable.GetEnumerator() |
ForEach-Object { Add-Member -inputObject $object `
-memberType NoteProperty -name $_.Name -value $_.Value }
$object
}
#}
|
PowerShellCorpus/PoshCode/Convert-BounceToX_5.ps1
|
Convert-BounceToX_5.ps1
|
# $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $
# $Revision: 610 $
#.Synopsis
# Convert Bounce to X500
#.Description
# Convert URL Encoded address in a Bounce message to an X500 address
# that can be added as an alias to the mail-enabled object
#.Parameter bounceAddress
# URL Encoded bounce message address#
#.Example
# Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"
#.Example
# "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500
[CmdletBinding()]
PARAM (
[Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress
)
BEGIN
{
Add-Type -AssemblyName System.Web|Out-Null
}
PROCESS
{
if($_) {$bounceAddress = $_}
$bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+"
$bounceAddress = $bounceAddress -Replace "%3D","="
$bounceAddress = $bounceAddress -Replace "\\+","%"
$bounceAddress = $bounceAddress -Replace "_O=","/O="
$bounceAddress = $bounceAddress -Replace "_OU=","/OU="
$bounceAddress = $bounceAddress -Replace "_CN=","/CN="
if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]}
}
|
PowerShellCorpus/PoshCode/O-ChristmasTree.ps1
|
O-ChristmasTree.ps1
|
ipmo PowerBoots
## Merry Christmas
boots {
$global:lights = @()
grid {
# A trunk
rectangle -width 20 -height 40 -fill brown -HorizontalAlignment Center -VerticalAlignment Bottom
# A perfect, triangular, tree
polygon -points { "87.5,0","0,150","175,150","87.5,0" } -margin "0,25,0,40" -fill darkgreen
# Christmas lights
1..60 | % { ellipse -width 2 -height 3 -fill red -HorizontalAlignment Center -VerticalAlignment Top -margin { $y = get-random -min 5 -max 140; $x = get-random -min 5 -max $($y * .75 + 5); if(Get-Random 1,0){ "{0},{1},0,0" -f $x,($y+30) } else { "0,{1},{0},0" -f $x,($y+30) } } -ov +global:lights }
# A Star topper
polygon -points { "15,0","25,30","0,10","30,10","5,30","15,0" } -fill white -HorizontalAlignment Center -VerticalAlignment Top -ov +global:lights
}
} -on_sourceinitialized {
# make all the lights blink!
$lights | % { $_.BeginAnimation( [System.Windows.Shapes.Shape]::OpacityProperty,
$(DoubleAnimation -From "1.0" -To $(Get-Random -Min 0.1 -Max 0.5) -Duration $("0:0:0.{0}" -f (Get-Random -Min 5 -Max 99)) -AutoReverse -RepeatBehavior ([system.windows.media.animation.RepeatBehavior]::Forever))) }
# Make the whole window draggable
} -on_mouseleftbuttondown {
$this.DragMove()
# Make the window (chromeless and) invisible except for the tree part....
} -windowstyle none -allowstransparency -background transparent -Topmost
## Happy New Year
boots {
$global:lights = @()
canvas {
# A light pole
rectangle -width 5 -height 500 -fill Gray -HorizontalAlignment Center -VerticalAlignment Bottom -"Canvas.Left" 82.5
# A Mirror ball ;)
ellipse -Width 50 -Height 50 -HorizontalAlignment Center -VerticalAlignment Top -Fill White -OV +global:lights -"Canvas.Left" 60
# Some rays of flickering light, for effect
polygon -HorizontalAlignment Center -VerticalAlignment Top -points "0,0", "75,10", "80,14",
"0,0", "-80,-10", "-75,-14",
"0,0", "60,40", "65,42",
"0,0", "-50,-30", "-57,-32",
"0,0", "75,-10", "85,-16",
"0,0", "-60,40", "-65,42" -fill LightYellow -margin "85,25,0,0" -Opacity 0.3 -OV +global:lights
} -width 170 -height 500
} -on_mouseleftbuttondown {
$this.DragMove()
} -on_sourceinitialized {
$lights | % {
$_.BeginAnimation( [System.Windows.Controls.Canvas]::TopProperty, $(DoubleAnimation -From 50 -To 550 -Duration '0:0:10') )
}
@($lights)[-1].BeginAnimation( [System.Windows.Shapes.Shape]::OpacityProperty,
$(DoubleAnimation -From "0.3" -To "0.0" -Duration "0:0:1" -AutoReverse -RepeatBehavior ([system.windows.media.animation.RepeatBehavior]::Forever)))
} -windowstyle none -allowstransparency -background transparent
|
PowerShellCorpus/PoshCode/Send-HTMLFormattedEmail_7.ps1
|
Send-HTMLFormattedEmail_7.ps1
|
##################################################
# cmdlets
##################################################
#-------------------------------------------------
# Send-HTMLFormattedEmail
#-------------------------------------------------
# Usage: Send-HTMLFormattedEmail -?
#-------------------------------------------------
function Send-HTMLFormattedEmail {
<#
.Synopsis
Used to send an HTML Formatted Email.
.Description
Used to send an HTML Formatted Email that is based on an XSLT template.
.Parameter To
Email address or addresses for whom the message is being sent to.
Addresses should be seperated using ;.
.Parameter ToDisName
Display name for whom the message is being sent to.
.Parameter CC
Email address if you want CC a recipient.
Addresses should be seperated using ;.
.Parameter BCC
Email address if you want BCC a recipient.
Addresses should be seperated using ;.
.Parameter From
Email address for whom the message comes from.
.Parameter FromDisName
Display name for whom the message comes from.
.Parameter Subject
The subject of the email address.
.Parameter Content
The content of the message (to be inserted into the XSL Template).
.Parameter Relay
FQDN or IP of the SMTP relay to send the message to.
.XSLPath
The full path to the XSL template that is to be used.
#>
param(
[Parameter(Mandatory=$True)][String]$To,
[Parameter(Mandatory=$True)][String]$ToDisName,
[String]$CC,
[String]$BCC,
[Parameter(Mandatory=$True)][String]$From,
[Parameter(Mandatory=$True)][String]$FromDisName,
[Parameter(Mandatory=$True)][String]$Subject,
[Parameter(Mandatory=$True)][String]$Content,
[Parameter(Mandatory=$True)][String]$Relay,
[Parameter(Mandatory=$True)][String]$XSLPath
)
try {
# Load XSL Argument List
$XSLArg = New-Object System.Xml.Xsl.XsltArgumentList
$XSLArg.Clear()
$XSLArg.AddParam("To", $Null, $ToDisName)
$XSLArg.AddParam("Content", $Null, $Content)
# Load Documents
$BaseXMLDoc = New-Object System.Xml.XmlDocument
$BaseXMLDoc.LoadXml("<root/>")
$XSLTrans = New-Object System.Xml.Xsl.XslCompiledTransform
$XSLTrans.Load($XSLPath)
#Perform XSL Transform
$FinalXMLDoc = New-Object System.Xml.XmlDocument
$MemStream = New-Object System.IO.MemoryStream
$XMLWriter = [System.Xml.XmlWriter]::Create($MemStream)
$XSLTrans.Transform($BaseXMLDoc, $XSLArg, $XMLWriter)
$XMLWriter.Flush()
$MemStream.Position = 0
# Load the results
$FinalXMLDoc.Load($MemStream)
$Body = $FinalXMLDoc.Get_OuterXML()
# Create Message Object
$Message = New-Object System.Net.Mail.MailMessage
# Now Populate the Message Object.
$Message.Subject = $Subject
$Message.Body = $Body
$Message.IsBodyHTML = $True
# Add From
$MessFrom = New-Object System.Net.Mail.MailAddress $From, $FromDisName
$Message.From = $MessFrom
# Add To
$To = $To.Split(";") # Make an array of addresses.
$To | foreach {$Message.To.Add((New-Object System.Net.Mail.Mailaddress $_.Trim()))} # Add them to the message object.
# Add CC
if ($CC){
$CC = $CC.Split(";") # Make an array of addresses.
$CC | foreach {$Message.CC.Add((New-Object System.Net.Mail.Mailaddress $_.Trim()))} # Add them to the message object.
}
# Add BCC
if ($BCC){
$BCC = $BCC.Split(";") # Make an array of addresses.
$BCC | foreach {$Message.BCC.Add((New-Object System.Net.Mail.Mailaddress $_.Trim()))} # Add them to the message object.
}
# Create SMTP Client
$Client = New-Object System.Net.Mail.SmtpClient $Relay
# Send The Message
$Client.Send($Message)
}
catch {
throw $_
}
}
##################################################
# Main
##################################################
Export-ModuleMember Send-HTMLFormattedEmail
### XSLT Template Example
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output media-type="xml" omit-xml-declaration="yes" />
<xsl:param name="To"/>
<xsl:param name="Content"/>
<xsl:template match="/">
<html>
<head>
<title>My First Formatted Email</title>
</head>
<body>
<div width="400px">
<p>Dear <xsl:value-of select="$To" />,</p>
<p></p>
<p><xsl:value-of select="$Content" /></p>
<p></p>
<p><strong>Please do not respond to this email!</strong><br />
An automated system sent this email, if any point you have any questions or concerns please open a help desk ticket.</p>
<p></p>
<Address>
Many thanks from your:<br />
Really Cool IT Team<br />
</Address>
</div>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
|
PowerShellCorpus/PoshCode/Start-ComputerJobs_1.ps1
|
Start-ComputerJobs_1.ps1
|
#requires -version 2.0
function Start-ComputerJobs{
<#
.NOTES
Name: Start-ComputerJobs
Author: Tome Tanasovski
Created: 6/25/2010
Modified: 6/25/2010
Version: 1.1
Website: http://powertoe.wordpress.com
.SYNOPSIS
Multithreads a scriptblock with jobs
.DESCRIPTION
The Start-ComputerJobs cmdlet runs a specified scriptblock within a maximum number of simultaneously spawned Powershell jobs.
You must pass a list of ComputerNames to it. The names passed to the cmdlet will replace $computername within the scriptblock prior to starting each thread.
This can be thought of as a multithreaded approach to a foreach loop.
.PARAMETER ComputerName
Specifies a list of computers that you wish to inject into your scriptblock. The list of computer names will replace $computername in the script block. This does not actually need to be a list of computer names. It can be anything you wish to inject into your scriptblock.
.PARAMETER ScriptBlock
Specifies the commands to run in the background jobs. Enclose the commands in braces ({}) or use $ExecutionContext.InvokeCommand.NewScriptBlock to create a scriptblock.
The scriptblock must contain a $computername variable. $computername will be replaced by each entry into the pipeline or from the parameter ComputerName.
.PARAMETER Threads
Specifies the maximum number of jobs that can be simultaneously running at any given time.
This defaults to 10 if nothing is specified.
.EXAMPLE
"computer1","computer2","computer3","computer4","computer5" |Start-ComputerJobs -ScriptBlock {dir \\\\$computername\\c$}
.INPUTS
System.String
.OUTPUTS
PSObject
Returns the results of the commands in the job. It is the data returned from receive-job. If you're scriptblock contains write-host it will write that to the console as it is running. To avoid this you should just return objects within your scriptblock. i.e. Instead of write-host "text" just use "text"
#>
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string[]]$ComputerName,
[Parameter(Mandatory=$true)]
[ScriptBlock]$ScriptBlock,
[Parameter(Mandatory=$false)]
[ValidateScript({$_ -gt 0})]
[int32]$Threads = 10,
[Parameter(Mandatory=$false)]
[ValidateScript({$_ -gt 0})]
[int32]$Sleep = 5
)
BEGIN {
$firstrun = $true
$computers = @()
$curthreads = 0
$jobs = @()
$valid = $false
}
PROCESS {
if ($firstrun) {
$firstrun = $false
# Validate scriptblock - Making sure it has a $computername variable to use
if ($ScriptBlock -match '\\$computername') {
$valid = $true
} else {
Write-Error 'You must specify a scriptblock that contains a variable called $computername'
$valid = $false
}
}
if ($valid) {
foreach ($computer in $computername) {
while ($jobs.count -eq $Threads) {
$newjobs = @()
$jobs |foreach {
Receive-Job $_.id
if ($_.state -eq "Running" -or $_.HasMoreData) {
$newjobs += $_
}
else {
$_ |Remove-Job
}
}
$jobs = $newjobs
if ($jobs.count -eq $Threads) {
sleep $sleep
}
}
$runscript = $ExecutionContext.InvokeCommand.NewScriptBlock(($ScriptBlock -replace '\\$computername', "$computer"))
Write-Verbose "Starting Job for computer: $computer"
$jobs += Start-Job -ScriptBlock $runscript
$curthreads++
}
}
}
END {
while ($jobs.count -ne 0) {
$newjobs = @()
$jobs |foreach {
Receive-Job $_.id
if ($_.state -eq "Running" -or $_.HasMoreData) {
$newjobs += $_
}
else {
$_ |Remove-Job
}
}
$jobs = $newjobs
if ($jobs.count -gt 0) {
sleep $sleep
}
}
}
}
|
PowerShellCorpus/PoshCode/Custom Accelerators_1.ps1
|
Custom Accelerators_1.ps1
|
#requires -version 2.0
## Custom Accelerators for PowerShell 2
####################################################################################################
## A script module for PowerShell 2 which allows the user to create their own custom type accelerators.
## Thanks to "Oisin Grehan for the discovery":http://www.nivot.org/2008/12/25/ListOfTypeAcceleratorsForPowerShellCTP3.aspx.
####################################################################################################
## Revision History
## v1.0 - Modularization of Oisin's idea, by Joel 'Jaykul' Bennett
## v2.0 - Update for RTM (nothing significant)
## v2.1 - Minor tweaks to make it more pipelineable (I'm including this in my Reflection module)
####################################################################################################
# get a reference to the Type
$xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators")
function Add-Accelerator {
<#
.Synopsis
Add a type accelerator to the current session
.Description
The Add-Accelerator function allows you to add a simple type accelerator (like [regex]) for a longer type (like [System.Text.RegularExpressions.Regex]).
.Example
Add-Accelerator list System.Collections.Generic.List``1
$list = New-Object list[string]
Creates an accelerator for the generic List[T] collection type, and then creates a list of strings.
.Example
Add-Accelerator "List T", GList System.Collections.Generic.List``1
$list = New-Object "list t[string]"
Creates two accelerators for the Generic List[T] collection type.
.Parameter Accelerator
The short form accelerator should be just the name you want to use (without square brackets).
.Parameter Type
The type you want the accelerator to accelerate (without square brackets)
.Notes
When specifying multiple values for a parameter, use commas to separate the values.
For example, "-Accelerator string, regex".
PowerShell requires arguments that are "types" to NOT have the square bracket type notation, because of the way the parsing engine works. You can either just type in the type as System.Int64, or you can put parentheses around it to help the parser out: ([System.Int64])
Also see the help for Get-Accelerator and Remove-Accelerator
.Link
http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/
#>
[CmdletBinding()]
PARAM(
[Parameter(Position=0,ValueFromPipelineByPropertyName=$true)]
[Alias("Key","Name")]
[string[]]$Accelerator
,
[Parameter(Position=1,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[Alias("Value","FullName")]
[type]$Type
)
PROCESS {
# add a user-defined accelerator
foreach($a in $Accelerator) {
$xlr8r::Add( $a, $Type)
trap [System.Management.Automation.MethodInvocationException] {
if($xlr8r::get.keys -contains $a) {
Write-Error "Cannot add accelerator [$a] for [$($Type.FullName)]`n [$a] is already defined as [$($xlr8r::get[$a].FullName)]"
Continue;
}
throw
}
}
}
}
function Get-Accelerator {
<#
.Synopsis
Get one or more type accelerator definitions
.Description
The Get-Accelerator function allows you to look up the type accelerators (like [regex]) defined on your system by their short form or by type
.Example
Get-Accelerator System.String
Returns the KeyValue pair for the [System.String] accelerator(s)
.Example
Get-Accelerator ps*,wmi*
Returns the KeyValue pairs for the matching accelerator definition(s)
.Parameter Accelerator
One or more short form accelerators to search for (Accept wildcard characters).
.Parameter Type
One or more types to search for.
.Notes
When specifying multiple values for a parameter, use commas to separate the values.
For example, "-Accelerator string, regex".
Also see the help for Add-Accelerator and Remove-Accelerator
.Link
http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/
#>
[CmdletBinding(DefaultParameterSetName="ByType")]
PARAM(
[Parameter(Position=0, ParameterSetName="ByAccelerator", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("Key","Name")]
[string[]]$Accelerator
,
[Parameter(Position=0, ParameterSetName="ByType", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("Value","FullName")]
[type[]]$Type
)
PROCESS {
# add a user-defined accelerator
switch($PSCmdlet.ParameterSetName) {
"ByAccelerator" {
$xlr8r::get.GetEnumerator() | % {
foreach($a in $Accelerator) {
if($_.Key -like $a) { $_ }
}
}
break
}
"ByType" {
if($Type -and $Type.Count) {
$xlr8r::get.GetEnumerator() | ? { $Type -contains $_.Value }
}
else {
$xlr8r::get.GetEnumerator() | %{ $_ }
}
break
}
}
}
}
function Remove-Accelerator {
<#
.Synopsis
Remove a type accelerator from the current session
.Description
The Remove-Accelerator function allows you to remove a simple type accelerator (like [regex]) from the current session. You can pass one or more accelerators, and even wildcards, but you should be aware that you can remove even the built-in accelerators.
.Example
Remove-Accelerator int
Add-Accelerator int Int64
Removes the "int" accelerator for Int32 and adds a new one for Int64. I can't recommend doing this, but it's pretty cool that it works:
So now, "$(([int]3.4).GetType().FullName)" would return "System.Int64"
.Example
Get-Accelerator System.Single | Remove-Accelerator
Removes both of the default accelerators for System.Single: [float] and [single]
.Example
Get-Accelerator System.Single | Remove-Accelerator -WhatIf
Demonstrates that Remove-Accelerator supports -Confirm and -Whatif. Will Print:
What if: Removes the alias [float] for type [System.Single]
What if: Removes the alias [single] for type [System.Single]
.Parameter Accelerator
The short form accelerator that you want to remove (Accept wildcard characters).
.Notes
When specifying multiple values for a parameter, use commas to separate the values.
For example, "-Accel string, regex".
Also see the help for Add-Accelerator and Get-Accelerator
.Link
http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/
#>
[CmdletBinding(SupportsShouldProcess=$true)]
PARAM(
[Parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("Key","FullName")]
[string[]]$Accelerator
)
PROCESS {
foreach($a in $Accelerator) {
foreach($key in $xlr8r::Get.Keys -like $a) {
if($PSCmdlet.ShouldProcess( "Removes the alias [$($Key)] for type [$($xlr8r::Get[$key].FullName)]",
"Remove the alias [$($Key)] for type [$($xlr8r::Get[$key].FullName)]?",
"Removing Type Accelerator" )) {
# remove a user-defined accelerator
$xlr8r::remove($key)
}
}
}
}
}
Add-Accelerator list System.Collections.Generic.List``1
Add-Accelerator dictionary System.Collections.Generic.Dictionary``2
|
PowerShellCorpus/PoshCode/New-SQLComputerLogin.ps1
|
New-SQLComputerLogin.ps1
|
function New-SQLComputerLogin {
param(
[Parameter(Mandatory=$True,Position=0)]
[String]$SQLServer,
[Parameter(Mandatory=$True,Position=1)]
[String]$ComputerName,
[Switch]$Force
)
## Import-Module QAD, SQLPS -DisableNameChecking
$Computer = Get-QADComputer $ComputerName
#$NTAccountName = $Computer.NTAccountName
#if(!$SID) { $SID = $Computer.SID.ToString() }
invoke-sqlcmd -ServerInstance $SQLServer -Query "CREATE LOGIN [$($Computer.NTAccountName)] FROM WINDOWS" -ErrorVariable SqlError -ErrorAction SilentlyContinue
## If this principal already exists, fail, or clean it out and recreate it:
if($SqlError[0].Exception.Message.EndsWith("already exists.")) {
if(!$Force) {
Write-Error $SqlError[0].Exception
} else {
$ExistingAccount =
invoke-sqlcmd -ServerInstance $SQLServer -Query "select name, sid, create_date from sys.server_principals where type IN ('U','G')" |
add-member -membertype ScriptProperty SSDL { new-object security.principal.securityidentifier $this.SID, 0 } -passthru |
where-object {$_.SSDL -eq $Computer.SID}
invoke-sqlcmd -ServerInstance $SQLServer -Query "DROP LOGIN [$($ExistingAccount.Name)]" -ErrorAction Stop
invoke-sqlcmd -ServerInstance $SQLServer -Query "CREATE LOGIN [$($Computer.NTAccountName)] FROM WINDOWS"
}
}
}
|
PowerShellCorpus/PoshCode/wlanscan.ps1
|
wlanscan.ps1
|
# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=
# Name: wlanscan
# Author: Kris Cieslak (defaultset.blogspot.com)
# Date: 2010-04-03
# Description: Simple script that uses netsh to show wireless networks.
#
# Parameters: wireless interface name (optional,but recommended if you have
# more than one card)
# Result: $ActiveNetworks
# Usage example: wlanscan WiFi
#
# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-
PARAM ($ifname = "")
# Windows Vista/2008/7
if ((gwmi win32_operatingsystem).Version.Split(".")[0] -lt 6) {
throw "This script works on Windows Vista or higher."
}
if ((gsv "wlansvc").Status -ne "Running" ) {
throw "WLAN AutoConfig service must be running."
}
$GLOBAL:ActiveNetworks = @();
$CurrentIfName = "";
$n = -1;
$iftest = $false;
netsh wlan show network mode=bssid | % {
if ( $_ -match "Interface") {
$CurrentIfName = [regex]::match($_.Replace("Interface name : ","")
,"\\w{1,}").ToString();
if (($CurrentIfName.ToLower() -eq $ifname.ToLower()) -or ($ifname.length -eq 0)) {
$iftest=$true;
} else { $iftest=$false }
}
$buf = [regex]::replace($_,"[ ]","");
if ([regex]::IsMatch($buf,"^SSID\\d{1,}(.)*") -and $iftest) {
$item = "" | Select-Object SSID,NetType,Auth,Encryption,BSSID,Signal,Radiotype,Channel;
$n+=1;
$item.SSID = [regex]::Replace($buf,"^SSID\\d{1,}:","");
$GLOBAL:ActiveNetworks+=$item;
}
if ([regex]::IsMatch($buf,"Networktype") -and $iftest) {
$GLOBAL:ActiveNetworks[$n].NetType=$buf.Replace("Networktype:","");
}
if ([regex]::IsMatch($buf,"Authentication") -and $iftest) {
$GLOBAL:ActiveNetworks[$n].Auth=$buf.Replace("Authentication:","");
}
if ([regex]::IsMatch($buf,"Encryption") -and $iftest) {
$GLOBAL:ActiveNetworks[$n].Encryption=$buf.Replace("Encryption:","");
}
if ([regex]::IsMatch($buf,"BSSID1") -and $iftest) {
$GLOBAL:ActiveNetworks[$n].BSSID=$buf.Replace("BSSID1:","");
}
if ([regex]::IsMatch($buf,"Signal") -and $iftest) {
$GLOBAL:ActiveNetworks[$n].Signal=$buf.Replace("Signal:","");
}
if ([regex]::IsMatch($buf,"Radiotype") -and $iftest) {
$GLOBAL:ActiveNetworks[$n].Radiotype=$buf.Replace("Radiotype:","");
}
if ([regex]::IsMatch($buf,"Channel") -and $iftest) {
$GLOBAL:ActiveNetworks[$n].Channel=$buf.Replace("Channel:","");
}
}
if ( ($CurrentIfName.ToLower() -eq $ifname.ToLower()) -or ($ifname.length -eq 0) ) {
write-host -ForegroundColor Yellow "`nInterface: "$CurrentIfName;
if (($GLOBAL:ActiveNetworks.length -gt 0)) {
$GLOBAL:ActiveNetworks | Sort-Object Signal -Descending |
ft @{Label = "BSSID"; Expression={$_.BSSID };width=18},
@{Label = "Channel"; Expression={$_.Channel};width=8},
@{Label = "Signal"; Expression={$_.Signal};width=7},
@{Label = "Encryption"; Expression={$_.Encryption};width=11},
@{Label = "Authentication"; Expression={$_.Auth};width=15},
SSID
} else {
Write-host "`n No active networks found.`n";
}
} else {
Write-host -ForegroundColor Red "`n Could not find interface: "$ifname"`n";
}
|
PowerShellCorpus/PoshCode/List AD Attributes.ps1
|
List AD Attributes.ps1
|
$forest = [DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
$Schema = $forest.schema
$Properties = $Schema.FindAllProperties()
foreach($property in $Properties)
{
"#################################"
"Name: {0}" -f $property.Name
"Link: {0}" -f $property.link
"LinkID: {0}" -f $property.linkid
if(!$?)
{
"Error: {0}" -f $error[0].message
}
"#################################"
}
|
PowerShellCorpus/PoshCode/Test-Server_2.ps1
|
Test-Server_2.ps1
|
Function Test-Server{
[cmdletBinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline=$true)]
[string[]]$ComputerName,
[parameter(Mandatory=$false)]
[switch]$CredSSP,
[Management.Automation.PSCredential] $Credential)
begin{
$total = Get-Date
$results = @()
if($credssp){if(!($credential)){Write-Host "must supply Credentials with CredSSP test";break}}
}
process{
foreach($name in $computername)
{
$dt = $cdt= Get-Date
Write-verbose "Testing: $Name"
$failed = 0
try{
$DNSEntity = [Net.Dns]::GetHostEntry($name)
$domain = ($DNSEntity.hostname).replace("$name.","")
$ips = $DNSEntity.AddressList | %{$_.IPAddressToString}
}
catch
{
$rst = "" | select Name,IP,Domain,Ping,WSMAN,CredSSP,RemoteReg,RPC,RDP
$rst.name = $name
$results += $rst
$failed = 1
}
Write-verbose "DNS: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
if($failed -eq 0){
foreach($ip in $ips)
{
$rst = "" | select Name,IP,Domain,Ping,WSMAN,CredSSP,RemoteReg,RPC,RDP
$rst.name = $name
$rst.ip = $ip
$rst.domain = $domain
####RDP Check (firewall may block rest so do before ping
try{
$socket = New-Object Net.Sockets.TcpClient($name, 3389)
if($socket -eq $null)
{
$rst.RDP = $false
}
else
{
$rst.RDP = $true
$socket.close()
}
}
catch
{
$rst.RDP = $false
}
Write-verbose "RDP: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
#########ping
if(test-connection $ip -count 1 -Quiet)
{
Write-verbose "PING: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
$rst.ping = $true
try{############wsman
Test-WSMan $ip | Out-Null
$rst.WSMAN = $true
}
catch
{$rst.WSMAN = $false}
Write-verbose "WSMAN: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
if($rst.WSMAN -and $credssp) ########### credssp
{
try{
Test-WSMan $ip -Authentication Credssp -Credential $cred
$rst.CredSSP = $true
}
catch
{$rst.CredSSP = $false}
Write-verbose "CredSSP: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
}
try ########remote reg
{
[Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, $ip) | Out-Null
$rst.remotereg = $true
}
catch
{$rst.remotereg = $false}
Write-verbose "remote reg: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
try ######### wmi
{
$w = [wmi] ''
$w.psbase.options.timeout = 15000000
$w.path = "\\\\$Name\\root\\cimv2:Win32_ComputerSystem.Name='$Name'"
$w | select none | Out-Null
$rst.RPC = $true
}
catch
{$rst.rpc = $false}
Write-verbose "WMI: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)"
}
else
{
$rst.ping = $false
$rst.wsman = $false
$rst.credssp = $false
$rst.remotereg = $false
$rst.rpc = $false
}
$results += $rst
}}
Write-Verbose "Time for $($Name): $((New-TimeSpan $cdt ($dt)).totalseconds)"
Write-Verbose "----------------------------"
}
}
end{
Write-Verbose "Time for all: $((New-TimeSpan $total ($dt)).totalseconds)"
Write-Verbose "----------------------------"
return $results
}
}
|
PowerShellCorpus/PoshCode/get windows product key_4.ps1
|
get windows product key_4.ps1
|
function get-windowsproductkey([string]$computer)
{
$Reg = [WMIClass] ("\\\\" + $computer + "\\root\\default:StdRegProv")
$values = [byte[]]($reg.getbinaryvalue(2147483650,"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion","DigitalProductId").uvalue)
$lookup = [char[]]("B","C","D","F","G","H","J","K","M","P","Q","R","T","V","W","X","Y","2","3","4","6","7","8","9")
$keyStartIndex = [int]52;
$keyEndIndex = [int]($keyStartIndex + 15);
$decodeLength = [int]29
$decodeStringLength = [int]15
$decodedChars = new-object char[] $decodeLength
$hexPid = new-object System.Collections.ArrayList
for ($i = $keyStartIndex; $i -le $keyEndIndex; $i++){ [void]$hexPid.Add($values[$i]) }
for ( $i = $decodeLength - 1; $i -ge 0; $i--)
{
if (($i + 1) % 6 -eq 0){$decodedChars[$i] = '-'}
else
{
$digitMapIndex = [int]0
for ($j = $decodeStringLength - 1; $j -ge 0; $j--)
{
$byteValue = [int](($digitMapIndex * [int]256) -bor [byte]$hexPid[$j]);
$hexPid[$j] = [byte] ([math]::Floor($byteValue / 24));
$digitMapIndex = $byteValue % 24;
$decodedChars[$i] = $lookup[$digitMapIndex];
}
}
}
$STR = ''
$decodedChars | % { $str+=$_}
$STR
}
get-windowsproductkey .
|
PowerShellCorpus/PoshCode/Add-SqlTable_4.ps1
|
Add-SqlTable_4.ps1
|
try {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop}
catch {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo"}
try {add-type -AssemblyName "Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop}
catch {add-type -AssemblyName "Microsoft.SqlServer.Smo"}
#######################
function Get-SqlType
{
param([string]$TypeName)
switch ($TypeName)
{
'Boolean' {[Data.SqlDbType]::Bit}
'Byte[]' {[Data.SqlDbType]::VarBinary}
'Byte' {[Data.SQLDbType]::VarBinary}
'Datetime' {[Data.SQLDbType]::DateTime}
'Decimal' {[Data.SqlDbType]::Decimal}
'Double' {[Data.SqlDbType]::Float}
'Guid' {[Data.SqlDbType]::UniqueIdentifier}
'Int16' {[Data.SQLDbType]::SmallInt}
'Int32' {[Data.SQLDbType]::Int}
'Int64' {[Data.SqlDbType]::BigInt}
default {[Data.SqlDbType]::VarChar}
}
} #Get-SqlType
#######################
<#
.SYNOPSIS
Creates a SQL Server table from a DataTable
.DESCRIPTION
Creates a SQL Server table from a DataTable using SMO.
.EXAMPLE
$dt = Invoke-Sqlcmd2 -ServerInstance "Z003\\R2" -Database pubs "select * from authors"; Add-SqlTable -ServerInstance "Z003\\R2" -Database pubscopy -TableName authors -DataTable $dt
This example loads a variable dt of type DataTable from a query and creates an empty SQL Server table
.EXAMPLE
$dt = Get-Alias | Out-DataTable; Add-SqlTable -ServerInstance "Z003\\R2" -Database pubscopy -TableName alias -DataTable $dt
This example creates a DataTable from the properties of Get-Alias and creates an empty SQL Server table.
.NOTES
Add-SqlTable uses SQL Server Management Objects (SMO). SMO is installed with SQL Server Management Studio and is available
as a separate download: http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=ceb4346f-657f-4d28-83f5-aae0c5c83d52
Version History
v1.0 - Chad Miller - Initial Release
v1.1 - Chad Miller - Updated documentation
v1.2 - Chad Miller - Add loading Microsoft.SqlServer.ConnectionInfo
v1.3 - Chad Miller - Added error handling
v1.4 - Chad Miller - Add VarCharMax and VarBinaryMax handling
#>
function Add-SqlTable
{
[CmdletBinding()]
param(
[Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance,
[Parameter(Position=1, Mandatory=$true)] [string]$Database,
[Parameter(Position=2, Mandatory=$true)] [String]$TableName,
[Parameter(Position=3, Mandatory=$true)] [System.Data.DataTable]$DataTable,
[Parameter(Position=4, Mandatory=$false)] [string]$Username,
[Parameter(Position=5, Mandatory=$false)] [string]$Password,
[ValidateRange(0,8000)]
[Parameter(Position=6, Mandatory=$false)] [Int32]$MaxLength=1000
)
try {
if($Username)
{ $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $ServerInstance,$Username,$Password }
else
{ $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $ServerInstance }
$con.Connect()
$server = new-object ("Microsoft.SqlServer.Management.Smo.Server") $con
$db = $server.Databases[$Database]
$table = new-object ("Microsoft.SqlServer.Management.Smo.Table") $db, $TableName
foreach ($column in $DataTable.Columns)
{
$sqlDbType = [Microsoft.SqlServer.Management.Smo.SqlDataType]"$(Get-SqlType $column.DataType.Name)"
if ($sqlDbType -eq 'VarBinary' -or $sqlDbType -eq 'VarChar')
{
if ($MaxLength -gt 0)
{$dataType = new-object ("Microsoft.SqlServer.Management.Smo.DataType") $sqlDbType, $MaxLength}
else
{ $sqlDbType = [Microsoft.SqlServer.Management.Smo.SqlDataType]"$(Get-SqlType $column.DataType.Name)Max"
$dataType = new-object ("Microsoft.SqlServer.Management.Smo.DataType") $sqlDbType
}
}
else
{ $dataType = new-object ("Microsoft.SqlServer.Management.Smo.DataType") $sqlDbType }
$col = new-object ("Microsoft.SqlServer.Management.Smo.Column") $table, $column.ColumnName, $dataType
$col.Nullable = $column.AllowDBNull
$table.Columns.Add($col)
}
$table.Create()
}
catch {
$message = $_.Exception.GetBaseException().Message
Write-Error $message
}
} #Add-SqlTable
|
PowerShellCorpus/PoshCode/Audit Script.ps1
|
Audit Script.ps1
|
#####################################################
# Audit script by Alan Renouf - Virtu-Al #
# Blog: http://teckinfo.blogspot.com/ #
# #
# Usage: Audit.ps1 'path' #
# #
# The file needs to be a plain text list of #
# computers to be audited one on each line #
# #
#####################################################
param( [string] $auditlist)
if ($auditlist -eq ""){
Write-Host "No list specified, using Localhost"
$targets = "localhost"
}
else
{
if ((Test-Path $auditlist) -eq $false)
{
Write-Host "Invalid audit path specified: $auditlist"
exit
}
else
{
Write-Host "Using Audit list: $auditlist"
$Targets = Get-Content $auditlist
}
}
$Date = Get-Date
Foreach ($Target in $Targets)
{
$Filename = ".\\" + $Target + "_" + $date.Hour + $date.Minute + "_" + $Date.Day + "-" + $Date.Month + "-" + $Date.Year + ".htm"
# =====================================================================================================================
# CREATE HTML OUTPUT
# =====================================================================================================================
Write-Output " "| out-file -Append -encoding ASCII -filepath $Filename
Write-Output '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output '<html ES_auditInitialized='false'><head><title>Audit</title>'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "<META http-equiv=Content-Type content='text/html; charset=windows-1252'>"| out-file -Append -encoding ASCII -filepath $Filename
# ---------- Start of Style Definition Section ------------------------------------------------------------------------
Write-Output "<STYLE type=text/css>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " DIV .expando {DISPLAY: block; FONT-WEIGHT: normal; FONT-SIZE: 8pt; RIGHT: 10px; COLOR: #ffffff; FONT-FAMILY: Tahoma; POSITION: absolute; TEXT-DECORATION: underline}"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " TABLE {TABLE-LAYOUT: fixed; FONT-SIZE: 100%; WIDTH: 100%}"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " #objshowhide {PADDING-RIGHT: 10px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; Z-INDEX: 2; CURSOR: hand; COLOR: #000000; MARGIN-RIGHT: 0px; FONT-FAMILY: Tahoma; TEXT-ALIGN: right; TEXT-DECORATION: underline; WORD-WRAP: normal}"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " .heading0_expanded {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 8px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; WIDTH: 100%; CURSOR: hand; COLOR: #FFFFFF; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; BACKGROUND-COLOR: #cc0000}"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " .heading1 {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 16px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 5px; BORDER-LEFT: #bbbbbb 1px solid; WIDTH: 100%; CURSOR: hand; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; BACKGROUND-COLOR: #7BA7C7}"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " .heading2 {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 16px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 5px; BORDER-LEFT: #bbbbbb 1px solid; WIDTH: 100%; CURSOR: hand; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; BACKGROUND-COLOR: #A5A5A5}"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " .tableDetail {BORDER-RIGHT: #bbbbbb 1px solid; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 16px; FONT-SIZE: 8pt;MARGIN-BOTTOM: -1px; PADDING-BOTTOM: 5px; MARGIN-LEFT: 5px; BORDER-LEFT: #bbbbbb 1px solid; WIDTH: 100%; COLOR: #000000; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; BACKGROUND-COLOR: #f9f9f9}"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " .filler {BORDER-RIGHT: medium none; BORDER-TOP: medium none; DISPLAY: block; BACKGROUND: none transparent scroll repeat 0% 0%; MARGIN-BOTTOM: -1px; FONT: 100%/8px Tahoma; MARGIN-LEFT: 43px; BORDER-LEFT: medium none; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: medium none; POSITION: relative}"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " .Solidfiller {BORDER-RIGHT: medium none; BORDER-TOP: medium none; DISPLAY: block; BACKGROUND: none transparent scroll repeat 0% 0%; MARGIN-BOTTOM: -1px; FONT: 100%/8px Tahoma; MARGIN-LEFT: 0px; BORDER-LEFT: medium none; COLOR: #000000; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: medium none; POSITION: relative; BACKGROUND-COLOR: #000000}"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " td {VERTICAL-ALIGN: TOP; FONT-FAMILY: Tahoma}"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " th {VERTICAL-ALIGN: TOP; COLOR: #cc0000; TEXT-ALIGN: left}"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "</STYLE>"| out-file -Append -encoding ASCII -filepath $Filename
# ---------- End of Style Definition Section --------------------------------------------------------------------------
# ---------- Start of Control Script Section --------------------------------------------------------------------------
Write-Output "<SCRIPT language=vbscript>"| out-file -Append -encoding ASCII -filepath $Filename
# ---------- Declare Global Variables for Routines --------------------------------------------------------------------
Write-Output " strShowHide = 1"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' strShow = "show"'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' strHide = "hide"'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' strShowAll = "show all"'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' strHideAll = "hide all"'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "Function window_onload()"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' If UCase(document.documentElement.getAttribute("ES_auditInitialized")) <> "TRUE" Then'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Set objBody = document.body.all"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " For Each obji in objBody"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " If IsSectionHeader(obji) Then"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " If IsSectionExpandedByDefault(obji) Then"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " ShowSection obji"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Else"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " HideSection obji"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " End If"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " End If"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Next"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " objshowhide.innerText = strShowAll"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' document.documentElement.setAttribute "ES_auditInitialized", "true"'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " End If"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "End Function"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "Function IsSectionExpandedByDefault(objHeader)"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' IsSectionExpandedByDefault = (Right(objHeader.className, Len("_expanded")) = "_expanded")'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "End Function"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "Function document_onclick()"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Set strsrc = window.event.srcElement"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' While (strsrc.className = "sectionTitle" or strsrc.className = "expando")'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Set strsrc = strsrc.parentElement"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Wend"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " If Not IsSectionHeader(strsrc) Then Exit Function"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " ToggleSection strsrc"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " window.event.returnValue = False"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "End Function"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "Sub ToggleSection(objHeader)"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' SetSectionState objHeader, "toggle"'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "End Sub"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "Sub SetSectionState(objHeader, strState)"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " i = objHeader.sourceIndex"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Set all = objHeader.parentElement.document.all"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' While (all(i).className <> "container")'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " i = i + 1"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Wend"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Set objContainer = all(i)"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' If strState = "toggle" Then'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' If objContainer.style.display = "none" Then'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' SetSectionState objHeader, "show" '| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Else"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' SetSectionState objHeader, "hide" '| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " End If"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Else"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Set objExpando = objHeader.children.item(1)"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' If strState = "show" Then'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' objContainer.style.display = "block" '| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " objExpando.innerText = strHide"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' ElseIf strState = "hide" Then'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' objContainer.style.display = "none" '| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " objExpando.innerText = strShow"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " End If"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " End If"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "End Sub"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "Function objshowhide_onClick()"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Set objBody = document.body.all"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Select Case strShowHide"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Case 0"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " strShowHide = 1"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " objshowhide.innerText = strShowAll"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " For Each obji In objBody"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " If IsSectionHeader(obji) Then"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " HideSection obji"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " End If"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Next"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Case 1"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " strShowHide = 0"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " objshowhide.innerText = strHideAll"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " For Each obji In objBody"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " If IsSectionHeader(obji) Then"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " ShowSection obji"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " End If"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " Next"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " End Select"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "End Function"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output 'Function IsSectionHeader(obj) : IsSectionHeader = (obj.className = "heading0_expanded") Or (obj.className = "heading1_expanded") Or (obj.className = "heading1") Or (obj.className = "heading2"): End Function'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output 'Sub HideSection(objHeader) : SetSectionState objHeader, "hide" : End Sub'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output 'Sub ShowSection(objHeader) : SetSectionState objHeader, "show": End Sub'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "</SCRIPT>"| out-file -Append -encoding ASCII -filepath $Filename
# ---------- End of Control Script Section ----------------------------------------------------------------------------
Write-Output " </HEAD>"| out-file -Append -encoding ASCII -filepath $Filename
# ---------- End of Head Section --------------------------------------------------------------------------------------
# ---------- Start of Body Section ------------------------------------------------------------------------------------
Write-Output "<BODY>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' <p><b><font face="Arial" size="5">'$Target' Audit<hr size="8" color="#CC0000"></font></b>'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' <font face="Arial" size="1"><b><i>Version 1.0 by Alan Renouf (Virtu-Al)</i></b></font><br>'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output ' <font face="Arial" size="1">Report generated on ' (Get-Date) '</font></p>'| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "<TABLE cellSpacing=0 cellPadding=0>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TBODY>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TR>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TD>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV id=objshowhide tabIndex=0><FONT face=Arial></FONT></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </TD>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </TR>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </TBODY>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "</TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
write-output "Writing Detail for $Target"
$ComputerSystem = Get-WmiObject -computername $Target Win32_ComputerSystem
switch ($ComputerSystem.DomainRole)
{
0 { $ComputerRole = "Standalone Workstation" }
1 { $ComputerRole = "Member Workstation" }
2 { $ComputerRole = "Standalone Server" }
3 { $ComputerRole = "Member Server" }
4 { $ComputerRole = "Domain Controller" }
5 { $ComputerRole = "Domain Controller" }
default { $ComputerRole = "Information not available" }
}
$OperatingSystems = Get-WmiObject -computername $Target Win32_OperatingSystem
$TimeZone = Get-WmiObject -computername $Target Win32_Timezone
$Keyboards = Get-WmiObject -computername $Target Win32_Keyboard
$SchedTasks = Get-WmiObject -computername $Target Win32_ScheduledJob
$BootINI = $OperatingSystems.SystemDrive + "boot.ini"
$RecoveryOptions = Get-WmiObject -computername $Target Win32_OSRecoveryConfiguration
# ---------- Start of COMPUTER DETAILS Section HTML Code --------------------------------------------------------------
Write-Output "<DIV class=heading0_expanded>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>$target Details</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "</DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output "<DIV class=filler></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
# ---------- Start of COMPUTER DETAILS - GENERAL Sub Section HTML Code ------------------------------------------------
write-output "..Computer Details"
Write-Output "<DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading1>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>General</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Computer Name</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'> " $ComputerSystem.Name "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Computer Role</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'> $ComputerRole </font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
switch ($ComputerRole)
{
"Member Workstation" { Write-Output " <th width='25%'><b>Computer Domain</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename }
"Domain Controller" { Write-Output " <th width='25%'><b>Computer Domain</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename }
"Member Server" { Write-Output " <th width='25%'><b>Computer Domain</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename }
default { Write-Output " <th width='25%'><b>Computer Workgroup</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename}
}
Write-Output " <td width='75%'>" $ComputerSystem.Domain "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Operating System</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $OperatingSystems.Caption "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Service Pack</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $OperatingSystems.CSDVersion "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>System Root</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $OperatingSystems.SystemDrive "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Manufacturer</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $ComputerSystem.Manufacturer "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Model</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $ComputerSystem.Model "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Number of Processors</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $ComputerSystem.NumberOfProcessors "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Memory</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $ComputerSystem.TotalPhysicalMemory "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Registered User</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $ComputerSystem.PrimaryOwnerName "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Registered Organisation</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $OperatingSystems.Organization "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Last System Boot</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
$LBTime=$OperatingSystems.ConvertToDateTime($OperatingSystems.Lastbootuptime)
Write-Output " <td width='75%'>" $LBTime "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=filler></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
#---------- End of COMPUTER DETAILS - GENERAL Sub-section HTML Code --------------------------------------------------
# ---------- Start of COMPUTER DETAILS - HOFIXES Sub-section HTML Code ------------------------------------------------
write-output "..Hotfix Information"
$colQuickFixes = Get-WmiObject Win32_QuickFixEngineering
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading1>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>HotFixes</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>HotFix Number</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='75%'><b>Description</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
ForEach ($objQuickFix in $colQuickFixes)
{
if ($objQuickFix.HotFixID -ne "File 1")
{
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='25%'>" $objQuickFix.HotFixID "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $objQuickFix.Description "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
}
}
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=filler></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
#---------- End of COMPUTER DETAILS - HOFIXES Sub-section HTML Code --------------------------------------------------
#---------- Start of COMPUTER DETAILS - LOGICAL DISK CONFIGURATION Sub-section HTML Code -----------------------------
write-output "..Logical Disks"
$colDisks = Get-WmiObject -ComputerName $Target Win32_LogicalDisk
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading1>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>Logical Disk Configuration</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='15%'><b>Drive Letter</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='20%'><b>Label</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='20%'><b>File System</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='15%'><b>Disk Size</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='15%'><b>Disk Free Space</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='15%'><b>% Free Space</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Foreach ($objDisk in $colDisks)
{
if ($objDisk.DriveType -eq 3)
{
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='15%'>"$objDisk.DeviceID"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='20%'>"$objDisk.VolumeName"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='20%'>"$objDisk.FileSystem"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
$disksize = [math]::round(($objDisk.size / 1048576))
Write-Output " <td width='15%'>"$disksize" MB</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
$freespace = [math]::round(($objDisk.FreeSpace / 1048576))
Write-Output " <td width='15%'>"$Freespace" MB</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
$percFreespace=[math]::round(((($objDisk.FreeSpace / 1048576)/($objDisk.Size / 1048676)) * 100),0)
Write-Output " <td width='15%'>"$percFreespace" %</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
}
}
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=filler></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
# ---------- End of COMPUTER DETAILS - LOGICAL DISK CONFIGURATION Sub-section HTML Code -------------------------------
# ---------- Start of COMPUTER DETAILS - NIC CONFIGURATION Sub-section HTML Code --------------------------------------
write-output "..Network Configuration"
$NICCount = 0
$colAdapters = Get-WmiObject -ComputerName $Target Win32_NetworkAdapterConfiguration
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading1>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>NIC Configuration</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
$NICCount = 0
Foreach ($objAdapter in $colAdapters)
{
if ($objAdapter.IPEnabled -eq "True")
{
$NICCount = $NICCount + 1
If ($NICCount -gt 1)
{
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=Solidfiller></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Description</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $objAdapter.Description "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Physical address</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $objAdapter.MACaddress "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
If ($objAdapter.IPAddress -ne $Null)
{
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>IP Address / Subnet Mask</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $objAdapter.IPAddress " / " $objAdapter.IPSubnet "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Default Gateway</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $objAdapter.DefaultIPGateway "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>DHCP enabled</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
If ($objAdapter.DHCPEnabled -eq "True")
{
Write-Output " <td width='75%'>Yes</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
Else
{
Write-Output " <td width='75%'>No</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>DNS Servers</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>"| out-file -Append -encoding ASCII -filepath $Filename
If ($objAdapter.DNSServerSearchOrder -ne $Null)
{
Write-Output $objAdapter.DNSServerSearchOrder | out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Primary WINS Server</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $objAdapter.WINSPrimaryServer "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Secondary WINS Server</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $objAdapter.WINSSecondaryServer "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
$NICCount = $NICCount + 1
}
}
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=filler></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
#---------- End of COMPUTER DETAILS - NIC CONFIGURATION Sub-section HTML Code ----------------------------------------
#---------- Start of COMPUTER DETAILS - Software Sub-section HTML Code -------------------------------------------
if ((get-wmiobject -namespace "root/cimv2" -list) | ? {$_.name -match "Win32_Product"})
{
write-output "..Installed Software"
$colShares = get-wmiobject -ComputerName $Target Win32_Product | select Name,Version,Vendor,InstallDate
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading1>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>Software</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Name</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Version</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Vendor</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Install Date</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Foreach ($objShare in $colShares)
{
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='50%'>" $objShare.Name "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='20%'>" $objShare.Version "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='15%'>" $objShare.Vendor "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='15%'>" $objShare.InstallDate "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=filler></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
}
# ---------- End of COMPUTER DETAILS - Software Sub-section HTML Code ---------------------------------------------
#---------- Start of COMPUTER DETAILS - LOCAL SHARES Sub-section HTML Code -------------------------------------------
write-output "..Local Shares"
$colShares = Get-wmiobject -ComputerName $Target Win32_Share
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading1>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>Local Shares</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Share</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Path</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='50%'><b>Comment</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Foreach ($objShare in $colShares)
{
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='25%'>" $objShare.Name "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='25%'>" $objShare.Path "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='50%'>" $objShare.Caption "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=filler></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
#---------- End of COMPUTER DETAILS - LOCAL SHARES Sub-section HTML Code ---------------------------------------------
#---------- Start of COMPUTER DETAILS - PRINTERS Sub-section HTML Code -----------------------------------------------
Write-output "..Printers"
$colInstalledPrinters = Get-WmiObject -ComputerName $Target Win32_Printer
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading1>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>Printers</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Printer</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Location</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Default Printer</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Portname</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Foreach ($objPrinter in $colInstalledPrinters)
{
If ($objPrinter.Name -eq "")
{
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='100%'>No Printers Installed</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
Else
{
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='25%'>" $objPrinter.Name "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='25%'>" $objPrinter.Location "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
if ($objPrinter.Default -eq "True")
{
Write-Output " <td width='25%'>Yes</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
Else
{
Write-Output " <td width='25%'>No</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " <td width='25%'>"$objPrinter.Portname"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=filler></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
#---------- End of COMPUTER DETAILS - PRINTERS Sub-section HTML Code -------------------------------------------------
#---------- Start of COMPUTER DETAILS - SERVICES Sub-section HTML Code -----------------------------------------------
Write-Output "..Services"
$colListOfServices = Get-WmiObject -ComputerName $Target Win32_Service
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading1>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>Services</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='20%'><b>Name</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='20%'><b>Account</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='20%'><b>Start Mode</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='20%'><b>State</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='20%'><b>Expected State</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Foreach ($objService in $colListOfServices)
{
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='20%'>"$objService.Caption"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='20%'>"$objService.Startname"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='20%'>"$objService.StartMode"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
If ($objService.StartMode -eq "Auto")
{
if ($objService.State -eq "Stopped")
{
Write-Output " <td width='20%'><font color='#FF0000'>"$objService.State"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='25%'><font face='Wingdings'color='#FF0000'>ű</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
}
If ($objService.StartMode -eq "Auto")
{
if ($objService.State -eq "Running")
{
Write-Output " <td width='20%'><font color='#009900'>"$objService.State"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='20%'><font face='Wingdings'color='#009900'>ü</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
}
If ($objService.StartMode -eq "Disabled")
{
If ($objService.State -eq "Running")
{
Write-Output " <td width='20%'><font color='#FF0000'>"$objService.State"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='25%'><font face='Wingdings'color='#FF0000'>ű</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
}
If ($objService.StartMode -eq "Disabled")
{
if ($objService.State -eq "Stopped")
{
Write-Output " <td width='20%'><font color='#009900'>"$objService.State"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='20%'><font face='Wingdings'color='#009900'>ü</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
}
If ($objService.StartMode -eq "Manual")
{
Write-Output " <td width='20%'><font color='#009900'>"$objService.State"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='20%'><font face='Wingdings'color='#009900'>ü</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
If ($objService.State -eq "Paused")
{
Write-Output " <td width='20%'><font color='#FF9933'>"$objService.State"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='20%'><font face='Wingdings'color='#009900'>ü</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=filler></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
#---------- End of COMPUTER DETAILS - SERVICES Sub-section HTML Code -------------------------------------------------
#---------- Start of COMPUTER DETAILS - REGIONAL SETTINGS Sub-section HTML Code --------------------------------------
Write-Output "..Regional Options"
$ObjKeyboards = Get-WmiObject -ComputerName $Target Win32_Keyboard
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading1>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>Regional Settings</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Time Zone</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $TimeZone.Description "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Country Code</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $OperatingSystems.Countrycode "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Locale</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $OperatingSystems.Locale"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Operating System Language</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $OperatingSystems.OSLanguage"</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
switch ($ObjKeyboards.Layout)
{
"00000402"{ $keyb = "BG" }
"00000404"{ $keyb = "CH" }
"00000405"{ $keyb = "CZ" }
"00000406"{ $keyb = "DK" }
"00000407"{ $keyb = "GR" }
"00000408"{ $keyb = "GK" }
"00000409"{ $keyb = "US" }
"0000040A"{ $keyb = "SP" }
"0000040B"{ $keyb = "SU" }
"0000040C"{ $keyb = "FR" }
"0000040E"{ $keyb = "HU" }
"0000040F"{ $keyb = "IS" }
"00000410"{ $keyb = "IT" }
"00000411"{ $keyb = "JP" }
"00000412"{ $keyb = "KO" }
"00000413"{ $keyb = "NL" }
"00000414"{ $keyb = "NO" }
"00000415"{ $keyb = "PL" }
"00000416"{ $keyb = "BR" }
"00000418"{ $keyb = "RO" }
"00000419"{ $keyb = "RU" }
"0000041A"{ $keyb = "YU" }
"0000041B"{ $keyb = "SL" }
"0000041C"{ $keyb = "US" }
"0000041D"{ $keyb = "SV" }
"0000041F"{ $keyb = "TR" }
"00000422"{ $keyb = "US" }
"00000423"{ $keyb = "US" }
"00000424"{ $keyb = "YU" }
"00000425"{ $keyb = "ET" }
"00000426"{ $keyb = "US" }
"00000427"{ $keyb = "US" }
"00000804"{ $keyb = "CH" }
"00000809"{ $keyb = "UK" }
"0000080A"{ $keyb = "LA" }
"0000080C"{ $keyb = "BE" }
"00000813"{ $keyb = "BE" }
"00000816"{ $keyb = "PO" }
"00000C0C"{ $keyb = "CF" }
"00000C1A"{ $keyb = "US" }
"00001009"{ $keyb = "US" }
"0000100C"{ $keyb = "SF" }
"00001809"{ $keyb = "US" }
"00010402"{ $keyb = "US" }
"00010405"{ $keyb = "CZ" }
"00010407"{ $keyb = "GR" }
"00010408"{ $keyb = "GK" }
"00010409"{ $keyb = "DV" }
"0001040A"{ $keyb = "SP" }
"0001040E"{ $keyb = "HU" }
"00010410"{ $keyb = "IT" }
"00010415"{ $keyb = "PL" }
"00010419"{ $keyb = "RU" }
"0001041B"{ $keyb = "SL" }
"0001041F"{ $keyb = "TR" }
"00010426"{ $keyb = "US" }
"00010C0C"{ $keyb = "CF" }
"00010C1A"{ $keyb = "US" }
"00020408"{ $keyb = "GK" }
"00020409"{ $keyb = "US" }
"00030409"{ $keyb = "USL" }
"00040409"{ $keyb = "USR" }
"00050408"{ $keyb = "GK" }
default { $keyb = "Unknown" }
}
Write-Output " <th width='25%'><b>Keyboard Layout</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='75%'>" $keyb "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </div>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=filler></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
#---------- End of COMPUTER DETAILS - REGIONAL SETTINGS Sub-section HTML Code ----------------------------------------
#---------- Start of COMPUTER DETAILS - EVENT LOGS Sub-section HTML Code ---------------------------------------------
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading1>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>Event Logs</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
#---------- Start of COMPUTER DETAILS - EVENT LOGS - EVENT LOG SETTINGS Sub-section HTML Code ------------------------
Write-Output "..Event Log Settings"
$colLogFiles = Get-WmiObject -ComputerName $Target Win32_NTEventLogFile
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading2>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>Event Log Settings</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Log Name</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Overwrite Outdated Records</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Maximum Size</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='25%'><b>Current Size</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
ForEach ($objLogFile in $colLogfiles)
{
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='25%'>" $objLogFile.LogFileName "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
If ($objLogfile.OverWriteOutdated -lt 0)
{
Write-Output " <td width='25%'>Never</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
if ($objLogFile.OverWriteOutdated -eq 0)
{
Write-Output " <td width='25%'>As needed</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
Else
{
Write-Output " <td width='25%'>After " $objLogFile.OverWriteOutdated " days</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " <td width='25%'>" (($objLogfile.MaxFileSize)/1024) " KB</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='25%'>" (($objLogfile.FileSize)/1024) " KB</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=filler></DIV>"| out-file -Append -encoding ASCII -filepath $Filename
#---------- End of COMPUTER DETAILS - EVENT LOGS - EVENT LOG SETTINGS Sub-section HTML Code --------------------------
# ---------- Start of COMPUTER DETAILS - EVENT LOGS - ERROR ENTRIES Sub-section HTML Code -----------------------------
write-output "..Event Log Errors"
$WmidtQueryDT = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime([DateTime]::Now.AddDays(-14))
$colLoggedEvents = Get-WmiObject -computer "Localhost" -query ("Select * from Win32_NTLogEvent Where Type='Error' and TimeWritten >='" + $WmidtQueryDT + "'")
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=heading2>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <SPAN class=sectionTitle tabIndex=0>ERROR Entries</SPAN>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <A class=expando href='#'></A>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=container>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <DIV class=tableDetail>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='10%'><b>Event Code</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='10%'><b>Source Name</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='15%'><b>Time</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='10%'><b>Log</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <th width='55%'><b>Message</b></font></th>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
ForEach ($objEvent in $colLoggedEvents)
{
$dtmEventDate = $ObjEvent.ConvertToDateTime($objEvent.TimeWritten)
Write-Output " <tr>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='10%'>" $objEvent.EventCode "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='10%'>" $objEvent.SourceName "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='15%'>" $dtmEventDate "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='10%'>" $objEvent.LogFile "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " <td width='55%'>" $objEvent.Message "</font></td>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </tr>"| out-file -Append -encoding ASCII -filepath $Filename
}
Write-Output " </TABLE>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DIV>"| out-file -Append -encoding ASCII -filepath $Filename
Write-Output " </DI
|
PowerShellCorpus/PoshCode/DefaultParameterValues_2.ps1
|
DefaultParameterValues_2.ps1
|
# DefaultParameters Module
# 1.3 - fixed denable/disable, added get and remove, and improved import and set
# 1.2 - added help and commands to enable/disable the defaults
# 1.0 - initial release
function Export-DefaultParameter {
#.Synopsis
# Exports the current default parameter values
[CmdletBinding()]
param(
# The path to export default parameter values to (defaults to "DefaultParameterValues.clixml" in your profile directory)
[String]$Path = $(Join-Path (Split-Path $Profile.CurrentUserAllHosts -Parent) DefaultParameterValues.clixml)
)
Export-CliXml -InputObject $Global:PSDefaultParameterValues -Path $Path
}
function Import-DefaultParameter {
#.Synopsis
# Imports new default parameter values
[CmdletBinding()]
param(
# The path to import default parameter values from (defaults to "DefaultParameterValues.clixml" in your profile directory)
[String]$Path = $(Join-Path (Split-Path $Profile.CurrentUserAllHosts -Parent) DefaultParameterValues.clixml),
# If set, overwrite current values (otherwise, keep current values)
[Switch]$Force
)
$TempParameterValues = $Global:PSDefaultParameterValues
if(Test-Path $Path) {
[System.Management.Automation.DefaultParameterDictionary]$NewValues =
Import-CliXml -Path ${ProfileDir}\\DefaultParameterValues.clixml
$repeats = @()
foreach($key in $NewValues.Keys) {
# don't import the disabled state, that's just silly
if($key -eq "disabled") { continue }
if($Global:PSDefaultParameterValues.ContainsKey($key)) {
$command,$parameter = $key -split ":"
if($Force) {
$repeats += [PSCustomObject]@{Command=$Command;Parameter=$Parameter;NewDefault=$NewValues.$key;OldDefault=$Global:PSDefaultParameterValues.$Key}
$Global:PSDefaultParameterValues.$Key = $NewValues.$key
} else {
$repeats += [PSCustomObject]@{Command=$Command;Parameter=$Parameter;CurrentDefault=$Global:PSDefaultParameterValues.$Key;SkippedValue=$NewValues.$key}
}
} else {
$Global:PSDefaultParameterValues.$Key = $NewValues.$key
}
}
if($repeats.Count) {
$Width = &{
$Local:ErrorActionPreference = "SilentlyContinue"
$Width = $Host.UI.RawUI.BufferSize.Width - 2
if($Width) { $Width } else { 80 }
}
if($Force) {
Write-Warning ("Some defaults overwritten:`n{0}" -f ($repeats | Out-String -Width $Width))
} else {
Write-Warning ("Some defaults already defined, use -Force to overwrite:`n{0}" -f ($repeats | Out-String -Width $Width))
}
}
# Make sure that everything is enabled
$Global:PSDefaultParameterValues["Disabled"] = $false
} else {
Write-Warning "Default Parameter file not found: '$Path'"
}
}
function Set-DefaultParameter {
#.Synopsis
# Sets a default parameter value for a command
#.Description
# Safely sets the default parameter value for a command, making sure that you've correctly typed the command and parameter combination
[CmdletBinding(DefaultParameterSetName="Colonated", SupportsShouldProcess=$true, ConfirmImpact="Low")]
param(
# The command that you want to change the default value of a parameter for
[parameter(Position=0,Mandatory=$true,ParameterSetName="Colonated")]
[parameter(Position=0,Mandatory=$true,ParameterSetName="SeparateInputs")]
$Command,
# The name of the parameter that you want to change the default value for
[parameter(Position=1,Mandatory=$true,ParameterSetName="SeparateInputs")]
$Parameter,
# The new default parameter value
[parameter(Position=1,Mandatory=$true,ParameterSetName="Colonated")]
[parameter(Position=2,Mandatory=$true,ParameterSetName="SeparateInputs")]
$Value
)
if($PSCmdlet.ParameterSetName -eq "Colonated") {
$command,$parameter = $command -split ":"
}
if($parameter.StartsWith("-")) {
$parameter = $parameter.TrimStart("-")
}
## Resolve the parameter to be sure
$cmd = Get-Command $command | Select -First 1
$parameters = $cmd.Parameters.Values
$param = @($parameters | Where-Object { $_.Name -match $parameter -or $_.Aliases -match $parameter} | Select -Expand Name -Unique)
if(!$param) {
$param = @($parameters | Where-Object { $_.Name -match "${parameter}*"} | Select -First 1 -Expand Name)
if(!$param) {
$param = @($parameters | Where-Object { $_.Aliases -match "${parameter}*"} | Select -First 1 -Expand Name)
}
}
if($param.Count -eq 1) {
if($cmd.CommandType -eq "Alias") {
$Command = $cmd.DisplayName
} else {
$Command = $cmd.Name
}
Write-Verbose "Setting Parameter $parameter on ${Command} to default: $($param[0])"
$Key = "${Command}:$($param[0])"
if( $Global:PSDefaultParameterValues.ContainsKey($Key) ) {
$WI = "Overwrote the default parameter value for '$Key' with $Value"
$CF = "Overwrite the existing default parameter value for '$Key'? ($($Global:PSDefaultParameterValues.$Key))"
} else {
$WI = "Added a default parameter value for '$Key' = $Value"
$CF = "Add a default parameter value for '$Key'? ($($Global:PSDefaultParameterValues.$Key))"
}
if($PSCmdlet.ShouldProcess( $WI, $CI, "Setting Default Parameter Values" )) {
$Global:PSDefaultParameterValues.$Key = $Value
}
} else {
Write-Warning "Parameter $parameter not found on ${Command}"
}
}
function Get-DefaultParameter {
#.Synopsis
# Gets the default parameter value for a command, if it's been set
#.Description
# Gets the default parameter value for a command from $PSDefaultParameterValues
[CmdletBinding(DefaultParameterSetName="Colonated")]
param(
# The command that you want to change the default value of a parameter for (allows wildcards)
[parameter(Position=0,Mandatory=$false)]
[string]$Command = "*",
# The name of the parameter that you want to change the default value for (allows wildcards)
[parameter(Position=1,Mandatory=$true,ParameterSetName="SeparateInputs")]
[string]$Parameter
)
if($PSCmdlet.ParameterSetName -eq "Colonated") {
$command,$parameter = $command -split ":"
}
if($parameter.StartsWith("-")) {
$parameter = $parameter.TrimStart("-")
}
$repeats = @()
foreach($key in $Global:PSDefaultParameterValues.Keys) {
# Handle the disabled state:
if($key -eq "disabled" -and $Global:PSDefaultParameterValues["Disabled"]) {
Write-Warning "Default Parameter Values are DISABLED and will not be used:"
continue
}
if($key -like "${Command}:${Parameter}*") {
$Cmd,$Param = $key -split ":"
$repeats += [PSCustomObject]@{Command=$Cmd;Parameter=$Param;CurrentDefault=$Global:PSDefaultParameterValues.$Key}
} else {
Write-Verbose "'$key' is -not -like '${Command}:${Parameter}*'"
}
}
$repeats
}
function Remove-DefaultParameter {
#.Synopsis
# Removed the default parameter value for a command, if it's been set
#.Description
# Removes the default parameter value for a command from $PSDefaultParameterValues
[CmdletBinding(DefaultParameterSetName="Colonated", SupportsShouldProcess=$true, ConfirmImpact="Low")]
param(
# The command that you want to change the default value of a parameter for (allows wildcards)
[parameter(Position=0,Mandatory=$false)]
[string]$Command = "*",
# The name of the parameter that you want to change the default value for (allows wildcards)
[parameter(Position=1,Mandatory=$true,ParameterSetName="SeparateInputs")]
[string]$Parameter
)
if($PSCmdlet.ParameterSetName -eq "Colonated") {
$command,$parameter = $command -split ":"
}
if($parameter.StartsWith("-")) {
$parameter = $parameter.TrimStart("-")
}
$keys
foreach($key in $Global:PSDefaultParameterValues.Keys | Where { $_ -like "${Command}:${Parameter}*" }) {
# Handle the disabled state:
if($key -ne "disabled") {
if($PSCmdlet.ShouldProcess( "Removed the default parameter value for '$Key'",
"Remove the default parameter value for '$Key'?",
"Removing Default Parameter Values" )) {
$Global:PSDefaultParameterValues.Remove($key)
}
}
}
}
function Disable-DefaultParameter {
#.Synopsis
# Turns OFF default parameters
#.Description
# By setting $PSDefaultParameterValues["Disabled"] to $true, we make sure that NONE of our default parameter values will be used
[CmdletBinding()]
param()
$Global:PSDefaultParameterValues["Disabled"]=$true
}
function Enable-DefaultParameter {
#.Synopsis
# Turns ON default parameters
#.Description
# By setting $PSDefaultParameterValues["Disabled"] to $false, we make sure that all of our default parameter values will be used
[CmdletBinding()]
param()
$Global:PSDefaultParameterValues["Disabled"]=$false
}
Set-Alias Add-DefaultParameter Set-DefaultParameter -ErrorAction SilentlyContinue
Import-DefaultParameter
|
PowerShellCorpus/PoshCode/Call WSPBuilder_1.ps1
|
Call WSPBuilder_1.ps1
|
function Run-DosCommand($program, [string[]]$programArgs)
{
write-host "Running command: $program";
write-host " Args:"
0..($programArgs.Count-1) | foreach { Write-Host " $($_): $($programArgs[$_])" }
& $program $programArgs
}
#Get-FullPath function defined elsewhere, refers to a "base directory" which allows me to make
#all path references RELATIVE to this base directory. Feel free to hardcode the path instead.
$wspbuilder = Get-FullPath("tools\\WSPBuilder.exe")
function Run-WspBuilder($rootDirectory)
{
pushd
cd $rootDirectory
Run-DosCommand -program $WSPBuilder -programArgs @("-BuildWSP",
"true",
"-OutputPath",
(Get-FullPath 'deployment'),
"-ExcludePaths",
(Join-Path -path (Get-FirstDirectoryUnderneathSrc).fullname -childPath "bin\\Debug"))
popd
}
|
PowerShellCorpus/PoshCode/ASPX Mailbox (3 of 6).ps1
|
ASPX Mailbox (3 of 6).ps1
|
<%@ Page Language="C#" CodeFile="MailboxConfirm.aspx.cs" AutoEventWireup="true" Inherits="MailboxConfirm" ClassName = "MailboxConfirm" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title> Domain Mailbox Task Confirm Page</title>
</head>
<body>
<form id="frmMailboxConfirm" runat="server" method="Post" action="MailboxTaskResults.aspx">
<script type="text/javascript" language="JavaScript" defer="defer">
function GoBack()
{
document.location = "MailboxTasks.aspx"
}
</script>
<asp:TextBox ID="newAddress" runat="server" Visible="False"></asp:TextBox>
<asp:CheckBox ID="chkKeepAddress" runat="server" Visible="False" />
</form>
</body>
</html>
|
PowerShellCorpus/PoshCode/Get-WebsiteCertificate.ps1
|
Get-WebsiteCertificate.ps1
|
function Get-WebsiteCertificate {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)] [System.Uri]
$Uri,
[Parameter()] [System.IO.FileInfo]
$OutputFile,
[Parameter()] [Switch]
$UseSystemProxy,
[Parameter()] [Switch]
$UseDefaultCredentials,
[Parameter()] [Switch]
$TrustAllCertificates
)
try {
$request = [System.Net.WebRequest]::Create($Uri)
if ($UseSystemProxy) {
$request.Proxy = [System.Net.WebRequest]::DefaultWebProxy
}
if ($UseSystemProxy -and $UseDefaultCredentials) {
$request.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
}
if ($TrustAllCertificates) {
# Create a compilation environment
$Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
$Compiler=$Provider.CreateCompiler()
$Params=New-Object System.CodeDom.Compiler.CompilerParameters
$Params.GenerateExecutable=$False
$Params.GenerateInMemory=$True
$Params.IncludeDebugInformation=$False
$Params.ReferencedAssemblies.Add("System.DLL") > $null
$TASource=@'
namespace Local.ToolkitExtensions.Net.CertificatePolicy {
public class TrustAll : System.Net.ICertificatePolicy {
public TrustAll() {
}
public bool CheckValidationResult(System.Net.ServicePoint sp,
System.Security.Cryptography.X509Certificates.X509Certificate cert,
System.Net.WebRequest req, int problem) {
return true;
}
}
}
'@
$TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
$TAAssembly=$TAResults.CompiledAssembly
## We now create an instance of the TrustAll and attach it to the ServicePointManager
$TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
[System.Net.ServicePointManager]::CertificatePolicy=$TrustAll
}
$response = $request.GetResponse()
$servicePoint = $request.ServicePoint
$certificate = $servicePoint.Certificate
if ($OutputFile) {
$certBytes = $certificate.Export(
[System.Security.Cryptography.X509Certificates.X509ContentType]::Cert
)
[System.IO.File]::WriteAllBytes( $OutputFile, $certBytes )
$OutputFile.Refresh()
return $OutputFile
} else {
return $certificate
}
} catch {
Write-Error "Failed to get website certificate. The error was '$_'."
return $null
}
<#
.SYNOPSIS
Retrieves the certificate used by a website.
.DESCRIPTION
Retrieves the certificate used by a website. Returns either an object or file.
.PARAMETER Uri
The URL of the website. This should start with https.
.PARAMETER OutputFile
Specifies what file to save the certificate as.
.PARAMETER UseSystemProxy
Whether or not to use the system proxy settings.
.PARAMETER UseDefaultCredentials
Whether or not to use the system logon credentials for the proxy.
.PARAMETER TrustAllCertificates
Ignore certificate errors for certificates that are expired, have a mismatched common name or are self signed.
.EXAMPLE
PS C:\\> Get-WebsiteCertificate "https://www.gmail.com" -UseSystemProxy -UseDefaultCredentials -TrustAllCertificates -OutputFile C:\\gmail.cer
.INPUTS
Does not accept pipeline input.
.OUTPUTS
System.Security.Cryptography.X509Certificates.X509Certificate, System.IO.FileInfo
#>
}
|
PowerShellCorpus/PoshCode/Import-Certificate_3.ps1
|
Import-Certificate_3.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 my\n\n .EXAMPLE\n PS C:\\> Import-Certificate -CertFile C:\\Temp\\myCert.cer -StoreNames my\n\n .EXAMPLE\n PS C:\\> Import-Certificate -Cert $certificate -StoreNames my -StoreType LocalMachine\n\n .EXAMPLE\n PS C:\\> Import-Certificate -Cert $certificate -StoreNames my -ST Machine\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: 20110428\n #Requires -Version 2.0\n .LINK\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}\n\nls "D:\\Temp\\Source" -filter "*.cet" | Import-Certificate -SN "My"
|
PowerShellCorpus/PoshCode/Invoke-SqlCmd_1.ps1
|
Invoke-SqlCmd_1.ps1
|
function Invoke-Sqlcmd2
{
param(
[string]$ServerInstance,
[string]$Database,
[string]$Query,
[Int32]$QueryTimeout=30
)
$conn=new-object System.Data.SqlClient.SQLConnection
$conn.ConnectionString="Server={0};Database={1};Integrated Security=True" -f $ServerInstance,$Database
$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)
$ds.Tables[0]
$conn.Close()
}
|
PowerShellCorpus/PoshCode/Split-Every Function.ps1
|
Split-Every Function.ps1
|
Function Split-Every($list, $count=4) {
$aggregateList = @()
$blocks = [Math]::Floor($list.Count / $count)
$leftOver = $list.Count % $count
for($i=0; $i -lt $blocks; $i++) {
$end = $count * ($i + 1) - 1
$aggregateList += @(,$list[$start..$end])
$start = $end + 1
}
if($leftOver -gt 0) {
$aggregateList += @(,$list[$start..($end+$leftOver)])
}
$aggregateList | % {"$_"}
}
|
PowerShellCorpus/PoshCode/Invoke-Inline_1.ps1
|
Invoke-Inline_1.ps1
|
#############################################################################\n##\n## Invoke-Inline\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n#############################################################################\n\n<#\n\n.SYNOPSIS\n\nDemonstrates the Add-Type cmdlet to invoke in-line C#\n\n#>\n\nSet-StrictMode -Version Latest\n\n$inlineType = Add-Type -Name InvokeInline_Inline -PassThru `\n -MemberDefinition @'\n public static int RightShift(int original, int places)\n {\n return original >> places;\n }\n'@\n\n$inlineType::RightShift(1024, 3)
|
PowerShellCorpus/PoshCode/PromptFor-File.ps1
|
PromptFor-File.ps1
|
function PromptFor-File
{
param
(
[String] $Type = "Open",
[String] $Title = "Select File",
[String] $Filename = $null,
[String[]] $FileTypes,
[switch] $RestoreDirectory,
[IO.DirectoryInfo] $InitialDirectory = $null
)
[void][System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
if ($FileTypes)
{
$FileTypes | % {
$filter += $_.ToUpper() + " Files|*.$_|"
}
$filter = $filter.TrimEnd("|")
}
else
{
$filter = "All Files|*.*"
}
switch ($Type)
{
"Open"
{
$dialog = New-Object System.Windows.Forms.OpenFileDialog
$dialog.Multiselect = $false
}
"Save"
{
$dialog = New-Object System.Windows.Forms.SaveFileDialog
}
}
$dialog.FileName = $Filename
$dialog.Title = $Title
$dialog.Filter = $filter
$dialog.RestoreDirectory = $RestoreDirectory
$dialog.InitialDirectory = $InitialDirectory.Fullname
$dialog.ShowHelp = $true
if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK)
{
return $dialog.FileName
}
else
{
return $null
}
}
|
PowerShellCorpus/PoshCode/Resolve-Aliases 1.6.ps1
|
Resolve-Aliases 1.6.ps1
|
#requires -version 2.0
## ResolveAliases Module v 1.6
########################################################################################################################
## Sample Use:
## Resolve-Aliases Script.ps1 | Set-Content Script.Resolved.ps1
## ls *.ps1 | Resolve-Aliases -Inplace
########################################################################################################################
## Version History
## 1.0 - First Version. "It worked on my sample script"
## 1.1 - Now it parses the $(...) blocks inside strings
## 1.2 - Some tweaks to spacing and indenting (I really gotta get some more test case scripts)
## 1.3 - I went back to processing the whole script at once (instead of a line at a time)
## Processing a line at a time makes it impossible to handle Here-Strings...
## I'm considering maybe processing the tokens backwards, replacing just the tokens that need it
## That would mean I could get rid of all the normalizing code, and leave the whitespace as-is
## 1.4 - Now resolves parameters too
## 1.5 - Fixed several bugs with command resolution (the ? => ForEach-Object problem)
## - Refactored the Resolve-Line filter right out of existence
## - Created a test script for validation, and
## 1.6 - Added resolving parameter ALIASES instead of just short-forms
##
## * *TODO:* Put back the -FullPath option to resolve cmdlets with their snapin path
## * *TODO:* Add an option to put #requires statements at the top for each snapin used
########################################################################################################################
function which {
PARAM( [string]$command )
# aliases, functions, cmdlets, scripts, executables, normal files
$cmds = @(Get-Command $command -EA "SilentlyContinue")
if($cmds.Count -gt 1) {
$cmd = @( $cmds | Where-Object { $_.Name -match "^$([Regex]::Escape($command))" })[0]
} else {
$cmd = $cmds[0]
}
if(!$cmd) {
$cmd = @(Get-Command "Get-$command" -EA "SilentlyContinue" | Where-Object { $_.Name -match "^Get-$([Regex]::Escape($command))" })[0]
}
if( $cmd.CommandType -eq "Alias" ) {
$cmd = which $cmd.Definition
}
return $cmd
}
Cmdlet Resolve-Aliases -ConfirmImpact low -DefaultParameterSet Files -snapin Huddled.Tests
{
Param (
#[ParameterSetName ("Text")]
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Text")]
[string]$Line
,
#[ParameterSetName ("Files")]
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Files")]
#[Alias("FullName","PSChildName","PSPath")]
[IO.FileSystemInfo]$File
,
#[ParameterSetName ("Files")]
[Parameter(Position=1, ParameterSetName="Files")]
[Switch]$InPlace
)
BEGIN {
Write-Debug $PSCmdlet.ParameterSetName
}
PROCESS {
if($PSCmdlet.ParameterSetName -eq "Files") {
if($File -is [System.IO.FileInfo]){
$Line = ((Get-Content $File) -join "`n")
} else {
throw "We can't resolve a whole folder at once yet"
}
}
$Tokens = [System.Management.Automation.PSParser]::Tokenize($Line,[ref]$null)
for($t = $Tokens.Count; $t -ge 0; $t--) {
$token = $Tokens[$t]
# DEBUG $token | fl * | out-host
switch($token.Type) {
"Command" {
$cmd = which $token.Content
Write-Debug "Command $($token.Content) => $($cmd.Name)"
#if($cmd.CommandType -eq "Alias") {
$Line = $Line.Remove( $token.Start, $token.Length ).Insert( $token.Start, $cmd.Name )
#}
}
"CommandParameter" {
Write-Debug "Parameter $($token.Content)"
for($c = $t; $c -ge 0; $c--) {
if( $Tokens[$c].Type -eq "Command" ) {
$cmd = which $Tokens[$c].Content
# if($cmd.CommandType -eq "Alias") {
# $cmd = @(which $cmd.Definition)[0]
# }
$short = $token.Content -replace "^-?","^"
Write-Debug "Parameter $short"
$parameters = $cmd.ParameterSets | Select -expand Parameters
$param = @($parameters | Where-Object { $_.Name -match $short -or $_.Aliases -match $short} | Select -Expand Name -Unique)
if($param.Count -eq 1) {
$Line = $Line.Remove( $token.Start, $token.Length ).Insert( $token.Start, "-$($param[0])" )
}
break
}
}
}
}
}
switch($PSCmdlet.ParameterSetName) {
"Text" {
$Line
}
"Files" {
switch($File.GetType()) {
"System.IO.FileInfo" {
if($InPlace) {
$Line | Set-Content $File
} else {
$Line
}
}
default { throw "We can't resolve a whole folder at once yet" }
}
}
default { throw "ParameterSet: $($PSCmdlet.ParameterSetName)" }
}
}
}
# SIG # Begin signature block
# MIIK0AYJKoZIhvcNAQcCoIIKwTCCCr0CAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUkWYGFloQGuBEm+o7XDUJCHug
# N4igggbEMIIGwDCCBKigAwIBAgIJAKpDRVMtv0LqMA0GCSqGSIb3DQEBBQUAMIHG
# MQswCQYDVQQGEwJVUzERMA8GA1UECBMITmV3IFlvcmsxEjAQBgNVBAcTCVJvY2hl
# c3RlcjEaMBgGA1UEChMRSHVkZGxlZE1hc3Nlcy5vcmcxHjAcBgNVBAsTFUNlcnRp
# ZmljYXRlIEF1dGhvcml0eTErMCkGA1UEAxMiSm9lbCBCZW5uZXR0IENlcnRpZmlj
# YXRlIEF1dGhvcml0eTEnMCUGCSqGSIb3DQEJARYYSmF5a3VsQEh1ZGRsZWRNYXNz
# ZXMub3JnMB4XDTA4MDcwMjAzNTA1OVoXDTA5MDcwMjAzNTA1OVowgcAxCzAJBgNV
# BAYTAlVTMREwDwYDVQQIEwhOZXcgWW9yazESMBAGA1UEBxMJUm9jaGVzdGVyMRow
# GAYDVQQKExFIdWRkbGVkTWFzc2VzLm9yZzEuMCwGA1UECxMlaHR0cDovL0h1ZGRs
# ZWRNYXNzZXMub3JnL0NvZGVDZXJ0LmNydDEVMBMGA1UEAxMMSm9lbCBCZW5uZXR0
# MScwJQYJKoZIhvcNAQkBFhhKYXlrdWxASHVkZGxlZE1hc3Nlcy5vcmcwggIiMA0G
# CSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDXuceXJZYARJbSTU4hoh91goVp2POx
# 6Mz/QZ6D5jcT/JNhdW2GwYQ9YUxNj8jkhXg2Ixbgb1djRGMFC/ekgRkgLxyiuhRh
# NrVE1IdV4hT4as3idqnvWOi0S3z2R2EGdebqwm2mrRmq9+DbY+FGxuNwLboWZx8Z
# roGlLLHRPzt9pabQq/Nu/FIFO+4JzZ8S5ZnEaKTm4dpD0g6j653OWYVvNXJbS/W4
# Dis5aRkHT1q1Gp02dYHh3NTKrpv1nus9BTDlJRwmU/FgGLNQIvnRwqVoBh+I7tVq
# NIRnI1RpDTGyFEohbH8mRlwq3z4ijtb6j9boUJEqd8hQshzUMcALoTIR1tN/5APX
# u2j4OqGFESM/OG0i2hLKbnP81u581aZT1BfVfQxvDuWrFiurMxllVGY1NvKkXwc8
# aOZktqMQWbWAs2bxZqERbOILXOmkL/mvPdy+e5yQveriHAhrDONu7a79ylreMHBR
# XrmYJTK2G/aHvB5vrXjMPw0TBeph0sM2BN2eVzenAAMsIiGlXPXvtKrpKRiBdx5f
# 9SV5dyUG2tR8ANDuc2AMB8FKICuMUd8Sx96p4FOBQhXhvF/RZcWZIW5o+A4sHvYE
# /s4oiX7LxGrQK2abNiCVs9BDLI/EcSs/TP+ZskBqu7Qb+AVeevoY3T7skihuyC/l
# h7EwqjfNpVQ9UwIDAQABo4G0MIGxMB0GA1UdDgQWBBTgB9XYJV/kJAvnkWmKDHsh
# 7Cn3PzAfBgNVHSMEGDAWgBQ+5x4ah0JG0o4iUj0TebNd4MCVxTAJBgNVHRMEAjAA
# MBEGCWCGSAGG+EIBAQQEAwIEEDAWBgNVHSUBAf8EDDAKBggrBgEFBQcDAzALBgNV
# HQ8EBAMCBsAwLAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRp
# ZmljYXRlMA0GCSqGSIb3DQEBBQUAA4ICAQAw8B6+s48CZZo5h5tUeKV7OWNXKRG7
# xkyavMkXpEi58BSLutmE3O7smc3uvu3TdCXENNUlGrcq/KQ8y2eEI8QkHgT99VgX
# r+v5xu2KnJXiOOIxi65EZybRFFFaGJNodTcrK8L/tY6QLF02ilOlEgfcc1sV/Sj/
# r60JS1iXIMth7nYZVjtWeYXOrsd+I+XwJuoVNJlELNdApOU4ZVNrPEuV+QRNMimj
# lqIOv2tn9TDdNGUqaOCI0w+a1XQvapEPWETfQK+o9pvYINTswGDjNeb7Xz8ar2JB
# 9IVs2xtxDohHB75kyRrlY1hkoY5j12ZhWOlm0L9Ks6XvmMtXJIjj0/m9Z+3s+9p6
# U7IYjz5NnzmDvtNUn2y9zxB/rUx/JqoUO3BWRKiLX0lvGRWJlzFr9978kH2SXxAD
# rsKfzB7YZzMh9hZkGNlJf4T+HTB/OXG1jyfkyqQvhNB/tDAaq+ejDtKNBF4hMS7K
# Z0B4vagIxFwMuTiei4UaOjrGzeCfT9w1Bmj6uLJme5ydQVM0V7z3Z6jR3LVq4c4s
# Y1dfPmYlw62cbyV9Kb/H2hYw5K0OMX60LfLQZOzIPzAeRJ87NufwZnC1afxsSCmU
# bvSx4kCMgRZMXw+d1SHRhh7z+06YTQjnUMmtTGt7DtUkU6I8LKEWF/mAzF7sq/7P
# AyhPsbu91X5FuzGCA3YwggNyAgEBMIHUMIHGMQswCQYDVQQGEwJVUzERMA8GA1UE
# CBMITmV3IFlvcmsxEjAQBgNVBAcTCVJvY2hlc3RlcjEaMBgGA1UEChMRSHVkZGxl
# ZE1hc3Nlcy5vcmcxHjAcBgNVBAsTFUNlcnRpZmljYXRlIEF1dGhvcml0eTErMCkG
# A1UEAxMiSm9lbCBCZW5uZXR0IENlcnRpZmljYXRlIEF1dGhvcml0eTEnMCUGCSqG
# SIb3DQEJARYYSmF5a3VsQEh1ZGRsZWRNYXNzZXMub3JnAgkAqkNFUy2/QuowCQYF
# Kw4DAhoFAKB4MBgGCisGAQQBgjcCAQwxCjAIoAKAAKECgAAwGQYJKoZIhvcNAQkD
# MQwGCisGAQQBgjcCAQQwHAYKKwYBBAGCNwIBCzEOMAwGCisGAQQBgjcCARUwIwYJ
# KoZIhvcNAQkEMRYEFOkXSmE2w+qbsv8RvTQvXPP19B/4MA0GCSqGSIb3DQEBAQUA
# BIICABNtvm3OA0q9Ak6rYuhQzUsUd+3QFEvU7wSxDP+EaMgNbCTIZ4+AAYkbK5sK
# g+k2GSxT3qWMjOsRho8tCoKj2cpXW5GTjnO0SRYK2G/mWnxkTIF/uhtwA1dadWHV
# bwN3LzfYzJC/rEQoTIpYwDfB2+3Kjz3BPugvcwPGhAnMl9sTV0bNcl89HfA/YPz1
# pOU+aYCWA5r74QMUYyOquDpWizaZLWHJoauBXjkamx5lGzcmMDiDf98fLAuqEoXo
# G6B9oxr5YaCK2xk0H581lybciS7jTzpXoYCrOK9pp2iPN3JbwDhN9v0foSo/cXh5
# uHQiYJVesoQkcrixp1QjJQW95k22qotTP1FNEubuRyTmTRlWqJOdcjl80e9qQIZF
# lAKDlPFFWWWraZwbMPGpZO8Q/50cmg5ypT5cVJvVvuZs+w2maKq5lUmH22kWwtdB
# +HQD2E9HWMs1Ya58W2KwO7hEWFc1iLdslasqsEfCQUkYk/HY70FDgg0n+pNXj9Wg
# /gn+KTOBZMMMLjSoI6uVyLqiWVIsf3rsCfbPCxTxtKxgvdk9QFxK6GezMgZ0tg89
# 2P4xBuGAjmbck1440d/ZK6cgkb4ZVAWkgo+uI3wrnrhNe7lAPdGbgdihhEFc2ikc
# CWztVjQcFr77QmUgnwQOFJifKJdXvTFsH2OtM7wB6H80ys76
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Deploy VM with Static IP_4.ps1
|
Deploy VM with Static IP_4.ps1
|
# 1. Create a simple customizations spec:
$custSpec = New-OSCustomizationSpec -Type NonPersistent -OSType Windows `
-OrgName “My Organization” -FullName “MyVM” -Domain “MyDomain” `
–DomainUsername “user” –DomainPassword “password”
# 2. Modify the default network customization settings:
$custSpec | Get-OSCustomizationNicMapping | Set-OSCustomizationNicMapping `
-IpMode UseStaticIP -IpAddress 192.168.121.228 -SubnetMask 255.255.248.0 `
-Dns 192.168.108.1 -DefaultGateway 192.168.108.1
# 3. Deploy a VM from a template using the newly created customization:
New-VM -Name “MyNewVM” -Template $template -VMHost $vmHost `
-OSCustomizationSpec $custSpec
|
PowerShellCorpus/PoshCode/New-SqlConnectionString.ps1
|
New-SqlConnectionString.ps1
|
function New-SqlConnectionString {
#.Synopsis
# Create a new SQL ConnectionString
#.Description
# Builds a SQL ConnectionString using SQLConnectionStringBuilder with the supplied parameters
#.Example
# New-SqlConnectionString -Server DBServer12 -Database NorthWind -IntegratedSecurity -MaxPoolSize 4 -Pooling
#.Example
# New-SqlConnectionString -Server DBServer4 -Database NorthWind -Login SA -Password ""
[CmdletBinding(DefaultParameterSetName='Default')]
PARAM(
# A full-blown connection string to start from
[String]${ConnectionString},
# The name of the application associated with the connection string.
[String]${ApplicationName},
# Whether asynchronous processing is allowed by the connection created by using this connection string.
[Switch]${AsynchronousProcessing},
# The name of the primary data file. This includes the full path name of an attachable database.
[String]${AttachDBFilename},
# The length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error.
[String]${ConnectTimeout},
# Whether a client/server or in-process connection to SQL Server should be made.
[Switch]${ContextConnection},
# The SQL Server Language record name.
[String]${CurrentLanguage},
# The name and/or network address of the instance of SQL Server to connect to.
[Parameter(Position=0)]
[Alias("Server","Address")]
[String]${DataSource},
# Whether SQL Server uses SSL encryption for all data sent between the client and server if the server has a certificate installed.
[Switch]${Encrypt},
# Whether the SQL Server connection pooler automatically enlists the connection in the creation thread's current transaction context.
[Switch]${Enlist},
# The name or address of the partner server to connect to if the primary server is down.
[String]${FailoverPartner},
# The name of the database associated with the connection.
[Parameter(Position=1)]
[Alias("Database")]
[String]${InitialCatalog},
# Whether User ID and Password are specified in the connection (when false) or whether the current Windows account credentials are used for authentication (when true).
[Switch]${IntegratedSecurity},
# The minimum time, in seconds, for the connection to live in the connection pool before being destroyed.
[Int]${LoadBalanceTimeout},
# The maximum number of connections allowed in the connection pool for this specific connection string.
[Int]${MaxPoolSize},
# The minimum number of connections allowed in the connection pool for this specific connection string.
[Int]${MinPoolSize},
# Whether multiple active result sets can be associated with the associated connection.
[Switch]${MultipleActiveResultSets},
# The name of the network library used to establish a connection to the SQL Server.
[String]${NetworkLibrary},
# The size in bytes of the network packets used to communicate with an instance of SQL Server.
[Int]${PacketSize},
# The password for the SQL Server account.
[AllowEmptyString()]
[String]${Password},
# Whether security-sensitive information, such as the password, is returned as part of the connection if the connection is open or has ever been in an open state.
[Switch]${PersistSecurityInfo},
# Whether the connection will be pooled or explicitly opened every time that the connection is requested.
[Switch]${Pooling},
# Whether replication is supported using the connection.
[Switch]${Replication},
# How the connection maintains its association with an enlisted System.Transactions transaction.
[String]${TransactionBinding},
# Whether the channel will be encrypted while bypassing walking the certificate chain to validate trust.
[Switch]${TrustServerCertificate},
# The type system the application expects.
[String]${TypeSystemVersion},
# The user ID to be used when connecting to SQL Server.
[Alias("UserName","Login")]
[String]${UserID},
# Whether to redirect the connection from the default SQL Server Express instance to a runtime-initiated instance running under the account of the caller.
[Switch]${UserInstance},
# The name of the workstation connecting to SQL Server.
[String]${WorkstationID},
# Whether to return the SqlConnectionStringBuilder for further modification instead of just a connection string.
[Switch]${AsBuilder}
)
BEGIN {
if(!( 'System.Data.SqlClient.SqlConnectionStringBuilder' -as [Type] )) {
$null = [Reflection.Assembly]::Load( 'System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' )
}
}
PROCESS {
$Builder = New-Object System.Data.SqlClient.SqlConnectionStringBuilder -Property $PSBoundParameters
if($AsBuilder) {
Write-Output $Builder
} else {
Write-Output $Builder.ToString()
}
}
}
|
PowerShellCorpus/PoshCode/UIAutomation _1.9.ps1
|
UIAutomation _1.9.ps1
|
## UI Automation v 1.10 -- REQUIRES the Reflection module
##
# WASP 2.0 is getting closer, but this is still just a preview:
# -- a lot of the commands have weird names still because they're being generated ignorantly
# -- eg: Invoke-Toggle.Toggle and Invoke-Invoke.Invoke
# v 1.7 - Fixes using multiple checks like: Select-UIElement Red: Edit
# v 1.8 - Fixes .Net version problems: specifying CSharpVersion3 when in PowerShell 2
# v 1.9 - Fix bug with Select-UIElement by processName / processId
# v 1.10 - Add the super-flexible but super-user-only -PropertyValue parameter to Select-UIElement
# IF your PowerShell is running in .Net 4
if($PSVersionTable.CLRVersion -gt "4.0") {
$Language = "CSharp" # Version 4
Add-Type -AssemblyName "UIAutomationClient, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Add-Type -AssemblyName "UIAutomationTypes, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
} else {
# In PowerShell 2, we need to use the .Net 3 version
$Language = "CSharpVersion3"
Add-Type -AssemblyName "UIAutomationClient, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Add-Type -AssemblyName "UIAutomationTypes, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
}
$SWA = "System.Windows.Automation"
# Add-Accelerator InvokePattern "$SWA.InvokePattern" -EA SilentlyContinue
# Add-Accelerator ExpandPattern "$SWA.ExpandCollapsePattern" -EA SilentlyContinue
# Add-Accelerator WindowPattern "$SWA.WindowPattern" -EA SilentlyContinue
# Add-Accelerator TransformPattern "$SWA.TransformPattern" -EA SilentlyContinue
# Add-Accelerator ValuePattern "$SWA.ValuePattern" -EA SilentlyContinue
# Add-Accelerator TextPattern "$SWA.TextPattern" -EA SilentlyContinue
# This is what requires the Reflection module:
Add-Accelerator Automation "$SWA.Automation" -EA SilentlyContinue
Add-Accelerator AutomationElement "$SWA.AutomationElement" -EA SilentlyContinue
Add-Accelerator TextRange "$SWA.Text.TextPatternRange" -EA SilentlyContinue
##### Conditions
Add-Accelerator Condition "$SWA.Condition" -EA SilentlyContinue
Add-Accelerator AndCondition "$SWA.AndCondition" -EA SilentlyContinue
Add-Accelerator OrCondition "$SWA.OrCondition" -EA SilentlyContinue
Add-Accelerator NotCondition "$SWA.NotCondition" -EA SilentlyContinue
Add-Accelerator PropertyCondition "$SWA.PropertyCondition" -EA SilentlyContinue
##### IDentifiers
Add-Accelerator AutoElementIds "$SWA.AutomationElementIdentifiers" -EA SilentlyContinue
Add-Accelerator TransformIds "$SWA.TransformPatternIdentifiers" -EA SilentlyContinue
##### Patterns:
$patterns = Get-Type -Assembly UIAutomationClient -Base System.Windows.Automation.BasePattern
#| Where { $_ -ne [System.Windows.Automation.InvokePattern] }
Add-Type -Language $Language -ReferencedAssemblies UIAutomationClient, UIAutomationTypes -TypeDefinition @"
using System;
using System.ComponentModel;
using System.Management.Automation;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Windows.Automation;
using System.Runtime.InteropServices;
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class StaticFieldAttribute : ArgumentTransformationAttribute {
private Type _class;
public override string ToString() {
return string.Format("[StaticField(OfClass='{0}')]", OfClass.FullName);
}
public override Object Transform( EngineIntrinsics engineIntrinsics, Object inputData) {
if(inputData is string && !string.IsNullOrEmpty(inputData as string)) {
System.Reflection.FieldInfo field = _class.GetField(inputData as string, BindingFlags.Static | BindingFlags.Public);
if(field != null) {
return field.GetValue(null);
}
}
return inputData;
}
public StaticFieldAttribute( Type ofClass ) {
OfClass = ofClass;
}
public Type OfClass {
get { return _class; }
set { _class = value; }
}
}
public static class UIAutomationHelper {
[DllImport ("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr FindWindow (string lpClassName, string lpWindowName);
[DllImport ("user32.dll", CharSet = CharSet.Auto)]
static extern bool AttachThreadInput (int idAttach, int idAttachTo, bool fAttach);
[DllImport ("user32.dll", CharSet = CharSet.Auto)]
static extern int GetWindowThreadProcessId (IntPtr hWnd, IntPtr lpdwProcessId);
[DllImport ("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SetForegroundWindow (IntPtr hWnd);
public static AutomationElement RootElement {
get { return AutomationElement.RootElement; }
}
///<synopsis>Using Win32 to set foreground window because AutomationElement.SetFocus() is unreliable</synopsis>
public static bool SetForeground(this AutomationElement element)
{
if(element == null) {
throw new ArgumentNullException("element");
}
// Get handle to the element
IntPtr other = FindWindow (null, element.Current.Name);
// // Get the Process ID for the element we are trying to
// // set as the foreground element
// int other_id = GetWindowThreadProcessId (other, IntPtr.Zero);
//
// // Get the Process ID for the current process
// int this_id = GetWindowThreadProcessId (Process.GetCurrentProcess().Handle, IntPtr.Zero);
//
// // Attach the current process's input to that of the
// // given element. We have to do this otherwise the
// // WM_SETFOCUS message will be ignored by the element.
// bool success = AttachThreadInput(this_id, other_id, true);
// Make the Win32 call
IntPtr previous = SetForegroundWindow(other);
return !IntPtr.Zero.Equals(previous);
}
}
"@
## TODO: Write Get-SupportedPatterns or rather ...
## Get-SupportedFunctions (to return the names of the functions for the supported patterns)
## TODO: Support all the "Properties" too
## TODO: Figure out why Notepad doesn't support SetValue
## TODO: Figure out where the menus support went
ForEach($pattern in $patterns){
$pattern | Add-Accelerator
$PatternFullName = $pattern.FullName
$PatternName = $Pattern.Name -Replace "Pattern","."
$newline = "`n`t`t"
New-Item "Function:ConvertTo-$($Pattern.Name)" -Value "
param(
[Parameter(ValueFromPipeline=`$true)][Alias('Element','AutomationElement')][AutomationElement]`$InputObject
)
process {
trap {
if(`$_.Exception.Message -like '*Unsupported Pattern.*') {
Write-Error `"Cannot get ```"$($Pattern.Name)```" from that AutomationElement, `$(`$_)` You should try one of: `$(`$InputObject.GetSupportedPatterns()|%{```"'```" + (`$_.ProgrammaticName.Replace(```"PatternIdentifiers.Pattern```",```"```")) + ```"Pattern'```"})`"; continue;
}
}
Write-Output `$InputObject.GetCurrentPattern([$PatternFullName]::Pattern).Current
}"
$pattern.GetMethods() |
Where { $_.DeclaringType -eq $_.ReflectedType -and !$_.IsSpecialName } |
ForEach {
$FunctionName = "Function:Invoke-$PatternName$($_.Name)"
$Position = 1
if (test-path $FunctionName) { remove-item $FunctionName }
$Parameters = @("$newline[Parameter(ValueFromPipeline=`$true)]"+
"$newline[Alias('Parent','Element','Root','AutomationElement')]"+
"$newline[AutomationElement]`$InputObject"
) +
@(
"[Parameter()]$newline[Switch]`$Passthru"
) +
@($_.GetParameters() | % { "[Parameter(Position=$($Position; $Position++))]$newline[$($_.ParameterType.FullName)]`$$($_.Name)" })
$Parameters = $Parameters -Join "$newline,$newline"
$ParameterValues = '$' + (@($_.GetParameters() | Select-Object -Expand Name ) -Join ', $')
$definition = @"
param(
$Parameters
)
process {
## trap { Write-Warning "`$(`$_)"; break }
`$pattern = `$InputObject.GetCurrentPattern([$PatternFullName]::Pattern)
if(`$pattern) {
`$Pattern.$($_.Name)($(if($ParameterValues.Length -gt 1){ $ParameterValues }))
}
if(`$passthru) {
`$InputObject
}
}
"@
trap {
Write-Warning $_
Write-Host $definition -fore cyan
}
New-Item $FunctionName -value $definition
}
$pattern.GetProperties() |
Where { $_.DeclaringType -eq $_.ReflectedType -and $_.Name -notmatch "Cached|Current"} |
ForEach {
$FunctionName = "Function:Get-$PatternName$($_.Name)".Trim('.')
if (test-path $FunctionName) { remove-item $FunctionName }
New-Item $FunctionName -value "
param(
[Parameter(ValueFromPipeline=`$true)]
[AutomationElement]`$AutomationElement
)
process {
trap { Write-Warning `"$PatternFullName `$_`"; continue }
`$pattern = `$AutomationElement.GetCurrentPattern([$PatternFullName]::Pattern)
if(`$pattern) {
`$pattern.'$($_.Name)'
}
}"
}
## So far this seems to be restricted to Text (DocumentRange) elements
$pattern.GetFields() |
Where { $_.FieldType.Name -like "*TextAttribute"} |
ForEach {
$FunctionName = "Function:Get-Text$($_.Name -replace 'Attribute')"
if (test-path $FunctionName) { remove-item $FunctionName }
New-Item $FunctionName -value "
param(
[Parameter(ValueFromPipeline=`$true)]
[AutomationElement]`$AutomationElement
)
process {
trap { Write-Warning `"$PatternFullName `$_`"; continue }
`$AutomationElement.GetAttributeValue([$PatternFullName]::$($_.Name))
}"
}
$pattern.GetFields() | Where { $_.FieldType -eq [System.Windows.Automation.AutomationEvent] } |
ForEach {
$Name = $_.Name -replace 'Event$'
$FunctionName = "Function:Register-$($PatternName.Trim('.'))$Name"
if (test-path $FunctionName) { remove-item $FunctionName }
New-Item $FunctionName -value "
param(
[Parameter(ValueFromPipeline=`$true)]
[AutomationElement]`$AutomationElement
,
[System.Windows.Automation.TreeScope]`$TreeScope = 'Element'
,
[ScriptBlock]`$EventHandler
)
process {
trap { Write-Warning `"$PatternFullName `$_`"; continue }
[Automation]::AddAutomationEventHandler( [$PatternFullName]::$Name, `$AutomationElement, `$TreeScope, `$EventHandler )
}"
}
}
$FalseCondition = [Condition]::FalseCondition
$TrueCondition = [Condition]::TrueCondition
Add-Type -AssemblyName System.Windows.Forms
Add-Accelerator SendKeys System.Windows.Forms.SendKeys -EA SilentlyContinue
$AutomationProperties = [system.windows.automation.automationelement+automationelementinformation].GetProperties()
Set-Alias Invoke-UIElement Invoke-Invoke.Invoke
function formatter { END {
$input | Format-Table @{l="Text";e={$_.Text.SubString(0,25)}}, ClassName, FrameworkId -Auto
}}
function Get-ClickablePoint {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
)
process {
$InputObject.GetClickablePoint()
}
}
function Show-Window {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
,
[Parameter()]
[Switch]$Passthru
)
process {
Set-UIFocus $InputObject
if($passthru) {
$InputObject
}
}
}
function Set-UIFocus {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
,
[Parameter()]
[Switch]$Passthru
)
process {
try {
[UIAutomationHelper]::SetForeground( $InputObject )
$InputObject.SetFocus()
} catch {
Write-Verbose "SetFocus fail, trying SetForeground"
}
if($passthru) {
$InputObject
}
}
}
function Send-UIKeys {
[CmdletBinding()]
param(
[Parameter(Position=0)]
[string]$Keys
,
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
,
[Parameter()]
[Switch]$Passthru
,
[Parameter()]
[Switch]$Async
)
process {
if(!$InputObject.Current.IsEnabled)
{
Write-Warning "The Control is not enabled!"
}
if(!$InputObject.Current.IsKeyboardFocusable)
{
Write-Warning "The Control is not focusable!"
}
Set-UIFocus $InputObject
if($Async) {
[SendKeys]::Send( $Keys )
} else {
[SendKeys]::SendWait( $Keys )
}
if($passthru) {
$InputObject
}
}
}
function Set-UIText {
[CmdletBinding()]
param(
[Parameter(Position=0)]
[string]$Text
,
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
,
[Parameter()]
[Switch]$Passthru
)
process {
if(!$InputObject.Current.IsEnabled)
{
Write-Warning "The Control is not enabled!"
}
if(!$InputObject.Current.IsKeyboardFocusable)
{
Write-Warning "The Control is not focusable!"
}
$valuePattern = $null
if($InputObject.TryGetCurrentPattern([ValuePattern]::Pattern,[ref]$valuePattern)) {
Write-Verbose "Set via ValuePattern!"
$valuePattern.SetValue( $Text )
}
elseif($InputObject.Current.IsKeyboardFocusable)
{
Set-UIFocus $InputObject
[SendKeys]::SendWait("^{HOME}");
[SendKeys]::SendWait("^+{END}");
[SendKeys]::SendWait("{DEL}");
[SendKeys]::SendWait( $Text )
}
if($passthru) {
$InputObject
}
}
}
function Select-UIElement {
[CmdletBinding(DefaultParameterSetName="FromParent")]
PARAM (
[Parameter(ParameterSetName="FromWindowHandle", Position="0", Mandatory=$true)]
[Alias("MainWindowHandle","hWnd","Handle","Wh")]
[IntPtr[]]$WindowHandle=[IntPtr]::Zero
,
[Parameter(ParameterSetName="FromPoint", Position="0", Mandatory=$true)]
[System.Windows.Point[]]$Point
,
[Parameter(ParameterSetName="FromParent", ValueFromPipeline=$true, Position=100)]
[System.Windows.Automation.AutomationElement]$Parent = [UIAutomationHelper]::RootElement
,
[Parameter(ParameterSetName="FromParent", Position="0")]
[Alias("WindowName")]
[String[]]$Name
,
[Parameter(ParameterSetName="FromParent", Position="1")]
[Alias("Type","Ct")]
[System.Windows.Automation.ControlType]
[StaticField(([System.Windows.Automation.ControlType]))]$ControlType
,
[Parameter(ParameterSetName="FromParent")]
[Alias("UId")]
[String[]]$AutomationId
,
## Removed "Id" alias to allow get-process | Select-Window pipeline to find just MainWindowHandle
[Parameter(ParameterSetName="FromParent", ValueFromPipelineByPropertyName=$true )]
[Alias("Id")]
[Int[]]$PID
,
[Parameter(ParameterSetName="FromParent")]
[Alias("Pn")]
[String[]]$ProcessName
,
[Parameter(ParameterSetName="FromParent")]
[Alias("Cn")]
[String[]]$ClassName
,
[switch]$Recurse
,
[switch]$Bare,
[Parameter(ParameterSetName="FromParent")]
[Alias("Pv")]
[Hashtable]$PropertyValue
)
process {
Write-Debug "Parameters Found"
Write-Debug ($PSBoundParameters | Format-Table | Out-String)
$search = "Children"
if($Recurse) { $search = "Descendants" }
$condition = [System.Windows.Automation.Condition]::TrueCondition
Write-Verbose $PSCmdlet.ParameterSetName
switch -regex ($PSCmdlet.ParameterSetName) {
"FromWindowHandle" {
Write-Verbose "Finding from Window Handle $HWnd"
$Element = $(
foreach($hWnd in $WindowHandle) {
[System.Windows.Automation.AutomationElement]::FromHandle( $hWnd )
}
)
continue
}
"FromPoint" {
Write-Verbose "Finding from Point $Point"
$Element = $(
foreach($pt in $Point) {
[System.Windows.Automation.AutomationElement]::FromPoint( $pt )
}
)
continue
}
"FromParent" {
Write-Verbose "Finding from Parent!"
## [System.Windows.Automation.Condition[]]$conditions = [System.Windows.Automation.Condition]::TrueCondition
[ScriptBlock[]]$filters = @()
if($AutomationId) {
[System.Windows.Automation.Condition[]]$current = $(
foreach($aid in $AutomationId) {
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::AutomationIdProperty), $aid
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
if($PID) {
[System.Windows.Automation.Condition[]]$current = $(
foreach($p in $PID) {
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ProcessIdProperty), $p
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
if($ProcessName) {
if($ProcessName -match "\\?|\\*|\\[") {
[ScriptBlock[]]$filters += { $(foreach($p in $ProcessName){ (Get-Process -id $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ProcessIdProperty)).ProcessName -like $p }) -contains $true }
} else {
[System.Windows.Automation.Condition[]]$current = $(
foreach($p in Get-Process -Name $ProcessName) {
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ProcessIdProperty), $p.id
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
}
if($Name) {
Write-Verbose "Name: $Name"
if($Name -match "\\?|\\*|\\[") {
[ScriptBlock[]]$filters += { $(foreach($n in $Name){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::NameProperty) -like $n }) -contains $true }
} else {
[System.Windows.Automation.Condition[]]$current = $(
foreach($n in $Name){
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::NameProperty), $n, "IgnoreCase"
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
}
if($ClassName) {
if($ClassName -match "\\?|\\*|\\[") {
[ScriptBlock[]]$filters += { $(foreach($c in $ClassName){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ClassNameProperty) -like $c }) -contains $true }
} else {
[System.Windows.Automation.Condition[]]$current = $(
foreach($c in $ClassName){
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ClassNameProperty), $c, "IgnoreCase"
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
}
if($ControlType) {
if($ControlType -match "\\?|\\*|\\[") {
[ScriptBlock[]]$filters += { $(foreach($c in $ControlType){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ControlTypeProperty) -like $c }) -contains $true }
} else {
[System.Windows.Automation.Condition[]]$current = $(
foreach($c in $ControlType){
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ControlTypeProperty), $c
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
}
if($PropertyValue) {
$Property = $PropertyValue.Keys[0]
$Value = $PropertyValue.Values[0]
if($Value -match "\\?|\\*|\\[") {
[ScriptBlock[]]$filters += { $(foreach($c in $PropertyValue.GetEnumerator()){
$_.GetCurrentPropertyValue(
[System.Windows.Automation.AutomationElement].GetField(
$c.Key).GetValue(([system.windows.automation.automationelement]))
) -like $c.Value }) -contains $true }
} else {
[System.Windows.Automation.Condition[]]$current = $(
foreach($c in $PropertyValue.GetEnumerator()){
new-object System.Windows.Automation.PropertyCondition (
[System.Windows.Automation.AutomationElement].GetField(
$c.Key).GetValue(([system.windows.automation.automationelement]))), $c.Value
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
}
if($conditions.Length -gt 1) {
[System.Windows.Automation.Condition]$condition = New-Object System.Windows.Automation.AndCondition $conditions
} elseif($conditions) {
[System.Windows.Automation.Condition]$condition = $conditions[0]
} else {
[System.Windows.Automation.Condition]$condition = [System.Windows.Automation.Condition]::TrueCondition
}
If($VerbosePreference -gt "SilentlyContinue") {
function Write-Condition {
param([Parameter(ValueFromPipeline=$true)]$condition, $indent = 0)
process {
Write-Debug ($Condition | fl * | Out-String)
if($condition -is [System.Windows.Automation.AndCondition] -or $condition -is [System.Windows.Automation.OrCondition]) {
Write-Verbose ((" "*$indent) + $Condition.GetType().Name )
$condition.GetConditions().GetEnumerator() | Write-Condition -Indent ($Indent+4)
} elseif($condition -is [System.Windows.Automation.PropertyCondition]) {
Write-Verbose ((" "*$indent) + $Condition.Property.ProgrammaticName + " = '" + $Condition.Value + "' (" + $Condition.Flags + ")")
} else {
Write-Verbose ((" "*$indent) + $Condition.GetType().Name + " where '" + $Condition.Value + "' (" + $Condition.Flags + ")")
}
}
}
Write-Verbose "CONDITIONS ============="
$global:LastCondition = $condition
foreach($c in $condition) {
Write-Condition $c
}
Write-Verbose "============= CONDITIONS"
}
if($filters.Count -gt 0) {
$Element = $Parent.FindAll( $search, $condition ) | Where-Object { $item = $_; foreach($f in $filters) { $item = $item | Where $f }; $item }
} else {
$Element = $Parent.FindAll( $search, $condition )
}
}
}
Write-Verbose "Element Count: $(@($Element).Count)"
if($Element) {
foreach($el in $Element) {
if($Bare) {
Write-Output $el
} else {
$e = New-Object PSObject $el
foreach($prop in $e.GetSupportedProperties() | Sort ProgrammaticName)
{
## TODO: make sure all these show up: [System.Windows.Automation.AutomationElement] | gm -sta -type Property
$propName = [System.Windows.Automation.Automation]::PropertyName($prop)
Add-Member -InputObject $e -Type ScriptProperty -Name $propName -Value ([ScriptBlock]::Create( "`$this.GetCurrentPropertyValue( [System.Windows.Automation.AutomationProperty]::LookupById( $($prop.Id) ))" )) -EA 0
}
foreach($patt in $e.GetSupportedPatterns()| Sort ProgrammaticName)
{
Add-Member -InputObject $e -Type ScriptProperty -Name ($patt.ProgrammaticName.Replace("PatternIdentifiers.Pattern","") + "Pattern") -Value ([ScriptBlock]::Create( "`$this.GetCurrentPattern( [System.Windows.Automation.AutomationPattern]::LookupById( '$($patt.Id)' ) )" )) -EA 0
}
Write-Output $e
}
}
}
}
}
Export-ModuleMember -cmdlet * -Function * -Alias *
# [Cmdlet(VerbsCommon.Add, "UIAHandler")]
# public class AddUIAHandlerCommand : PSCmdlet
# {
# private AutomationElement _parent = AutomationElement.RootElement;
# private AutomationEvent _event = WindowPattern.WindowOpenedEvent;
# private TreeScope _scope = TreeScope.Children;
#
# [Parameter(ValueFromPipeline = true)]
# [Alias("Parent", "Element", "Root")]
# public AutomationElement InputObject { set { _parent = value; } get { return _parent; } }
#
# [Parameter()]
# public AutomationEvent Event { set { _event = value; } get { return _event; } }
#
# [Parameter()]
# public AutomationEventHandler ScriptBlock { set; get; }
#
# [Parameter()]
# public SwitchParameter Passthru { set; get; }
#
# [Parameter()]
# public TreeScope Scope { set { _scope = value; } get { return _scope; } }
#
# protected override void ProcessRecord()
# {
# Automation.AddAutomationEventHandler(Event, InputObject, Scope, ScriptBlock);
#
# if (Passthru.ToBool())
# {
# WriteObject(InputObject);
# }
#
# base.ProcessRecord();
# }
# }
|
PowerShellCorpus/PoshCode/PowerOracle.ps1
|
PowerOracle.ps1
|
# Load assembly
[System.Reflection.Assembly]::LoadWithPartialName("Oracle.DataAccess")
# Connection information
$ConnectionString = "Data Source=your_server/sid;User Id=user_name;Password=password"
#Standard SQL Query Syntax
$QueryString = "SELECT * FROM table_name WHERE #Case"
$OracleConnection = New-Object Oracle.DataAccess.Client.OracleConnection($ConnectionString)
$dtSet = New-Object System.Data.DataSet
$OracleAdapter = New-Object Oracle.DataAccess.Client.OracleDataAdapter($QueryString, $OracleConnection)
[void]$OracleAdapter.Fill($dtSet)
|
PowerShellCorpus/PoshCode/Note, open Notepad++_1.ps1
|
Note, open Notepad++_1.ps1
|
# Limited Notepad++ support with the simple call 'Note' So long Notepad!
function Note
{
<#
.Synopsis
Opens Notepad++
.Description
Opens Notepad++
.Parameter File
File name(s) to open, accepts wildcards. (absolute or relative path name)
.Parameter MultiInstance
Launch another Notepad++ instance
.Parameter PluginsOff
Launch Notepad++ without plugins, good for debugging cause
of a crash, Notepad++ or plugins?
.Parameter Language
Launch Notepad++ by applying indicated language to the file to open.
.Parameter SessionOff
Launch Notepad++ without any session. (without loading
files opened when notepad++ was last in use.)
.Parameter TabBarOff
Launch Notepad++ without tabbar.
.Example
Note -Language xml -MultiInstance -TabBarOff -File C:\\Script\\MyScript.ps1
Opens file 'MyScript.ps1' as xml file in a new instance
of Notepad++ with no tab bar.
.Link
http://notepad-plus.sourceforge.net/uk/cmdLine-HOWTO.php
.Link
http://notepad-plus.sourceforge.net/
.Link
http://poshcode.org/notepad++lexer/
.Link
http://sourceforge.net/apps/mediawiki/notepad-plus/index.php?title=Command_Line_Switches
.Notes
Most of this script is courtesy of Joel Bennet @ PoshCode. Added a couple features to handle the lack
of a -File parameter as well as creation of a file.
#>
[CmdletBinding()]
Param
(
[Parameter(ValueFromPipeline=$true,Position=1)]
[Alias("FileName","LitteralPath","Path")]
[string[]]
$File
,
[Parameter()]
[string]$Language
,
[Parameter()]
[Switch]$MultiInstance
,
[Parameter()]
[Switch]$PluginsOff
,
[Parameter()]
[Switch]$SessionOff
,
[Parameter()]
[Switch]$TabBarOff
)
BEGIN
{
$NPP = "C:\\Program Files (x86)\\Notepad++\\Notepad++.exe"
$Param = @(
if($Language) {"-l$Language"}
if($MultiInstance) {"-multiInst"}
if($PluginsOff) {"-noPlugins"}
if($SessionOff) {"-nosession"}
if($TabBarOff) {"-notabbar"}
" "
)-join " "
}
Process
{
###
# No -File parameter was received, opens Notepad++ anyway
###
if($File -eq $null){
Write-Host "hmmm....`nOpening Notepad++" -foregroundcolor "green"
Write-Verbose "$NPP $param"
[void][Diagnostics.Process]::Start($NPP,$param).WaitForInputIdle(500)
}elseif(Test-Path $File){
ForEach($Path in $File){
ForEach($f in Convert-Path (Resolve-Path $Path)){
$parameters = $param + """" + $f + """"
Write-Verbose "$NPP $parameters"
[void][Diagnostics.Process]::Start($NPP,$parameters).WaitForInputIdle(500)
}
}
###
# A nonexistent -File parameter was received.
# Query user to attempt creation or not.
###
}elseif(!(Test-Path $File)){
$Title = "File did not exist."
$Message = "Would you like to attempt to create?"
$Yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes",`
"Passes file name to Notepad++ to attempt creation."
$No = New-Object System.Management.Automation.Host.ChoiceDescription "&No",`
"Does not pass file name to Notepad++. Face it, you misspelled something =("
$Options = [System.Management.Automation.Host.ChoiceDescription[]]($Yes, $No)
$Result = $Host.UI.PromptForChoice($Title, $Message, $Options, 0)
Switch($Result){
0{
$Parameters = $Param + $File
Write-Verbose "$NPP $Parameters"
[void][Diagnostics.Process]::Start($NPP,$Parameters).WaitForInputIdle(500)
}
1{
Write-Host "Yes, well..." -foregroundcolor "Green"
}
}
}
}
}
# I just wanted 120 lines =P
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.