full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PoshCode/Receive-Stream.ps1
|
Receive-Stream.ps1
|
function Receive-Stream {
#.Synopsis
# Read a stream to the end and close it
#.Description
# Will read from a byte stream and output a string or a file
#.Param reader
# The stream to read from
#.Param fileName
# A file to write to. If this parameter is provided, the function will output to file
#.Param encoding
# The text encoding, if you want to override the default.
param( [System.IO.Stream]$reader, $fileName, $encoding = [System.Text.Encoding]::GetEncoding( $null ) )
if($fileName) {
$writer = new-object System.IO.FileStream $fileName, "Create"
} else {
[string]$output = ""
}
[byte[]]$buffer = new-object byte[] 4096
[int]$total = [int]$count = 0
do
{
$count = $reader.Read($buffer, 0, $buffer.Length)
if($fileName) {
$writer.Write($buffer, 0, $count)
} else {
$output += $encoding.GetString($buffer, 0, $count)
}
} while ($count -gt 0)
$reader.Close()
if(!$fileName) { $output }
}
|
PowerShellCorpus/PoshCode/Get_Set Signature 2.5.ps1
|
Get_Set Signature 2.5.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.5 - Added support for storing a different default cert per computer in the psd1
## Now I can sync from work to home, and still use the right cert in each place.
## 2.4 - Added a -Module parameter to the Set-AuthenticodeSignature
## It will recursively sign all the signable files in a module...
## - Tweaked Get-AuthenticodeCertificate to first search Cert:\\CurrentUser\\My
## 's much faster on my home PC this way
## 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 ConvertTo-StringData { param([Parameter(ValueFromPipeline=$true)]$InputObject)
switch($InputObject.GetType().FullName) {
'System.Collections.Hashtable' { ($InputObject.Keys | % { "$_=$($InputObject.$_)" }) -join "`n" }
} }
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 {
$PrivateData = ConvertFrom-StringData (Get-Module -ListAvailable $PSCmdlet.MyInvocation.MyCommand.Module.Name).PrivateData
if(!$PrivateData) { $PrivateData = @{} }
## 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 $PrivateData.${Env:ComputerName}
) {
## Verbose output
if($VerbosePreference -gt "SilentlyContinue") {
if(!(Test-Path Variable:Script:UserCertificate)) {
Write-Verbose "Loading User Certificate from Module Config: $($PrivateData.${Env:ComputerName} )"
} else {
Write-Verbose "Saving User Certificate to Module Config: ($($Script:UserCertificate.Thumbprint) -ne $($PrivateData.${Env:ComputerName}))"
}
}
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 $PrivateData.${Env:ComputerName}
}
Write-Verbose "Confirming Certificate: $($Script:UserCertificate.Thumbprint)"
## If their cert isn't stored at least temporarily...
if($Script:UserCertificate -and (!$PrivateData.${Env:ComputerName} -or
($PrivateData.${Env:ComputerName} -ne $Script:UserCertificate.Thumbprint)))
{
## Store it temporarily ...
$PrivateData.${Env:ComputerName} = $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 = (Get-Module -ListAvailable $PSCmdlet.MyInvocation.MyCommand.Module.Name).Version
Write-Verbose "Version: $mVersion"
if($MVersion -le "2.5") { $MVersion = 2.5 }
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 ($PrivateData | ConvertTo-StringData)
$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"
## Check "CurrentUsers\\My" first, because it's MOST LIKELY there, and it will be MUCH faster in some cases.
$ResolvedPath = Get-ChildItem Cert:\\CurrentUser\\My -Recurse -CodeSign | Where {$_.ThumbPrint -like $Name } | Select -Expand PSPath
if(!$ResolvedPath) {
## We have to at least check the other folders too, if we didn't find it.
$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.
.EXAMPLE
Set-AuthenticodeSignature -Module PSCX
Signs the whole PSCX module at once (all the ps1, psm1, psd1, dll, exe, and ps1xml files, etc.).
.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 ModuleName
Specifies a module name (or path) to sign.
When you specify a module name, all of the files in that folder and it's subfolders are signed (if they're signable).
.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(DefaultParameterSetName="File")]
param (
[Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ValueFromPipeline=$true, ParameterSetName="File")]
[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=1, Mandatory=$true, ParameterSetName="Module")]
[ValidateScript({
Write-Verbose $_
if(!(Get-Module -List $_)) {
throw "Cannot find a module by that name: '$_'"
}
return $true
})]
[string[]]$ModuleName
,
[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($PSCmdlet.ParameterSetName -eq "Module"){
Write-Verbose ($ModuleName -join ", ")
$FilePath = Get-Module -List $ModuleName | Split-Path | Get-ChildItem -Recurse | Where { !$_.PsIsContainer } | Select -Expand FullName
$FilePath | Write-Verbose
$null = $PSBoundParameters.Remove("ModuleName")
}
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
# MIIRDAYJKoZIhvcNAQcCoIIQ/TCCEPkCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUt4v4Bto6gQNB6jCEtBtvurjP
# 8viggg5CMIIHBjCCBO6gAwIBAgIBFTANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQG
# EwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERp
# Z2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2Vy
# dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDcxMDI0MjIwMTQ1WhcNMTIxMDI0MjIw
# MTQ1WjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzAp
# BgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRlIFNpZ25pbmcxODA2BgNV
# BAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJbnRlcm1lZGlhdGUgT2JqZWN0
# IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyiOLIjUemqAbPJ1J
# 0D8MlzgWKbr4fYlbRVjvhHDtfhFN6RQxq0PjTQxRgWzwFQNKJCdU5ftKoM5N4YSj
# Id6ZNavcSa6/McVnhDAQm+8H3HWoD030NVOxbjgD/Ih3HaV3/z9159nnvyxQEckR
# ZfpJB2Kfk6aHqW3JnSvRe+XVZSufDVCe/vtxGSEwKCaNrsLc9pboUoYIC3oyzWoU
# TZ65+c0H4paR8c8eK/mC914mBo6N0dQ512/bkSdaeY9YaQpGtW/h/W/FkbQRT3sC
# pttLVlIjnkuY4r9+zvqhToPjxcfDYEf+XD8VGkAqle8Aa8hQ+M1qGdQjAye8OzbV
# uUOw7wIDAQABo4ICfzCCAnswDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAQYwHQYD
# VR0OBBYEFNBOD0CZbLhLGW87KLjg44gHNKq3MIGoBgNVHSMEgaAwgZ2AFE4L7xqk
# QFulF2mHMMo0aEPQQa7yoYGBpH8wfTELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0
# YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRl
# IFNpZ25pbmcxKTAnBgNVBAMTIFN0YXJ0Q29tIENlcnRpZmljYXRpb24gQXV0aG9y
# aXR5ggEBMAkGA1UdEgQCMAAwPQYIKwYBBQUHAQEEMTAvMC0GCCsGAQUFBzAChiFo
# dHRwOi8vd3d3LnN0YXJ0c3NsLmNvbS9zZnNjYS5jcnQwYAYDVR0fBFkwVzAsoCqg
# KIYmaHR0cDovL2NlcnQuc3RhcnRjb20ub3JnL3Nmc2NhLWNybC5jcmwwJ6AloCOG
# IWh0dHA6Ly9jcmwuc3RhcnRzc2wuY29tL3Nmc2NhLmNybDCBggYDVR0gBHsweTB3
# BgsrBgEEAYG1NwEBBTBoMC8GCCsGAQUFBwIBFiNodHRwOi8vY2VydC5zdGFydGNv
# bS5vcmcvcG9saWN5LnBkZjA1BggrBgEFBQcCARYpaHR0cDovL2NlcnQuc3RhcnRj
# b20ub3JnL2ludGVybWVkaWF0ZS5wZGYwEQYJYIZIAYb4QgEBBAQDAgABMFAGCWCG
# SAGG+EIBDQRDFkFTdGFydENvbSBDbGFzcyAyIFByaW1hcnkgSW50ZXJtZWRpYXRl
# IE9iamVjdCBTaWduaW5nIENlcnRpZmljYXRlczANBgkqhkiG9w0BAQUFAAOCAgEA
# UKLQmPRwQHAAtm7slo01fXugNxp/gTJY3+aIhhs8Gog+IwIsT75Q1kLsnnfUQfbF
# pl/UrlB02FQSOZ+4Dn2S9l7ewXQhIXwtuwKiQg3NdD9tuA8Ohu3eY1cPl7eOaY4Q
# qvqSj8+Ol7f0Zp6qTGiRZxCv/aNPIbp0v3rD9GdhGtPvKLRS0CqKgsH2nweovk4h
# fXjRQjp5N5PnfBW1X2DCSTqmjweWhlleQ2KDg93W61Tw6M6yGJAGG3GnzbwadF9B
# UW88WcRsnOWHIu1473bNKBnf1OKxxAQ1/3WwJGZWJ5UxhCpA+wr+l+NbHP5x5XZ5
# 8xhhxu7WQ7rwIDj8d/lGU9A6EaeXv3NwwcbIo/aou5v9y94+leAYqr8bbBNAFTX1
# pTxQJylfsKrkB8EOIx+Zrlwa0WE32AgxaKhWAGho/Ph7d6UXUSn5bw2+usvhdkW4
# npUoxAk3RhT3+nupi1fic4NG7iQG84PZ2bbS5YxOmaIIsIAxclf25FwssWjieMwV
# 0k91nlzUFB1HQMuE6TurAakS7tnIKTJ+ZWJBDduUbcD1094X38OvMO/++H5S45Ki
# 3r/13YTm0AWGOvMFkEAF8LbuEyecKTaJMTiNRfBGMgnqGBfqiOnzxxRVNOw2hSQp
# 0B+C9Ij/q375z3iAIYCbKUd/5SSELcmlLl+BuNknXE0wggc0MIIGHKADAgECAgFR
# MA0GCSqGSIb3DQEBBQUAMIGMMQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRD
# b20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2ln
# bmluZzE4MDYGA1UEAxMvU3RhcnRDb20gQ2xhc3MgMiBQcmltYXJ5IEludGVybWVk
# aWF0ZSBPYmplY3QgQ0EwHhcNMDkxMTExMDAwMDAxWhcNMTExMTExMDYyODQzWjCB
# qDELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5ldyBZb3JrMRcwFQYDVQQHEw5XZXN0
# IEhlbnJpZXR0YTEtMCsGA1UECxMkU3RhcnRDb20gVmVyaWZpZWQgQ2VydGlmaWNh
# dGUgTWVtYmVyMRUwEwYDVQQDEwxKb2VsIEJlbm5ldHQxJzAlBgkqhkiG9w0BCQEW
# GEpheWt1bEBIdWRkbGVkTWFzc2VzLm9yZzCCASIwDQYJKoZIhvcNAQEBBQADggEP
# ADCCAQoCggEBAMfjItJjMWVaQTECvnV/swHQP0FTYUvRizKzUubGNDNaj7v2dAWC
# rAA+XE0lt9JBNFtCCcweDzphbWU/AAY0sEPuKobV5UGOLJvW/DcHAWdNB/wRrrUD
# dpcsapQ0IxxKqpRTrbu5UGt442+6hJReGTnHzQbX8FoGMjt7sLrHc3a4wTH3nMc0
# U/TznE13azfdtPOfrGzhyBFJw2H1g5Ag2cmWkwsQrOBU+kFbD4UjxIyus/Z9UQT2
# R7bI2R4L/vWM3UiNj4M8LIuN6UaIrh5SA8q/UvDumvMzjkxGHNpPZsAPaOS+RNmU
# Go6X83jijjbL39PJtMX+doCjS/lnclws5lUCAwEAAaOCA4EwggN9MAkGA1UdEwQC
# MAAwDgYDVR0PAQH/BAQDAgeAMDoGA1UdJQEB/wQwMC4GCCsGAQUFBwMDBgorBgEE
# AYI3AgEVBgorBgEEAYI3AgEWBgorBgEEAYI3CgMNMB0GA1UdDgQWBBR5tWPGCLNQ
# yCXI5fY5ViayKj6xATCBqAYDVR0jBIGgMIGdgBTQTg9AmWy4SxlvOyi44OOIBzSq
# t6GBgaR/MH0xCzAJBgNVBAYTAklMMRYwFAYDVQQKEw1TdGFydENvbSBMdGQuMSsw
# KQYDVQQLEyJTZWN1cmUgRGlnaXRhbCBDZXJ0aWZpY2F0ZSBTaWduaW5nMSkwJwYD
# VQQDEyBTdGFydENvbSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eYIBFTCCAUIGA1Ud
# IASCATkwggE1MIIBMQYLKwYBBAGBtTcBAgEwggEgMC4GCCsGAQUFBwIBFiJodHRw
# Oi8vd3d3LnN0YXJ0c3NsLmNvbS9wb2xpY3kucGRmMDQGCCsGAQUFBwIBFihodHRw
# Oi8vd3d3LnN0YXJ0c3NsLmNvbS9pbnRlcm1lZGlhdGUucGRmMIG3BggrBgEFBQcC
# AjCBqjAUFg1TdGFydENvbSBMdGQuMAMCAQEagZFMaW1pdGVkIExpYWJpbGl0eSwg
# c2VlIHNlY3Rpb24gKkxlZ2FsIExpbWl0YXRpb25zKiBvZiB0aGUgU3RhcnRDb20g
# Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgUG9saWN5IGF2YWlsYWJsZSBhdCBodHRw
# Oi8vd3d3LnN0YXJ0c3NsLmNvbS9wb2xpY3kucGRmMGMGA1UdHwRcMFowK6ApoCeG
# JWh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL2NydGMyLWNybC5jcmwwK6ApoCeGJWh0
# dHA6Ly9jcmwuc3RhcnRzc2wuY29tL2NydGMyLWNybC5jcmwwgYkGCCsGAQUFBwEB
# BH0wezA3BggrBgEFBQcwAYYraHR0cDovL29jc3Auc3RhcnRzc2wuY29tL3N1Yi9j
# bGFzczIvY29kZS9jYTBABggrBgEFBQcwAoY0aHR0cDovL3d3dy5zdGFydHNzbC5j
# b20vY2VydHMvc3ViLmNsYXNzMi5jb2RlLmNhLmNydDAjBgNVHRIEHDAahhhodHRw
# Oi8vd3d3LnN0YXJ0c3NsLmNvbS8wDQYJKoZIhvcNAQEFBQADggEBACY+J88ZYr5A
# 6lYz/L4OGILS7b6VQQYn2w9Wl0OEQEwlTq3bMYinNoExqCxXhFCHOi58X6r8wdHb
# E6mU8h40vNYBI9KpvLjAn6Dy1nQEwfvAfYAL8WMwyZykPYIS/y2Dq3SB2XvzFy27
# zpIdla8qIShuNlX22FQL6/FKBriy96jcdGEYF9rbsuWku04NqSLjNM47wCAzLs/n
# FXpdcBL1R6QEK4MRhcEL9Ho4hGbVvmJES64IY+P3xlV2vlEJkk3etB/FpNDOQf8j
# RTXrrBUYFvOCv20uHsRpc3kFduXt3HRV2QnAlRpG26YpZN4xvgqSGXUeqRceef7D
# dm4iTdHK5tIxggI0MIICMAIBATCBkjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoT
# DVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmlj
# YXRlIFNpZ25pbmcxODA2BgNVBAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJ
# bnRlcm1lZGlhdGUgT2JqZWN0IENBAgFRMAkGBSsOAwIaBQCgeDAYBgorBgEEAYI3
# AgEMMQowCKACgAChAoAAMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3AgEEMBwGCisG
# AQQBgjcCAQsxDjAMBgorBgEEAYI3AgEWMCMGCSqGSIb3DQEJBDEWBBSxGd+l67e0
# vg6+xp9cQrCL7gtwETANBgkqhkiG9w0BAQEFAASCAQBoM9aLC7iUQZvZuxl25Pd5
# fT7VFokWiP7RyomLBHDeORS5hu+Hkv/UuQsMrAAbrmqAyyKJU1CrWGjqFqBlc979
# 7Ust7ILymoALd2AatdOIIpj0SQuZq3OP+vyt+lqd5toFNXLtUmnkhQusBh2QLkJ5
# rpb9QjvqTMhxEnE2w+RDL6mpWjQQOfJIHMVZbz/PD4pkrfrHFHFasZc/hnLVs9O7
# mFGNGFBNZu032vrSt1fg7eAgwCa60isTwzBTU94O69gA8oBfKFX7nUbre4EkLG+j
# A+tI5Qwn+HcTCHFpvUE0225uWoMZ4rllUWFukzra6muILTIQl6hRxABT0TOJ3Y2s
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Dell hardware checker.ps1
|
Dell hardware checker.ps1
|
function load-omsa([string]$server) {
$omsaie = new-object -com InternetExplorer.Application
if (($server -eq $null) -or ($server -eq "")) {
write-host -foregroundcolor "yellow" "Usage: omsa servername"
write-host -foregroundcolor "yellow" " Enter servername to open OMSA connection to server"
write-host -foregroundcolor "yellow" ""
exit
}
$portopen = tcpt $server 1311
if ($portopen -eq $false) {
write-host -foregroundcolor "red" "OMSA Port not accessible, may be behind firewall or service not running"
exit
}
$omsaie.visible = 1
$url = "https://" + $server + ":1311//servlet/Login?omacmd=getlogin&page=Login"
$omsaie.navigate($url)
sleep 5
if ($omsaie.document -ne $null) {
if ($omsaie.document.getElementById("overridelink") -ne $null) {
$omsaie.document.getElementById("overridelink").click()
}
}
}
function tcpt ([string]$serv, [string]$p) {
#simple tcp port checker. Return true if port is open and connection worked
$error.clear()
trap {continue;}
$conn = new-object system.net.sockets.tcpclient($serv,$p)
if ($error) { return $false } else { return $true}
}
Function memory ([string]$server) {
$errfound = $false
if ($server -eq $null) {
write-host -foregroundcolor "yellow" "Usage memory servername"
write-host -foregroundcolor "yellow" " Enter servername to see DIMM status"
exit
}
$server = &namescrub $server
$a = Get-WMIObject -Namespace root\\CIMv2\\Dell -computername $server -Class CIM_PhysicalMemory -erroraction silentlycontinue -errorvariable err
if (-not($?)) {
omsaerr
exit
}
if ($a -eq $null) {
write-host -foregroundcolor "red" "Could not get memory information on this machine"
&wantomsa
write-host
exit
} else {
$b = $a |select-object Name,Capacity,Status
echo "Location Capacity Status"
write-host
foreach ($item in $b) {
$item.capacity = $item.capacity / 1073741824
$itemstring = [string]$item.capacity + " GB"
write-host $item.Name " " $itemstring " " $item.status
}
foreach ($item in $b) {
if ($item.Status -eq "Error") {
$errfound = $true
}
}
write-host
if ($errfound) {
&amdb $server
}
exit
}
}
Function hwlog ([string]$server) {
if ($server -eq $null) {
write-host -foregroundcolor "yellow" "Usage hwlog servername"
write-host -foregroundcolor "yellow" " Enter servername to pull OMSA hardware event log"
write-host -foregroundcolor "yellow" ""
exit
}
$server = &namescrub $server
$a = Get-WMIOBject -Namespace root\\CIMv2\\DELL -computername $server -Class DELL_EsmLog -erroraction silentlycontinue -errorvariable err
if (-not($?)) {
omsaerr
exit
}
if ($a -eq $null) {
write-host -foregroundcolor "red" "Could not get omsa log for this machine"
write-host
exit
} else {
$b = $a |select-object EventTime,LogRecord
foreach ($item in $b) {
if ($item.EventTime -ne $null) {
$item.EventTime = &converttime $item.EventTime
} else {
}
}
$b |format-table -wrap -autosize |more
write-host
}
}
Function perc ([string]$server) {
if ($server -eq $null) {
write-host -foregroundcolor "yellow" "Usage perc servername"
write-host -foregroundcolor "yellow" " Enter servername to get Perc events"
write-host
exit
}
$server = &namescrub $server
$a = Get-WmiObject -Class Win32_NTLogEvent -filter "Logfile='Application' AND SourceName='VxSvc_PercPro' AND Type='Warning'" -computer $server -erroraction silentlycontinue -errorvariable err
if ($a -eq $null) {
write-host -foregroundcolor "red" "Could not get event log perc events"
&wantomsa
write-host
exit
} else {
$n = 6
$b = $a |select-object TimeGenerated,EventCode,Message
foreach ($item in $b) {
if ($item.TimeGenerated -ne $null) {
$item.TimeGenerated = &converttime $item.TimeGenerated
write-host $item.TimeGenerated $item.EventCode $item.Message
} else {
write-host "No time given" $item.LogRecord
}
$n = $n - 1
if ($n -eq 0) { write-host; exit}
}
#$b | format-list |more
}
}
Function hwstatus ([string]$server) {
if ($server -eq $null) {
write-host -foregroundcolor "yellow" "Usage hwstatus servername"
write-host -foregroundcolor "yellow" " Enter servername to get status of chassis"
write-host
exit
}
$server = &namescrub $server
$a = Get-WMIObject -Namespace root\\CIMv2\\Dell -computername $server -Class DELL_Chassis -erroraction silentlycontinue -errorvariable err
if (-not($?)) {
omsaerr
exit
}
if ($a -eq $null) {
write-host -foregroundcolor "red" "Could not get chassis status on this machine"
write-host
exit
} else {
$b = $a |select-object Model,SerialNumber,Status,ProcStatus,PsStatus,TempStatus,VoltStatus,FanStatus
$b
}
}
function omsaerr {
$exception = $error[0].Exception.ErrorCode
if ($exception -eq "InvalidNamespace") {
write-host "OMSA version not high enough to query machine" -foregroundcolor "red"
} elseif ($error[0].CategoryInfo.Reason -eq "UnauthorizedAccessException") {
write-host "Access is Denied" -foregroundcolor "red"
} elseif ($error[0].Exception.ErrorCode -eq -2147023174) {
write-host "Can't connect to RPC service on machine, if OS is windows, server might be down or behind a firewall. " -foregroundcolor "red"
} else {
write-host "OMSA connection failed" -foregroundcolor "red"
}
write-host
$error.clear()
&wantomsa
}
function firmware ([string]$server) {
if (($server -eq $null) -or ($server -eq "")) {
write-host -foregroundcolor "yellow" "Usage: Firmware servername"
write-host -foregroundcolor "yellow" " Enter servername to get all firmware information on the dell components"
write-host
exit
}
$server = &namescrub $server
$a = Get-WMIObject -Namespace root\\CIMv2\\Dell -computername $server -Class DELL_Firmware -erroraction silentlycontinue -errorvariable err
if (-not($?)) {
omsaerr
exit
}
if ($a -eq $null) {
write-host -foregroundcolor "red" "Could not get firmware information for this machine (OMSA needs to be >=4.4)"
&wantomsa
write-host
exit
} else {
$b = $a |select-object Name,SoftwareElementID
$b
}
}
Function wantomsa() {
$omsatest = tcpt $server 1311
if ($omsatest) {
write-host
echo "Would you like to run OMSA to check further? (y/n)"
$key = $host.ui.RawUI.ReadKey(12)
if (($key.Character -eq 'y') -or ($key.Character -eq 'Y')) {
&load-omsa $server
}
}
write-host
}
Function gettag([string]$server) {
#This function gets the machine's service tag
$server = &namescrub $server
if ($server -eq "") {
write-host -foregroundcolor "yellow" "Usage: gettag servername"
write-host -foregroundcolor "yellow" " Enter the name of the server that you would like to get"
write-host -foregroundcolor "yellow" " the service tag for"
exit
}
write-host
$a = Get-WmiObject Win32_BIOS -computername $server -erroraction silentlycontinue -errorvariable err
if ($a -eq $null) {
write-host -foregroundcolor "red" "Server not found or can't connect, could not get tag number"
&wantomsa
exit
}
else {
$a = $a | select-object SerialNumber
$b = $a.serialnumber
echo "Service tag for $server is $b"
write-host
}
}
Function converttime ([string]$timestr) {
$formattime = $timestr.Substring(0,4) + " " + $timestr.Substring(4,2) + "M " + $timestr.Substring(6,2) + "D " + $timestr.Substring(8,2) + ":" + $timestr.Substring(10,2)
return $formattime
}
$server = $args[1]
$function = $args[0]
if ($function -eq $null -or $server -match "\\?") {
Write-Host -ForegroundColor "yellow" "Usage: Dell-hwchecks-wmi.ps1 <function> [servername]"
Write-Host -ForegroundColor "yellow" " Functions:"
Write-Host -ForegroundColor "yellow" " hwlog - Prints ESM log"
write-host -ForegroundColor "yellow" " load-omsa - Open OMSA web interface on remote machine"
Write-Host -ForegroundColor "yellow" " hwstatus - Chassis component health check"
Write-Host -ForegroundColor "yellow" " gettag - Print service tag"
Write-Host -ForegroundColor "yellow" " firmware - List firmware versions"
Write-Host -ForegroundColor "yellow" " perc - Search event log for perc events"
Write-Host -ForegroundColor "yellow" " memory - List memory modules and status"
exit
}
if ($server -eq $null -or $server -eq "") { $server = "locahost" }
&$function $server
|
PowerShellCorpus/PoshCode/Search-NetworkService_1.ps1
|
Search-NetworkService_1.ps1
|
#Define PreReqs
$timeStamp = Get-Date -UFormat "%m-%d-%Y-%H-%M"
$systemVars = Gwmi Win32_ComputerSystem -Comp "."
$userName = $systemVars.UserName
$compName = $systemVars.Name
#User Vars
$serviceName = "Spooler" # Spooler will check the Print Spooler <<< Change To Suit Your needs
$errorLog = "C:\\Temp\\Log_"+$serviceName+"_"+$timeStamp+"_Errors.txt" #Service Not Installed
$fullLog = "C:\\Temp\\Log_"+$serviceName+"_"+$timeStamp+"_All.txt" #Services Needed To Be Started / Running
#Write Some Info To Logs
"Check Service: " + $serviceName > $errorLog; Get-Date >> $errorLog; $compName >> $errorLog; $userName >> $errorLog; "_____________" >> $errorLog; "" >> $errorLog;
"Check Service: " + $serviceName > $fullLog; Get-Date >> $fullLog; $compName >> $fullLog; $userName >> $fullLog; "_____________" >> $fullLog; "" >> $fullLog;
# Define Functions
function Get-NetView {
switch -regex (NET.EXE VIEW) { "^\\\\\\\\(?<Name>\\S+)\\s+" {$matches.Name}}
}
function Process-PCs ($currentName) {
$olStatus = Ping-Address $currentName
If ($olStatus -eq "True") {
Check-Service $currentName
}
#Else {Write-Host "PC Not Online"}
Write-Host " "
}
function Ping-Address ($pingAddress) {
$ping = new-object system.net.networkinformation.ping
$pingReply = $ping.send($pingAddress)
If ($pingReply.status -eq "Success") {
Return "True"
}
Else {
Return "False"
}
}
function Check-Service ($currentName) {
$currentService = Get-Service -ComputerName $currentName -Name $serviceName -ErrorAction SilentlyContinue
If ($currentService.Status -eq $Null){
$currentServiceStatus = "Not Installed"
$currentName >> $errorLog
}
ElseIf ($currentService.Status -eq "Running"){
$currentServiceStatus = "Running"
}
ElseIf ($currentService.Status -eq "Stopped"){
$currentServiceStatus = "Stopped"
}
Else {
$currentServiceStatus = "Unknown"
}
Write-Host $serviceName " is " $currentServiceStatus " on " $currentName
$serviceName + " was " + $currentServiceStatus + " on " + $currentName >> $fullLog
If ($currentService.Status -eq "Stopped"){
Write-Host "Service was stoppped, trying to start it . . ."
$currentService | Start-Service -ErrorAction SilentlyContinue
$recheckService = Get-Service -ComputerName $currentName -Name $serviceName -ErrorAction SilentlyContinue
If ($recheckService.Status -eq "Running"){
" Service Successfully Started" >> $fullLog
}
Else {
" Service Could Not Be Started" >> $fullLog
}
}
}
#Run Everything
cls
Get-NetView | %{Process-PCs $_}
# Test a single PC, Uncomment line below change pc name and comment line above
# Process-PCs "localhost" | %{Process-PCs $_}
|
PowerShellCorpus/PoshCode/script does not continue.ps1
|
script does not continue.ps1
|
Process {
# If the computer isn't pingable, move on to next in pipeline.
@@ if ( -not ( SelectAlive $_ ) ) { continue }
|
PowerShellCorpus/PoshCode/Get-LeaderBoard_1.ps1
|
Get-LeaderBoard_1.ps1
|
<#
.SYNOPSIS
Pulls down the leaderboards for the 2011 Scripting Games
.DESCRIPTION
Quick and dirty script to pull down the leaderboards for the 2011 scripting games.
Can choose either beginner or advanced via a command line switch.
.PARAMETER Level
The leaderboard to parse
.EXAMPLE
Get-LeaderBoard -Level Beginner
Retrieves the beginner leaderboard.
.EXAMPLE
Get-LeaderBoard -Level Advanced
Retrieves the advanced leaderboard
#>
function Get-LeaderBoard
{
param(
[Parameter(
Position = 0,
Mandatory = $true,
HelpMessage = "Leaderboard to parse. Advanced, or Beginner")]
[ValidateSet("Advanced","Beginner")]
[String]$Level="Advanced"
)
# create a webclient
$WebClient = New-Object System.Net.WebClient
# download the page
$LeaderPage = $WebClient.DownloadString("http://2011sg.poshcode.org/Reports/TopUsers?filter=$Level")
# create a horrific looking regular expression
@@ $RegEx = '<a href="/Scripts/By/\\d{1,3}">(?<UserName>[\\w\\S]*)</a>\\s*</td>\\s*<td>\\s*(?<TotalPoints>\\d{1,2}\\.\\d{1,2})\\s*</td>\\s*<td>\\s*(?<ScriptsRated>\\d*)'
# split the page into seperate objects so we can parse each invidual
$LeaderPage -split "<tr>" | ForEach {
# match the regex
$_ -match $RegEx | Out-Null
# create a new PSObject, supply a hashtable with the properties
New-Object PSObject -Property @{
"UserName" = $Matches.UserName
"ScriptsRated" = $Matches.ScriptsRated
"TotalPoints" = $Matches.TotalPoints
"AverageRating" = if ($Matches.ScriptsRated -gt 0)
{
# get average round to two decimal places
"{0:N2}" -f ($Matches.TotalPoints / $Matches.ScriptsRated)
}
}
# clear matches
if ($Matches) { $Matches.Clear() }
# get our objects in a specific order.
} | select -Unique UserName,ScriptsRated,AverageRating,TotalPoints
}
|
PowerShellCorpus/PoshCode/Get-User_10.ps1
|
Get-User_10.ps1
|
function Get-User($user)
{
# this function should be passed the CN of the user to be returned
$dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$root = [ADSI] "LDAP://$($dom.Name)"
$searcher = New-Object System.DirectoryServices.DirectorySearcher $root
$searcher.filter = "(&(objectCategory=person)(objectClass=user)(cn=$user))"
$user = $searcher.FindOne()
[System.Collections.Arraylist]$names = $user.Properties.PropertyNames
[System.Collections.Arraylist]$props = $user.Properties.Values
$userobj = New-Object System.Object
for ($i = 0; $i -lt $names.Count)
{
$userobj | Add-Member -type NoteProperty -Name $($names[$i]) -Value $($props[$i])
$i++
}
$userobj.pwdlastset = [System.DateTime]::FromFileTime($userobj.pwdlastset)
$userobj.lastlogontimestamp = [System.DateTime]::FromFileTime($userobj.lastlogontimestamp)
return $userobj
}
|
PowerShellCorpus/PoshCode/Reset-Tray_1.ps1
|
Reset-Tray_1.ps1
|
function Reset-Tray {
Add-Type -Assembly UIAutomationClient
$Window = Add-Type -Name ([char[]](65..90 | Get-Random -count 10) -join "") -Member @"
[DllImport("user32")]
public static extern IntPtr PostMessage(IntPtr hWnd, UInt32 Msg, Int32 wParam, Int32 lParam);
public static void SendMouseMove(IntPtr hWnd, ushort x, ushort y) {
int point = (y << 16) + x;
PostMessage(hWnd, 0x200, 0, point);
}
"@ -Passthru
$tray = [System.Windows.Automation.AutomationElement]::RootElement.FindAll( "Descendants" , [System.Windows.Automation.Condition]::TrueCondition ) |
Where { $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ClassNameProperty) -like "SysPager" } |
ForEach { $_.FindAll( "Children" , [System.Windows.Automation.Condition]::TrueCondition ) } |
Where { $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::NameProperty) -like "*Notification Area" }
$handle = $tray.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::NativeWindowHandleProperty)
$rect = $tray.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::BoundingRectangleProperty)
$y = $rect.Height/2
for ( $x = 0; $x -lt $rect.Width; $x += 8) {
$Window::SendMouseMove( $handle, $x, $y )
}
}
|
PowerShellCorpus/PoshCode/Set-ToStringMethod.ps1
|
Set-ToStringMethod.ps1
|
function Set-ToStringMethod {
<#
.Synopsis
Overwrites default .ToString() method of a given type.
.Description
Some commands use .ToString() method of an object to produce output.
Default (inherited from System.Object) result of that method is object's type FullName.
That is usually not very interesting and useful - thus need to replace it with something else.
Use $this special variable inside ScriptBlock to refer to object's properties and methods.
.Example
Set-ToStringMethod -TypeName System.Array -ScriptBlock { ($this | foreach { $_.ToString() ) -Join ';' }
Results of:
(1,2,3,4,(Get-Date)).ToString()
Before:
System.Object[]
After:
1;2;3;4;07/03/2011 23:09:20
What do you prefer? Meaningless name of the type or string representation of members? Choice is yours... ;)
#>
[CmdletBinding()]
param (
# Name of type to be modified.
[Parameter(Mandatory = $true)]
[string]$TypeName,
# Scriptblock that will be used as .ToString() method.
[Parameter()]
[scriptblock]$ScriptBlock = { $this.Name }
)
if ($TypeName -eq 'System.Object') {
# To many types depend on this object's ToString method - most likely it will kill your shell. :(
throw "Suicide action detected... I quit! :P"
}
$XML = @"
<Types>
<Type>
<Name>$TypeName</Name>
<Members>
<ScriptMethod>
<Name>ToString</Name>
<Script>
$ScriptBlock
</Script>
</ScriptMethod>
</Members>
</Type>
</Types>
"@
$XMLFile = [io.path]::GetTempFileName() + '.ps1xml'
try {
New-Item -ItemType File -Path $XMLFile -Value $XML | Write-Verbose
Update-TypeData -PrependPath $XMLFile -ErrorAction Stop
} catch {
# One day I will do something wiser than that... ;)
Write-Error $_
}
}
|
PowerShellCorpus/PoshCode/vibackup-lx1.ps1
|
vibackup-lx1.ps1
|
Param (
$viServer,
$bakVM,
$lxDest
)
#region check
if (!$viServer) { $viServer = Read-Host -Prompt "VI Server " }
if (!$bakVM) { $bakVM = Read-Host -Prompt "VM to Backup " }
if (!$lxDest) { $lxDest = Read-Host -Prompt "Backup Path (ex. /srv/backup) " }
#endregion
#region globalvars
$encoding = "OEM"
$version = "0.6"
$scriptout = @()
[regex]$curlpat = "(\\s{1})+(.*vmdk$)"
#endregion
#region stkmvars
$viUser = "vmware"
$viPass = "vmware"
#endregion
Write-Host "viBackup Script Generator - " $version
Write-Host "--------------------------------------------"
if (($vmCon = Connect-VIServer -Protocol https $viServer) -eq "") { exit }
$vm = Get-VM $bakVM -Server $vmCon -ErrorAction SilentlyContinue
if (!$vm) {
Write-Host "No VM found."
Write-Host "Enter the Display Name from the VI Center:" -NoNewline
$tvm = Read-Host
if (!($vm=Get-VM $tvm -ErrorAction SilentlyContinue)) {
return $false
exit
}
Write-Host "You have entered 2 different Names. Please check that the VMX and the VM Name are the same!"
Write-Host -ForegroundColor yellow "Entered VMX Name: {$bakVM}"
Write-Host -ForegroundColor yellow "Entered VM Name: {$tvm}"
Write-Host -ForegroundColor yellow "Returned VM Name: {$vm}"
Write-Host -ForegroundColor yellow "IS THIS CORRECT (Yes/No)?:" -NoNewline
$sure = Read-Host
if ($sure -ne "yes") { exit }
}
#check Snapshots
if ((Get-Snapshot -VM $vm -Server $vmCon)) {
Write-Host "VM has Snapshots. No Backup possible."
return $false
exit
}
#write script
$scriptname = $vm.name + ".sh"
$vmname = $vm.name
$vmhost = $vm.Host
$vmview= Get-View $vm.id
$vmvname = $vmview.config.files.vmpathname
#generate Text
$header = "#!/bin/bash"
$user = "USER=`"${viUser}`""
$pass = "PASS=`"${viPass}`""
$dest = "DEST=`"${lxDest}`""
$lxVM = "VM=`"${vmname}`""
$dcPath = $vm | Get-Datacenter
#region writefile
$scriptout += $header
$scriptout += $user
$scriptout += $pass
$scriptout += $dest
$scriptout += $lxvm
$scriptout += ""
$scriptout += "BKUP=`"${vmvname}`""
$scriptout += "SNAPCHECK=``vmware-cmd -H ${viserver} -T ${vmhost} -U `${USER} -P `${PASS} `"`${BKUP}`" hassnapshot`` "
$scriptout += "if [ `"`$SNAPCHECK`" != `"hassnapshot () =`" ]; then `n echo 'VM has a Snapshot. Aborting...' `n exit `n fi"
$scriptout += "vmrun -T esx -h https://${viserver}/sdk -u `${USER} -p `${PASS} snapshot `"`${BKUP}`" vmBackup"
# Hard Disk
foreach ($hd in $vm.Harddisks) {
$hdname = $hd.Filename
$patstr = $curlpat.split($hdname)
#dirty hack
$patstr[0] = $patstr[0].replace("[","")
$patstr[0] = $patstr[0].replace("]","")
$dsPath = $patstr[0].replace(" ","%20")
$vmdkpath = $patstr[2].replace(" ","%20")
$vmdkflatpath = $patstr[2].replace(".vmdk","-flat.vmdk")
#curl options
$vmdk = "curl --user `${USER}:`${PASS} -o `${DEST}/`${VM}.vmdk `"https://${viserver}/folder/${vmdkpath}?dcPath=${dcPath}&dsName=${dsPath}`" --insecure "
$vmdkflat = "curl --user `${USER}:`${PASS} -o `${DEST}/`${VM}.vmdk `"https://${viserver}/folder/${vmdkflatpath}?dcPath=${dcPath}&dsName=${dsPath}`" --insecure"
#$vmdk = "vifs --server ${viserver} --dc 'KM' --username `${USER} --password `${PASS} --get `"``echo $hdname```" `${DEST}/`${VM}.vmdk "
#$vmdkflat = "vifs --server ${viserver} --dc 'KM' --username `${USER} --password `${PASS} --get `"``echo $hdname | sed 's/.vmdk/-flat.vmdk/g'```" `${DEST}/`${VM}-flat.vmdk "
$scriptout += $vmdk
$scriptout += $vmdkflat
}
$scriptout += "vmrun -T esx -h https://${viserver}/sdk -u `${USER} -p `${PASS} deleteSnapshot `"`${BKUP}`" vmBackup"
$scriptout | Out-File $scriptname -Encoding $encoding
#endregion
Write-Host "Finished"
Write-Host "Don't forget to convert the script under *nix/Linux with dos2unix!"
|
PowerShellCorpus/PoshCode/Export-PSCredential_5.ps1
|
Export-PSCredential_5.ps1
|
# Author: Hal Rottenberg <hal@halr9000.com>
# Url: http://halr9000.com/article/tag/lib-authentication.ps1
# Purpose: These functions allow one to easily save network credentials to disk in a relatively
# secure manner. The resulting on-disk credential file can only [1] be decrypted
# by the same user account which performed the encryption. For more details, see
# the help files for ConvertFrom-SecureString and ConvertTo-SecureString as well as
# MSDN pages about Windows Data Protection API.
# [1]: So far as I know today. Next week I'm sure a script kiddie will break it.
#
# Usage: Export-PSCredential [-Credential <PSCredential object>] [-Path <file to export>]
#
# If Credential is not specififed, user is prompted by Get-Credential cmdlet.
# If not specififed, Path is "./credentials.enc.xml".
# Output: FileInfo object referring to saved credentials
#
# Import-PSCredential [-Path <file to import>]
#
# If not specififed, Path is "./credentials.enc.xml".
# Output: PSCredential object
function Export-PSCredential {
param ( $Credential = (Get-Credential), $Path = "credentials.enc.xml" )
# Look at the object type of the $Credential parameter to determine how to handle it
switch ( $Credential.GetType().Name ) {
# It is a credential, so continue
PSCredential { continue }
# It is a string, so use that as the username and prompt for the password
String { $Credential = Get-Credential -credential $Credential }
# In all other caess, throw an error and exit
default { Throw "You must specify a credential object to export to disk." }
}
# Create temporary object to be serialized to disk
$export = New-Object PSObject
Add-Member -InputObject $export -Name Username -Value $Credential.Username `
-MemberType NoteProperty
# Encrypt SecureString password using Data Protection API
$EncryptedPassword = $Credential.Password | ConvertFrom-SecureString
Add-Member -InputObject $export -Name EncryptedPassword -Value $EncryptedPassword `
-MemberType NoteProperty
# Give object a type name which can be identified later
$export.PSObject.TypeNames.Insert(0,ĺExportedPSCredentialĺ)
# Export using the Export-Clixml cmdlet
$export | Export-Clixml $Path
Write-Host -foregroundcolor Green "Credentials saved to: " -noNewLine
# Return FileInfo object referring to saved credentials
Get-Item $Path
}
function Import-PSCredential {
param ( [string]$Path = "credentials.enc.xml",[string]$cred)
#modified 8/4/08 JDH
#to create a global credential with a specified name
# Import credential file
$import = Import-Clixml $Path
# Test for valid import
if ( !$import.UserName -or !$import.EncryptedPassword ) {
Throw "Input is not a valid ExportedPSCredential object, exiting."
}
$Username = $import.Username
# Decrypt the password and store as a SecureString object for safekeeping
$SecurePass = $import.EncryptedPassword | ConvertTo-SecureString
# Build the new credential object
$Credential = New-Object System.Management.Automation.PSCredential $Username, $SecurePass
if ($cred) {
New-Variable -Name $cred -scope Global -value $Credential
} else {
Write-Output $Credential
}
}
|
PowerShellCorpus/PoshCode/Invoke-ElevatedCommand_1.p.ps1
|
Invoke-ElevatedCommand_1.p.ps1
|
param
(
## The script block to invoke elevated
[Parameter(Mandatory = $true)]
[ScriptBlock] $Scriptblock,
## Any input to give the elevated process
[Parameter(ValueFromPipeline = $true)]
$InputObject,
## Switch to enable the user profile
[switch] $EnableProfile
)
begin
{
Set-StrictMode -Version Latest
$inputItems = New-Object System.Collections.ArrayList
}
process
{
$null = $inputItems.Add($inputObject)
}
end
{
## Create some temporary files for streaming input and output
$outputFile = [IO.Path]::GetTempFileName()
$inputFile = [IO.Path]::GetTempFileName()
$errorFile = [IO.Path]::GetTempFileName()
## Stream the input into the input file
$inputItems.ToArray() | Export-CliXml -Depth 1 $inputFile
## Start creating the command line for the elevated PowerShell session
$commandLine = ""
if(-not $EnableProfile) { $commandLine += "-NoProfile " }
## Convert the command into an encoded command for PowerShell
$commandString = "Set-Location '$($pwd.Path)'; " +
"`$output = Import-CliXml '$inputFile' | " +
"& {" + $scriptblock.ToString() + "} 2>&1 ; " +
@@ "Out-File -filepath `$errorFile -inputobject `$error;" +
"Export-CliXml -Depth 1 -In `$output '$outputFile';"
$commandBytes = [System.Text.Encoding]::Unicode.GetBytes($commandString)
$encodedCommand = [Convert]::ToBase64String($commandBytes)
$commandLine += "-EncodedCommand $encodedCommand"
## Start the new PowerShell process
$process = Start-Process -FilePath (Get-Command powershell).Definition `
-ArgumentList $commandLine -Verb RunAs `
-Passthru `
-WindowStyle Hidden
$process.WaitForExit()
@@ if($process.ExitCode -eq 0)
{
## Return the output to the user
if((Get-Item $outputFile).Length -gt 0)
{
Import-CliXml $outputFile
}
}
else
{
@@ Write-Error -Message $(gc $errorFile | Out-String)
}
## Clean up
Remove-Item $outputFile
Remove-Item $inputFile
@@ Remove-Item $errorFile
}
|
PowerShellCorpus/PoshCode/New-Event.ps1
|
New-Event.ps1
|
#.Synopsis
# Parse natural language descriptions of appointments or meetings ...
#.EXAMPLE
@@# New-Event Lunch every other Friday at 11:45
@@#
@@# day_of_week interval start_date start_time type message
@@# ----------- -------- ---------- ---------- ---- -------
@@# fri 2 20100122 11:45:00 weekly Lunch
function New-Event {
$query = [System.Web.HttpUtility]::UrlEncode( "$args" )
$wc = New-Object System.Net.WebClient
[xml]$event = $wc.DownloadString( "http://naturalinputs.com/query?q=$query" )
$event.naturalinputsResponse | Join-Object {$_.occurrence} { $_ | select message }
}
## Depends on this http://poshcode.org/1596 (which I keep as a SCRIPT on my path):
function Join-Object {
Param(
[Parameter(Position=0)]
$First
,
[Parameter(Position=1)]
$Second
,
[Parameter(ValueFromPipeline=$true)]
$InputObject
)
BEGIN {
if($First -isnot [ScriptBlock]) {
$Out1 = $First
[string[]] $p1 = $First | gm -type Properties | select -expand Name
}
}
Process {
if($First -is [ScriptBlock]){
$Out1 = $InputObject | &$First
[string[]] $p1 = $Out1 | gm -type Properties | select -expand Name
}
$Output = $Out1 | Select $p1
if($Second -is [ScriptBlock]) {
$Out2 = $InputObject | &$Second
} elseif(!$Second) {
$Out2 = $InputObject
} else {
$Out2 = $Second
}
foreach($p in $Out2 | gm -type Properties | Where { $p1 -notcontains $_.Name } | select -expand Name) {
Add-Member -in $Output -type NoteProperty -name $p -value $Out2.($p)
}
$Output
}
}
|
PowerShellCorpus/PoshCode/Update-DeptGPOs_1.ps1
|
Update-DeptGPOs_1.ps1
|
<#
.SYNOPSIS
Update permissions on Departmental GPO's
.DESCRIPTION
This script will backup all existing GPO's in the domain prior to making any changes. After the backup
has been made Departmental GPOs will be updated based on their Dept Code.
.PARAMETER DeptCode
A code that uniquely identifies the GPOs for your department, this is used as a filter against the
name of the GPO in question.
.PARAMETER TargetName
The name of the user/group to assign permissions to
.PARAMETER TargetType
The default for this parameter is User, but if TargetName is a group, then
this should be set to Group.
.PARAMETER PermissionLevel
Valid permission levels are
GpoRead
GpoApply
GpoEdit
GpoEditDeleteModifySecurity
None
.PARAMETER BackupLocation
A valid location either local or UNC to store the GPO backups.
.PARAMETER Test
Set to $False in order to update security and perform backup.
.EXAMPLE
.\\Update-DeptGPOs.ps1 -DeptCode "Admin" -TargetName "MyUser" -BackupLocation "c:\\temp"
Description
-----------
This example shows basic usage, and assumes the default permissionlevel of None.
.EXAMPLE
.\\Update-DeptGPOs.ps1 -DeptCode "Admin" -TargetName "MyUser" -PermissionLevel "GpoEditDeleteModifySecurity" -BackupLocation "c:\\temp"
Description
-----------
This example assigns GpoEditDeleteModifySecurity to the MyUser account for all GPOs tagged as Admin
.NOTES
ScriptName: Update-DeptGPOs
Created By: Jeff Patton
Date Coded: June 7, 2011
ScriptName is used to register events for this script
LogName is used to determine which classic log to write to
This script depends on PowerShell GroupPolicy modules to functino properly, the linked in
cmdlets are used in this script.
If a backup cannot be made the script terminates.
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/Production/Update-DeptGPOs
.LINK
http://technet.microsoft.com/en-us/library/ee461059.aspx
.LINK
http://technet.microsoft.com/en-us/library/ee461038.aspx
.LINK
http://technet.microsoft.com/en-us/library/ee461052.aspx
#>
Param
(
$DeptCode,
$TargetName,
$TargetType = "User",
[ValidateSet("GpoRead", "GpoApply", "GpoEdit", "GpoEditDeleteModifySecurity","None")]
$PermissionLevel = "None",
$BackupLocation,
$Test = $True
)
Begin
{
$ScriptName = $MyInvocation.MyCommand.ToString()
$LogName = "Application"
$ScriptPath = $MyInvocation.MyCommand.Path
$Username = $env:USERDOMAIN + "\\" + $env:USERNAME
New-EventLog -Source $ScriptName -LogName $LogName -ErrorAction SilentlyContinue
$Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nStarted: " + (Get-Date).toString()
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message
$ErrorActionPreference = "Stop"
Try
{
Import-Module GroupPolicy
$DeptGPOs = Get-GPO -All |Where-Object {$_.DisplayName -like "*$($DeptCode)*"}
Foreach ($DeptGPO in $DeptGPOs)
{
If ($Test -eq $False)
{
Backup-GPO -Guid $DeptGPO.Id -Path $BackupLocation -Comment "Updating Security on $($DeptCode) GPOs"
$Message = "Backed up $($DeptGPO.DisplayName) to $($BackupLocation)"
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message
}
Else
{
Write-Host "Backed up $($DeptGPO.Displayname) to $($BackupLocation)"
}
}
}
Catch
{
$Message = $Error[0].Exception.InnerException.Message.ToString().Trim()
Write-EventLog -LogName $LogName -Source $ScriptName -EventId "102" -EntryType "Error" -Message $Message
Write-Error $Message
Break
}
}
Process
{
foreach ($DeptGPO in $DeptGPOs)
{
Try
{
If ($Test -eq $False)
{
Set-GPPermissions -Guid $DeptGPO.Id -TargetName $TargetName -PermissionLevel $PermissionLevel -TargetType $TargetType
$Message = "Adding $($TargetName) to $($DeptGPO.DisplayName) with permission level $($PermissionLevel)"
Write-EventLog -LogName $LogName -Source $ScriptName -EventId "101" -EntryType "Information" -Message $Message
}
Else
{
Set-GPPermissions -Guid $DeptGPO.Id -TargetName $TargetName -PermissionLevel $PermissionLevel -TargetType $TargetType -WhatIf
}
}
Catch
{
$Message = $Error[0].Exception.InnerException.Message.ToString().Trim()
Write-EventLog -LogName $LogName -Source $ScriptName -EventId "102" -EntryType "Error" -Message $Message
Return $Error[0].Exception.InnerException.Message.ToString().Trim()
}
}
}
End
{
$Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nFinished: " + (Get-Date).toString()
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message
Return $?
}
|
PowerShellCorpus/PoshCode/SQL Query - AD Pwd Reset.ps1
|
SQL Query - AD Pwd Reset.ps1
|
<#
.SYNOPSIS
Author:......Vidrine
Date:........2012/04/08
.DESCRIPTION
Script connects to a SQL database and runs a query against the specified table. Depending on table record values,
an Active Directory user object will have it's password reset. Once, the account is reset the SQL record is updated.
This SQL update is to prevent resetting the user object's password, again, and to store the password for use.
.NOTES
Requirements:
.. Microsoft ActiveDirectory cmdlets
.. Microsoft SQL cmdlets
Additionally:
The script must be ran as account that has access to the database and access to 'reset passwords' within ActiveDirectory.
#>
##====================================================================================
## Load snapins and modules
##====================================================================================
add-pssnapin SqlServerCmdletSnapin100 -ErrorAction SilentlyContinue
add-pssnapin SqlServerProviderSnapin100 -ErrorAction SilentlyContinue
Import-Module activeDirectory -ErrorAction SilentlyContinue
##====================================================================================
## Variables: SQL Connection
##====================================================================================
$sqlServerInstance = 'SERVER\\INSTANCE' # ex. '.\\SQLEXPRESS'
$sqlDatabase = 'DatabaseName'
$sqlTable = 'TableName'
##====================================================================================
## Variables: Password Creation/Reset Configuration
##====================================================================================
## File contains a list of 5-character words, 1 per line.
$word = Get-Content "C:\\..\\5CharacterDictionary.txt"
## List of allowed special characters for use
$special ='!','@','#','$','%','^','&','*','(',')','-','_','+','='
## Length of the random number
$nmbr = 4
##====================================================================================
## Variables: Log
##====================================================================================
$logFile = (Get-Date -Format yyyyMMdd) + '_LogFile.csv'
$logPath = 'C:\\..\\Logs'
$log = Join-Path -ChildPath $logFile -Path $logPath
##====================================================================================
## Functions
##====================================================================================
function Get-Timestamp {
Get-Date -Format u
}
function Write-Log {
param(
[string] $Path,
[string] $Value
)
$Value | Out-File $Path -Append
}
function Create-Password {
## Generate random 4 digit integer.
$NewString = ""
1..$nmbr | ForEach { $NewString = $NewString + (Get-Random -Minimum 0 -Maximum 9) }
## Select random 5-character word from wordlist
$lowerWord = Get-Random $word
## Normalize the selected word. Convert all to lowerCase and then convert third character to UPPERcase
$firstLetters = $lowerWord.Substring(0,2)
$upperLetters = $lowerWord.Substring(2,1).toUpper()
$lastLetters = $lowerWord.Substring(3,2)
$NewWord = $firstLetters + $upperLetters + $lastLetters
## Select random special character from wordlist
$NewSpecial = Get-Random $special
## Combine selected word, random number, and special character to generate password
$NewPassword = ($NewWord + $NewSpecial + $NewString)
## Returns the newly created random string to the function
return $NewPassword
}
Function Reset-Password {
param (
[string]$emailAddress,
[string]$password
)
## Convert the password to secure string
$password_secure = ConvertTo-SecureString $password -AsPlainText -Force
## Query for the user based on email address; Resets the user account password with value from database
try
{
Get-ADUser -Filter {emailAddress -like $emailAddress} | Set-ADAccountPassword -Reset -NewPassword $password_secure
$Value = (get-timestamp)+"`tSUCCESS`tReset Password`tPassword reset completed for end user ($emailAddress)."
Write-Log -Path $log -Value $Value
}
catch
{
$Value = (get-timestamp)+"`tERROR`tReset Password`tUnable to reset password ($emailAddress). $_"
Write-Log -Path $log -Value $Value
}
}
function Get-Username {
param (
[string]$emailAddress
)
try
{
$user = Get-ADUser -Filter {emailAddress -like $emailAddress}
$Value = (get-timestamp)+"`tSUCCESS`tQuery Username`tDirectory lookup for username was successful ($emailAddress)."
Write-Log -Path $log -Value $Value
return $user.sAMAccountName
}
catch
{
$Value = (get-timestamp)+"`tERROR`tQuery Username`tDirectory lookup failed ($emailAddress). $_"
Write-Log -Path $log -Value $Value
}
}
function SQL-Select {
<#
.EXAMPLE
$results = SQL-Select -server $sqlServerInstance -database $sqlDatabase -table $sqlTable -selectWhat '*'
.EXAMPLE
$results = SQL-Select -server $sqlServerInstance -database $sqlDatabase -table $sqlTable -selectWhat '*' -where "id='64'"
#>
param(
[string]$server,
[string]$database,
[string]$table,
[string]$selectWhat,
[string]$where
)
## SELECT statement with a WHERE clause
if ($where){
$sqlQuery = @"
SELECT $selectWhat
FROM $table
WHERE $where
"@
}
## General SELECT statement
else {
$sqlQuery = @"
SELECT $selectWhat
FROM $table
"@
}
try
{
$results = Invoke-SQLcmd -ServerInstance $server -Database $database -Query $sqlQuery
$Value = (get-timestamp)+"`tSUCCESS`tSQL Select`tDatabase query was successful (WHERE: $where)."
Write-Log -Path $log -Value $Value
return $results
}
catch
{
$Value = (get-timestamp)+"`tERROR`tSQL Select`tDatabase query failed (WHERE: $where). $_"
Write-Log -Path $log -Value $Value
}
}
function SQL-Update {
<#
.EXAMPLE
SQL-Update -server $sqlServerInstance -database $sqlDatabase -table $sqlTable -dataField $sqlDataField -dataValue $sqlDataValue -updateID $sqlDataID
#>
param(
[string]$server,
[string]$database,
[string]$table,
[string]$dataField,
[string]$dataValue,
[string]$updateID
)
$sqlQuery = @"
UPDATE $database.$table
SET $dataField='$dataValue'
WHERE id=$updateID
"@
try
{
Invoke-SQLcmd -ServerInstance $server -Database $database -Query $sqlQuery
$Value = (get-timestamp)+"`tSUCCESS`tSQL Update`tUpdated database record, ID $updateID ($dataField > $dataValue)."
Write-Log -Path $log -Value $Value
}
catch
{
$Value = (get-timestamp)+"`tERROR`tSQL Update`tUnable to update database record, ID $updateID ($dataField > $dataValue). $_"
Write-Log -Path $log -Value $Value
}
}
function Check-Status {
$results = $NULL
$results = SQL-Select -server $sqlServerInstance -database $sqlDatabase -table $sqlTable -selectWhat 'id,email,pword,pwordSet,status' -where "(pwordSet IS Null OR pwordSet='') AND status='CheckedIn'"
$results | ForEach {
if ($_.pword.GetType().name -eq 'DBNull')
{
## Generate a new password for the end-user
$password = Create-Password
$sqlDataID = $_.id
## Configure SQL statement to UPDATE the end-user 'pword'
$sqlDataField = 'pword'
$sqlDataValue = $password
SQL-Update -server $sqlServerInstance -database $sqlDatabase -table $sqlTable -dataField $sqlDataField -dataValue $sqlDataValue -updateID $sqlDataID
## Reset the end-user's password
Reset-Password -emailAddress $_.email -password $password
## Configure SQL statement to UPDATE the end-user 'pwordSet'
$sqlDataField = 'pwordSet'
$sqlDataValue = 'Yes'
SQL-Update -server $sqlServerInstance -database $sqlDatabase -table $sqlTable -dataField $sqlDataField -dataValue $sqlDataValue -updateID $sqlDataID
## Configure SQL statement to UPDATE the end-user 'samaccountname'
$sqlDataField = 'samaccountname'
$sqlDataValue = Get-Username -emailAddress $_.email
SQL-Update -server $sqlServerInstance -database $sqlDatabase -table $sqlTable -dataField $sqlDataField -dataValue $sqlDataValue -updateID $sqlDataID
}
elseif($_.pword -eq '')
{
## Generate a new password for the end-user
$password = Create-Password
$sqlDataID = $_.id
## Configure SQL statement to UPDATE the end-user 'pword'
$sqlDataField = 'pword'
$sqlDataValue = $password
SQL-Update -server $sqlServerInstance -database $sqlDatabase -table $sqlTable -dataField $sqlDataField -dataValue $sqlDataValue -updateID $sqlDataID
## Reset the end-user's password
Reset-Password -emailAddress $_.email -password $password
## Configure SQL statement to UPDATE the end-user 'pwordSet'
$sqlDataField = 'pwordSet'
$sqlDataValue = 'Yes'
SQL-Update -server $sqlServerInstance -database $sqlDatabase -table $sqlTable -dataField $sqlDataField -dataValue $sqlDataValue -updateID $sqlDataID
## Configure SQL statement to UPDATE the end-user 'samaccountname'
$sqlDataField = 'samaccountname'
$sqlDataValue = Get-Username -emailAddress $_.email
SQL-Update -server $sqlServerInstance -database $sqlDatabase -table $sqlTable -dataField $sqlDataField -dataValue $sqlDataValue -updateID $sqlDataID
}
else
{
Reset-Password -emailAddress $_.email -password $_.pword
$sqlDataID = $_.id
## Configure SQL statement to UPDATE the end-user 'pwordSet'
$sqlDataField = 'pwordSet'
$sqlDataValue = 'Yes'
SQL-Update -server $sqlServerInstance -database $sqlDatabase -table $sqlTable -dataField $sqlDataField -dataValue $sqlDataValue -updateID $sqlDataID
## Configure SQL statement to UPDATE the end-user 'samaccountname'
$sqlDataField = 'samaccountname'
$sqlDataValue = Get-Username -emailAddress $_.email
SQL-Update -server $sqlServerInstance -database $sqlDatabase -table $sqlTable -dataField $sqlDataField -dataValue $sqlDataValue -updateID $sqlDataID
}
}
return $results
}
##====================================================================================
## Main script begins here
##====================================================================================
Check-Status
|
PowerShellCorpus/PoshCode/BufferBox 3.0.ps1
|
BufferBox 3.0.ps1
|
####################################################################################################
## This script is just a demonstration of some of the things you can do with the buffer
## in the default PowerShell host... it serves as a reminder of how much work remains on
## PoshConsole, and as an inspirations to anyone who is thinking about trying to create
## "interactive" PowerShell applications.
##
####################################################################################################
$global:BoxChars = new-object PSObject -Property @{
'HorizontalDouble' = ([char]9552).ToString()
'VerticalDouble' = ([char]9553).ToString()
'TopLeftDouble' = ([char]9556).ToString()
'TopRightDouble' = ([char]9559).ToString()
'BottomLeftDouble' = ([char]9562).ToString()
'BottomRightDouble' = ([char]9565).ToString()
'HorizontalDoubleSingleDown' = ([char]9572).ToString()
'HorizontalDoubleSingleUp' = ([char]9575).ToString()
'Horizontal' = ([char]9472).ToString()
'Vertical' = ([char]9474).ToString()
'TopLeft' = ([char]9484).ToString()
'TopRight' = ([char]9488).ToString()
'BottomLeft' = ([char]9492).ToString()
'BottomRight' = ([char]9496).ToString()
'Cross' = ([char]9532).ToString()
'VerticalDoubleRightSingle' = ([char]9567).ToString()
'VerticalDoubleLeftSingle' = ([char]9570).ToString()
}
$global:RectType = "system.management.automation.host.rectangle"
function Reset-Buffer {
param(
$Position = $Host.UI.RawUI.WindowPosition,
[int]$Height = $Host.UI.RawUI.WindowSize.Height,
[int]$Width = $Host.UI.RawUI.WindowSize.Width,
# Note: all edges are padded by 1 for the box edges, but we also pad each side by this ammount:
[int]$Padding = 1,
$ForegroundColor = $Host.UI.RawUI.ForegroundColor,
$BackgroundColor = $Host.UI.RawUI.BackgroundColor,
$BorderColor = "Yellow",
[switch]$NoBorder,
[switch]$ShowInput,
[string]$Title = ""
)
$global:BufferHeight = $Height
$global:BufferWidth = $Width
$global:BufferPadding = $Padding
$global:BufferForegroundColor = $ForegroundColor
$global:BufferBackgroundColor = $BackgroundColor
$global:BufferBorderColor = $BorderColor
if($NoBorder) {
$global:BufferBoxSides = 0
} else {
$global:BufferBoxSides = 2
}
if($ShowInput) {
$global:BufferHeight -= 2
}
$Host.UI.RawUI.SetBufferContents($Position,(New-BufferBox $BufferHeight $BufferWidth -Title:$Title -NoBorder:$NoBorder -ShowInput:$ShowInput -Background $BufferBackgroundColor -Border $BufferBorderColor))
$global:BufferPosition = $Position
$global:BufferPosition.X += $global:BufferPadding + ($global:BufferBoxSides/2)
# this gets set to the BOTTOM line, because I assume text will flow in from the bottom.
$global:BufferPosition.Y += $global:BufferHeight - 2
# and this goes below that ...
$global:BufferPromptPosition = $BufferPosition
$global:BufferPromptPosition.Y += 2
$global:BufferPromptPosition.X += 2 - $global:BufferPadding # Prompt = "> "
}
function New-BufferBox {
param(
[int]$Height = $global:BufferHeight,
[int]$Width = $global:BufferWidth,
$Title = "",
[switch]$NoBorder,
[switch]$ShowInput,
$BackgroundColor = $global:BufferBackgroundColor,
$BorderColor = $global:BufferBorderColor
)
$Width = $Width - $global:BufferBoxSides
$LineTop =( $global:BoxChars.HorizontalDouble * 2) + $Title `
+ $($global:BoxChars.HorizontalDouble * ($Width - ($Title.Length+2)))
$LineField = ' ' * $Width
$LineBottom = $global:BoxChars.HorizontalDouble * $Width
$LineSeparator = $global:BoxChars.Horizontal * $Width
$LinePrompt = '> ' + ' ' * ($Width-2) # Prompt = "> "
if(!$NoBorder) {
$LineField = $global:BoxChars.VerticalDouble + $LineField + $global:BoxChars.VerticalDouble
$LinePrompt = $global:BoxChars.VerticalDouble + $LinePrompt + $global:BoxChars.VerticalDouble
$LineBottom = $global:BoxChars.BottomLeftDouble + $LineBottom + $global:BoxChars.BottomRightDouble
$LineTop = $global:BoxChars.TopLeftDouble + $LineTop + $global:BoxChars.TopRightDouble
$LineSeparator = $global:BoxChars.VerticalDoubleRightSingle + $LineSeparator + $global:BoxChars.VerticalDoubleLeftSingle
}
if($ShowInput) {
$box = &{$LineTop;1..($Height - 2) |% {$LineField};$LineSeparator;$LinePrompt;$LineBottom}
} else {
$box = &{$LineTop;1..($Height - 2) |% {$LineField};$LineBottom}
}
$boxBuffer = $Host.UI.RawUI.NewBufferCellArray($box,$BorderColor,$BackgroundColor)
return ,$boxBuffer
}
function Move-Buffer {
param(
$Position = $global:BufferPosition,
[int]$Left = $($global:BufferBoxSides/2),
[int]$Top = (2 - $global:BufferHeight),
[int]$Width = $global:BufferWidth - $global:BufferBoxSides,
[int]$Height = $global:BufferHeight,
[int]$Offset = -1
)
$Position.X += $Left
$Position.Y += $Top
$Rect = New-Object $RectType $Position.X, $Position.Y, ($Position.X + $width), ($Position.Y + $height -1)
$Position.Y += $OffSet
$Host.UI.RawUI.ScrollBufferContents($Rect, $Position, $Rect, (new-object System.Management.Automation.Host.BufferCell(' ',$global:BufferForegroundColor,$global:BufferBackgroundColor,'complete')))
}
function Out-Buffer {
param(
[Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
$Message,
[Parameter(ValueFromPipelineByPropertyName=$true)]
$ForegroundColor = $global:BufferForegroundColor,
[Parameter(ValueFromPipelineByPropertyName=$true)]
$BackgroundColor = $global:BufferBackgroundColor,
[switch]$NoScroll,
[Parameter(ValueFromPipelineByPropertyName=$true)]
$Position = $global:BufferPosition,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[int]$Left = 0,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[int]$Top = $(3 - $global:BufferHeight), # Box Edge + New Lines
[Parameter(ValueFromPipelineByPropertyName=$true)]
[int]$Width = ($global:BufferWidth - $global:BufferBoxSides), # Box Edge
[Parameter(ValueFromPipelineByPropertyName=$true)]
[int]$Height = ($global:BufferHeight - $global:BufferBoxSides), # Box Edge
[Parameter(ValueFromPipelineByPropertyName=$true)]
[int]$Offset = $( 0 - ($Message.Split("`n").Count))
)
process {
$lineCount = $Message.Split("`n").Count
$Width = $Width - ($global:BufferPadding * 2)
if(!$NoScroll){ Move-Buffer $Position $Left $Top $Width $Height $Offset }
$MessageBuffer = New-Object "System.Management.Automation.Host.BufferCell[,]" $lineCount, $width
$index = 0
foreach( $line in $Message.Split("`n") ) {
$Buffer = $Host.UI.RawUI.NewBufferCellArray( @($line.Trim("`r").PadRight($Width)), $ForegroundColor, $BackgroundColor )
for($i = 0; $i -lt $width; $i++) {
$MessageBuffer[$index,$i] = $Buffer[0,$i]
}
$index++
}
$Y = $global:BufferPosition.Y
$global:BufferPosition.Y -= $lineCount - 1
$Host.UI.RawUI.SetBufferContents($global:BufferPosition,$MessageBuffer)
$global:BufferPosition.Y = $Y
}
}
function Set-BufferInputLine {
param([String]$Line = "")
$PromptText = $line.PadRight(($global:BufferWidth - $line.Length - 3)) # Prompt = "> "
$CursorPosition = $BufferPromptPosition
$CursorPosition.X += $line.Length
$Prompt = $Host.UI.RawUI.NewBufferCellArray( @($PromptText),$global:BufferForegroundColor, $global:BufferBackgroundColor)
$Host.UI.RawUI.SetBufferContents( $BufferPromptPosition, $prompt )
$Host.UI.RawUI.CursorPosition = $CursorPosition
}
function Demo1 {
$Position = $Host.UI.RawUI.WindowPosition
$Position.X += 10
$Position.Y += 3
Reset-Buffer $Position 20 66 3 -ForegroundColor 'Gray' -BackgroundColor 'Black' -BorderColor 'Green'
Out-Buffer 'Greetings!' 'Yellow' 'black'
sleep -m 600
Out-Buffer '' 'Gray' 'black'
sleep -m 600
Out-Buffer '- - - Thank you for running this simple demo script! - - -' 'Green' 'black'
sleep -m 600
Out-Buffer '' 'Gray' 'black'
sleep -m 600
Out-Buffer 'We are demonstrating how the scroll buffer works: you can
add more than one line at a time, but you don''t really
need to, since they add almost as fast one at a time.' 'white' 'black'
sleep -m 3000
Out-Buffer '' 'Gray' 'black'
Out-Buffer 'That is, as long as you don''t have any delay, you can just' 'white' 'black'
Out-Buffer 'write out as many lines as you like, one-at-a-time, like' 'white' 'black'
Out-Buffer 'this, and there is really no downside to doing that.' 'white' 'black'
sleep -m 3000
Out-Buffer '' 'Gray' 'black'
Out-Buffer 'Right? '.PadRight(58,"-") 'Red' 'black'
Out-Buffer '' 'Gray' 'black'
sleep -m 600
Out-Buffer 'It''s clearly not as slick to just pop in multiple lines' 'white' 'black'
sleep -m 1200
Out-Buffer 'with absolutely no scroll delay, and it makes it a little ' 'white' 'black'
sleep -m 1200
Out-Buffer 'hard to tell what you have read already, but that''s ok.' 'white' 'black'
sleep -m 1200
Out-Buffer '' 'Gray' 'black'
sleep -m 600
Out-Buffer 'If you delay between paragraphs.' 'Red' 'black'
sleep -m 600
Out-Buffer '' 'Gray' 'black'
sleep -m 600
Out-Buffer 'But: don''t scroll off-screen faster than I can read!' 'Yellow' 'black'
sleep -m 600
Out-Buffer '' 'Gray' 'black'
}
## Test-BufferBox 3.0
####################################################################################################
## Imagine it's a chat window: you can type, but the whole time, the ongoing conversation in the
## chat room you have joined is going on in the background.
##
## NOTE: because this is a "chat" demo, we treat your input as text, and to execute script in-line
## you have to enclose it inside $() braces.
####################################################################################################
function Demo2 {
param( $title = "PowerShell Interactive Buffer Demo" )
Reset-Buffer -ShowInput -Title $Title
###################################################################################################
##### We only need this for the purposes of the demo...
##### In a real script you would, presumably, be getting stuff from somewhere else to display
$noise = $MyInvocation.MyCommand.Definition -split "`n"
$index = 0;
$random = New-Object "Random"
##### Printing a "How to Exit" message
Out-Buffer " " -Fore DarkGray -Back Cyan
Out-Buffer " This is just a demo. " -Fore Black -Back Cyan
Out-Buffer " We will stream in the source code of this script ... " -Fore Black -Back Cyan
Out-Buffer " And you can type at the bottom while it's running. " -Fore Black -Back Cyan
Out-Buffer " Imagine this as an n-way chat application like IRC, except that " -Fore Black -Back Cyan
Out-Buffer " FOR THIS PERFORMANCE ONLY: " -Fore Black -Back Cyan
Out-Buffer " The part of your chatting friends is played by my source code. " -Fore DarkGray -Back Cyan
Out-Buffer " " -Fore DarkGray -Back Cyan
Out-Buffer " Press ESC to exit, or enter 'exit' and hit Enter" -Fore Black -Back Cyan
Out-Buffer " " -Fore DarkGray -Back Cyan
##### Setting the prompt
Set-BufferInputLine
##### And initializing our two variables ...
$line=""
$exit = $false
while(!$exit){
while(!$exit -and $Host.UI.RawUI.KeyAvailable) {
$char = $Host.UI.RawUI.ReadKey("IncludeKeyUp,IncludeKeyDown,NoEcho");
# we don't want the key up events, but we do want to get rid of them
if($char.KeyDown) {
switch([int]$char.Character) {
13 { # Enter
if($line.Trim() -eq "exit") { $exit = $true; break; }
###################################################################################################
###################################################################################################
############# WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING #############
############# This executes the user input! #############
############# Don't use this on, say, content you got from a web page or chat room #############
iex "Out-Buffer `"$line`" -Fore Red"; #############
###################################################################################################
###################################################################################################
$line = "";
Set-BufferInputLine
}
27 { # Esc
$exit = $true; break;
}
8 { # Backspace
if($line.Length -gt 0) {
$line = $line.SubString(0,$($line.Length-1))
}
# $pos = $Host.UI.RawUI.CursorPosition
Set-BufferInputLine $line
}
0 {
# Not actually a key
# Out-Buffer $($Char | Out-String)
}
default {
$line += $char.Character
Set-BufferInputLine $line
}
}
}
}
# Simulate doing useful things 25% of the time
if($random.NextDouble() -gt 0.75) {
$noise[($index)..($index++)] | Out-Buffer
if($index -ge $noise.Length){$index = 0}
}
sleep -milli 100
}
$CursorPosition = $BufferPromptPosition
$CursorPosition.Y += 2
$CursorPosition.X = 0
$Host.UI.RawUI.CursorPosition = $CursorPosition
}
|
PowerShellCorpus/PoshCode/Set-Computername.ps1
|
Set-Computername.ps1
|
function Set-ComputerName {
param( [switch]$help,
[string]$computerName=$(read-host "Please specify the new name of the computer"))
$usage = "set-ComputerName -computername AnewName"
if ($help) {Write-Host $usage}
$computer = Get-WmiObject Win32_ComputerSystem
$computer.Rename($computerName)
}
|
PowerShellCorpus/PoshCode/Fifteen.ps1
|
Fifteen.ps1
|
Imports System
Imports System.Drawing
Imports System.Reflection
Imports System.Globalization
Imports System.Windows.Forms
<assembly: AssemblyDescription("Fifteen")>
<assembly: AssemblyProduct("fifteen.exe")>
<assembly: AssemblyTitle("Fifteen")>
<assembly: AssemblyVersion("2.0.0.0")>
<assembly: CLSCompliant(True)>
Namespace Fifteen
Class AssemblyInfo
Private asm As Type
Public Sub New()
asm = GetType(frmMain)
End Sub
Public ReadOnly Property Title() As String
Get
Dim atr As Type = GetType(AssemblyTitleAttribute)
Dim r() As Object = asm.Assembly.GetCustomAttributes(atr, False)
Dim ata As AssemblyTitleAttribute = CType(r(0), AssemblyTitleAttribute)
Return ata.Title
End Get
End Property
End Class
Class frmMain
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
Private mnuMain As MainMenu
Private mnuFile As MenuItem
Private mnuPlay As MenuItem
Private mnuExit As MenuItem
Private mnuHelp As MenuItem
Private mnuInfo As MenuItem
Private lblTime As Label
Private tmrTick As Timer
Private sbMoves As StatusBar
'two static fields
Private Const pnt As Integer = 4
Private Const nul As Integer = pnt * pnt
'additional fields
Private nulX As Integer = pnt - 1, nulY As Integer = pnt - 1
Private btnNums As Button(,) = New Button(3, 3) {}
Private num As Integer(,) = New Integer(3, 3) {}
Private bln As Boolean
Private mov As UInteger
Private spn As TimeSpan
Private rnd As New Random()
Private Sub InitializeComponent()
Me.mnuMain = New MainMenu()
Me.mnuFile = New MenuItem()
Me.mnuPlay = New MenuItem()
Me.mnuExit = New MenuItem()
Me.mnuHelp = New MenuItem()
Me.mnuInfo = New MenuItem()
Me.lblTime = New Label()
Me.tmrTick = New Timer()
Me.sbMoves = New StatusBar()
'
'mnuMain
'
Me.mnuMain.MenuItems.AddRange(New MenuItem() {Me.mnuFile, Me.mnuHelp})
'
'mnuFile
'
Me.mnuFile.MenuItems.AddRange(New MenuItem() {Me.mnuPlay, Me.mnuExit})
Me.mnuFile.Text = "&Game"
'
'mnuPlay
'
Me.mnuPlay.Shortcut = Shortcut.F5
Me.mnuPlay.Text = "&Play"
AddHandler mnuPlay.Click, AddressOf mnuPlay_Click
'
'mnuExit
'
Me.mnuExit.Shortcut = Shortcut.CtrlX
Me.mnuExit.Text = "E&xit"
AddHandler mnuExit.Click, AddressOf mnuExit_Click
'
'mnuHelp
'
Me.mnuHelp.MenuItems.AddRange(New MenuItem() {Me.mnuInfo})
Me.mnuHelp.Text = "&Help"
'
'mnuInfo
'
Me.mnuInfo.Text = "About..."
AddHandler mnuInfo.Click, AddressOf mnuInfo_Click
'
'lblTime
'
Me.lblTime.BackColor = Color.Linen
Me.lblTime.BorderStyle = BorderStyle.FixedSingle
Me.lblTime.Font = New Font("Tahoma", 14, FontStyle.Bold)
Me.lblTime.Location = New Point(10, 10)
Me.lblTime.Size = New Size(pnt * 50, 20)
Me.lblTime.Text = "00:00:00"
Me.lblTime.TextAlign = ContentAlignment.MiddleCenter
'
'tmrTick
'
Me.tmrTick.Enabled = False
Me.tmrTick.Interval = 1000
AddHandler tmrTick.Tick, AddressOf tmrTick_Tick
'
'frmMain
'
Me.BackColor = Color.MintCream
Me.ClientSize = New Size(pnt * 50 + 20, pnt * 50 + 70)
Me.Controls.AddRange(New Control() {Me.lblTime, Me.sbMoves})
Me.FormBorderStyle = FormBorderStyle.FixedSingle
Me.MaximizeBox = False
Me.Menu = Me.mnuMain
Me.StartPosition = FormStartPosition.CenterScreen
AddHandler Load, AddressOf frmMain_Load
End Sub
Private Sub mnuPlay_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim i As Integer, j As Integer, vec As Integer
Dim mix As Integer = pnt * 100
For k As Integer = 0 To mix - 1
vec = rnd.Next(4)
'moving vector
Select Case vec.ToString(CultureInfo.CurrentCulture)
Case "0"
If nulX - 1 >= 0 Then
num(nulX, nulY) = num(nulX - 1, nulY)
nulX -= 1
Else
For i = 0 To pnt - 2
num(i, nulY) = num(i + 1, nulY)
Next
nulX = pnt - 1
End If
Exit Select
Case "1"
If nulX + 1 < pnt Then
num(nulX, nulY) = num(nulX + 1, nulY)
nulX += 1
Else
For i = pnt - 1 To 1 Step - 1
num(i, nulY) = num(i - 1, nulY)
Next
nulX = 0
End If
Exit Select
Case "2"
If nulY - 1 >= 0 Then
num(nulX, nulY) = num(nulX, nulY - 1)
nulY -= 1
Else
For j = 0 To pnt - 2
num(nulX, j) = num(nulX, j + 1)
Next
nulY = pnt - 1
End If
Exit Select
Case Else
If nulY + 1 < pnt Then
num(nulX, nulY) = num(nulX, nulY + 1)
nulY += 1
Else
For j = pnt - 1 To 1 Step - 1
num(nulX, j) = num(nulX, j - 1)
Next
nulY = 0
End If
Exit Select
End Select
num(nulX, nulY) = nul
Next
'break order
For i = 0 To pnt - 1
For j = 0 To pnt - 1
If num(i, j) <> nul Then
btnNums(i, j).Text = Convert.ToString(num(i, j), CultureInfo.CurrentCulture)
Else
btnNums(i, j).Text = ""
End If
Next
Next
'flush data
mov = 0
spn = New TimeSpan(0, 0, 0)
bln = True
lblTime.Text = "00:00:00"
sbMoves.Text = "Moves: " & mov
tmrTick.Start()
End Sub
Private Sub mnuExit_Click(ByVal sender As Object, ByVal e As EventArgs)
Application.Exit()
End Sub
Private Sub mnuInfo_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim frm As New frmAbout()
frm.ShowDialog(Me)
frm.Dispose()
End Sub
Private Sub tmrTick_Tick(ByVal sender As Object, ByVal e As EventArgs)
spn += New TimeSpan(0, 0, 1)
lblTime.Text = spn.ToString()
End Sub
Private Sub frmMain_Load(ByVal sender As Object, ByVal e As EventArgs)
'window caption
Dim ai As New AssemblyInfo()
Me.Text = ai.Title
'generate field of buttons
For i As Integer = 0 To pnt - 1
For j As Integer = 0 To pnt - 1
btnNums(i, j) = New Button()
btnNums(i, j).Parent = Me
num(i, j) = i * pnt + j + 1
If num(i, j) <> nul Then
btnNums(i, j).Text = Convert.ToString(num(i, j), CultureInfo.CurrentCulture)
End If
'position and style of a button
btnNums(i, j).Left = 10 + j * 50
btnNums(i, j).Top = 40 + i * 50
btnNums(i, j).Size = New Size(50, 50)
btnNums(i, j).BackColor = Color.Linen
btnNums(i, j).Font = New Font("Tahoma", 14, FontStyle.Bold)
btnNums(i, j).Tag = New Point(i, j)
'event for a button
AddHandler btnNums(i, j).Click, AddressOf btnNumX_Click
Next
Next
'moves at start
sbMoves.Text = "Moves: " & mov
End Sub
'is winner?
Private Function PuzzleDone() As Boolean
Dim k As Integer = 1
For i As Integer = 0 To pnt - 1
For j As Integer = 0 To pnt - 1
If num(i, j) <> k Then
Return False
End If
k += 1
Next
Next
Return True
End Function
'counting moves
Private Function MovesLeft() As String
mov += 1
Return ("Moves: " & mov)
End Function
Private Sub btnNumX_Click(ByVal obj As Object, ByVal e As EventArgs)
If Not bln Then
Return
End If
Dim btn As Button = DirectCast(obj, Button)
Dim i As Integer = CType(btn.Tag, Point).X
Dim j As Integer = CType(btn.Tag, Point).Y
'moving
If Math.Abs(i - nulX) + Math.Abs(j - nulY) = 1 Then
num(nulX, nulY) = num(i, j)
btnNums(nulX, nulY).Text = btnNums(i, j).Text
'null
nulX = i
nulY = j
num(nulX, nulY) = nul
btnNums(nulX, nulY).Text = ""
'moves
sbMoves.Text = MovesLeft()
End If
'wins
If nulX = pnt - 1 AndAlso nulY = pnt - 1 Then
If PuzzleDone() Then
tmrTick.Stop()
End If
End If
End Sub
'if focus lost set pause and back
Protected Overrides Sub OnActivated(ByVal ea As EventArgs)
MyBase.OnActivated(ea)
If bln Then
tmrTick.Start()
End If
End Sub
Protected Overrides Sub OnDeactivate(ByVal ea As EventArgs)
MyBase.OnDeactivate(ea)
If bln Then
tmrTick.Stop()
End If
End Sub
End Class
Class frmAbout
Inherits Form
Public Sub New()
InitializeComponent()
End Sub
Private pbImage As PictureBox
Private lblName As Label
Private lblDesc As Label
Private btnExit As Button
Private Sub InitializeComponent()
Me.pbImage = New PictureBox()
Me.lblName = New Label()
Me.lblDesc = New Label()
Me.btnExit = New Button()
'
'pbImage
'
Me.pbImage.Location = New Point(16, 16)
Me.pbImage.Size = New Size(32, 32)
Me.pbImage.SizeMode = PictureBoxSizeMode.StretchImage
'
'lblName
'
Me.lblName.Font = New Font("Microsoft Sans Serif", 9.5F, FontStyle.Bold)
Me.lblName.Location = New Point(52, 19)
Me.lblName.Size = New Size(360, 18)
Me.lblName.Text = "Fifteen v1.00"
'
'lblDesc
'
Me.lblDesc.Location = New Point(67, 37)
Me.lblDesc.Size = New Size(360, 23)
Me.lblDesc.Text = "This is an example that you can make better."
'
'btnExit
'
Me.btnExit.Location = New Point(135, 67)
Me.btnExit.Text = "OK"
'
'frmAbout
'
Me.AcceptButton = Me.btnExit
Me.CancelButton = Me.btnExit
Me.ClientSize = New Size(350, 100)
Me.Controls.AddRange(New Control() {Me.pbImage, Me.lblName, Me.lblDesc, Me.btnExit})
Me.FormBorderStyle = FormBorderStyle.FixedToolWindow
Me.ShowInTaskbar = False
Me.StartPosition = FormStartPosition.CenterParent
Me.Text = " About..."
AddHandler Load, AddressOf frmAbout_Load
End Sub
Private Sub frmAbout_Load(ByVal sender As Object, ByVal e As EventArgs)
pbImage.Image = Me.Owner.Icon.ToBitmap()
End Sub
End Class
Friend NotInheritable Class Program
<STAThread()> _
Shared Sub Main()
Application.EnableVisualStyles()
Application.Run(New frmMain())
End Sub
End Class
End Namespace
|
PowerShellCorpus/PoshCode/Get-ObjectIdentifier.ps1
|
Get-ObjectIdentifier.ps1
|
#####################################################################
# Get-ObjectIdentifier.ps1
# Version 1.0
#
# Resolves OID value to a Friendly Name and vice versa.
#
# Vadims Podans (c) 2010
# http://en-us.sysadmins.lv/
#####################################################################
#requires -Version 2.0
function Get-ObjectIdentifier {
<#
.Synopsis
Resolves OID value to a Friendly Name and vice versa.
.Description
Resolves OID value to a Friendly Name and vice versa. The cmdlet resolves both
well-known OIDs (used in Internet PKI) and Active Directory forest specific
registered OIDs.
.Parameter OIDString
Specifies the OID value or Friendly name.
.Example
Get-ObjectIdentifier "Server Authentication"
Will resolve "Server Authentication" OID to an object identifier value (1.3.6.1.5.5.7.3.1).
.Example
Get-ObjectIdentifier "1.3.6.1.5.5.7.3.9"
Will resolve "1.3.6.1.5.5.7.3.9" value to a friendly name (OCSP Signing).
.Outputs
System.Security.Cryptography.Oid
#>
[CmdletBinding()]
[OutputType('System.Security.Cryptography.Oid')]
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[String[]]$OIDString
)
$OIDString | %{New-Object Security.Cryptography.Oid $OIDString}
}
|
PowerShellCorpus/PoshCode/Get-SameTimeChatHistory.ps1
|
Get-SameTimeChatHistory.ps1
|
# TITLE: Get-SameTimeChatHistory.ps1
# PURPOSE: Reads Sametime R8 chat transcript HTML files and outputs custom objects
# AUTHOR: Hal Rottenberg <hal@halr9000.com
# OUTPUT:
# - [datetime] Timestamp - can be easily filtered
# - [string] LastName
# - [string] FirstName
# - [string] Message
#
# REQUIREMENTS:
# - Must install PoshHttp snapin to use the ConvertFrom-Html cmdlet
# http://huddledmasses.org/get-web-another-round-of-wget-for-powershell/
# (Cmdlet needed because the HTML files won't cast to XML nicely.)
# - Sametime R8 chat client transcripts
#
# TODO:
# - each session needs an index to aid with sorting & grouping
# - parameters to limit transcripts by name or date
# - there's a minor null index bug somewhere
# - automatically determine location of transcripts
param (
$TranscriptPath = "$env:userprofile\\SametimeTranscripts"
)
# get all chat transcript files
$html = Get-ChildItem -Recurse -Path $TranscriptPath -Filter *.html
$html | Foreach-Object {
# convert contents of each HTML file to XML using PoshHttp cmdlet
$xml = $_ | Get-Content | ConvertFrom-Html
# each XML object represents a single chat session with a single contact
$xml | Foreach-Object {
# each chat session has multiple message blocks
$mb = $_.html.body.div[1].div
$day = $mb[0].InnerText # first record in block is the day the chat occurred
$mb[1..$mb.Length] | Foreach-Object {
$_ | Foreach-Object {
$out = "" | Select-Object Timestamp, LastName, FirstName, Message
# username field is an ugly LDAP CN field that needs fixing
$uname = $_.username -split '/' -replace '\\\\' -replace ' '
$out.LastName = $uname[0]
$out.FirstName = $uname[1]
$out.Timestamp = [datetime]( $day + " " + $_.div[0].nobr )
$out.Message = $_.div[2].span[0]."#text"
Write-Output $out
}
}
}
}
|
PowerShellCorpus/PoshCode/IniFile Functions 1.1.ps1
|
IniFile Functions 1.1.ps1
|
function Get-IniSection($inifile,$section)
{
$sections = select-string "^\\[.*\\]" $inifile
if(!$section) {
return $sections | %{$_.Line.Trim("[]")}
}
$start = 0
switch($sections){
{$_.Line.Trim() -eq "[$section]"}{
$start = $_.LineNumber -1
}
default {
if($start){
return (gc $inifile)[($start)..($start + ($_.LineNumber-2 - $start))]
}
}
}
$lines = gc $inifile
return $lines[$start..($lines.length-1)]
}
function Get-IniValue($inifile,$section,$name)
{
$section = Get-IniSection $inifile $section
($section | Select-String "^\\s*$name\\s*=").Line.Split("=",2)[1]
}
function Set-IniValue($inifile,$section,$name,$value)
{
$lines = gc $inifile
$sections = select-string "^\\[.*\\]" $inifile
$start,$end = 0,0
@@ if($sections.GetType().IsArray) {
for($l=0; $l -lt $sections.Count; ++$l){
if($sections[$l].Line.Trim() -eq "[$section]") {
$start = $sections[$l].LineNumber
if($l+1 -ge $sections.Count) {
$end = $lines.length-1;
} else {
$end = $sections[$l+1].LineNumber -2
}
}
@@ }
@@ } else {
@@ if($sections.Line.Trim() -eq "[$section]") {
@@ $start = $sections.LineNumber
@@ $end = $lines.length-1
@@ }
@@ }
if($start -and $end) {
$done = $false
for($l=$start;$l -le $end;++$l){
if( $lines[$l] -match "^\\s*$name\\s*=" ) {
$lines[$l] = "{0} = {1}" -f $name, $value
$done = $true
break;
}
}
if(!$done) {
$output = $lines[0..$start]
$output += "{0} = {1}" -f $name, $value
$output += $lines[($start+1)..($lines.Length-1)]
$lines = $output
}
}
Set-Content $inifile $lines
}
##
## This is a ... different way of doing it,
## which will be faster if you need to read lots of values
#### HOWEVER ####
## I don't recommend using Set-IniFile, because it will loose any comments etc
##
function Get-IniFile {
param([string]$inifile=$(Throw "You must specify the name of an ini file!"))
$INI = @{}
$s,$k,$v = $null
foreach($line in (gc $inifile | ? {$_[0] -ne ";" -and $_.Trim().Length -gt 0})) {
$k,$v = $line.Split("=",2)
if($v -eq $null) {
$s = $k.Trim("[]")
$INI[$s] = @{}
} else {
$INI[$s][$k.Trim()] = $v.Trim()
}
}
return $INI
}
function Set-IniFile {
param([HashTable]$ini,[string]$inifile=$(Throw "You must specify the name of an ini file!"))
[string[]]$inistring = @()
foreach($section in $ini.Keys) {
#Add-Content $inifile ("[{0}]" -f $section)
$inistring += ("`n[{0}]" -f $section)
foreach($key in $ini[$section].Keys) {
$inistring += ("{0} = {1}" -f $key, $ini[$section][$key])
}
}
# make the write be atomic ...
Set-Content $inifile $inistring
}
|
PowerShellCorpus/PoshCode/Enable_Disable NIC, XP+.ps1
|
Enable_Disable NIC, XP+.ps1
|
# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# Name: ifstate
# Author: Kris Cieslak (defaultset.blogspot.com)
# Date: 2010-04-21
# Description: Enabling/Disabling network adapter.
# Works on Windows XP and higher.
# If your os is WinXP and its language is not English,
# you'll have to change values in $UpStateLabel and $DownStateLabel
#
# Parameters: network interface name,
# state [up/down] (optional, if up then down, or if down then up :))
# Usage example:
# ./ifstate 'Local network connection' down
# or
# ./ifstate 'Local network connection'
#
# -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
PARAM ($ifname = $(throw "Specifiy interface name"),$state = "")
trap [Exception] {
Write-Host 'Ups! Something wrong.' -ForegroundColor Red
continue;
}
# These values depends on your os language
@@$UpStateLabel = 'En&able';
@@$DownStateLabel = 'Disa&ble';
$st = 0;
if ($state.length -gt 0) {
switch ($state.ToLower()) {
'up' { $st = 1 }
'down' {$st = 0 }
}
} else {
$c =(gwmi Win32_NetworkAdapter | ? { $_.NetConnectionID -eq $ifname }).ConfigManagerErrorCode;
if ($c -eq 22) { $st = 1 } else { $st = 0 }
}
if ($st -eq 1) {
$StateLabel = $UpStateLabel;
} else {
$StateLabel = $DownStateLabel;
}
if ([int](([regex]('\\d{1,3}')).match((gwmi win32_OperatingSystem).Version).ToString()) -le 5) {
$shell = New-Object -comObject Shell.Application;
$test=(($shell.NameSpace(3).Items() |
? { $_.Path -like '*7007ACC7-3202-11D1-AAD2-00805FC1270E*'}).GetFolder.Items() |
? { $_.Name -eq $ifname }).Verbs() | ? { $_.Name -eq $StateLabel }
if ($test -ne $null) {
($test).DoIt()
}
} else {
if ($st -eq 1) {
(gwmi Win32_NetworkAdapter | ? { $_.NetConnectionID -eq $ifname } ).Enable() | Out-Null
} else {
(gwmi Win32_NetworkAdapter | ? { $_.NetConnectionID -eq $ifname } ).Disable() | Out-Null
}
}
|
PowerShellCorpus/PoshCode/ActiveDirectoryFunctions.ps1
|
ActiveDirectoryFunctions.ps1
|
#.SYNOPSIS
# Gets a directory entry from ActiveDirectory based on the login user name
function Get-ADUser {
[CmdletBinding()]
param([string]$UserName=${Env:userName})
$ads = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'')
$ads.filter = "(&(objectClass=Person)(samAccountName=$UserName))"
$ads.FindAll().GetEnumerator() | %{ $_.GetDirectoryEntry() }
}
#.SYNOPSIS
# Gets a directory entry from ActiveDirectory based on the computer name
function Get-ADComputer {
[CmdletBinding()]
param([string]$ComputerName=${Env:ComputerName})
$ads = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'')
$ads.filter = "(&(objectClass=Computer)(name=$ComputerName))"
$ads.FindAll().GetEnumerator() | %{
$Computer = $_.GetDirectoryEntry()
$Computer = Resolve-PropertyValueCollection -InputObject $Computer
Add-Member -InputObject $Computer -Type NoteProperty -Name SID -Value $(new-object security.principal.securityidentifier $Computer.objectSID, 0)
Add-Member -InputObject $Computer -Type NoteProperty -Name GUID -Value $(new-object GUID (,[byte[]]$Computer.objectGUID))
Add-Member -InputObject $Computer -Type NoteProperty -Name CreatorSID -Value $(new-object security.principal.securityidentifier $Computer."mS-DS-CreatorSID", 0)
$Computer
}
}
#.SYNOPSIS
# Gets a directory entry from ActiveDirectory based on the group's friendly name
function Get-ADGroup {
[CmdletBinding()]
param([string]$UserName)
$ads = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'')
$ads.filter = "(&(objectClass=Group)(samAccountName=$UserName))"
$ads.FindAll().GetEnumerator() | %{ $_.GetDirectoryEntry() }
}
#.SYNOPSIS
# Look up a DN from a user's (login) name
function Get-DistinguishedName {
[CmdletBinding()]
param([string]$UserName)
(Get-ADUser $UserName).DistinguishedName
}
#.SYNOPSIS
# Get Active Directory group membership recursively
#.EXAMPLE
# $groups = Get-GroupMembership (Get-DistinguishedName Jaykul)
#.EXAMPLE
# $groups = Get-GroupMembership (Get-DistinguishedName Jaykul) -RecurseLimit 0
#
# Gets the groups the user belongs to without recursing
function Get-GroupMembership {
[CmdletBinding()]
param([string]$Name,[int]$RecurseLimit=-1)
if(!$Name.StartsWith("CN=","InvariantCultureIgnoreCase")) {
$Name = Get-DistinguishedName $Name
}
$groups = ([adsi]"LDAP://$Name").MemberOf
if ($groups -and $RecurseLimit) {
Foreach ($gr in $groups) {
$groups += @(Get-GroupMembership $gr -RecurseLimit:$($RecurseLimit-1) |
? {$groups -notcontains $_})
}
}
return $groups | Convert-DistinguishedName
}
function Convert-DistinguishedName {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Position=0)]
[string]$name
)
process {
if(!$Name.StartsWith("CN=","InvariantCultureIgnoreCase")) {
$Name = Get-DistinguishedName $Name
}
$name -replace "CN=","Name=" -replace "DC=","Domain=" -replace "OU=","Org=" | ConvertFrom-PropertyString -Delimiter "," | ForEach { $_.Domain = $_.Domain -join "."; $_ } | Add-Member NoteProperty DN $name -passthru
}
}
function Resolve-PropertyValueCollection {
param(
[Parameter(ValueFromPipeline=$true)]
$InputObject
)
process {
$SingleMembers = @()
$MultiMembers = @()
$InputObject | Get-Member -Type Property | ForEach-Object {
$Name = $_.Name
if($InputObject.($Name).Count -le 1) {
$SingleMembers += $Name
} else {
$MultiMembers += $Name
}
}
$OutputObject = Select-Object -InputObject $InputObject -Property $MultiMembers
foreach($member in $singleMembers) {
Add-Member -InputObject $OutputObject -Type NoteProperty -Name $Member -Value ($InputObject.$Member)[0]
}
$OutputObject
}
}
#. SYNOPSIS
# Pretty-print the vitals on a user...
function Select-UserInfo {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,Position=0,ParameterSetName="Input",ValueFromPipeline=$true)]
[System.DirectoryServices.DirectoryEntry[]]$InputObject
,
[Parameter(Mandatory=$true,Position=0,ParameterSetName="Name",ValueFromPipelineByPropertyName=$true)]
[string[]]$name
)
process {
switch($PSCmdlet.ParameterSetName) {
"Name" {
foreach($n in $Name) {
Write-Verbose "Getting $n User Info"
Get-ADUser $n | Resolve-PropertyValueCollection
}
}
"Input" {
foreach($io in $InputObject) {
Write-Verbose "Converting User Info for $($io.displayName)"
Resolve-PropertyValueCollection -InputObject $io
}
}
}
}
}
function Get-GroupMembers {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,Position=0,ParameterSetName="Input",ValueFromPipeline=$true)]
[string]$GroupName
)
process {
Foreach ($member in (Get-ADGroup $GroupName).Members() ) {
new-object System.DirectoryServices.DirectoryEntry $member | Resolve-PropertyValueCollection
}
}
}
|
PowerShellCorpus/PoshCode/Skip-Object.ps1
|
Skip-Object.ps1
|
function Skip-Object {
param(
[int]$First = 0
,
[int]$Last = 0
,
[int]$Every = 0
,
[int]$UpTo = 0
)
begin {
if($Last) {
$Queue = new-object System.Collections.Queue $Last
}
$e = $every
$UpTo++
# $u = $UpTo
}
process {
$_ |
where {
--$First -lt 0
} |
foreach {
if($Last) {
$Queue.EnQueue($_)
if($Queue.Count -gt $Last) {
$Queue.DeQueue()
}
} else { $_ }
} |
foreach {
if(!$UpTo) {
$_
} elseif( --$u -le 0) {
$_; $U = $UpTo
}
} |
foreach {
if($every -and (--$e -le 0)) {
$e = $every
} else { $_ }
}
}
}
|
PowerShellCorpus/PoshCode/Set account password.ps1
|
Set account password.ps1
|
Function Set-Password {
#requires -version 2.0
<#
.Synopsis
Allows the changing of the local account password on a local or remote machine.
.Description
Allows the changing of the local account password on a local or remote machine.
.Parameter computer
Computer that the password will be changed on. Supports a single computer or collection of computers and can be processed
through the pipeline.
.Parameter user
Account that will have the password changed.
.Example
Set-Password -computer 'server' -user 'Administrator'
User will be prompted to type in the password for Administrator prior to being changed on 'server'
.Example
Set-Password -computer @('server','server2') -user 'Administrator'
User will be prompted to type in the password for Administrator prior to being changed on 'server' and 'server2'
.Example
@('server','server2') | Set-Password -user 'Administrator'
User will be prompted to type in the password for Administrator prior to being changed on 'server' and 'server2'
.Example
Set-Password -computer (Get-Content hosts.txt) -user 'Administrator'
User will be prompted to type in the password for Administrator prior to being changed on 'server' and 'server2'
.Inputs
None
.Outputs
None
.Link
http://boeprox.wordpress.com
.Notes
NAME: Set-Password
VERSION: 1.0
AUTHOR: Boe Prox
Date: 26 August 2010
#>
[CmdletBinding(
SupportsShouldProcess = $True,
ConfirmImpact = 'low',
DefaultParameterSetName = 'server'
)]
Param (
[Parameter(
ValueFromPipeline=$True,
Position=0,
Mandatory=$True,
HelpMessage="List of servers")]
[ValidateNotNullOrEmpty()]
[array]$computer,
[Parameter(
ValueFromPipeline=$False,
Position=1,
Mandatory=$True,
HelpMessage="Account to change password")]
[ValidateNotNullOrEmpty()]
[string]$user
)
Begin {
Write-Verbose "Building container for report"
$arrlist = @()
Write-Verbose "Prompting for password"
$password = Read-Host "Type password -- VERIFY BEFORE CLICKING RETURN!!!"
Write-Verbose "Checking for existence of error log and clearing contents"
$errorlog = "passwordchangeerrors.txt"
If ([system.io.file]::exists($errorlog)) {
Clear-content $errorlog
}
}
Process {
#Iterate through computer list
ForEach ($c in $computer) {
$temp = New-Object PSobject
Try {
Write-Verbose "Testing Connection to $($c)"
Test-Connection -comp $c -count 1 -ea stop | out-null
#Verify account exists before attempting password change
Write-Verbose "Verifying that $($user) exists on $($computer)"
$colusers = ([ADSI]("WinNT://$c,computer")).children | ? {$_.psbase.schemaClassName -eq "User"} | Select -expand Name
If ($colusers -contains $user) {
Write-Host -foregroundcolor Green "Changing password on $c..."
$ErrorActionPreference = 'stop'
Try {
#Make connection to remote/local computer and user account
$account = [adsi]("WinNT://"+$c+"/$user, user")
#Change password on user account
If ($pscmdlet.ShouldProcess($($user))) {
$account.psbase.invoke("SetPassword", $password)
$account.psbase.CommitChanges()
}
Write-Verbose "Adding information to report"
$temp | Add-Member NoteProperty TimeStamp "$(get-date)"
$temp | Add-Member NoteProperty Server $c
$temp | Add-Member NoteProperty Account $user
$temp | Add-Member NoteProperty Status "Password Changed"
$temp | Add-Member NoteProperty Notes ""
}
Catch {
$errorflag = $True
Write-Verbose "Writing errors to $($errorlog)"
"$(get-date) :: Server:$($c) :: $($error[0].exception)" | Out-File -append $errorlog
Write-Verbose "Adding information to report"
$temp | Add-Member NoteProperty TimeStamp "$(get-date)"
$temp | Add-Member NoteProperty Server $c
$temp | Add-Member NoteProperty Account $user
$temp | Add-Member NoteProperty Status "Error Changing Password"
$temp | Add-Member NoteProperty Notes $error[0]
}
}
Else {
$errorflag = $True
Write-Verbose "Writing errors to $($errorlog)"
"$(get-date) :: Server:$($c) :: $($user) does not exist!)" | Out-File -append $errorlog
Write-Verbose "Adding information to report"
$temp | Add-Member NoteProperty TimeStamp "$(get-date)"
$temp | Add-Member NoteProperty Server $c
$temp | Add-Member NoteProperty Account $user
$temp | Add-Member NoteProperty Status "Unable to change password"
$temp | Add-Member NoteProperty Notes "Username does not exist"
}
}
Catch {
$errorflag = $True
Write-Verbose "Writing errors to $($errorlog)"
"$(get-date) :: Server:$($c) :: $($error[0].exception)" | Out-File -append $errorlog
Write-Verbose "Adding information to report"
$temp | Add-Member NoteProperty TimeStamp "$(get-date)"
$temp | Add-Member NoteProperty Server $c
$temp | Add-Member NoteProperty Account $user
$temp | Add-Member NoteProperty Status "Error Connecting to computer"
$temp | Add-Member NoteProperty Notes $error[0]
}
Finally {
#Merge temp report with main report
Write-Verbose "Merging report"
$arrlist += $temp
}
}
}
End {
#Generate report to screen
Write-Verbose "Generating report"
$arrlist
If ($errorflag) {
Write-Host -fore Yellow "Errors were reported during run, please look at $($pwd)\\$($errorlog) for more details."
}
Write-Verbose "Removing password from variable `$password"
$password = $Null
}
}
|
PowerShellCorpus/PoshCode/TruncatePath_1.ps1
|
TruncatePath_1.ps1
|
###
# TruncatePath
# Version 1.0.6 (05 Nov 2008)
# Description: Replaces long provider paths in the prompt with ellipses
# Notes: Place in your profile
#
# By Mike Hays, http://www.mike-hays.net
###
$maxPathLength = 40
$showFullPath = $false
Function Prompt
{
$currentPath = (Get-Location).Path
if ( ($currentPath.Length -gt $maxPathLength) -and ($showFullPath -ne $true) -and (($currentPath.Split("\\")).Count -gt 3) )
{
$currentPathSplit = $currentPath.Split("\\")
$truncatedPath = $currentPathSplit[0] + "\\" + $currentPathSplit[1] + "\\" + "..." + "\\" + `
$currentPathSplit[$currentPathSplit.Length - 1]
if ($truncatedPath.Length -lt $currentPath.Length)
{
$displayPath = $truncatedPath
}
else
{
$displayPath = get-location
}
}
else
{
$displayPath = get-location
}
Write-Host ("PS ") -NoNewLine -ForegroundColor DarkYellow ; Write-Host ("" + $displayPath + ">") -NoNewLine
return " "
}
|
PowerShellCorpus/PoshCode/get-ESXiHostConfigBackup.ps1
|
get-ESXiHostConfigBackup.ps1
|
<#
.SYNOPSIS
Creates config bundle backup for ESXi hosts. Works where 80 is blocked to ESXi host
Originally script by Alan Renouf (http://www.virtu-al.net/2011/02/23/backing-up-the-esxi-system-image)
Heavily Modified by Jimmy Hester
.DESCRIPTION
Checks for connection to a vCenter or ESXi server
If not connected, connects to the server specified
If already connected, connects to the server listed in $Global:DefaultVIServer
Connects to each vmhost in a vCenter, pulls a backup of its configuration, and saves it to the client machine.
If connected to an ESXi host, it will backup that host.
Once backed up, it will disconnect from the server if the connection was intially created by this script. It will leave pre-existing connections intact.
If run in an environment where access to the ESXi host(s) on port 80 (from the machine running this script) is blocked,
the script will bypass the access failure and download the config bundle directly.
See this VMware Community thread for details: http://communities.vmware.com/thread/419926
.PARAMETER <paramName>
VIServer = The name of the vCenter server or ESXi host to use. If a vCenter server is specified, all the hosts in the vCenter will be backed up
If an ESXi host is specified, only that host will be backed up.
#>
Param (
[string]$VIServer
)
#Check for PowerCLI
If ( (Get-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin VMware.VimAutomation.Core
}
#Change this to a local folder that already exists
$RootFolder = "C:\\admin\\ESXi_Backups\\"
If (($VIServer) -and (-not($VIServer -eq $global:defaultviserver))) {
Connect-VIServer $VIServer -Credential (Get-Credential) | Out-Null
Write-Host ""
Write-Host "Connecting to $VIServer"
Write-Host ""
$Disconnect = $true
}
elseif (!$global:DefaultVIServer) {
Write-Host "Cannot determine which VCenter to use. No backups taken."
Write-Host ""
break
}
else {
$VIServer = $global:DefaultVIServer
Write-Host "Connected to $VIServer"
Write-Host ""
}
$VMhosts = Get-VMHost -Server $VIServer
Foreach ($VMhost in $VMhosts) {
Write-Host "Backing up state for $VMhost"
$Date = Get-Date -f yyyyMMdd_hhmm
$Folder = $RootFolder + "$($VIServer)\\" + $Date
If (-not (test-path $Folder)) {
MD $Folder | Out-Null
}
Get-VMHostFirmware $VMhost -BackupConfiguration -DestinationPath $Folder -ErrorAction SilentlyContinue | Out-Null
#Uncomment next line if the path for $Folder has hyphens
#MV ($RootFolder + "*") $Folder -ErrorAction SilentlyContinue
#This will bypass the port http get failure in environments where port 80 is blocked to the ESXi host.
#This tests to see if the Get-VMHostFirmware cmdlet was able to download the config bundle.
#If not, calls the same https URL as the Get-VMHostFirmware cmdlet
If (-not (test-path $Folder\\configBundle-$vmhost.tgz)){
Invoke-Webrequest https://$vmhost/downloads/configBundle-$vmhost.tgz -outfile $folder\\configBundle-$vmhost.tgz
}
}
If ($Disconnect) {
Write-Host "Disconnecting from $VIServer"
Disconnect-VIServer $VIServer -Confirm:$false | Out-Null
}
Write-Host ""
Write-Host "The config backups for $VIServer are located at:"
Write-Host $Folder
Write-Host ""
|
PowerShellCorpus/PoshCode/TruncatePath_2.ps1
|
TruncatePath_2.ps1
|
###
# TruncatePath
# Version 1.0.6 (05 Nov 2008)
# Description: Replaces long provider paths in the prompt with ellipses
# Notes: Place in your profile
#
# By Mike Hays, http://www.mike-hays.net
###
$maxPathLength = 40
$showFullPath = $false
Function Prompt
{
$currentPath = (Get-Location).Path
if ( ($currentPath.Length -gt $maxPathLength) -and ($showFullPath -ne $true) `
-and (($currentPath.Split("\\")).Count -gt 3) )
{
$currentPathSplit = $currentPath.Split("\\")
$truncatedPath = $currentPathSplit[0] + "\\" + $currentPathSplit[1] + "\\" + "..." + "\\" + `
$currentPathSplit[$currentPathSplit.Length - 1]
if ($truncatedPath.Length -lt $currentPath.Length)
{
$displayPath = $truncatedPath
}
else
{
$displayPath = get-location
}
}
else
{
$displayPath = get-location
}
Write-Host ("PS ") -NoNewLine -ForegroundColor DarkYellow ; Write-Host ("" + $displayPath + ">") -NoNewLine
return " "
}
|
PowerShellCorpus/PoshCode/Findup_10.ps1
|
Findup_10.ps1
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.IO;
namespace Findup
{
public class FileInfoExt
{
public FileInfoExt(FileInfo fi)
{
FI = fi;
}
public byte[] SHA512_1st1K = new byte[64];
public byte[] SHA512_All = new byte[64];
public FileInfo FI { get; private set; }
public bool Checked { get; set; }
public bool SHA512_1st1KSet { get; set; }
public bool SHA512_AllSet { get; set; }
}
class Recurse // Add FileInfoExt objects of files matching filenames, file specifications (E.G. *.txt), and in directories in pathRec, to returnList
{
public void Recursive(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfoExt> returnList)
{
foreach (string d in pathRec)
{
Recursive(d, searchPattern, recursiveFlag, returnList);
}
return;
}
public void Recursive(string pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfoExt> returnList)
{
if (File.Exists(pathRec))
{
try
{
returnList.Add(new FileInfoExt(new FileInfo(pathRec)));
}
catch (Exception e)
{
Console.WriteLine("Add file error: " + e.Message);
}
}
else if (Directory.Exists(pathRec))
{
try
{
DirectoryInfo Dir = new DirectoryInfo(pathRec);
foreach (FileInfo addf in (Dir.GetFiles(searchPattern)))
{
returnList.Add(new FileInfoExt(addf));
}
}
catch (Exception e)
{
Console.WriteLine("Add files from Directory error: " + e.Message);
}
if (recursiveFlag == true)
{
try
{
foreach (string d in (Directory.GetDirectories(pathRec)))
{
Recursive(d, searchPattern, recursiveFlag, returnList);
}
}
catch (Exception e)
{
Console.WriteLine("Add Directory error: " + e.Message);
}
}
}
else
{
try
{
string filePart = Path.GetFileName(pathRec);
string dirPart = Path.GetDirectoryName(pathRec);
if (filePart.IndexOfAny(new char[] { '?', '*' }) >= 0)
{
if ((dirPart == null) || (dirPart == ""))
dirPart = Directory.GetCurrentDirectory();
if (Directory.Exists(dirPart))
{
Recursive(dirPart, filePart, recursiveFlag, returnList);
}
else
{
Console.WriteLine("Invalid file path, directory path, file specification, or program option specified: " + pathRec);
}
}
else
{
Console.WriteLine("Invalid file path, directory path, file specification, or program option specified: " + pathRec);
}
}
catch (Exception e)
{
Console.WriteLine("Parse error on: " + pathRec);
Console.WriteLine("Make sure you don't end a directory with a \\\\ when using quotes. The console arg parser doesn't accept that.");
Console.WriteLine("Exception: " + e.Message);
return;
}
}
return;
}
}
class Findup
{
public static void Main(string[] args)
{
Console.WriteLine("Findup.exe v1.0 - use -help for usage information. Created in 2010 by James Gentile.");
Console.WriteLine(" ");
string[] paths = new string[0];
System.Boolean recurse = false;
System.Boolean delete = false;
System.Boolean noprompt = false;
System.Boolean b4b = false;
List<FileInfoExt> fs = new List<FileInfoExt>();
long bytesInDupes = 0; // bytes in all the duplicates
long numOfDupes = 0; // number of duplicate files found.
long bytesRec = 0; // number of bytes recovered.
long delFiles = 0; // number of files deleted.
int c = 0;
int i = 0;
string deleteConfirm;
for (i = 0; i < args.Length; i++)
{
if ((System.String.Compare(args[i], "-help", true) == 0) || (System.String.Compare(args[i], "-h", true) == 0))
{
Console.WriteLine("Usage: findup.exe <file/directory #1> <file/directory #2> ... <file/directory #N> [-recurse] [-delete] [-noprompt]");
Console.WriteLine(" ");
Console.WriteLine("Options: -help - displays this help infomration.");
Console.WriteLine(" -recurse - recurses through subdirectories.");
Console.WriteLine(" -delete - deletes duplicates with confirmation prompt.");
Console.WriteLine(" -noprompt - when used with -delete option, deletes files without confirmation prompt.");
Console.WriteLine(" -b4b - do a byte-for-byte comparison, instead of SHA-512 hashing. Might be much slower, but most secure.");
Console.WriteLine(" ");
Console.WriteLine("Examples: findup.exe c:\\\\finances -recurse");
Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data -recurse -delete -noprompt");
Console.WriteLine(" findup.exe c:\\\\data .\\\\*.txt c:\\\\reports\\\\quarter.doc -recurse -b4b");
Console.WriteLine(" ");
return;
}
if (System.String.Compare(args[i], "-recurse", true) == 0)
{
recurse = true;
continue;
}
if (System.String.Compare(args[i], "-delete", true) == 0)
{
delete = true;
continue;
}
if (System.String.Compare(args[i], "-noprompt", true) == 0)
{
noprompt = true;
continue;
}
if (System.String.Compare(args[i], "-b4b", true) == 0)
{
b4b = true;
continue;
}
Array.Resize(ref paths, paths.Length + 1);
paths[c] = args[i];
c++;
}
if (paths.Length == 0)
{
Console.WriteLine("No files specified, try findup.exe -help");
return;
}
Recurse recurseMe = new Recurse();
recurseMe.Recursive(paths, "*.*", recurse, fs);
if (fs.Count < 2)
{
Console.WriteLine("Findup.exe needs at least 2 files to compare. try findup.exe -help");
return;
}
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(salt); // get 512-bit SHA-512 salt.
for (i = 0; i < fs.Count; i++)
{
if (fs[i].Checked == true) // If file was already matched, then skip to next.
continue;
for (c = i + 1; c < fs.Count; c++)
{
if (fs[c].Checked == true) // skip already matched inner loop files.
continue;
if (fs[i].FI.Length != fs[c].FI.Length) // If file size matches, then check hash.
continue;
if (System.String.Compare(fs[i].FI.FullName, fs[c].FI.FullName, true) == 0) // don't count the same file as a match.
continue;
if (fs[i].SHA512_1st1KSet == false) // check/hash first 1K first.
if (Compute1KHash(fs[i]) == false)
continue;
if (fs[c].SHA512_1st1KSet == false)
if (Compute1KHash(fs[c]) == false)
continue;
if (CompareHash(fs[i].SHA512_1st1K, fs[c].SHA512_1st1K) == false) // if the 1st 1K has the same hash..
continue;
if (b4b == true) // byte for byte comparison specified?
{
if (B4b(fs[i].FI.FullName, fs[c].FI.FullName) == false) // call the byte for byte comparison function
continue;
}
else if (fs[i].FI.Length > 1024) // skip hashing the file again if < 1024 bytes.
{
if (fs[i].SHA512_AllSet == false) // check/hash the rest of the files.
if (ComputeFullHash(fs[i]) == false)
continue;
if (fs[c].SHA512_AllSet == false)
if (ComputeFullHash(fs[c]) == false)
continue;
if (CompareHash(fs[i].SHA512_All, fs[c].SHA512_All) == false)
continue;
}
Console.WriteLine("Match : " + fs[i].FI.FullName);
Console.WriteLine("with : " + fs[c].FI.FullName);
fs[c].Checked = true; // do not check or match against this file again.
numOfDupes++; // increase count of matches.
bytesInDupes += fs[c].FI.Length; // accumulate number of bytes in duplicates.
if (delete != true) // if delete is specified, try to delete the duplicate file.
continue;
if (noprompt == false)
{
Console.Write("Delete the duplicate file <Y/n>?");
deleteConfirm = Console.ReadLine();
if ((deleteConfirm[0] != 'Y') && (deleteConfirm[0] != 'y'))
continue;
}
try
{
File.Delete(fs[c].FI.FullName);
Console.WriteLine("Deleted: " + fs[c].FI.FullName);
bytesRec += fs[c].FI.Length;
delFiles++;
}
catch (Exception e)
{
Console.WriteLine("File delete error: " + e.Message);
}
}
}
Console.WriteLine(" ");
Console.WriteLine("Files checked : {0:N0}", fs.Count);
Console.WriteLine("Duplicate files : {0:N0}", numOfDupes);
Console.WriteLine("Duplicate bytes : {0:N0}", bytesInDupes);
Console.WriteLine("Duplicates deleted : {0:N0}", delFiles);
Console.WriteLine("Recovered bytes : {0:N0}", bytesRec);
return;
}
private static Boolean B4b(string path1, string path2)
{
try
{
using (var stream = File.OpenRead(path1))
{
using (var stream2 = File.OpenRead(path2))
{
System.Boolean EOF = false;
do
{
var length = stream.Read(largeBuf, 0, largeBuf.Length);
var length2 = stream2.Read(largeBuf2, 0, largeBuf2.Length);
if (length != length2)
return false;
if (length != largeBuf.Length)
EOF = true;
int i = 0;
while (i < length)
{
if (largeBuf[i] != largeBuf2[i])
return false;
i++;
}
} while (EOF == false);
}
}
return true;
}
catch (Exception e)
{
Console.WriteLine("Byte for Byte comparison failed: " + e.Message);
return false;
}
}
private static Boolean CompareHash(byte[] hash1, byte[] hash2)
{
int i = 0;
while (i < hash1.Length)
{
if (hash1[i] != hash2[i])
return false;
i++;
}
return true ;
}
private static readonly byte[] readBuf = new byte[1024];
private static readonly byte[] largeBuf = new byte[64*200];
private static readonly byte[] largeBuf2 = new byte[64*200];
private static readonly byte[] salt = new byte[64];
private static byte[] hash = new byte[64];
private static bool Compute1KHash(FileInfoExt path)
{
try
{
using (var stream = File.OpenRead(path.FI.FullName))
{
var length = stream.Read(readBuf, 0, readBuf.Length);
var _SHA512 = SHA512.Create();
_SHA512.TransformBlock(salt, 0, salt.Length, salt, 0);
_SHA512.TransformFinalBlock(readBuf, 0, length);
path.SHA512_1st1K = _SHA512.Hash;
path.SHA512_1st1KSet = true;
return true;
}
}
catch (Exception e)
{
Console.WriteLine("Hash Error: " + e.Message);
return false;
}
}
private static bool ComputeFullHash(FileInfoExt path)
{
try
{
var _SHA512 = SHA512.Create();
_SHA512.TransformBlock(salt, 0, salt.Length, salt, 0);
using (var stream = File.OpenRead(path.FI.FullName))
{
while (true)
{
var length = stream.Read(largeBuf, 0, largeBuf.Length);
if (stream.Position < stream.Length)
_SHA512.TransformBlock(largeBuf, 0, length, largeBuf, 0);
else
{
_SHA512.TransformFinalBlock(largeBuf, 0, length);
break;
}
}
}
path.SHA512_All = _SHA512.Hash;
path.SHA512_AllSet = true;
return true;
}
catch (Exception e)
{
Console.WriteLine("Hash error: " + e.Message);
return false;
}
}
}
}
|
PowerShellCorpus/PoshCode/Powershell iTunes.ps1
|
Powershell iTunes.ps1
|
#
#*****************************************************************
#
# Powershell iTunes v1 $Rev: 752 $
# (c) 2004-2010 Thomas Maurer. All rights reserved.
# created by Thomas Maurer
#
# http://www.thomasmaurer.ch
# http://www.thomasmaurer.ch/projects
#
# last Update by $Author: tmaurer $ on $Date: 2010-11-23 11:52:27 +0100 (Di, 23 Nov 2010) $
#
# Version 1.0.0.0
#
#*****************************************************************
#
# Welcome
Write-Host " " -BackgroundColor Black -ForegroundColor White
Write-Host " ____ __ ____ " -BackgroundColor Black -ForegroundColor White
Write-Host " / __ \\____ _ _____ __________/ /_ ___ / / / " -BackgroundColor Black -ForegroundColor White
Write-Host " / /_/ / __ \\ | /| / / _ \\/ ___/ ___/ __ \\/ _ \\/ / / " -BackgroundColor Black -ForegroundColor White
Write-Host " / ____/ /_/ / |/ |/ / __/ / (__ ) / / / __/ / / " -BackgroundColor Black -ForegroundColor White
Write-Host "/_/ \\____/|__/|__/\\___/_/ /____/_/ /_/\\___/_/_/ " -BackgroundColor Black -ForegroundColor White
Write-Host " " -BackgroundColor Black -ForegroundColor White
Write-Host " _ ______ " -BackgroundColor Black -ForegroundColor White
Write-Host " (_)_ __/_ ______ ___ _____ " -BackgroundColor Black -ForegroundColor White
Write-Host " / / / / / / / / __ \\/ _ \\/ ___/ " -BackgroundColor Black -ForegroundColor White
Write-Host " / / / / / /_/ / / / / __(__ ) " -BackgroundColor Black -ForegroundColor White
Write-Host "/_/ /_/ \\__,_/_/ /_/\\___/____/ " -BackgroundColor Black -ForegroundColor White
Write-Host " " -BackgroundColor Black -ForegroundColor White
Write-Host "******************************************************************" -BackgroundColor Black -ForegroundColor White
Write-Host " " -BackgroundColor Black -ForegroundColor White
Write-Host " Welcome to the Powershell iTunes " -BackgroundColor Black -ForegroundColor White
Write-Host " " -BackgroundColor Black -ForegroundColor White
Write-Host " (c) 2010 Thomas Maurer www.thomasmaurer.ch/projects " -BackgroundColor Black -ForegroundColor White
Write-Host " " -BackgroundColor Black -ForegroundColor White
Write-Host "******************************************************************" -BackgroundColor Black -ForegroundColor White
Write-Host " " -BackgroundColor Black -ForegroundColor White
Write-Host " for Help use the Get-PSiTunesHelp " -BackgroundColor Black -ForegroundColor White
Write-Host " " -BackgroundColor Black -ForegroundColor White
# Add ComObjects to $iTunes
$iTunes = New-Object -ComObject iTunes.Application
# Function to start itunes
function Start-iTunes {
process {
$iTunesRunning = Get-Process | Where-Object {$_.ProcessName -eq "iTunes"}
if(!$iTunesRunning) {
$iTunes = New-Object -ComObject iTunes.Application
Write-Host "(PS iTunes): iTunes started" -BackgroundColor Black -ForegroundColor green
}
else {
Write-Host "(PS iTunes): iTunes allready running" -BackgroundColor Black -ForegroundColor red
}
}
}
# Function to close itunes
function Close-iTunes {
process {
$iTunesRunning = Get-Process | Where-Object {$_.ProcessName -eq "iTunes"}
if(!$iTunesRunning) {
Write-Host "(PS iTunes): iTunes not running" -BackgroundColor Black -ForegroundColor red
}
else {
Stop-Process $iTunesRunning.Id
Write-Host "(PS iTunes): iTunes closed" -BackgroundColor Black -ForegroundColor red
}
}
}
# Function to play a song
function Play-Track {
process {
if ($iTunes.Playerstate -eq "0"){
$iTunes.Play()
Write-Host "(PS iTunes): Now playing:" $iTunes.CurrentTrack.Name "from" $iTunes.CurrentTrack.Artist -BackgroundColor Black -ForegroundColor green
}
else {
Write-Host "(PS iTunes): Already playing Track:" $iTunes.CurrentTrack.Name "from" $iTunes.CurrentTrack.Artist -BackgroundColor Black -ForegroundColor red
}
}
}
# Function to stop a song
function Pause-Track {
process {
if ($iTunes.Playerstate -eq "1"){
$iTunes.Pause()
Write-Host "(PS iTunes): iTunes paused" -BackgroundColor Black -ForegroundColor Red
}
else {
Write-Host "(PS iTunes): Not playing any track" -BackgroundColor Black -ForegroundColor red
}
}
}
# Function to resume a song
function Resume-Track {
process {
if ($iTunes.Playerstate -eq "0"){
$iTunes.Play()
Write-Host "(PS iTunes): Now playing:" $iTunes.CurrentTrack.Name "from" $iTunes.CurrentTrack.Artist -BackgroundColor Black -ForegroundColor green
}
else {
Write-Host "(PS iTunes): Already playing Track:" $iTunes.CurrentTrack.Name "from" $iTunes.CurrentTrack.Artist -BackgroundColor Black -ForegroundColor red
}
}
}
# Function to go a song back
function Back-Track {
process {
$iTunes.BackTrack()
Write-Host "(PS iTunes): Now playing:" $iTunes.CurrentTrack.Name "from" $iTunes.CurrentTrack.Artist -BackgroundColor Black -ForegroundColor green
}
}
# Function to go to the next
function Next-Track {
process {
$iTunes.NextTrack()
Write-Host "(PS iTunes): Now playing:" $iTunes.CurrentTrack.Name "from" $iTunes.CurrentTrack.Artist -BackgroundColor Black -ForegroundColor green
}
}
# Function to get infos about the current track
function Get-CurrentTrack {
process {
Write-Host "(PS iTunes): Currently playing:" $iTunes.CurrentTrack.Name "from" $iTunes.CurrentTrack.Artist -BackgroundColor Black -ForegroundColor White
}
}
# Function to mute itunes
function Mute-iTunes {
process {
if($itunes.Mute -eq $false) {
$itunes.Mute = $true
Write-Host "(PS iTunes): iTunes muted" -BackgroundColor Black -ForegroundColor Red
}
else {
Write-Host "(PS iTunes): iTunes already muted" -BackgroundColor Black -ForegroundColor red
}
}
}
# Function to unmute itunes
function Unmute-iTunes {
process {
if($itunes.Mute -eq $true) {
$itunes.Mute = $false
Write-Host "(PS iTunes): iTunes unmuted" -BackgroundColor Black -ForegroundColor green
}
else {
Write-Host "(PS iTunes): iTunes already unmuted" -BackgroundColor Black -ForegroundColor red
}
}
}
# Function to set iTunes volume up
function Set-VolumeUP {
process {
if($iTunes.SoundVolume -lt 100) {
$iTunes.SoundVolume = $iTunes.SoundVolume + 2
Write-Host "(PS iTunes): iTunes Volume" $iTunes.SoundVolume -BackgroundColor Black -ForegroundColor green
}
else {
Write-Host "(PS iTunes): iTunes Volume is already 100%" -BackgroundColor Black -ForegroundColor red
}
}
}
# Function to set iTunes volume down
function Set-VolumeDown {
process {
if($iTunes.SoundVolume -gt 0) {
$iTunes.SoundVolume = $iTunes.SoundVolume - 2
Write-Host "(PS iTunes): iTunes Volume" $iTunes.SoundVolume -BackgroundColor Black -ForegroundColor red
}
else {
Write-Host "(PS iTunes): iTunes Volume is already 0%" -BackgroundColor Black -ForegroundColor red
}
}
}
# Function to set iTunes
function Set-Volume {
param (
[int]$Volume
)
process {
if($Volume -ge 0 -and $Volume -le 100) {
$iTunes.SoundVolume = $Volume
Write-Host "(PS iTunes): iTunes Volume" $iTunes.SoundVolume -BackgroundColor Black -ForegroundColor green
}
else {
Write-Host "(PS iTunes): Volume has to be 0-100" -BackgroundColor Black -ForegroundColor red
}
}
}
# Function to show the Version of iTunes
function Show-iTunesVersion {
process {
Write-Host "(PS iTunes): iTunes Version" $iTunes.version -BackgroundColor Black -ForegroundColor White
}
}
# Function to show the Version of iTunes
function get-PSiTunesHelp {
process {
Write-Host " "
Write-Host " Powershell iTunes Help"
Write-Host " "
Write-Host "********************************************************"
Write-Host " "
Write-Host " Commands"
Write-Host " "
Write-Host " Start-iTunes Starts iTunes"
Write-Host " Close-iTunes Closes iTunes"
Write-Host " Play-Track Plays a iTunes Track"
Write-Host " Pause-Track Pauses a iTunes Track"
Write-Host " Resume-Track Resumes a iTunes Track"
Write-Host " Back-Track Go to the last iTunes Track"
Write-Host " Next-Track Plays next iTunes Track"
Write-Host " Mute-Track Mutes iTunes"
Write-Host " Unmute-Track Unmutes iTunes"
Write-Host " Show-iTunesVersion Shows iTunes Version"
Write-Host " Set-VolumeDown Set Volume Down"
Write-Host " Set-VolumeUp Set Volume Up"
Write-Host " Set-Volume Set iTunes Volume (0-100)"
}
}
|
PowerShellCorpus/PoshCode/MoveExch2010SP1Archives.ps1
|
MoveExch2010SP1Archives.ps1
|
#=================================================================================
# MoveArchives.ps1
#
# THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
# KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
# PARTICULAR PURPOSE.
#
# Description:
#
# # This Script Written By: David Pekmez (http://unifiedit.wordpress.com/)
#
# Version: 1
# Last Updated: 29/07/2010
#=================================================================================
#=======================================
# Parameter definition
#=======================================
Param(
[string] $User,
[string] $ArchiveDatabase
)
If([String]::IsNullOrEmpty($User)) {
$User = Ĺ*ĺ
}
#==========================================================================
# Function that returns true if the incoming argument is a help request
#==========================================================================
function IsHelpRequest
{
param($argument)
return ($argument -eq "-?" -or $argument -eq "-help");
}
#===================================================================
# Function that displays the help related to this script following
# the same format provided by get-help or <cmdletcall> -?
#===================================================================
function Usage
{
@"
NAME: MoveArchives.ps1
SYNOPSIS:
Move User's Archive to another Database
Exchange 2010 SP1 Requiered
SYNTAX:
MoveArchives.ps1
`t[-User <UserName>]
`t[-ArchiveDatabase <ArchiveDatabaseName>]
PARAMETERS:
-User (optional)
The Username you want the archive to be moved.
If not used, all users archives will be moved to the target Database.
-ArchiveDatabase (required)
The Target Database Name where the archive will be moved
-------------------------- EXAMPLE 1 --------------------------
.\\MoveArchives.ps1 -User dpekmez -ArchiveDatabase ArchiveDB1
-------------------------- EXAMPLE 2 --------------------------
.\\MoveArchives.ps1 -ArchiveDatabase ArchiveDB1
"@
}
#=======================================
# Check for Usage Statement Request
#=======================================
$args | foreach { if (IsHelpRequest $_) { Usage; exit; } }
#==============================================
# Function that validates the script parameters
#==============================================
function ValidateParams
{
$validInputs = $true
$errorString = ""
if ($ArchiveDatabase -eq "")
{
$validInputs = $false
$errorString += "`nMissing Parameter: The -ArchiveDatabase parameter is required. Please pass in the desired Target Database Name."
}
if (!$validInputs)
{
Write-error "$errorString"
}
return $validInputs
}
#==============================================
# Move Request
#==============================================
Get-Mailbox -identity $User | where { $_.ArchiveDatabase -ne $null } | New-MoveRequest -ArchiveTargetDatabase $ArchiveDatabase ľArchiveOnly
|
PowerShellCorpus/PoshCode/Search cmdlet help_1.ps1
|
Search cmdlet help_1.ps1
|
function Search-Help($term) {
Get-Command | Where { Get-Help -full -ea SilentlyContinue $_ |
Out-String | Select-String $term }
}
|
PowerShellCorpus/PoshCode/dc580007-f61d-477a-a409-395481ffb01a.ps1
|
dc580007-f61d-477a-a409-395481ffb01a.ps1
|
CREATE LOGIN [vCenter_Owner] WITH PASSWORD=N'KVx$!|mhQ^', CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
GO
--Modify Drive and size to match your environment
CREATE DATABASE [vCenter] ON PRIMARY
( NAME = N'vCenter', FILENAME = N'S:\\Data\\vCenter.mdf' , SIZE = 100MB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%)
LOG ON
( NAME = N'vCenter_log', FILENAME = N'T:\\Logs\\vCenter.ldf' , SIZE = 10MB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO
use vCenter
GO
CREATE USER [vCenter_Owner] FOR LOGIN [vCenter_Owner] WITH DEFAULT_SCHEMA=[dbo]
GO
sp_addrolemember db_owner, [vCenter_Owner]
GO
use msdb
CREATE USER [vCenter_Owner] FOR LOGIN [vCenter_Owner] WITH DEFAULT_SCHEMA=[dbo]
GO
sp_addrolemember db_owner, [vCenter_Owner]
GO
--After vCenter installation completes, remove the vCenter login from msdb.
use msdb
drop user [vCenter_Owner]
|
PowerShellCorpus/PoshCode/FTP upload_2.ps1
|
FTP upload_2.ps1
|
$File = "D:\\Dev\\somefilename.zip"
$ftp = "ftp://username:password@example.com/pub/incoming/somefilename.zip"
"ftp url: $ftp"
$webclient = New-Object System.Net.WebClient
$uri = New-Object System.Uri($ftp)
"Uploading $File..."
$webclient.UploadFile($uri, $File)
|
PowerShellCorpus/PoshCode/Get-WmiNamespace.ps1
|
Get-WmiNamespace.ps1
|
# In order to enumerate all the WMI namespaces, you must first connect to the "root" namespace,
# query for all the "__NAMESPACE" instances, and for each instance recursively repeat this process.
# You can use the computerName parameter of Get-WmiNamespace to list the WMI namespaces on the remote computer.
function Get-WmiNamespace {
param (
[string]$rootns = "root",
[string]$computerName = ".",
$credential
)
if ($credential -is [String] ) {
$credential = Get-Credential $credential
}
if ($credential -eq $null) {
gwmi -class __namespace -namespace $rootns -computerName $computerName |
where {$_.name} | foreach {
$ns = "{0}\\{1}" -f $rootns,$_.name
$ns
Get-WmiNamespace -rootns $ns -computer $computerName
}
}
else {
gwmi -class __namespace -namespace $rootns -computerName $computerName -credential $credential |
where {$_.name} | foreach {
$ns = "{0}\\{1}" -f $rootns,$_.name
$ns
Get-WmiNamespace -rootns $ns -computer $computerName -credential $credential
}
}
}
|
PowerShellCorpus/PoshCode/Delete Files per folder.ps1
|
Delete Files per folder.ps1
|
<#
.SYNOPSIS
Deletes files in directory based on age measured in days
.DESCRIPTION
Delete files in folder with use of regular filter, either recursive or not.
.PARAMETER DelFilter
Provide a filter like "*.txt" or "mylogs*"
.PARAMETER DelPath
The directory where files are to be deleted from, use the Recurse switch to delete from subfolder as well
.EXAMPLE
Remove-Files -delpath "C:\\temp" -delfilter "Whatever-*" -fileage "30" -LogPath "C:\\temp"
.NOTES
Instead of simply using a gci -Path -Filter -Recurse | Remove-Item I wanted a clean output per folder
Enable debug mode, to write delete actions to the log file without actually deleting the files
#>
Param(
$DelPath = $(throw "Provide path to delete files from"),
$DelFilter = $(throw "Provide a filter like *.txt or mylogs*"),
[int] $FileAge = $(throw "number of days to keep, set it to 0 for all files"),
$LogPath = $($Env:windir),
[switch] $Recurse,
[switch] $Debug
)
#named parameters
"Path: {0}" -f $DelPath
"DelFilter: {0}" -f $DelFilter
"Age: {0}" -f $FileAge
"LogPath: {0}" -f $LogPath
#begin log action
$LogFile = $LogPath + "\\DelFiles" + ".log"
$global:FileCount = 0
# function as one place to set output action
Function WriteLog ($Output){
Write-output $Output | Out-File -Append -FilePath $LogFile
}
# delete files in every parsed folder
Function DeleteFiles ($DelFolder){
foreach ($Item in Get-ChildItem -Force -Path $DelFolder -Filter $DelFilter){
if ($Item.CreationTime -lt ($(Get-Date).AddDays(-$FileAge))){
#if -debug parameter is used only log action, no delete action
if (-not $Debug) { Remove-Item $Item.FullName}
#delete log action
WriteLog "`t $Item"
$global:FileCount = $global:FileCount +1
}
}
}
# actual script execution
WriteLog "Deleting file(s) older than $FileAge day(s) at $DelPath"
$Date = Get-Date
WriteLog "Begin of operation at: $Date"
# file delete action
WriteLog $Delpath
DeleteFiles $Delpath
if ($Recurse){
foreach ($Folder in (gci -Path $DelPath -recurse:$Recurse | ?{$_.PSIsContainer})){
# create array first to report if only one or no item
$NrFiles = @(Get-ChildItem -Force -Path $Folder.Fullname -Filter $DelFilter).count
if ( $NrFiles -gt 0){
WriteLog $Folder.Fullname
DeleteFiles $Folder.Fullname
}
}
}
# end log action
WriteLog "$global:FileCount file(s) deleted successfully"
$Date = Get-Date
WriteLog "End of operation at: $Date"
|
PowerShellCorpus/PoshCode/Out-Posh.ps1
|
Out-Posh.ps1
|
# Personally, I use this as a script (just save in your path as Out-Posh.ps1, and delete all but the middle line (that starts with "end")
function out-posh {
end { New-BootsWindow { $input } -inline }
}
|
PowerShellCorpus/PoshCode/Reset Time Sync Setting.ps1
|
Reset Time Sync Setting.ps1
|
########################################################
# Created by Brian English
# Brian.English@charlottefl.com
# eddiephoenix@gmail.com
#
# for Charlotte County Government
# No warranty suggested or implied
########################################################
# Purpose: Cycle through all VMs on a Virtualcenter Server
# and update the 'SyncTimeWithHost' to either true or false
########################################################
# Notes: VMware Tools must be installed on guest vm
########################################################
#################
$prodhost = "virtualcenter"
$devhost = "virtualtest"
#################
#$SavedEA=$Global:ErrorActionPreference
#$Global:ErrorActionPreference="SilentlyContinue"
#############
###########
#
"1 Prod Hosts"
"2 Dev Hosts"
$hosts = read-host "What hosts to copy to"
switch($hosts)
{ "1"{$hosts = $prodhost}
"2"{$hosts = $devhost}
}
get-esx $hosts
$swtch = read-host "Sync time to host yes/no"
switch($swtch)
{
"yes"{$swtch = $true}
"no"{$swtch = $false}
}
$vms = Get-VM
foreach($vm in $vms)
{
$view = get-view $vm.ID
$config = $view.config
$tools = $config.tools
$spec = new-object VMware.Vim.VirtualMachineConfigSpec
$spec.tools = $tools
$spec.tools.SyncTimeWithHost = $swtch
@@ #this line executes the update to VMTools
@@ $rslt = $view.ReconfigVM_task($spec)
write-host ($vm.name + " " + $tools.SyncTimeWithHost)
}
|
PowerShellCorpus/PoshCode/Calculate HA Capaicty.ps1
|
Calculate HA Capaicty.ps1
|
### Written by Mark A. Weaver
## Date: 7/27/2008
## Version: 1.0
## Blog site: blog.vmweaver.com
##
## Call this function and pass in -ServerName <VC Server Name> -ClusterName <ClusterName>
## Output should be an object containing the information
##
## Feel free to modify as needed to suit your needs, but please keep this header
##
## Thanks -- Mark
function Get-HACapacity(
[string]$ServerName,
[string]$ClusterName)
{
if (($ServerName -ne "") -and ($ClusterName -ne ""))
{
# These booleans tell me if I am using the VMware default memory and cpu reservations for the cluster.
$DASMemDefault = $True
$DASCPUDefault = $True
# The following numbers are derived from VMware published numbers for memory overhead.
# I have dropped them into arrays using the number of vCPUs as an index to get the correct constant.
# This is why you will notice only [1], [2], and [4] have non-zero values
# These constants are used later on when calculating Memory Reserve.
$MemConst32 = 0, 3.262, 5.769059, 0, 6.77933
$MemConst64 = 0, 3.2678, 5.79251, 0, 6.82622
$MemBase32 = 0, 87.56, 108.73, 0, 146.75
$MemBase64 = 0, 107.54, 146.41, 0, 219.82
# Initialize some Variables
$MaxMemRes = 0
$MacNumCPU = 0
$MaxCPUResVM = ""
$VMCount = 0
# define default memory and cpu reservation
$DASMinMHz = 256
$DASMinMemory = 256
$viServerName = $ServerName
$viClusterName = $ClusterName
# Connect to the VirtualCenter Server and get some info
$viServer = Connect-VIServer $viServerName
$viCluster = get-cluster $viClusterName
$viHosts = get-vmhost -location $viCluster
$viClusterV = get-view $viCluster.ID
# Get the "Resources" Resource Pool from the cluster.
# This gives us the Reservation Pools for Memory and CPU
$viResGroup = Get-ResourcePool -Name "Resources" -Location $viCluster
$viCPURes = $viResGroup.CpuReservationMHz
$viMemRes = $viResGroup.MemReservationMB
$viHostCount = $viClusterV.Summary.NumHosts
# Get HA cluster configuration information
$viHostFailures = $viClusterV.Configuration.DasConfig.FailoverLevel
# Get a list of options that may be configured at the clusters level
# We are looking for whether or not the default memory and cpu
# reservations have been overridden
$viDASOptions = $viClusterV.Configuration.DASConfig.Option
$viVMs = get-vm -Location $viCluster
# Is Adminisssion Control enabled on the cluster?
$viClusterControl = $viClusterV.Configuration.DASConfig.AdmissionControlEnabled
# See if das.vmMemoryMinMB key is defined and grab its value
# See if das.vmCpuMinMHZ key is defined and grab its value
if ($viDASoptions.Count -ne 0)
{
foreach ($viDASOption in $viDASOptions)
{
if ($viDASOption.Key -eq "das.vmMemoryMinMB")
{
$DASMemDefault = $False
$DASMinMemory = $viDASOption.Value }
if ($viDASOption.Key -eq "das.vmCpuMinMHz")
{
$DASCPUDefault = $False
$DASMinMHz = $viDASOption.Value }
}
}
# Let's go through every VM and see what the maximum CPU and Memory reservation is.
# We will also get a count of powered on VMs.
# When we hit a maximum reservation, save the machine name that set that maximum
foreach ($viVM in $viVMs)
{
$NumCPU = $viVm.NumCPU
$VMMem = $viVm.MemoryMB
$MemRes = 0
if ($viVM.PowerState -eq "PoweredOn")
{
$VMCount += 1
}
# Get the VM-view and determine if the current guest CPU or memory reservations configured
$vmView = get-view $viVM.ID
$vmViewCPURes = $vmView.ResourceConfig.CpuAllocation.Reservation
$vmViewMemRes = $vmView.ResourceConfig.MemoryAllocation.Reservation
# If no reservations are set at the VM level, calculate the memory reservation.
if ($vmViewMemRes -eq 0)
{
if ($VMMem -le 256)
{
$MemRes = $MemConst64[$NumCpu] + $MemBase64[$NumCPU]
}
else
{
if ((($viVM.Guest.OSFullName | Select-String "64-bit").Matches.Count) -ge 1)
{
$MemRes = ($VMMem / 256) * $MemConst64[$NumCPU] + $MemBase64[$NumCPU]
}
else
{
$MemRes = ($VMMem / 256) * $MemConst32[$NumCPU] + $MemBase32[$NumCPU]
}
}
$MemRes += $DASMinMemory
}
else
{
$MemRes = $vmViewMemRes
}
#Figure out if the current VM holds the highest reservation so far
if ($vmViewCPURes -gt $DASMinMHz)
{
$DASMinMHz = $vmViewCPURes
$MaxCPUResVM = $viVM.Name
}
if ($MemRes -gt $MaxMemRes)
{
$MaxMemRes = $MemRes
$MaxMemResVM = $viVM.Name
}
if ($NumCPU -gt $MaxNumCPU)
{
$MaxNumCPU = $NumCPU
$MaxCPUNumVM = $viVM.Name
}
}
if ($MaxCPUResVM -eq "") { $MaxCPUResVM = $MaxCPUNumVM }
$MaxCPURes = $MaxNumCPU * $DASMinMHz
# Calculate the VM Capacity for the cluster based on memory and cpu reservations.
$ClusterVMCapacityMEM = [Math]::Truncate(((($viMemRes / $MaxMemRes) * ( $viHostCount - $viHostFailures )) / $viHostCount))
$ClusterVMCapacityCPU = [Math]::Truncate(((($viCPURes / $MaxCPURes) * ( $viHostCount - $viHostFailures )) / $viHostCount))
if ($ClusterVMCapacityMEM -lt $ClusterVMCapacityCPU)
{
$ClusterVMCapacity = $ClusterVMCapacityMEM
}
else
{
$ClusterVMCapacity = $ClusterVMCapacityCPU
}
# Create an object to return
$CPUObj = New-Object System.Object
$CPUObj | Add-Member -type NoteProperty -name ClusterCPURes -value $viCPURes
$CPUObj | Add-Member -type NoteProperty -name DefaultCPURes -value $DASCPUDefault
$CPUObj | Add-Member -type NoteProperty -name MinCPURes -value $DASMinMHz
$CPUObj | Add-Member -type NoteProperty -name MaxCPUNumVM -value $MaxCPUNumVM
$CPUObj | Add-Member -type NoteProperty -name MaxCPURes -value $MaxCPURes
$CPUObj | Add-Member -type NoteProperty -name MaxCPUResVM -value $MaxCPUResVM
$CPUObj | Add-Member -type NoteProperty -name MaxCPUs -value $MaxNumCPU
$CPUObj | Add-Member -type NoteProperty -name VMCapacityCPU -value $ClusterVMCapacityCPU
$MemObj = New-Object System.Object
$MemObj | Add-Member -type NoteProperty -name ClusterMemRes -value $viMemRes
$MemObj | Add-Member -type NoteProperty -name DefaultMemRes -value $DASMemDefault
$MemObj | Add-Member -type NoteProperty -name MinMemRes -value $DASMinMemory
$MemObj | Add-Member -type NoteProperty -name MaxMemRes -value $MaxMemRes
$MemObj | Add-Member -type NoteProperty -name MaxMemResVM -value $MaxMemResVM
$MemObj | Add-Member -type NoteProperty -name VMCapacityMem -value $ClusterVMCapacityMEM
$OutObj = New-Object System.Object
$OutObj | Add-Member -type NoteProperty -name AdmissionControl -value $viClusterControl
$OutObj | Add-Member -type NoteProperty -name CPU -value $CPUObj
$OutObj | Add-Member -type NoteProperty -name FailoverHosts -value $viHostFailures
$OutObj | Add-Member -type NoteProperty -name HostCount -value $viHostCount
$OutObj | Add-Member -type NoteProperty -name Memory -value $MemObj
$OutObj | Add-Member -type NoteProperty -name RunningVMs -value $VMCount
$OutObj | Add-Member -type NoteProperty -name VIServer -value $viServerName
$OutObj | Add-Member -type NoteProperty -name VICluster -value $viClusterName
$OutObj | Add-Member -type NoteProperty -name VMCapacity -value $ClusterVMCapacity
return($outObj)
}
else
{
# Write usage info
Write-Host ("")
Write-Host ("-------------------------------------")
Write-Host ("Get-HACapacity.ps1 Usage:")
Write-Host( "You must specify the following parameters: ")
Write-Host (" '-ServerName <servername>' where <servername> is the name of the VirtualCenter Server")
Write-Host(" '-ClusterName <clustername>' where <clustername> is the name of the cluster to query")
Write-Host ("")
}
}
|
PowerShellCorpus/PoshCode/ServicePWChgReset_1.ps1
|
ServicePWChgReset_1.ps1
|
# ==============================================================================================
#
# NAME: ServicePWChgReset.ps1
#
# AUTHOR: Saehrig, Steven
# DATE : 8/26/2008
@@# Requires - Quest ActiveRoles Snapin
@@# COMMENT: Please read comments on each section!
# 1st - Search Domain computers for matching name and import into array.
# 2nd - Export matching hosts from array to text file. (comment out after text file created)
# 3rd - Create CSV file of all Matching Critera with full service detail. ( so you have record of modified
# services)
# 4th - Create text file of all matching services with limited info
# 5th - Change password on matching services
# 6th - Restart services if running if not running skip restart. (with console feedback)
#
# I would like to Thank Halr9000 and glnsize from powershellcomunity.org for there guidance during this
# script creation. I would not have been able to complete this without them and i would have been spending
# alot of time manually updating every service. Granted if they actually wrote this it would be much nicer :).
# But hey everyone has to start somewhere.
# ==============================================================================================
#discover Servers for Host.txt file
function func_Forest()
{
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().Domains | ForEach-Object {
Get-QADComputer -Service $_.Name -SizeLimit 0 -ErrorAction SilentlyContinue `
| Add-Member -Name 'DomainName' -MemberType NoteProperty -Value $_.Name -PassThru
}
}
#initialize Array for Output
$Array = @()
#This should be run once to fill the host file then commented out.
#Fill Array
func_forest | where { $_.Name -like 'jxr*' } | Sort-Object -property "Name" |? { $array += $_.name}
$file = $array | Out-File -FilePath c:\\txt\\host.txt -Append
#Variables
$StartName = "username"
$csvlocation = "c:\\txt\\service.csv"
$txtlocation = "c:\\txt\\service.txt"
$computer = gc c:\\txt\\host.txt
$password = "password"
$service = gwmi -Class Win32_Service -namespace root\\CIMV2 -ComputerName $computer | Where-Object {$_.StartName -match $startname}
#exports discovered services for documentation of modified services
$service | Export-Csv $csvlocation
#Function Declarations
function exporttxt { #This function exports the services to a text file in limited data fields.
foreach ($i in $service) {
($i | FT systemname, Displayname, State, Startname, Status | Out-File -Append -FilePath $txtlocation )
}
}
function changepw { #This function will change the password to the variable assigned above.
foreach ($i in $service) {
(Write-Host -ForegroundColor "Yellow" "Changing password on" $i.SystemName "Service Name"$i.Name)
($i.Change($Null,$Null,$Null,$Null,$Null,$Null,$Null,$password))
(Write-Host -ForegroundColor "green" "Password Successfully Changed on" $i.SystemName "Service Name"$i.Name)
}
}
function restartsvc { #This function will restart the service for the new password to take effect.
$s = gwmi -Class Win32_Service -namespace root\\CIMV2 -ComputerName $computer | Where-Object {$_.StartName -match $startname}
foreach ($i in $s) {
if ($i.State -eq "running") {
Write-Host -ForegroundColor "Yellow" "Service name" $i.SystemName "Service name"$i.Name "is" $i.state
$i.StopService()
Sleep -Seconds 20 #allow time for service to stop.
$b = gwmi -Class Win32_Service -namespace root\\CIMV2 -ComputerName $computer | Where-Object {$_.StartName -match $startname}
Write-Host -ForegroundColor "RED" "Service name" $b.SystemName "Service name" $b.Name "is" $b.state
$i.StartService()
$c = gwmi -Class Win32_Service -namespace root\\CIMV2 -ComputerName $computer | Where-Object {$_.StartName -match $startname}
Write-Host -ForegroundColor "Green" "Server name" $c.SystemName "Service name" $c.Name "is" $c.state }
elseif ($i.State -eq "Stopped") {
Write-Host -ForegroundColor "RED" "Service name" $i.SystemName "Service name" $i.Name $i.state "Service will not be Started" }
}
}
#Execute
exporttxt
changepw | out-null
restartsvc | out-null
|
PowerShellCorpus/PoshCode/WIMM Emulator Launcher.ps1
|
WIMM Emulator Launcher.ps1
|
##
## Start-WimmEmulator.ps1
##
## Starts the WIMM emulator - must be placed in the add-ons\\addon_wimm_one_7\\tools
## directory along with the rest of the WIMM tools.
##
## http://dev.wimm.com/
if(-not $env:ANDROID_SDK_DIR)
{
$env:ANDROID_SDK_DIR = Resolve-Path (Join-Path $psscriptRoot ..\\..\\..)
}
if(-not (Test-Path "$env:HOMEPATH\\.android\\avd\\WIMMOne.ini"))
{
Write-Verbose "Creating WIMMOne avd"
& "$env:ANDROID_SDK_DIR\\tools\\android.bat" create avd -s WIMMOne -n WIMMOne -t "WIMM Labs, Inc.:WIMM One Add-On:7" -c 9M --force
}
$certPath = Join-Path $env:ANDROID_SDK_DIR "add-ons\\addon_wimm_one_7\\credentials"
$certFile = dir "$certPath\\*.pfx" | Select -Last 1
if(-not $certFile)
{
throw "You must have a PFX certificate file installed at $certPath"
}
Write-Verbose "CertFile is $($certFile.FullName)"
$id = dir "$env:ANDROID_SDK_DIR\\add-ons\\addon_wimm_one_7\\credentials\\*.id" | Select -Last 1
if(-not $id)
{
throw "You must have an ID file installed at $certPath"
}
$id = $id | Get-Content
Write-Verbose "ID is $id"
$imagePath = "$env:HOMEPATH\\.android\\avd\\WIMMOne.avd\\env.img"
$otpPath= "$env:HOMEPATH\\.android\\avd\\WIMMOne.avd\\otp.img"
$imagePath,$otpPath | Foreach-Object {
if(-not (Test-Path $_))
{
$bytes = [byte[]] (Get-Content (Join-Path $psscriptRoot nand.dat) -Encoding Byte)
Set-Content $_ ($bytes * 1024) -Encoding Byte
}
}
& $env:ANDROID_SDK_DIR\\tools\\emulator.exe -avd WIMMOne -prop dev.id=$id -qemu -nand "env,size=0x40000,file=$imagePath" -nand "otp,size=0x40000,file=$otpPath"
& $env:ANDROID_SDK_DIR\\platform-tools\\adb.exe -e wait-for-device push "$($certFile.FullName)" /data/misc/nv/cert.pfx
|
PowerShellCorpus/PoshCode/Test-Help.ps1
|
Test-Help.ps1
|
function Test-Help {
<#
.Synopsis
Test-Help -Function Get-USB
.Description
Test-Help was written to get information why that !@##$%#$%# help is not working ;)
For now works only if v2 comments are used (starting with < # and ending with # > )
Using fancy regex that probably could be shorter, more elegant and so long and so forth... ;)
.Example
Test-Help -Function Test-Help
If you want to find mistakes made by other - try to find yours first. ;)
.Link
Not yet implemented
.Parameter Function
Name of the function to be tested.
#>
param ([string]$Function)
try {
$Definition = (Get-Command -CommandType function -Name $function -ErrorAction Stop).definition -split '\\n'
$regKey = [regex]'^\\s*\\.(?<KEY>\\w+)($|\\s*($|(?<PARAM>[\\w-]+))($|\\s*(?<ERROR>\\S*)$))'
$regComStart = [regex]'^\\s*<#\\s*$'
$regComEnd = [regex]'^\\s*#>\\s*$'
$IsComment = $false
$KEYS = @('SYNOPSIS','DESCRIPTION','EXAMPLE','INPUTS','OUTPUTS','NOTES','LINK','COMPONENT','ROLE','FUNCTIONALITY')
$EXTKEYS = @('PARAMETER','FORWARDHELPTARGETNAME','FORWARDHELPCATEGORY','REMOTEHELPRUNSPACE','EXTERNALHELP')
foreach ($line in $Definition) {
$line = $line -replace '\\r', ''
$invocation = "Line : $line Function : $function"
if ($IsComment) {
if ($RegKey.IsMatch($line)) {
# should contain keyword
$RegKey.Match($line) | ForEach-Object {
$Key = $_.Groups['KEY'].Value
$Par = $_.Groups['PARAM'].Value
$Err = $_.Groups['ERROR'].Value
}
if (![string]::IsNullOrEmpty($Err)) {
Write-Host -ForegroundColor Cyan "Unexpected token - not more than two: $Err $invocation"
continue
}
if ($KEYS -contains $Key) {
if (![string]::IsNullOrEmpty($Par)) {
Write-Host -ForegroundColor Yellow "Unexpected token - keyword without additional parameters: $Par $invocation"
continue
}
} else {
if ($EXTKEYS -contains $Key) {
if ([string]::IsNullOrEmpty($Par)) {
Write-Host -ForegroundColor Magenta "Missing token - $Key should be followed by something, $invocation"
}
} else {
# Looks like spelling mistake...
Write-Host -ForegroundColor Green "Key probably with spelling mistake: $Key $invocation"
}
}
} else {
if ($RegComEnd.IsMatch($line)) {
$IsComment = $false
}
}
} else {
if ($RegComStart.IsMatch($line)) {
$IsComment = $true
}
}
}
} catch {
Write-Host -ForegroundColor Red "Error: $_ "
}
}
|
PowerShellCorpus/PoshCode/Get-FeedInfo.ps1
|
Get-FeedInfo.ps1
|
function Get-FeedInfo([string[]]$feeds) {
# $feeds is an array of rss/atom URLs
$blogs=@(); $broken=@(); $feeds = $feeds | sort -unique {$_}
foreach($feed in $feeds){
try {
$xml = Get-WebPageContent $feed;
} catch {
$broken += $feed
$xml = $null
}
if($xml.html.rss) { $xml = $xml.html; write-warning $feed }
if($xml.rss) {
$blogs += New-Object PSObject -Property @{
title= $xml.rss.channel.title
link = $xml.rss.channel.link | ? { $_ -is [string] }
feed = $feed
}
} elseif($xml.feed) {
$blogs += New-Object PSObject -Property @{
title= $xml.feed.title.'#text'
link = $xml.feed.link |? {$_.rel -eq 'alternate' } | select -expand href
feed = $feed
}
} else {
$broken += $feed
$blogs += New-Object PSObject -Property @{ feed = $feed }
}
}
Write-Output $blogs, $broken
}
|
PowerShellCorpus/PoshCode/New-XML 2.ps1
|
New-XML 2.ps1
|
#requires -version 2.0
#### NOTE: you can revert this to work in PowerShell 1.0 by just removing the [Parameter(...)] lines
#### BUT YOU WILL HAVE TO pass the $Version $Encoding $Standalone parameters EACH TIME
#### UNLESS you remove them, and switch back to a hardcoded XDeclaration ... or something.
####################################################################################################
#### I still have to add documentation comments to these, but in the meantime ...
### please see the samples at the bottom to understand how to use them :)
####
$xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators")
$xlinq = [Reflection.Assembly]::Load("System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
$xlinq.GetTypes() | ? { $_.IsPublic -and !$_.IsSerializable -and $_.Name -ne "Extensions" -and !$xlr8r::Get[$_.Name] } | % {
$xlr8r::Add( $_.Name, $_.FullName )
}
function New-Xml {
Param(
[Parameter(Mandatory = $true, Position = 0)]
[System.Xml.Linq.XName]$root
,
[Parameter(Mandatory = $false)]
[string]$Version = "1.0"
,
[Parameter(Mandatory = $false)]
[string]$Encoding = "UTF-8"
,
[Parameter(Mandatory = $false)]
[string]$Standalone = "yes"
,
[Parameter(Position=99, Mandatory = $false, ValueFromRemainingArguments=$true)]
[PSObject[]]$args
)
BEGIN {
if(![string]::IsNullOrEmpty( $root.NamespaceName )) {
Function New-XmlDefaultElement {
Param([System.Xml.Linq.XName]$tag)
if([string]::IsNullOrEmpty( $tag.NamespaceName )) {
$tag = $($root.Namespace) + $tag
}
New-XmlElement $tag @args
}
Set-Alias xe New-XmlDefaultElement
}
}
PROCESS {
#New-Object XDocument (New-Object XDeclaration "1.0", "UTF-8", "yes"),(
New-Object XDocument (New-Object XDeclaration $Version, $Encoding, $standalone),(
New-Object XElement $(
$root
# foreach($ns in $namespace){
# $name,$url = $ns -split ":",2
# New-Object XAttribute ([XNamespace]::Xmlns + $name),$url
# }
while($args) {
$attrib, $value, $args = $args
if($attrib -is [ScriptBlock]) {
&$attrib
} elseif ( $value -is [ScriptBlock] -and "-Content".StartsWith($attrib)) {
&$value
} elseif ( $value -is [XNamespace]) {
New-XmlAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-")) $value
} else {
New-XmlAttribute $attrib.TrimStart("-") $value
}
}
))
}
END {
Set-Alias xe New-XmlElement
}
}
function New-XmlAttribute {
Param($name,$value)
New-Object XAttribute $name,$value
}
Set-Alias xa New-XmlAttribute
function New-XmlElement {
Param([System.Xml.Linq.XName]$tag)
Write-Verbose $($args | %{ $_ | Out-String } | Out-String)
New-Object XElement $(
$tag
while($args) {
$attrib, $value, $args = $args
if($attrib -is [ScriptBlock]) {
&$attrib
} elseif ( $value -is [ScriptBlock] -and "-Content".StartsWith($attrib)) {
&$value
} elseif ( $value -is [XNamespace]) {
New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-")),$value
} else {
New-Object XAttribute $attrib.TrimStart("-"), $value
}
}
)
}
Set-Alias xe New-XmlElement
####################################################################################################
###### EXAMPLE SCRIPT: NOTE the `: in the http`: is only there for PoshCode, you can just use http:
# [XNamespace]$dc = "http`://purl.org/dc/elements/1.1"
#
# $xml = New-Xml rss -dc $dc -version "2.0" {
# xe channel {
# xe title {"Test RSS Feed"}
# xe link {"http`://HuddledMasses.org"}
# xe description {"An RSS Feed generated simply to demonstrate my XML DSL"}
# xe ($dc + "language") {"en"}
# xe ($dc + "creator") {"Jaykul@HuddledMasses.org"}
# xe ($dc + "rights") {"Copyright 2009, CC-BY"}
# xe ($dc + "date") {(Get-Date -f u) -replace " ","T"}
# xe item {
# xe title {"The First Item"}
# xe link {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"}
# xe guid -isPermaLink true {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"}
# xe description {"Ema Lazarus' Poem"}
# xe pubDate {(Get-Date 10/31/2003 -f u) -replace " ","T"}
# }
# }
# }
#
# $xml.Declaration.ToString() ## I can't find a way to have this included in the $xml.ToString()
# $xml.ToString()
#
####### OUTPUT: (NOTE: I added the space in the http: to paste it on PoshCode -- those aren't in the output)
# <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
# <rss xmlns:dc="http ://purl.org/dc/elements/1.1" version="2.0">
# <channel>
# <title>Test RSS Feed</title>
# <link>http ://HuddledMasses.org</link>
# <description>An RSS Feed generated simply to demonstrate my XML DSL</description>
# <dc:language>en</dc:language>
# <dc:creator>Jaykul@HuddledMasses.org</dc:creator>
# <dc:rights>Copyright 2009, CC-BY</dc:rights>
# <dc:date>2009-07-26T00:50:08Z</dc:date>
# <item>
# <title>The First Item</title>
# <link>http ://huddledmasses.org/new-site-new-layout-lost-posts/</link>
# <guid isPermaLink="true">http ://huddledmasses.org/new-site-new-layout-lost-posts/</guid>
# <description>Ema Lazarus' Poem</description>
# <pubDate>2003-10-31T00:00:00Z</pubDate>
# </item>
# </channel>
# </rss>
####################################################################################################
###### ANOTHER EXAMPLE SCRIPT, this time with a default namespace
## IMPORTANT! ## NOTE that I use the "xe" shortcut which is redefined when you specify a namespace
## ## for the root element, so that all child elements (by default) inherit that.
## ## You can still control the prefixes by passing the namespace as a parameter
## ## e.g.: -atom $atom
###### The `: in the http`: is still only there for PoshCode, you can just use http: ...
####################################################################################################
#
# [XNamespace]$atom="http`://www.w3.org/2005/Atom"
# [XNamespace]$dc = "http`://purl.org/dc/elements/1.1"
#
# New-Xml ($atom + "feed") -Encoding "UTF-16" -$([XNamespace]::Xml +'lang') "en-US" -dc $dc {
# xe title {"Test First Entry"}
# xe link {"http`://HuddledMasses.org"}
# xe updated {(Get-Date -f u) -replace " ","T"}
# xe author {
# xe name {"Joel Bennett"}
# xe uri {"http`://HuddledMasses.org"}
# }
# xe id {"http`://huddledmasses.org/" }
#
# xe entry {
# xe title {"Test First Entry"}
# xe link {"http`://HuddledMasses.org/new-site-new-layout-lost-posts/" }
# xe id {"http`://huddledmasses.org/new-site-new-layout-lost-posts/" }
# xe updated {(Get-Date 10/31/2003 -f u) -replace " ","T"}
# xe summary {"Ema Lazarus' Poem"}
# xe link -rel license -href "http://creativecommons.org/licenses/by/3.0/" -title "CC By-Attribution"
# xe ($dc + "rights") {"Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)"}
# xe category -scheme "http://huddledmasses.org/tag/" -term "huddled-masses"
# }
# } | % { $_.Declaration.ToString(); $_.ToString() }
#
####### OUTPUT: (NOTE: I added the spaces again to the http: to paste it on PoshCode)
# <?xml version="1.0" encoding="UTF-16" standalone="yes"?>
# <feed xml:lang="en-US" xmlns="http ://www.w3.org/2005/Atom">
# <title>Test First Entry</title>
# <link>http ://HuddledMasses.org</link>
# <updated>2009-07-29T17:25:49Z</updated>
# <author>
# <name>Joel Bennett</name>
# <uri>http ://HuddledMasses.org</uri>
# </author>
# <id>http ://huddledmasses.org/</id>
# <entry>
# <title>Test First Entry</title>
# <link>http ://HuddledMasses.org/new-site-new-layout-lost-posts/</link>
# <id>http ://huddledmasses.org/new-site-new-layout-lost-posts/</id>
# <updated>2003-10-31T00:00:00Z</updated>
# <summary>Ema Lazarus' Poem</summary>
# <link rel="license" href="http ://creativecommons.org/licenses/by/3.0/" title="CC By-Attribution" />
# <dc:rights>Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)</dc:rights>
# <category scheme="http ://huddledmasses.org/tag/" term="huddled-masses" />
# </entry>
# </feed>
#
#
|
PowerShellCorpus/PoshCode/Impersonation.ps1
|
Impersonation.ps1
|
$global:ImpContextStack = new-object System.Collections.Generic.Stack[System.Security.Principal.WindowsImpersonationContext]\n$global:IdStack = new-object System.Collections.Generic.Stack[System.Security.Principal.WindowsIdentity]\n\n\n$global:UserToysClass = Add-Type -Namespace Huddled -Name UserToys -MemberDefinition @"\n // http://msdn.microsoft.com/en-us/library/aa378184.aspx\n [DllImport("advapi32.dll", SetLastError = true)]\n public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);\n\n // http://msdn.microsoft.com/en-us/library/aa379317.aspx\n [DllImport("advapi32.dll", SetLastError=true)]\n public static extern bool RevertToSelf();\n"@ -passthru\n\n\nfunction Push-ImpersonationContext {\n[CmdletBinding(DefaultParameterSetName="Credential")]\nParam(\n[Parameter(Position=0,Mandatory=$true,ParameterSetName="Credential")]\n[System.Management.Automation.PSCredential]$Credential, \n[Parameter(Position=0,Mandatory=$true,ParameterSetName="Password")]\n[string]$name,\n[Parameter(Position=1,Mandatory=$true,ParameterSetName="Password")]\n$password = (Read-Host "Password" -AsSecureString),\n[Parameter(Position=2,Mandatory=$false,ParameterSetName="Password")]\n[string]$domain\n)\nif(!$Credential) {\n if($password -is [string]) {\n $secure = New-Object System.Security.SecureString\n $password.GetEnumerator() | %{ $secure.AppendChar( $_ ) }\n $password = $secure\n }\n if($domain) {\n $user = "${name}@${domain}"\n }\n $Credential = new-object System.Management.Automation.PSCredential $user, $password\n}\n\n Write-Verbose ([Security.Principal.WindowsIdentity]::GetCurrent() | Format-Table Name, Token, User, Groups -Auto | Out-String)\n\n [IntPtr]$userToken = [Security.Principal.WindowsIdentity]::GetCurrent().Token\n if(!$UserToysClass::LogonUser( \n $Credential.GetNetworkCredential().UserName, \n $Credential.GetNetworkCredential().Domain, \n $Credential.GetNetworkCredential().Password, 9, 0, [ref]$userToken)\n ) {\n throw (new-object System.ComponentModel.Win32Exception( [System.Runtime.InteropServices.Marshal]::GetLastWin32Error() ) )\n }\n\n $identity = New-Object Security.Principal.WindowsIdentity $userToken\n $global:IdStack.Push( $identity )\n \n $context = $Identity.Impersonate()\n $global:ImpContextStack.Push( $context )\n\n Write-Verbose ([Security.Principal.WindowsIdentity]::GetCurrent() | Format-Table Name, Token, User, Groups -Auto | Out-String)\n \n return $global:ImpContextStack.Peek()\n}\n\n\nfunction Pop-ImpersonationContext {\n $context = $global:ImpContextStack.Pop()\n $context.Undo();\n $context.Dispose();\n}\n\nfunction Get-ImpersonationContext {\n Write-Host "There are $($global:ImpContextStack.Count) contexts on the stack"\n $global:ImpContextStack.Peek()\n}
|
PowerShellCorpus/PoshCode/11a7b312-21b4-4faa-8224-35bea9db7f89.ps1
|
11a7b312-21b4-4faa-8224-35bea9db7f89.ps1
|
param(
[Parameter(Position=0,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$true)]
[alias("Name","ComputerName")] $Computer = @($env:computername),
[string] $NTDomain = ($env:UserDomain),
[string[]] $LocalGroups = @("Administrators"),
[string[]] $Identities, # can be domain user or group
[switch] $Output,
[switch] $Add,
[switch] $Remove
)
begin{
$Global:objReport = @()
# list current members in defined group
Function ListMembers ($Group){
$members = $Group.psbase.invoke("Members") | %{$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}
return $members
}
}
process{
if (Test-Connection -ComputerName $Computer -Count 1 -Quiet -EA "Stop"){
foreach ($Group in $LocalGroups){
try{
$tmpComputer = [ADSI]("WinNT://" + $Computer + ",computer")
$tmpGroup = $tmpComputer.psbase.children.find($Group)
foreach ($User in $(ListMembers $tmpGroup)){
$objOutput = New-Object PSObject -Property @{
Machinename = [string]$Computer
GroupName = $Group
UserName = $User
Action = "Existing"
}#end object
$Global:objReport+= $objoutput
}
if ($Identities){
foreach ($User in $Identities){
$Action = "none"
If ($Add){
$tmpGroup.Add("WinNT://" + $NTDomain + "/" + $User)
$Action = "Added"
}
If ($Remove){
$tmpGroup.Remove("WinNT://" + $NTDomain + "/" + $User)
$Action = "Removed"
}
$objOutput = New-Object PSObject -Property @{
Machinename = [string]$Computer
GroupName = $Group
UserName = $User
Action = $Action
}#end object
$Global:objReport+= $objoutput
}
}
}
catch{
$continue = $False
$objOutput = New-Object PSObject -Property @{
Machinename = [string]$Computer
GroupName = $Group
UserName = $User
Action = $Error[0].Exception.InnerException.Message.ToString().Trim()
}#end object
$Global:objReport+= $objoutput
}
}
}
}
end{
$Global:objReport
}
|
PowerShellCorpus/PoshCode/73cbcdc1-9397-4ed2-99e3-b043b8c53905.ps1
|
73cbcdc1-9397-4ed2-99e3-b043b8c53905.ps1
|
# 1. Create a simple customizations spec:
$custSpec = New-OSCustomizationSpec -Type NonPersistent -OSType Windows -OrgName “My Organization” -FullName “MyVM” -Domain “MyDomain” –DomainAdminUsername “user” –DomainAdminPassword “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/Get-StrictMode.psm1.ps1
|
Get-StrictMode.psm1.ps1
|
<#
.SYNOPSIS
A very simple module to retrieve the Set-StrictMode setting of the session.
.DESCRIPTION
This procedure is necessary as there is, apparently, no PowerShell variable
for this and enables the user setting to be returned to its original state
after possibly being changed within a script.
The various values returned will be Version 1, Version 2, or Off.
#>
function Get-StrictMode {
try {
$version = '2'
$z = "2 * $nil" #V2 will catch this one.
$version = '1'
$z = 2 * $nil #V1 will catch this.
Write-Host "StrictMode: Off"
}
catch {
Write-Host "StrictMode: Version $version"
}
}
|
PowerShellCorpus/PoshCode/Validate SPN Mappings.ps1
|
Validate SPN Mappings.ps1
|
###########################################################################"
#
# NAME: SPNValidation.psm1
#
# AUTHOR: Jan Egil Ring
# BLOG: http://blog.crayon.no/blogs/janegil
#
# COMMENT: Script module for validating SPN mappings.
# For installation instructions and sample usage, see the following blog post:
#http://blog.crayon.no/blogs/janegil/archive/2010/01/28/validate_2D00_spn_2D00_mappings_2D00_using_2D00_windows_2D00_powershell.aspx
#
# 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 28.01.2010 - Initial release
#
###########################################################################"
function Resolve-SPN {
################################################################
#.Synopsis
# Resolves the provided SPN and checks for duplicate entries
#.Parameter SPN
# The SPN to perform the check against
################################################################
param( [Parameter(Mandatory=$true)][string]$SPN)
$Filter = "(ServicePrincipalName=$SPN)"
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.Filter = $Filter
$SPNEntry = $Searcher.FindAll()
$Count = $SPNEntry | Measure-Object
if ($Count.Count -gt 1) {
Write-Host "Duplicate SPN Found!" -ForegroundColor Red -BackgroundColor Black
Write-Host "The following Active Directory objects contains the SPN $SPN :"
$SPNEntry | Format-Table Path -HideTableHeaders
}
elseif ($Count.Count -eq 1) {
Write-Host "No duplicate SPN found" -ForegroundColor Green
Write-Host "The following Active Directory objects contains the SPN $SPN :"
$SPNEntry | Format-Table Path -HideTableHeaders
}
else
{
Write-Host "SPN not found"
}
}
#Imports the PowerShell ActiveDirectory available in Windows Server 2008 R2 and Windows 7 Remote Server Administration Tools (RSAT)
Import-Module ActiveDirectory
function Resolve-AllDuplicateDomainSPNs {
################################################################
#.Synopsis
# # Resolves all domain SPNs and checks for duplicate entries
################################################################
$DomainSPNs = Get-ADObject -LDAPFilter "(ServicePrincipalName=*)" -Properties ServicePrincipalName
foreach ($item in $DomainSPNs) {
$SPNCollection = $item.ServicePrincipalName
foreach ($SPN in $SPNCollection){
$Filter = "(ServicePrincipalName=$SPN)"
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.Filter = $Filter
$SPNEntry = $Searcher.FindAll()
$Count = $SPNEntry | Measure-Object
if ($count.Count -gt 1) {
Write-Host "Warning: Duplicate SPN Found!" -ForegroundColor Red -BackgroundColor Black
Write-Host "The following Active Directory objects contains the SPN $SPN :"
$SPNEntry | Format-Table Path -HideTableHeaders
}
}
}
}
|
PowerShellCorpus/PoshCode/ModuleWriteError.psd1.ps1
|
ModuleWriteError.psd1.ps1
|
#
# Module manifest for module 'ModuleWriteError'
#
# Generated by: Thell Fowler
#
# Generated on: 1/13/2010
#
@{
# Script module or binary module file associated with this manifest
ModuleToProcess = 'ModuleWriteError.psm1'
# Version number of this module.
ModuleVersion = '1.0'
# ID used to uniquely identify this module
GUID = '64a09a69-e432-43ab-907e-18470da14621'
# Author of this module
Author = 'Thell Fowler'
# Company or vendor of this module
CompanyName = 'NPPCR'
# Copyright statement for this module
Copyright = 'GNU GPL v3'
# Description of the functionality provided by this module
Description = 'Generic module and advanced function aware exception class and error record generator for use with Write-Error and $PSCmdlet.WriteError() allowing embedding of the module name and prefixed or non-prefixed advanced function name into error messages.'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = ''
# Name of the Windows PowerShell host required by this module
PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
PowerShellHostVersion = ''
# Minimum version of the .NET Framework required by this module
DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module
CLRVersion = ''
# Processor architecture (None, X86, Amd64, IA64) required by this module
ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module
ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
TypesToProcess = 'FunctionInfo.types.ps1xml'
# Format files (.ps1xml) to be loaded when importing this module
FormatsToProcess = @()
# Modules to import as nested modules of the module specified in ModuleToProcess
NestedModules = @()
# Functions to export from this module
FunctionsToExport = '*'
# Cmdlets to export from this module
CmdletsToExport = '*'
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module
AliasesToExport = '*'
# List of all modules packaged with this module
ModuleList = @()
# List of all files packaged with this module
FileList = 'ModuleWriteError.psm1', 'FunctionInfo.types.ps1xml'
# Private data to pass to the module specified in ModuleToProcess
PrivateData = ''
}
|
PowerShellCorpus/PoshCode/IE Proxy Toggle (Silent).ps1
|
IE Proxy Toggle (Silent).ps1
|
# Process command line parameter (if present).
[bool] $DISABLE_PROXY = $false;
foreach ($param in $MyInvocation.UnboundArguments) {
if ($param -like 'disable') { $DISABLE_PROXY = $true; }
}
# Apply/refresh the organization's default proxy settings.
@@ [string] $proxyServer = '###.###.###.###:####';
@@ [string] $proxyOverride = '*.local;192.168.*;<local>';
@@ [int] $migrateProxy = 1;
@@ [int] $proxyHttp11 = 1;
REG ADD """HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"" /v ""ProxyServer"" /t REG_SZ /d ""$proxyServer"" /f" | Out-Null;
REG ADD """HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"" /v ""ProxyOverride"" /t REG_SZ /d ""$proxyOverride"" /f" | Out-Null;
REG ADD """HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"" /v ""MigrateProxy"" /t REG_DWORD /d $migrateProxy /f" | Out-Null;
REG ADD """HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"" /v ""ProxyHttp1.1"" /t REG_DWORD /d $proxyHttp11 /f" | Out-Null;
<#
Define a function to start a 'hidden' Internet Explorer process.
This is needed since there is no easy way to programmatically 'refresh'
the user's proxy settings after they have been changed in the registry.
#>
function Start-HiddenIEProcess () {
[object] $ieProcess = $null;
# Launch Internet Explorer (use 32-bit version only) in a hidden window.
if (Test-Path "$env:PROGRAMFILES(X86)\\Internet Explorer\\iexplore.exe") {
$ieProcess = Start-Process -Passthru -FilePath "$env:PROGRAMFILES(X86)\\Internet Explorer\\iexplore.exe" -WindowStyle Hidden -ErrorAction SilentlyContinue;
} else {
$ieProcess = Start-Process -Passthru -FilePath "$env:PROGRAMFILES\\Internet Explorer\\iexplore.exe" -WindowStyle Hidden;
}
# Wait for Internet Explorer to load fully.
[int] $count = 10;
do {
if (($ieProcess.WaitForInputIdle())) {
$waiting = $false; # IE is ready.
$count = 0;
} else {
Start-Sleep 1; # Sleep for another second.
$count--; # Decrement wait counter.
}
} while ($waiting -or ($count -gt 0));
# Check to see if our new process exists.
if ((Get-Process -Name iexplore -ErrorAction SilentlyContinue)) {
return $true;
} else {
return $false;
}
} # END
<#
Define a function to toggle the user's proxy settings by altering the
required registry entry and then forcing a 'refresh' of the proxy status
by utilizing a hidden/temporary Internet Explorer process.
#>
function Set-ProxyState ([bool] $disable) {
# Kill existing IE processes.
Stop-Process -Name iexplore -Force -ErrorAction SilentlyContinue;
# Toggle proxy state.
if ($disable) {
Write-Host 'DISABLING user''s proxy settings...';
REG ADD '"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v "ProxyEnable" /t REG_DWORD /d 0 /f' | Out-Null; # Disable proxy.
} else {
Write-Host 'ENABLING user''s proxy settings...';
REG ADD '"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v "ProxyEnable" /t REG_DWORD /d 1 /f' | Out-Null; # Enable proxy.
}
# Start a new/hidden IE process temporarily.
Start-HiddenIEProcess;
# Kill existing IE processes.
Stop-Process -Name iexplore -Force -ErrorAction SilentlyContinue;
Write-Host '[DONE]';
return $null;
} # END
# Toggle the user's proxy settings.
$null = Set-ProxyState $DISABLE_PROXY;
|
PowerShellCorpus/PoshCode/Sith.ps1
|
Sith.ps1
|
' Script: Master_Audit_AD_Account_Management - 2008 v4 S1S2.vbs (Version 4 Section1 and Section2 combi script)
' Purpose: Parse a DC's security event log and generate account management events, log and e-mail for past 24hs
' Author: Paperclips (The Dark Lord)
' Email: magiconion_M@hotmail.com
' Date: Feb 2011
' Comments: Make sure relevant auditing is already set up in AD before using this script. Auditing event logs must be set up for relevant ID's to be audited
' Notes:
' -
'================================================================SECTION 1 AD Auditing MASTER REPORT GEN==============================================================
Dim objFSO, objFolder, objFile, objWMI, objItem, objEmail
Dim strComputer, strFileName, strFileOpen, strFolder, strPath
Dim intEvent, colLoggedEvents, datenow, EventDate
Dim count1, count2, count3, count4, count5, count6, count7, count8, count9, count10
Dim count11, count12, count13, count14, count15, count16, count17, count18, count19, count20
Dim count21, count22, count23, count24, count25
count1 = 0
count2 = 0
count3 = 0
count4 = 0
count5 = 0
count6 = 0
count7 = 0
count8 = 0
count9 = 0
count10 = 0
count11 = 0
count12 = 0
count13 = 0
count14 = 0
count15 = 0
count16 = 0
count17 = 0
count18 = 0
count19 = 0
count20 = 0
count21 = 0
count22 = 0
count23 = 0
count24 = 0
count25 = 0
On error resume next
' ---------------------------------------------------Set the folder and file name-------------------------------------------------------------------
strComputer = "."
strFileName = "\\AD_Account_Management_Events.txt"
strFolder = "c:\\audit_AD"
strPath = strFolder & strFileName
'-----------------------------------------------------Set numbers/Date------------------------------------------------------------------------------
DateNow = Now()
' ----------------------------------------------------Create the File System Object-----------------------------------------------------------------
Set objFSO = CreateObject("Scripting.FileSystemObject")
'-----------------------------------------------------Check that the strFolder folder exists--------------------------------------------------------
If objFSO.FolderExists(strFolder) Then
Set objFolder = objFSO.GetFolder(strFolder)
Else
Set objFolder = objFSO.CreateFolder(strFolder)
End If
If objFSO.FileExists(strFolder & strFileName) Then
Set objFolder = objFSO.GetFolder(strFolder)
Else
Set objFile = objFSO.CreateTextFile(strFolder & strFileName)
End If
' ----------------------------------------------------CLEANUP --------------------------------------------------------------------------------------
set objFile = nothing
set objFolder = nothing
' -----------------------------------------------------Write the information to the file------------------------------------------------------------
Set strFileOpen = objFSO.CreateTextFile(strPath, True)
' -----------------------------------------------------Log Header-----------------------------------------------------------------------------------
strFileOpen.WriteLine("Script started at " & Datenow & " on Your DC")
strFileOpen.WriteLine("===================================================")
strFileOpen.WriteLine("")
strFileOpen.WriteLine("Created by Paperclips")
strFileOpen.WriteLine("......................")
strFileOpen.WriteLine("")
strFileOpen.WriteLine("IMPORTANT NOTES:")
strFileOpen.WriteLine("----------------")
strFileOpen.WriteLine("Sections 21,22,23,24 all related to Directory Service Objects. These 4 categories are repetative of other sections,")
strFileOpen.WriteLine("meaning that if an object was amended, (For example the permissions changed on a user account in section 5 etc.) the")
strFileOpen.WriteLine("event will also appear in section 24 with specific details. Thus sections 21,22,23 and 24 will log in depth changes")
strFileOpen.WriteLine("creations, deletions, move's and permissions. Thus in this example section 5 will only notify that a change has occured")
strFileOpen.WriteLine("and section 24 will log the exact specific change made.")
strFileOpen.WriteLine("")
strFileOpen.WriteLine("Thus when reviewing logs in sections 21,22,23 and 24, look at the line that says Class: to see what object was changed")
strFileOpen.WriteLine("This will be either, user, computer, group, organisationalunit etc.....")
strFileOpen.WriteLine("Additionally if the LDAP Display Name: variable is NTSecurityDescriptor and the Class: is OrganisationalUnit this means")
strFileOpen.WriteLine("that the permission has changed on the OU. Additional Totals have been added for OU's in the summary report with regards")
strFileOpen.WriteLine("to sections 21, 22, 23 and 24.")
strFileOpen.WriteLine("")
strFileOpen.WriteLine("")
' -----------------------------------------------------WMI Core Section1----------------------------------------------------------------------------
Set objWMI = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate,(Security)}!\\\\" _
& strComputer & "\\root\\cimv2")
Set colLoggedEvents = objWMI.ExecQuery _
("Select * from Win32_NTLogEvent Where Logfile = 'Security' AND EventCode = '1102'" )
'------------------------------------------------------Next few sections loops through ID properties------------------------------------------------
strFileOpen.WriteLine(" =====================================================================")
strFileOpen.WriteLine(" = The Security Event Log on this Domain Controller was last cleared =")
strFileOpen.WriteLine(" =====================================================================")
strFileOpen.WriteLine(" ")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
'If DateDiff("h",DateNow,EventDate) > -25 Then
'If objItem.EventType=4 then
'If objItem.EventCode =1102 Then
strFileOpen.WriteLine ("Time of last clear: " & EventDate)
strFileOpen.WriteLine("DC Name: " & objItem.ComputerName)
strFileOpen.WriteLine("Logfile: " & objItem.SourceName)
strFileOpen.WriteLine("Message: " & objItem.Message)
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
'End If
'End If
'end if
Next
' -----------------------------------------------------WMI Core Section2 ----------------------------------------------------------------------------
Set objWMI = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate,(Security)}!\\\\" _
& strComputer & "\\root\\cimv2")
Set colLoggedEvents = objWMI.ExecQuery _
("Select * from Win32_NTLogEvent Where Logfile = 'Security'" )
'1------------------------------------------------------Next few sections loops through ID properties------------------------------------------------
strFileOpen.WriteLine("===========================================================================================")
strFileOpen.WriteLine("= 1. User Password Change Attempts by SUBJECT in the past 24hrs (most likely by an admin) =")
strFileOpen.WriteLine("===========================================================================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =4724 Then
count1 = count1 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 1.)User Password Change Attempts by SUBJECT in the past 24hrs (most likely by an admin) TOTAL = " & Count1)
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine(" ")
'2---------------------------------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("==============================================================================")
strFileOpen.WriteLine("= 2. User Password Change Attempts by THE USER HIM/HERSELF in the past 24hrs =")
strFileOpen.WriteLine("==============================================================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =4723 Then
count2 = count2 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 2.)User Password Change Attempts by THE USER HIM/HERSELF in the past 24hrs TOTAL = " & Count2)
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine(" ")
'3---------------------------------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("==============================================")
strFileOpen.WriteLine("= 3. User Accounts Created in the past 24hrs =")
strFileOpen.WriteLine("==============================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =4720 Then
count3 = count3 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 3.)User Accounts Created in the past 24hrs TOTAL = " & Count3)
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine(" ")
'4---------------------------------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("==============================================")
strFileOpen.WriteLine("= 4. User Accounts Deleted in the past 24hrs =")
strFileOpen.WriteLine("==============================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =4726 Then
count4 = count4 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 4.)User Accounts Deleted in the past 24hrs TOTAL = " & Count4)
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine(" ")
'5---------------------------------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("==============================================")
strFileOpen.WriteLine("= 5. User Accounts Changed in the past 24hrs =")
strFileOpen.WriteLine("==============================================")
strFileOpen.WriteLine("")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =4738 Then
count5 = count5 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Important Note: To see exactly what changed on the user object refer to events created")
strFileOpen.WriteLine ("--------------- for (Directory Service Changes) later in this log for Class: User")
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 5.)User Accounts Changed in the past 24hrs TOTAL = " & Count5)
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine(" ")
'6---------------------------------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("=================================================")
strFileOpen.WriteLine("= 6. User Accounts Locked Out in the past 24hrs =")
strFileOpen.WriteLine("=================================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =4740 Then
count6 = count6 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 6.)User Accounts Locked Out in the past 24hrs TOTAL = " & Count6)
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine(" ")
'7---------------------------------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("===============================================")
strFileOpen.WriteLine("= 7. User Accounts Unlocked in the past 24hrs =")
strFileOpen.WriteLine("===============================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =4767 Then
count7 = count7 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 7.)User Accounts Unlocked in the past 24hrs TOTAL = " & Count7)
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine(" ")
'8---------------------------------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("==================================================")
strFileOpen.WriteLine("= 8. Computer Accounts Created in the past 24hrs =")
strFileOpen.WriteLine("==================================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =4741 Then
count8 = count8 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 8.)Computer Accounts Created in the past 24hrs TOTAL = " & Count8)
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine(" ")
'9---------------------------------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("==================================================")
strFileOpen.WriteLine("= 9. Computer Accounts Deleted in the past 24hrs =")
strFileOpen.WriteLine("==================================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =4743 Then
count9 = count9 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 9.)Computer Accounts Deleted in the past 24hrs TOTAL = " & Count9)
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine(" ")
'10---------------------------------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("===================================================")
strFileOpen.WriteLine("= 10. Computer Accounts Amended in the past 24hrs =")
strFileOpen.WriteLine("===================================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =4742 Then
count10 = count10 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Important Note: To see exactly what changed on the computer object refer to events created")
strFileOpen.WriteLine ("--------------- for (Directory Service Changes) later in this log for Class: Computer")
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 10.)Computer Accounts Amended in the past 24hrs TOTAL = " & Count10)
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine(" ")
'11---------------------------------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("===========================================================")
strFileOpen.WriteLine("= 11. User or Computer Objects Disabled in the past 24hrs =")
strFileOpen.WriteLine("===========================================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =4725 Then
count11 = count11 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 11.)User or Computer Objects Disabled in the past 24hrs TOTAL = " & Count11)
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine(" ")
'12---------------------------------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("==========================================================")
strFileOpen.WriteLine("= 12. User or Computer Objects Enabled in the past 24hrs =")
strFileOpen.WriteLine("==========================================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =4722 Then
count12 = count12 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 12.)User or Computer Objects Enabled in the past 24hrs TOTAL = " & Count12)
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine(" ")
'13---------------------------------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("=========================================================")
strFileOpen.WriteLine("= 13. Users Added to Security Groups in the past 24hrs =")
strFileOpen.WriteLine("=========================================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =4728 Then
count13 = count13 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 13.)Users Added to Security Groups in the past 24hrs TOTAL = " & Count13)
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine(" ")
'14-----------------------------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("==================================================")
strFileOpen.WriteLine("= 14. Security Groups Deleted in the past 24hrs =")
strFileOpen.WriteLine("==================================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =4730 Then
count14 = count14 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 14.)Security Groups Deleted in the past 24hrs TOTAL = " & Count14)
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine(" ")
'15-------------------------------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("=================================================")
strFileOpen.WriteLine("= 15. Security Groups Created in the past 24hrs =")
strFileOpen.WriteLine("=================================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =4727 Then
count15 = count15 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 15.)Security Groups Created in the past 24hrs TOTAL = " & Count15)
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine(" ")
'16-------------------------------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("=========================================================")
strFileOpen.WriteLine("= 16. Security Groups Amended/Changed in the past 24hrs =")
strFileOpen.WriteLine("=========================================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =4737 Then
count16 = count16 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Important Note: To see exactly what changed on the Group object refer to events created")
strFileOpen.WriteLine ("--------------- for (Directory Service Changes) later in this log for Class: Group")
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 16.)Security Groups Amended/Changed in the past 24hrs TOTAL = " & Count16)
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine(" ")
'17------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("==========================================================")
strFileOpen.WriteLine("= 17. Mail Distribution Groups Created in the past 24hrs =")
strFileOpen.WriteLine("==========================================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =4749 Then
count17 = count17 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 17.)Mail Distribution Groups Created in the past 24hrs TOTAL = " & Count17)
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine(" ")
'18------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("==========================================================")
strFileOpen.WriteLine("= 18. Mail Distribution Groups Deleted in the past 24hrs =")
strFileOpen.WriteLine("==========================================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =4753 Then
count18 = count18 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 18.)Mail Distribution Groups Deleted in the past 24hrs TOTAL = " & Count18)
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine(" ")
'19------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("=================================================================")
strFileOpen.WriteLine("= 19. Users Added To Mail Distribution Groups in the past 24hrs =")
strFileOpen.WriteLine("=================================================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =4751 Then
count19 = count19 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 19.)Users Added To Mail Distribution Groups in the past 24hrs TOTAL = " & Count19)
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine(" ")
'20------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("==================================================================")
strFileOpen.WriteLine("= 20. Mail Distribution Groups Amended/Changed in the past 24hrs =")
strFileOpen.WriteLine("==================================================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =4750 Then
count20 = count20 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Important Note: To see exactly what changed on the Group object refer to events created")
strFileOpen.WriteLine ("--------------- for (Directory Service Changes) later in this log for Class: Group")
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 20.)Mail Distribution Groups Amended/Changed in the past 24hrs TOTAL = " & Count20)
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine(" ")
'21------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("=========================================================================")
strFileOpen.WriteLine("= 21. Directory Service Objects Created in the past 24hrs (Check CLASS) =")
strFileOpen.WriteLine("=========================================================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =5137 Then
count21 = count21 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 21.)Directory Service Objects Created in the past 24hrs (Check CLASS) TOTAL = " & Count21)
strFileOpen.WriteLine("stop21")
strFileOpen.WriteLine(" ")
'22------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("=======================================================================")
strFileOpen.WriteLine("= 22. Directory Service Objects Moved in the past 24hrs (Check CLASS) =")
strFileOpen.WriteLine("=======================================================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =5139 Then
count22 = count22 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 22.)Directory Service Objects Moved in the past 24hrs (Check CLASS) TOTAL = " & Count22)
strFileOpen.WriteLine("stop22")
strFileOpen.WriteLine(" ")
'23------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("=========================================================================")
strFileOpen.WriteLine("= 23. Directory Service Objects Deleted in the past 24hrs (Check CLASS) =")
strFileOpen.WriteLine("=========================================================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =5141 Then
count23 = count23 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 23.)Directory Service Objects Deleted in the past 24hrs (Check CLASS) TOTAL = " & Count23)
strFileOpen.WriteLine("stop23")
strFileOpen.WriteLine(" ")
'24------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("=================================================================================================")
strFileOpen.WriteLine("= 24. A directory service object was modified (CHECK OBJECT CLASS) for object that was modified =")
strFileOpen.WriteLine("=================================================================================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =5136 Then
count24 = count24 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 24.)A directory service object was modified (CHECK OBJECT CLASS) for object that was modified TOTAL = " & Count24)
strFileOpen.WriteLine("stop24")
strFileOpen.WriteLine(" ")
'25---------------------------------------------------------------------------------------------------------------------------------------------------
strFileOpen.WriteLine("========================================================================================================================")
strFileOpen.WriteLine("==================================")
strFileOpen.WriteLine("= 25. EPIC LOGON FAILED ATTEMPTS =")
strFileOpen.WriteLine("==================================")
For Each objItem in colLoggedEvents
EventDate = GetVBDate(objItem.TimeGenerated)
If DateDiff("h",DateNow,EventDate) > -24 Then
If objItem.EventCode =4625 Then
count25 = count25 + 1
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine ("---------------------------------Start Of Entry--------------------------------")
strFileOpen.WriteLine ("EventDate\\Time: " & EventDate)
strFileOpen.WriteLine ("Message: " & objItem.Message)
strFileOpen.WriteLine ("----------------------------------End Of Entry---------------------------------")
strFileOpen.WriteLine (" ")
strFileOpen.WriteLine (" ")
End If
end if
Next
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine("** 25.)EPIC LOGON FAILED ATTEMPTS TOTAL = " & Count25)
strFileOpen.WriteLine(" ")
strFileOpen.WriteLine(" ")
'-------------------------------------backup and Clear security event log---------------------------------------------------------------------------
dtmThisDay = Day(Date)
dtmThisMonth = Month(Date)
dtmThisYear = Year(Date)
strBackupName = dtmThisYear & "_" & dtmThisMonth _
& "_" & dtmThisDay
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate,(Backup)}!\\\\" & _
strComputer & "\\root\\cimv2")
Set colLogFiles = objWMIService.ExecQuery _
("Select * from Win32_NTEventLogFile " _
& "Where LogFileName='Security'")
For Each objLogfile in colLogFiles
objLogFile.BackupEventLog("c:\\audit_AD\\" _
& strBackupName & _
"_Security.evt")
objLogFile.ClearEventLog()
Next
'---------------------------------------------------------------------------------------------------------------------------------------------------
Function GetVBDate(wd)
GetVBDate = DateSerial(left(wd,4),mid(wd,5,2),mid(wd,7,2))+ TimeSerial(mid(wd,9,2),mid(wd,11,2),mid(wd,13,2))
End Function
'---------------------------------------------------------------------------------------------------------------------------------------------------
'================================================================SECTION 2 AD Auditing==============================================================
'-----------------------------------------------------Declaring and setting variables---------------------------------------------------------------
WScript.Sleep(4000)
Dim strEmailFrom, strEmailTo, strEmailSubject, strEmailBody, strSMTP, OUcreateCount, OUDeleteCount, OUMoveCount, OUChangeCount
Dim PermChangeCount
OUcreateCount = 0
OUDeleteCount = 0
OUMoveCount = 0
OUChangeCount = 0
PermChangeCount = 0
Const ForReading=1
Set WshNetwork = WScript.CreateObject("WScript.Network")
StrComputer = WshNetwork.ComputerName
Set objFSO = CreateObject("Scripting.FileSystemObject")
folder = "C:\\audit_AD\\"
filePath = folder & "AD_Account_Management_Events.txt" 'original log created by SECTION 1 that will be used in this script to generate the
Set myFile = objFSO.OpenTextFile(filePath, ForReading, True) 'summary report, This file must exist for this Script to work
strEmailFrom = "xx@xx.com"
strEmailTo = "aa@aa.com; bb@bb.com"
strEmailSubject = "Summary Of AD Activity on " & StrComputer & " for the past 24hrs - Date/TimeStamp: " & Datenow
strSMTP = "xxx.xxx.xxx.xxx"
'------------------------------------------------------Important Notes Area in Body Of E-mail-------------------------------------------------------
strEmailBody = strEmailbody & vbCRLf & "IMPORTANT NOTES to Auditor:"
strEmailBody = strEmailbody & vbCRLf
strEmailBody = strEmailbody & vbCRLf & "Sections 21,22,23,24 all related to Directory Service Objects. These 4 categories are repetative of other sections,"
strEmailBody = strEmailbody & vbCRLf & "meaning that if an object was amended, (For example the permissions changed on a user account in section 5 etc.) the"
strEmailBody = strEmailbody & vbCRLf & "event will also appear in section 24 with specific details. Thus sections 21,22,23 and 24 will log in depth changes"
strEmailBody = strEmailbody & vbCRLf & "creations, deletions, move's and permissions. Thus in this example section 5 will only notify that a change has occured"
strEmailBody = strEmailbody & vbCRLf & "and section 24 will log the exact specific change made."
strEmailBody = strEmailbody & vbCRLf & ""
strEmailBody = strEmailbody & vbCRLf & "Thus when reviewing logs in sections 21,22,23 and 24, look at the line that says Class: to see what object was changed"
strEmailBody = strEmailbody & vbCRLf & "This will be either, user, computer, group, organisationalunit etc....."
strEmailBody = strEmailbody & vbCRLf & "Additionally if the LDAP Display Name: variable is NTSecurityDescriptor and the Class: is OrganisationalUnit this means"
strEmailBody = strEmailbody & vbCRLf & "that the permission has changed on the OU. Additional Totals have been added for OU's in the summary report with regards to sections 21, 22, 23 and 24."
strEmailBody = strEmailbody & vbCRLf & ""
strEmailBody = strEmailbody & vbCRLf & "The Full report can be viewed at on the DC at C:\\Audit_Ad"
strEmailBody = strEmailbody & vbCRLf
strEmailBody = strEmailbody & vbCRLf
'------------------This section reads the original log file created in SECTION 1 and generates a summary report-------------------------------------
Do While Not myFile.AtEndofStream
myLine = myFile.ReadLine
MarkersLine = left(myline,3) ' main summary markers(Will read all lines starting with "** " in log and append into email body)
EventLine = left(myline,19) 'eventlog (Will read all lines starting with "defined field" in original log and append into email body)
If EventLine = "Time of last clear:" Then
strEmailBody = strEmailbody & vbCRLf & "Security Event Log " & MyLine & " on " & StrComputer & vbCRLf
strEmailBody = strEmailbody & vbCRLf
End If
If MarkersLine = "** " Then
strEmailBody = strEmailbody & vbCRLf & MyLine & vbCRLf
End If
Loop
myFile.Close
'1.---------This section reads the original log file created in SECTION 1 and generates a summary report specifically for OU Creations--------------
Set objFSO = CreateObject("Scripting.FileSystemObject")
folder = "C:\\audit_AD\\"
filePath = folder & "AD_Account_Management_Events.txt"
Set myFile = objFSO.OpenTextFile(filePath, ForReading, True)
blnAddToBody = False
Do While Not myFile.AtEndofStream
myLine = myFile.ReadLine
ClassLine = " Class: organizationalUnit" ' Sets the class that will be searched inside the original log
strStartLine1 = "= 21. Directory Service Objects Created in the past 24hrs (Check CLASS) ="
StrEndLine1 = "stop21"
If myLine = strStartLine1 Then
blnAddToBody = True
End If
If myLine = ClassLine Then
If blnAddToBody = True Then
OUcreateCount = OUcreateCount + 1
end if
end if
if myLine = strEndLine1 Then
blnAddToBody = False
end if
Loop
myFile.Close
'2.---------This section reads the original log file created in SECTION 1 and generates a summary report specifically for OU Moves-------------------
Set objFSO = CreateObject("Scripting.FileSystemObject")
folder = "C:\\audit_AD\\"
filePath = folder & "AD_Account_Management_Events.txt"
Set myFile = objFSO.OpenTextFile(filePath, ForReading, True)
blnAddToBody = True
Do While Not myFile.AtEndofStream
myLine = myFile.ReadLine
ClassLine = " Class: organizationalUnit" ' Sets the class that will be searched inside the original log
strStartLine2 = "= 22. Directory Service Objects Moved in the past 24hrs (Check CLASS) ="
StrEndLine2 = "stop22"
If myLine = strStartLine2 Then
blnAddToBody = True
End If
If myLine = ClassLine Then
If blnAddToBody = True Then
OUMoveCount = OUMoveCount + 1
end if
end if
if myLine = strEndLine2 Then
blnAddToBody = False
end if
Loop
myFile.Close
'3.---------This section reads the original log file created in SECTION 1 and generates a summary report specifically for OU Deletions----------------
Set objFSO = CreateObject("Scripting.FileSystemObject")
folder = "C:\\audit_AD\\"
filePath = folder & "AD_Account_Management_Events.txt"
Set myFile = objFSO.OpenTextFile(filePath, ForReading, True)
blnAddToBody = False
Do While Not myFile.AtEndofStream
myLine = myFile.ReadLine
ClassLine = " Class: organizationalUnit" ' Sets the class that will be searched inside the original log
strStartLine3 = "= 23. Directory Service Objects Deleted in the past 24hrs (Check CLASS) ="
StrEndLine3 = "stop23"
If myLine = strStartLine3 Then
blnAddToBody = True
End If
If myLine = ClassLine Then
If blnAddToBody = True Then
OUDeleteCount = OUDeleteCount + 1
end if
end if
if myLine = strEndLine3 Then
blnAddToBody = False
end if
Loop
myFile.Close
'4.---------This section reads the original log file created in SECTION 1 and generates a summary report specifically for OU Changes----------------
Set objFSO = CreateObject("Scripting.FileSystemObject")
folder = "C:\\audit_AD\\"
filePath = folder & "AD_Account_Management_Events.txt"
Set myFile = objFSO.OpenTextFile(filePath, ForReading, True)
blnAddToBody = False
Do While Not myFile.AtEndofStream
myLine = myFile.ReadLine
ClassLine = " Class: organizationalUnit" ' Sets the class that will be searched inside the original log
strStartLine4 = "= 24. A directory service object was modified (CHECK OBJECT CLASS) for object that was modified ="
StrEndLine4 = "stop24"
If myLine = strStartLine4 Then
blnAddToBody = True
End If
If myLine = ClassLine Then
If blnAddToBody = True Then
OUChangeCount = OUChangeCount + 1
end if
end if
if myLine = strEndLine4 Then
blnAddToBody = False
end if
Loop
myFile.Close
'============================================================END OF SUMMARY ENUMERATION=============================================================
strEmailBody = strEmailbody & vbCRLf
strEmailBody = strEmailbody & vbCRLf & "With regards to section 21: Specific OU Creations = " & OUCreateCount & vbCRLf
strEmailBody = strEmailbody & vbCRLf & "With regards to section 22: Specific OU Moves = " & OUMoveCount & vbCRLf
strEmailBody = strEmailbody & vbCRLf & "With regards to section 23: Specific OU Deletions = " & OUDeleteCount & vbCRLf
strEmailBody = strEmailbody & vbCRLf & "With regards to section 24: Specific OU Changes e.g. Permissions = " & OUChangeCount & vbCRLf
Set objEmail = CreateObject("CDO.Message")
objEmail.From = strEmailFrom
objEmail.To = strEmailTo
objEmail.Subject = strEmailSubject
objEmail.Textbody = strEmailBody
objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = strSMTP
objEmail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objEmail.Configuration.Fields.Update
objEmail.Send
|
PowerShellCorpus/PoshCode/Script for mBull.ps1
|
Script for mBull.ps1
|
$endDate = New-Object datetime(2013,1, 1)
for ($date = [DateTime]::Today; $date -le $endDate; $date = $date.AddDays(1);)
{
if ($date.DayOfWeek -ne [DayOfWeek]::Saturday -and $date.DayOfWeek -ne [DayOfWeek]::Saturday)
{
New-Item -type directory $date.ToShortDateString()
}
}
|
PowerShellCorpus/PoshCode/d599ff7e-17c4-40a4-b3fc-8666dd953df5.ps1
|
d599ff7e-17c4-40a4-b3fc-8666dd953df5.ps1
|
function Get-VCTime() {
return (Get-View "ServiceInstance-ServiceInstance").CurrentTime()
}
$lastCheckTime = Get-VCTime
while ($true)
{
$modifiedVMs = @()
$freshEventsStartTime = $lastCheckTime
$lastCheckTime = Get-VCTime
# Get all the VM network edit events
foreach ($event in Get-VIEvent -Start $freshEventsStartTime -Types Info)
{
if ($event.GetType().FullName -eq "VimApi.VmReconfiguredEvent" -and
$event.configSpec -ne $null)
{
foreach ($change in $event.configSpec.deviceChange)
{
if ($change.operation -eq "edit" -and
$change.device -ne $null -and
$change.device.GetType().FullName -eq "VimApi.VirtualPCNet32")
{
# VM's networking was reconfigured.
$vmId = $event.vm.vm.Type + '-' + $event.vm.vm.Value
$modifiedVMs += Get-VM -Id $vmId
}
}
}
}
# Did one of these edits violate isolation?
foreach ($vm in $modifiedVMs | select -Unique)
{
$intranetNics = $vm.NetworkAdapters | where { $_.NetworkName -eq 'Intranet' }
$dmzNics = $vm.NetworkAdapters | where { $_.NetworkName -eq 'DMZ' }
if ($intranetNics -ne $null -and $dmzNics -ne $null)
{
# Send an email notification
$message = "VM '" + $vm.Name + "' violates network isolation rules!"
Write-Host $message -ForegroundColor Yellow
# Use .Net’s SmtpClient to send mail. Just tell it which SMTP server to use
(New-Object 'System.Net.Mail.SmtpClient' 'smtp.example1234.com').Send(
'NetworkMonitor@example1234.com', # Sender
'john.doe@example1234.com', # Recipient
'Network isolation violation', # Subject
$message)
}
}
Start-Sleep 60
} # while ($true)
|
PowerShellCorpus/PoshCode/Reverse filename sequenc_2.ps1
|
Reverse filename sequenc_2.ps1
|
# Reverse filename sequence v 0.9
# Author: Sean Wendt
#
# This script will rename a sequenced set of files in a directory.
# For example, you have foobar01.jpg, foobar02.jpg, foobar03.jpg
# -- it will reverse the order, so the last file is now 01, the second to last 02, etc..
#
# Limitations: -You cannot use the same filename prefix, i.e. foobar must change to foobars.
# -It's hardcoded to only support 5 digit numbers right now.
# -Similarly, it will only support a file sequence with up to 5 digits.
# This is the first script I've written, I know it's not great! ;)
# Help to make it better would be appreciated. Thanks.
#
$file_extension = Read-Host "Enter file extension, i.e. .jpg or .txt"
$file_prefix = Read-Host "Enter file prefix, i.e. entering foobar will rename files to foobar001.ext, foobar002.ext, etc.."
$files = Get-ChildItem | ?{ $_.PSIsContainer -ne "True"} # Creates array of files in current directory, ignores folders
$idx = 0 # Sets index value (0 = filenames start at foobar00000.jpg, modify to 1 to start at foobar00001.jpg)
for ($ctr=$files.count; $ctr -gt 0 ; --$ctr)
{
if (($idx -ge 0) -and ($idx -le 9))
{
Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '00000' + $idx++ + $file_extension)
}
elseif (($idx -ge 10) -and ($idx -le 99))
{
Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '0000' + $idx++ + $file_extension)
}
elseif (($idx -ge 100) -and ($idx -le 999))
{
Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '000' + $idx++ + $file_extension)
}
elseif (($idx -ge 1000) -and ($idx -le 9999))
{
Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '00' + $idx++ + $file_extension)
}
elseif (($idx -ge 10000) -and ($idx -le 99999))
{
Rename-Item -path $files[$ctr-1].name -newname ($file_prefix + '0' + $idx++ + $file_extension)
}
$idx #prints the index # it just completed
}
|
PowerShellCorpus/PoshCode/mGet-DatastoreList.ps1
|
mGet-DatastoreList.ps1
|
Function mGet-DatastoreList {
#Parameter- Name of the VMware cluster to choose a datastore from.
param($Cluster)
#get alphabetically last ESX host in the VMware cluster (it's likely the last host added to the cluster, so this might smoke out any problems)
$VMH = get-vmhost -Location $cluster | Where-Object { ($_.ConnectionState -eq "Connected") -and ($_.PowerState -eq "PoweredOn") } | Select-Object -Property Name | Sort-Object Name | Select -Last 1 -Property Name
# Get all the datastores, filtered for exclusions
$DSTs = Get-Datastore -VMHost $VMH.Name | Where-Object { ($_.Type -eq "VMFS") -and ($_.Name -notmatch "local") -and ($_.Name -notmatch "iso") -and ($_.Name -notmatch "template") -and ($_.Name -notmatch "CLD") -and ($_.Name -notmatch "TRX") }
Write-Output $DSTs
}
|
PowerShellCorpus/PoshCode/VMtoolsUpgrade-disable.ps1
|
VMtoolsUpgrade-disable.ps1
|
#####################################################################
# TIAA-CREF VMWare Standard Scripts - PowerCLI
#
# Purpose: "Check and upgrade Tools during power cycling"
# Author: David Chung
# Support: IT Infrastructure
# Docs: N/A
#
# Instruction: 1. Create CSV file with list of servers
# 2. Execute script from PowerCLI
# 3. Enter virtual server name
#
#####################################################################
$viserver = read-host "Please enter vCenter Server:"
connect-viserver $viserver
$vms = Import-Csv c:\\server.csv
foreach ($vm.name in $vms)
{
Write-Host $vm.name " - Disabling VMTools Update at Power Cycle"
$vmConfig = New-Object VMware.Vim.VirtualMachineConfigSpec
$vmConfig.Tools = New-Object VMware.Vim.ToolsConfigInfo
$vmConfig.Tools.ToolsUpgradePolicy = "Manual"
Get-VM $vm.name | where {$_.Extensiondata.ReconfigVM($vmconfig)}
}
|
PowerShellCorpus/PoshCode/Test-UserCredential.ps1
|
Test-UserCredential.ps1
|
function Test-UserCredential {
[CmdletBinding()] [OutputType([System.Boolean])]
param(
[Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()]
[System.String] $Username,
[Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()]
[System.String] $Password,
[Parameter()]
[Switch] $Domain
)
Begin {
$assembly = [system.reflection.assembly]::LoadWithPartialName('System.DirectoryServices.AccountManagement')
}
Process {
try {
$system = Get-WmiObject -Class Win32_ComputerSystem
if ($Domain) {
if (0, 2 -contains $system.DomainRole) {
throw 'This computer is not a member of a domain.'
} else {
$principalContext = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext 'Domain', $system.Domain
}
} else {
$principalContext = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext 'Machine', $env:COMPUTERNAME
}
return $principalContext.ValidateCredentials($Username, $Password)
}
catch {
throw 'Failed to test user credentials. The error was: "{0}".' -f $_
}
}
<#
.SYNOPSIS
Validates credentials for local or domain user.
.PARAMETER Username
The user's username.
.PARAMETER Password
The user's password.
.EXAMPLE
PS C:\\> Test-UserCredential -Username andy -password secret
.EXAMPLE
PS C:\\> Test-UserCredential -Username 'mydomain\\andy' -password secret -domain
.EXAMPLE
PS C:\\> Test-UserCredential -Username 'andy' -password secret -domain
.INPUTS
None.
.OUTPUTS
System.Boolean.
.NOTES
Revision History
2011-08-21: Andy Arismendi - Created.
#>
}
|
PowerShellCorpus/PoshCode/ImaginaryFriendFeed_1.ps1
|
ImaginaryFriendFeed_1.ps1
|
#.SYNOPSIS
# A few functions for working with FriendFeed and Twitter
#.DESCRIPTION
# Allows you to copy your users from Twitter to imaginary FriendFeed users...
#.EXAMPLE
# ## Get any twitter friends who aren't on friendfeed
# ## Make sure you use FriendFeed's built in "add all your twitter friends" first
# $twits = Get-TwitterFriends `
# -Nickname jaykul
# -Exclude $(Get-FriendFeedFriends jaykul | select -expand twitter)
#
# ## YOU MIGHT want to remove people who aren't updating, while you're messing around ...
# $threshold = (Get-Date).AddDays(-14)
# $twits = $twits | Where { $_.protected -or ([DateTime]::ParseExact($_.status.created_at, "ddd MMM dd HH:mm:ss +0000 yyyy", $Null) -gt $threshold) }
#
# ## Add them to friend feed
# foreach($twit in $twits) {
# New-ImaginaryFriend $twit.name @{twitter=$twit.screen_name} $twit.profile_image_url
# }
function New-ImaginaryFriend {
##.Note
## DEPENDS on the WatiN module in http://poshcode.org/1108
##.Synopsis
## Creates a new "Imaginary Friend" on friendfeed by automating your browser
##.Example
## New-ImaginaryFriend PoshCode @{Twitter="PoshCode"} http://poshcode.org/PoshCode.png
##
[CmdletBinding()]
PARAM($name,[hashtable]$services,$avatar)
## BEGIN ...
if($global:ie -is [WatiN.Core.IE]) {
New-Watin "http`://friendfeed.com/settings/imaginary"
while( $ie.Url -ne "http`://friendfeed.com/settings/imaginary" ) {
Set-WatinUrl "http`://friendfeed.com/settings/imaginary"
Read-Host "Press Enter after you have logged into FriendFeed"
}
}
## TEST/Validate
Set-WatinUrl http`://friendfeed.com/settings/imaginary
if($ie.Url -ne "http`://friendfeed.com/settings/imaginary" ) {
throw "You are not authenticated to FriendFeed. Please log in and try again"
}
## PROCESS
Find-Button value "Create imaginary friend" | % { $_.Click() }
Find-TextField name name | % { $_.TypeText( $name ) }
(Find-Form action "/a/createimaginary").Buttons | % { $_.click() }
$null = $ie.url -match "http`://friendfeed.com/([^/]*)/services";
$ffid = $matches[1]
# Write-Output $ffid
foreach($service in $services.GetEnumerator()) {
Write-Verbose "$($service.Key): $($service.Value)"
Find-Link service $service.Key | % { $_.Click() }
$form = Find-Form action "/a/configureservice"
@($form.TextFields)[0].TypeText( $service.Value )
@($form.Buttons)[0].click();
}
if($avatar) {
Set-WatinUrl "http`://friendfeed.com/$ffid"
$avatarFile = Get-WebFile $avatar ([uri]$avatar).segments[-1]
Write-Verbose "Downloaded? $($avatarFile.FullName)"
Start-Sleep -milli 500
Find-Link innertext "Change picture" | %{ $_.Click() }
Find-FileUpload id pictureupload | % { $_.Set( $avatarFile.FullName ) }
(Find-Form action "/a/changepicture").Buttons | % { $_.click() }
Start-Sleep -milli 500
Remove-Item $avatarFile
}
}
## DEPENDS on the HttpRest module in http://poshcode.org/1107
Function Get-FriendFeedFriends {
Param([string]$UserName,[string[]]$Exclude)
$friendNames = Get-WebPageText "http`://friendfeed.com/api/user/$username/profile" //user/subscription/nickname @{format="xml";include="subscriptions"} |
Where {$Exclude -notcontains $_ }
ForEach($incoming in (Get-WebPageContent "http`://friendfeed.com/api/profiles" //profiles/profile @{ format="xml"; nickname=$($friendNames -join ",") })) {
$output = Select -Input $incoming Name, NickName |
Add-Member noteproperty Lists @($incoming.SelectNodes("//list/nickname").InnerText) -Passthru |
Add-Member noteproperty Rooms @($incoming.SelectNodes("//room/nickname").InnerText) -Passthru
ForEach($service in $incoming.service) {
if(!$output."$($service.id)") {
if($service.username) {
Add-Member -input $output noteproperty $service.id $service.username
} else {
Add-Member -input $output noteproperty $service.id $service.profileUrl
}
} else {
if($service.username) {
$output."$($service.id)" = @($output."$($service.id)") + $service.username
} else {
$output."$($service.id)" = @($output."$($service.id)") + $service.profileUrl
}
}
}
$output
}
}
## DEPENDS on the HttpRest module in http://poshcode.org/1107
function Get-TwitterFriends {
Param($UserName, [string[]]$Exclude)
$page = 0; $tweeters = @()
do {
$tweeters = Get-WebPageContent "http`://twitter.com/statuses/friends.xml" //users/user @{page=(++$page); screen_name=$UserName} |
Where {$Exclude -notcontains $_.screen_name }
Write-Output $tweeters
} while($tweeters)
}
|
PowerShellCorpus/PoshCode/Ping-Host.ps1
|
Ping-Host.ps1
|
function Ping-Host {param( [string]$HostName,
[int32]$Requests = 3)
for ($i = 1; $i -le $Requests; $i++) {
$Result = Get-WmiObject -Class Win32_PingStatus -ComputerName . -Filter "Address='$HostName'"
Start-Sleep -Seconds 1
if ($Result.StatusCode -ne 0) {return $FALSE}
}
return $TRUE
}
|
PowerShellCorpus/PoshCode/DriveSpace.format.ps1xml.ps1
|
DriveSpace.format.ps1xml.ps1
|
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<Controls>
<Control>
<Name>DriveSpaceChart</Name>
<CustomControl>
<CustomEntries>
<CustomEntry>
<CustomItem>
<Frame>
<CustomItem>
<ExpressionBinding>
<ScriptBlock>
$G, $Drive, $Width = "$([char]9608)", $_, ($Host.UI.RawUI.BufferSize.Width/2)
if($drive.Size) {
$UsedSpace = $drive.Size - $drive.Freespace
$FreeBar = $g * ($Width * [Math]::Round($drive.FreeSpace / $drive.Size, 2))
$UsedBar = $g * ($Width * [Math]::Round($UsedSpace / $drive.Size, 2))
# Write-Verbose "G: $G`nDrive: $Drive`nWidth:$Width`n$FreeBar`n$UsedBar"
write-host $("[{0}] {1} " -f $drive.systemname.PadRight($longest.length),$drive.DeviceID) -NoNewline
write-host $UsedBar -ForegroundColor red -NoNewline
write-host $FreeBar -ForegroundColor darkgreen -NoNewline
write-host (" {0:P} free ({1:N} GB)" -f ($drive.FreeSpace / $drive.Size), ($drive.FreeSpace/1GB)) -NoNewline
}
</ScriptBlock>
</ExpressionBinding>
</CustomItem>
</Frame>
</CustomItem>
</CustomEntry>
</CustomEntries>
</CustomControl>
</Control>
</Controls>
<ViewDefinitions>
<View>
<Name>SpaceGraph</Name>
<ViewSelectedBy>
<TypeName>System.Management.ManagementObject#root\\cimv2\\Win32_LogicalDisk</TypeName>
</ViewSelectedBy>
<WideControl>
<WideEntries>
<WideEntry>
<WideItem>
<ScriptBlock>
$G, $Drive, $Width = "$([char]9608)", $_, ($Host.UI.RawUI.BufferSize.Width/2)
# Write-Verbose "G: $G`nDrive: $Drive`nWidth:$Width`n$FreeBar`n$UsedBar"
write-host $("[{0}] {1} " -f $drive.systemname.PadRight($longest.length),$drive.DeviceID) -NoNewline
if($drive.Size) {
$UsedSpace = $drive.Size - $drive.Freespace
$FreeBar = $g * ($Width * [Math]::Round($drive.FreeSpace / $drive.Size, 2))
$UsedBar = $g * ($Width * [Math]::Round($UsedSpace / $drive.Size, 2))
write-host $UsedBar -ForegroundColor red -NoNewline
write-host $FreeBar -ForegroundColor darkgreen -NoNewline
write-host (" {0:P} free ({1:N} GB) {2}" -f ($drive.FreeSpace / $drive.Size), ($drive.FreeSpace/1GB), $drive.Description) -NoNewline
}
return $null
</ScriptBlock>
</WideItem>
</WideEntry>
</WideEntries>
</WideControl>
<!--
<CustomControl>
<CustomEntries>
<CustomEntry>
<CustomItem>
<ExpressionBinding>
<CustomControlName>DriveSpaceChart</CustomControlName>
</ExpressionBinding>
</CustomItem>
</CustomEntry>
</CustomEntries>
</CustomControl>
-->
</View>
</ViewDefinitions>
</Configuration>
|
PowerShellCorpus/PoshCode/Get-CryptoBytes.ps1
|
Get-CryptoBytes.ps1
|
function Get-CryptoBytes {
#.Synopsis
# Generate Cryptographically Random Bytes
#.Description
# Uses RNGCryptoServiceProvider to generate arrays of random bytes
#.Parameter Count
# How many bytes to generate
#.Parameter AsString
# Output hex-formatted strings instead of byte arrays
param(
[Parameter(ValueFromPipeline=$true)]
[int[]]$count = 64
,
[switch]$AsString
)
begin {
$RNGCrypto = New-Object System.Security.Cryptography.RNGCryptoServiceProvider
$OFS = ""
}
process {
foreach($length in $count) {
$bytes = New-Object Byte[] $length
$RNGCrypto.GetBytes($bytes)
if($AsString){
Write-Output ("{0:X2}" -f $bytes)
} else {
Write-Output $bytes
}
}
}
end {
$RNGCrypto = $null
}
}
|
PowerShellCorpus/PoshCode/DataStoreBalancer.ps1
|
DataStoreBalancer.ps1
|
#======================================================================================
# File Name : DataStoreBalancer.ps1
# Original Author : Kenneth C. Mazie
# Description : Scans VM datastores and moves a single VM from the most heavily
# : loaded to the most lightly loaded.
# :
# Notes : This script was cobbled together from various sources around the
# : Internet and adjusted to suit my purposes. Original scripts at
# : http://poshcode.org/2449 and http://www.vcritical.com/2009/10/powershell-prevents-datastore-emergencies/
# :
# Operation : Normal operation is with no command line options. Script may be
# : fed from Virtual Center alarms to automatically start clearing
# : VM guests from conjested datastores. As written will run a single
# : time and exit. May be looped via internal or external triggers
# : if desired, additional coding is required.
# : The script creates a new Windows Application Event Log called
# : "PowerShellScripts" and writes status to it. Also optional
# : status to the screen is available.
# : To call from Virtual Center to automatically relocate a guest VM
# : when a datastore goes into alarm set an alarm to run a program
# : and use a command line similar to the following:
# : "c:\\windows\\system32\\cmd.exe" "/c echo.|powershell.exe -nologo -noprofile -noninteractive c:\\scripts\\datastoremigrator.ps1"
# : More on this at http://www.vcritical.com/2009/10/powershell-prevents-datastore-emergencies/
# :
# Warnings : Remove the comment from the WHATIF to enable the move
# :
# 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 - 02-18-11 - Original
# Change History : v1.1 - 00-00-00 -
#
#=======================================================================================
#--[ Clear the screen, disable error notification, and create the event log ]--
Clear-Host
$ErrorActionPreference = "SilentlyContinue"
New-EventLog Application PowerShellScripts
$EventID = "33333" #--[ Set whatever Event ID number here that you like ]--
#--[ Load the VMWare snapin if not already ]--
$out = Get-PSSnapin | Where-Object {$_.Name -like "vmware.vimautomation.core"}
if ($out -eq $null){Add-PSSnapin vmware.vimautomation.core}
#--[ Connect to the Virtual Center server ]--
Connect-VIServer -Server <YourVCenterServer> -User <UserName> -Password <Password>
#--[ Write status to Windows event log ]--
#Write-Output "`n$(Get-Date)- Script started`n"
Write-EventLog -LogName Application -Source PowerShellScripts -EntryType Information -EventId $EventID -Message "`n$(Get-Date) - VMWare Datastore balancing script started`n"
#--[ Get the list of valid datastores and pick the ones with the most and least free space.
$DataStores = Get-datastore | Sort-Object FreeSpaceMB | Where-Object {$_.Name -like "A*" -or $_.Name -like "B*" -and $_.Name -notmatch "B202_Perf"}
$DSInfo = $DataStores | Select-Object Name,@{n="CapacityGB";e={[math]::round(($_.CapacityMB/1024))}},@{n="FreeSpaceGB";e={[math]::round(($_.FreeSpaceMB/1024))}},@{n="FreeSpacePercent";e={[math]::round(($_.FreeSpaceMB/$_.CapacityMB*100))}} | Sort-Object FreeSpacePercent
$DSLeastFree = $DSInfo | Select-Object -first 1
$DSMostFree = $DSInfo | Select-Object -last 1
#--[ Write status to Windows event log ]--
#Write-Output $DSLeastFree #| Select-Object FreeSpacePercent
#Write-Output $DSMostFree
Write-EventLog -LogName Application -Source PowerShellScripts -EntryType Information -EventId $EventID -Message "`n $(Get-Date) - The $(($DSLeastFree).Name) Datastore has the least free space and The $(($DSMostFree).Name) Datastore has the most free space available.`n"
#--[ Pick the largest VM on the datastore to relocate that does not match the exclusion ]--
#--[ NOTE: Swap these lines to switch to using a datastore targeted from a VirtualCenter alarm. ]--
$SourceVMToMove = Get-VM -Datastore $DSLeastFree | Where-Object {$_.Name -notlike "P*"} | select Name, @{ Name="Disks"; Expression={ ($_ | get-harddisk | measure-object -property CapacityKB -sum).Sum }} | sort Disks -descending | Select -first 1
#$SourceVMToMove = Get-VM -Datastore $env:VMWARE_ALARM_TARGET_NAME | Where-Object {$_.Name -notlike "P*"} | select Name, @{ Name="Disks"; Expression={ ($_ | get-harddisk | measure-object -property CapacityKB -sum).Sum }} | sort Disks -descending | Select -first 1
#--[ Write status to Windows event log ]--
#Write-Output "`n $(Get-Date)- Moving $($SourceVMToMove.Name) from $(($DSTLeastFree).Name) to $(($DSTMostFree).Name)`n"
Write-EventLog -LogName Application -Source PowerShellScripts -EntryType Information -EventId $EventID -Message "`n $(Get-Date) - Moving $($SourceVMToMove.Name) from $(($DSLeastFree).Name) to $(($DSMostFree).Name)`n"
#--[ svMotion the VM to the datastore with the most free space ]--
Move-VM -VM $SourceVMToMove.Name -Datastore ($DSMostFree).Name -Confirm:$false -whatif #--[ Comment out the WHATIF to enable the move ]--
#--[ Write status to Windows event log ]--
#Write-Output "`n$(Get-Date)- Script finished`n"
Write-EventLog -LogName Application -Source PowerShellScripts -EntryType Information -EventId $EventID -Message "`n $(Get-Date) - VMWare Datastore balancing script completed`n"
|
PowerShellCorpus/PoshCode/AD_bulk_new_OU_1.ps1
|
AD_bulk_new_OU_1.ps1
|
param(
$searchBase = "OU=Organisation,DC=uza,DC=local",
$NewOUs = @(Import-csv -Path "d:\\projects\\AD\\departments.csv" -Delimiter ";"),
$SubOUs = @("Computers","Users"),
[switch]$ProtectOU
)
$Protect = $false
If ($ProtectOU){$Protect = $true}
foreach ($NewOU in $NewOUs){
New-ADOrganizationalUnit -Name $NewOU.name -Description $NewOU.description -City "Antwerp" -Country "BE" -ManagedBy $NewOU.manager -State "Antwerp" -Path $searchBase -ProtectedFromAccidentalDeletion $Protect
$SubOUPath = "OU=" + $Newou.Name + "," + $searchBase
foreach ($SubOU in $SubOUs){
New-ADOrganizationalUnit -Name $SubOU -Path $SubOUPath -ProtectedFromAccidentalDeletion $Protect
}
}
#example of CSV:
# headers => Name;description;manager
# datarow => accounting;ACC;TommyLee
# datarow => human resources;HRM;WendyRatzig
|
PowerShellCorpus/PoshCode/ConvertTo-ASCII.ps1
|
ConvertTo-ASCII.ps1
|
#requires –version 2.0
#region Help
<#
.SYNOPSIS
Automation script for file character set format convertion to ASCII encoding.
.DESCRIPTION
Script for automating the convertion of files to ASCII format. Good for if you've used Out-File without specifying the
encoding. Which would make a Unicode formatted file by default. If you then used Add-Content to append data to that
file it would have garbage characters because even though it states it defaults to Unicode it will write ASCII/ANSI.
.INPUTS
Full Path to files to convert.
.OUTPUTS
Replacement files in ASCII format.
.NOTES
AUTHOR: Levon Becker
TITLE: ConvertTo-Ascii
VERSION: 1.001
DATE: 4/13/2011
ENV: Powershell v2
TOOLS: PowerGUI Script Editor, RegexBuddy
.EXAMPLE
.\\ConvertTo-Ascii -path "C:\\Folder1\\Folder2\\*" -include "*.txt"
Will convert all of the files with a TXT file extension in the directory named Folder2.
.EXAMPLE
.\\ConvertTo-Ascii -path "C:\\Folder1\\Folder2\\*" -include "filename.txt"
Will convert a single file named filename.txt in the directory named Folder2
.EXAMPLE
.\\ConvertTo-Ascii -path "C:\\Folder1\\Folder2\\*" -include "*.txt" -recursive $true
Will convert all of the files with a TXT file extension in the directory named Folder2 and any subdirectories.
.EXAMPLE
.\\ConvertTo-Ascii -path "C:\\Folder1\\Folder2\\*" -include "filename.txt" -recursive $true
Will convert a single file named filename.txt in the directory named Folder2 and any subdirectories.
.PARAMETER path
Full path to file/s to process. Standard wild cards are excepted. Be sure to put in quotation marks.
It should work without a trailing backslash or asterisk, but it's recommended to simply include.
See examples
.PARAMETER include
Filename filtering opiton. Standard wild cards are excepted. Be sure to put in quotation marks.
.PARAMETER recursive
Specifies if the script should look in subfolders off the path provided. Default is False (Do not do recursive).
Use -recursive $true to enable.
.LINK
#>
#endregion Help
#region Changelog
<#
04/12/2011: Created
04/13/2011: Added timestamp capture and write in order to keep the replacement files with the same time information as the original.
Cleaned up comments and regions.
#>
#endregion Changelog
#region Sources
<#
http://rosettacode.org/wiki/File_modification_time#PowerShell
http://www.powergui.org
http://www.regexbuddy.com
#>
#endregion Sources
#region Parameters
[CmdletBinding()]
Param (
[parameter(Mandatory=$true)][string]$path,
[parameter(Mandatory=$true)][string]$include,
[parameter(Mandatory=$false)][string]$recursive = "$false"
)
#endregion Parameters
#region Variables
$scriptver = '1.001'
$originaltitle = $Host.UI.RawUI.WindowTitle
$title = "File Convert to ASCII Script v$scriptver by Levon Becker"
$count = $null
$file = $null
#endregion Variables
Clear
$Host.UI.RawUI.WindowTitle = $title
#region Check Parameters
If ((Test-Path -Path $path) -eq $false) {
Write-Host "ERROR: PATH NOT FOUND ($path)" -BackgroundColor Red -ForegroundColor White
Break
}
#endregion Check Parameters
#region Main Process
# Check that \\* is at the end of the path
$regex = '\\b\\\\\\*'
# If not then add \\* to the end of the path
If ($path -notmatch $regex) {
$path = $path + '\\*'
}
# Get list of filenames
If ($recursive -eq $true) {
$filelist = Get-ChildItem -path $path -Include $include -Recurse
}
Else {
$filelist = Get-ChildItem -path $path -Include $include
}
Foreach ($file in $filelist) {
$count++
# Get File Information
$fullname = ($file.FullName)
$creationtime = ($file.CreationTime)
$creationtimeutc = ($file.CreationTimeUtc)
$lastwritetime = ($file.LastWriteTime)
$lastwritetimeutc = ($file.LastWriteTimeUtc)
$lastaccesstime = ($file.LastAccessTime)
$lastaccesstimeutc = ($file.LastAccessTimeUtc)
# Get File Contents
$content = Get-Content $fullname
# Replace file with corrected character set
Out-File -FilePath $fullname -Encoding ASCII -Force -InputObject $content
# Set original time stamp information on new file
Set-ItemProperty -Path $fullname -Name CreationTime ($creationtime)
Set-ItemProperty -Path $fullname -Name CreationTimeUtc ($creationtimeutc)
Set-ItemProperty -Path $fullname -Name LastWriteTime ($lastwritetime)
Set-ItemProperty -Path $fullname -Name LastWriteTimeUtc ($lastwritetimeutc)
Set-ItemProperty -Path $fullname -Name LastAccessTime ($lastaccesstime)
Set-ItemProperty -Path $fullname -Name LastAccessTimeUtc ($lastaccesstimeutc)
Write-Host $file
}
#endregion Main Process
#region Conclusion Information
Write-Host '----------------------------------------------------------------------'
Write-Host ''
Write-Host "Total Converted: " -ForegroundColor Green -NoNewline
Write-Host $count
Write-Host ''
Write-Host '-------------' -ForegroundColor Green
Write-Host '| COMPLETED |' -ForegroundColor Green
Write-Host '-------------' -ForegroundColor Green
Write-Host ''
#endregion Conclusion Information
$Host.UI.RawUI.WindowTitle = $title + ' (COMPLETED)'
Sleep -Seconds 1
$Host.UI.RawUI.WindowTitle = $originaltitle
|
PowerShellCorpus/PoshCode/Start-Process.ps1
|
Start-Process.ps1
|
function Start($app,$param) {
if($param) {
[Diagnostics.Process]::Start( $app, $param )
} else {
[Diagnostics.Process]::Start( $app )
}
}
|
PowerShellCorpus/PoshCode/Script-Object_2.ps1
|
Script-Object_2.ps1
|
#Copyright (c) 2011 Justin Dearing
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in
#all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#THE SOFTWARE.
param(
[Parameter(Mandatory=$true, HelpMessage='The name of the database object we wish to script')]
[string] $ObjectName,
[string] $Path = "$($ObjectName).sql",
[string] $ConnectionString = 'Data Source=.\\sqlexpress2k8R2;Initial Catalog=master;Integrated Security=SSPI;',
[string] $AtlantisSchemaEngineBaseDir = 'F:\\src\\Atlantis.SchemaEngine\\' # Adjust for your environment
);
Add-Type -Path "$($AtlantisSchemaEngineBaseDir)\\Atlantis.SchemaEngine\\bin\\Debug\\Atlantis.SchemaEngine.dll"
$schemaReader = [Atlantis.SchemaEngine.Container.SQLServer.SQLServerSchemaReaderFactory]::GetSpecificSQLServerSchemaReader($ConnectionString, [Atlantis.SchemaEngine.Enumerations.ContainerMode]::Navigation)
$dbObjects = $schemaReader.ReadObjects() | Where-Object { $_.ObjectName,$_.ObjectDesriptiveName,$_.ObjectQualifiedName -contains $ObjectName };
if ($dbObjects -eq $null) {
Throw New-Object System.ArgumentException "Object `"$($ObjectName)`" not found.",'-ObjectName';
}
$dbObjects.Script([Atlantis.SchemaEngine.Enumerations.ScriptGenerationType]::Create, (New-Object Atlantis.SchemaEngine.Configuration.GenerationOptions)).Scripts
|
PowerShellCorpus/PoshCode/Open-ISEFile.ps1
|
Open-ISEFile.ps1
|
#Requires -Version 2.0
function Open-ISEFile {
<#
.NOTES
Name: Open-ISEFile
Author: Tome Tanasovski
Created: 6/20/2010
Version: 1.0
.SYNOPSIS
Open a new file in ISE
.DESCRIPTION
This cmdlet allows you to open a file in a new file tab within your current Powershell tab. You can pass a collection of files to open more than one file.
.PARAMETER Path
Specifies a path to one or more files. Wildcards are permitted. The default location is the current directory (.).
.EXAMPLE
Open-ISEFile -Path $profile
Opens your profile in ISE.
.EXAMPLE
dir *.ps1 |Open-ISEFile
Opens up all ps1 files in the current directory as new file tabs in ISE.
.EXAMPLE
Open-ISEFile *.ps1
Opens up all ps1 files in the current directory as new file tabs in ISE.
.EXAMPLE
$file = Open-ISEFile "c:\\file1.ps1" -PassThru
Opens up file1.ps1 in ISE. The command uses the passthru parameter to generate an object that represents a file in ISE.
.INPUTS
System.String
.OUTPUTS
None or Microsoft.PowerShell.Host.ISE.ISEFile
When you use the PassThru parameter, Open-ISEFile returns a Microsoft.PowerShell.Host.ISE.ISEFile for each file opened. Otherwise, this cmdlet does not generate any output.
.LINK
http://powertoe.wordpress.com
#>
param(
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeline=$true)]
[string[]] $Path,
[Parameter(Mandatory = $false)]
[switch] $PassThru
)
BEGIN {
if (!$psise) {
"You are not in a Powershell ISE window"
}
}
PROCESS {
if ($psise) {
foreach ($file in $Path) {
if (Test-Path $file) {
Get-ChildItem $file | foreach {
$file = $psise.CurrentPowerShellTab.Files.Add($_.fullname)
if ($PassThru) {
$file
}
}
}
}
}
}
}
|
PowerShellCorpus/PoshCode/PowerShellServer Cmdlet _1.ps1
|
PowerShellServer Cmdlet _1.ps1
|
\n#Global Hashtable to Control all Powershell Server Runspace\nSet-Variable -name '__PSRUNSPACES__' -scope 'global' -value @{} -force\n\nfunction global:New-PowerShellServerRunspace\n{\n param(\n $Credential,\n $ErrorAction='Stop',\n [switch]$Force,\n $Password,\n $Port=22,\n $Server='127.0.0.1',\n $SSHAccept,\n $Timeout=30,\n $user\n )\n $ErrorActionPreference = $ErrorAction\n trap{\n Throw "Function New-PowerShellServerRunspace threw error $($error[0])"\n }\n if(($Credential -eq $null) -and (($User -eq $null) -and ($Password -eq $null))){\n Throw "You Must Provide Authenication `n PSCredential or User and Password"\n } \n if( ($global:__PSRUNSPACES__.Keys -contains "$Server") -and ($global:__PSRunspaces__['10.27.1.4'].RunspaceStateInfo -eq 'OPENED' ) )\n {\n Write-Output $global:__PSRUNSPACES__["$Server"]\n return\n }\n else\n {\n if($Force){\n if($Credential){\n $script:rs = & (Get-Command -commandType 'Cmdlet' -name 'New-PowerShellServerRunspace') -Server $Server -Credential $Credential -Port $Port -Force -ErrorAction $ErrorAction -Timeout $Timeout\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Credential' -value $Credential -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Port' -value $Port -force\n [scriptblock]$SB = { $This = New-PowerShellServerRunspace -Server $This.SSHServer -Credential $This.Credential -Port $This.Port -Force ; $This.RunspaceStateInfo = 'OPENED'}\n Add-Member -inputObject $script:rs -memberType ScriptMethod -name 'Reconnect' -value $SB -force\n }\n else{\n $script:rs = & (Get-Command -commandType 'Cmdlet' -name 'New-PowerShellServerRunspace') -Server $Server -User $User -Password $Password -Port $Port -Force -ErrorAction $ErrorAction -Timeout $Timeout\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'User' -value $User -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Password' -value $Password -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Port' -value $Port -force\n [scriptblock]$SB = { $This = New-PowerShellServerRunspace -Server $This.SSHServer -User $This.User -Password $This.Password -Port $This.Port -Force ; $This.RunspaceStateInfo = 'OPENED'}\n Add-Member -inputObject $script:rs -memberType ScriptMethod -name 'Reconnect' -value $SB -force\n }\n }\n elseif($SSHAccept){\n if($Credential){\n $script:rs = & (Get-Command -commandType 'Cmdlet' -name 'New-PowerShellServerRunspace') -Server $Server -Credential $Credential -Port $Port -SSHAccept $SSHAccept -ErrorAction $ErrorAction -Timeout $Timeout\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Credential' -value $Credential -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Port' -value $Port -force\n [scriptblock]$SB = { $This = New-PowerShellServerRunspace -Server $This.SSHServer -Credential $This.Credential -Port $This.Port -Force ; $This.RunspaceStateInfo = 'OPENED'}\n Add-Member -inputObject $script:rs -memberType ScriptMethod -name 'Reconnect' -value $SB -force\n }\n else{\n $script:rs = & (Get-Command -commandType 'Cmdlet' -name 'New-PowerShellServerRunspace') -Server $Server -User $User -Password $Password -Port $Port -SSHAccept $SSHAccept -ErrorAction $ErrorAction -Timeout $Timeout\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'User' -value $User -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Password' -value $Password -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Port' -value $Port -force\n [scriptblock]$SB = { $This = New-PowerShellServerRunspace -Server $This.SSHServer -User $This.User -Password $This.Password -Port $This.Port -Force ; $This.RunspaceStateInfo = 'OPENED'}\n Add-Member -inputObject $script:rs -memberType ScriptMethod -name 'Reconnect' -value $SB -force\n }\n }\n else{\n if($Credential){\n $script:rs = & (Get-Command -commandType 'Cmdlet' -name 'New-PowerShellServerRunspace') -Server $Server -Credential $Credential -Port $Port -ErrorAction $ErrorAction -Timeout $Timeout\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Credential' -value $Credential -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Port' -value $Port -force\n [scriptblock]$SB = { $This = New-PowerShellServerRunspace -Server $This.SSHServer -Credential $This.Credential -Port $This.Port -Force ; $This.RunspaceStateInfo = 'OPENED'}\n Add-Member -inputObject $script:rs -memberType ScriptMethod -name 'Reconnect' -value $SB -force\n }\n else{\n $script:rs = & (Get-Command -commandType 'Cmdlet' -name 'New-PowerShellServerRunspace') -Server $Server -User $User -Password $Password -Port $Port -ErrorAction $ErrorAction -Timeout $Timeout\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'User' -value $User -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Password' -value $Password -force\n Add-Member -inputObject $script:rs -memberType NoteProperty -name 'Port' -value $Port -force\n [scriptblock]$SB = { $This = New-PowerShellServerRunspace -Server $This.SSHServer -User $This.User -Password $This.Password -Port $This.Port -Force ; $This.RunspaceStateInfo = 'OPENED'}\n Add-Member -inputObject $script:rs -memberType ScriptMethod -name 'Reconnect' -value $SB -force\n }\n }\n $global:__PSRUNSPACES__["$Server"] = $script:rs\n Write-Output $global:__PSRUNSPACES__["$Server"]\n return\n }\n}\n\nfunction global:Remove-PowerShellServerRunspace\n{\n param(\n $SSHRunspace\n )\n if($SSHRunspace)\n {\n & (Get-Command -commandType 'Cmdlet' -name 'Remove-PowerShellServerRunspace') -SSHRunspace $SSHRunspace\n if( $global:__PSRUNSPACES__.Keys -contains $SSHRunspace.SSHServer )\n {\n $global:__PSRUNSPACES__.Remove($SSHRunspace.SSHServer)\n }\n }\n elseif( $global:__FPRUNSPACES__.Count -gt 0 )\n {\n $global:__FPRUNSPACES__ | Foreach-Object { \n & (Get-Command -commandType 'Cmdlet' -name 'Remove-PowerShellServerRunspace') -SSHRunspace $_\n }\n $global:__PSRUNSPACES__.Clear()\n }\n}
|
PowerShellCorpus/PoshCode/test.ps1
|
test.ps1
|
function Write-EventDetail {
param(
$id
)
$id | Write-Host
$Event | Write-Host
$EventSubscriber | Write-Host
$Sender | Write-Host
$SourceEventArgs | Write-Host
$SourceArgs | Write-Host
}
'test'
|
PowerShellCorpus/PoshCode/Am I a purist_.ps1
|
Am I a purist_.ps1
|
###########
# PS1 script to launch gpupdate on all computers in domain, without some stupid QAD cmdlets, just pure PS1 and WMI
# Made by pan_2@LJ (gunkan@yandex.ru)
# Note: if by some reason RPC host was unavaible - there will be exception throwed, I didn't use trap so I can see real reason.
###########
function PingComputer ([string]$Compname)
{
$pingvar = Get-WmiObject -Class Win32_PingStatus -Filter "Address='$Compname'"
if ($pingvar.STatusCode -eq 0) {return $True} else {return $False}
}
function SearchAD ()
{
$strFilter = "(objectCategory=Computer)"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$colProplist = "name"
foreach ($i in $colPropList)
{
$null = $objSearcher.PropertiesToLoad.Add($i)
}
$colResults = $objSearcher.FindAll()
foreach ($objResult in $colResults)
{
$objItem = $objResult.Properties;
[string]$str = ""
$str = $objItem.name
$str
}
}
foreach($str in SearchAD )
{
Write-host "Now trying... $str " -nonew
if (PingComputer $str)
{
if ( (([WMICLASS]"\\\\$str\\ROOT\\CIMV2:win32_process").Create("gpupdate.exe").ReturnValue) -eq 0) {write-host " succesfully!" -fo Green} else {write-host "failed!" -fo Red}
}
else
{ write-host "not responding..." -fo yellow}
}
|
PowerShellCorpus/PoshCode/Get-Parameter 2.1.ps1
|
Get-Parameter 2.1.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 (This Version)
# - 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 Bartek's criticism ;)
#.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")
$MoreParameters = Get-Command $command -Args $drive | Select -Expand Parameters
$Dynamic = $MoreParameters | Select -Expand Values | Where { $_.IsDynamic }
foreach($k in $Parameters.Keys | Where { $Dynamic.Keys -notcontains $_ } ){ $null = $MoreParameters.Remove($k) }
$Parameters += $MoreParameters
# 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/TSRemoteApp.ps1
|
TSRemoteApp.ps1
|
function New-TSRemoteApp {
<#
.SYNOPSIS
Creates a new RemoteApp on Windows Server 2008 Terminal Server.
.DESCRIPTION
Creates a new RemoteApp using the supplied parameters.
.PARAMETER Alias
Alias for the new RemoteApp. Accepts ValueFromPipeline and ValueFromPipelineByPropertyName.
.PARAMETER Applicationpath
Path to the executable file for for the new RemoteApp. This file must exist before creating the new RemoteApp.
Accepts ValueFromPipeline and ValueFromPipelineByPropertyName.
.PARAMETER Displayname
Displayname for the new RemoteApp. This is the application name the users will see. Accepts ValueFromPipeline and ValueFromPipelineByPropertyName.
.PARAMETER ShowinRDWebAccess
True or false. Determines if the RemoteApp should be visible in RD Web Access. Defaults to true if the parameter is omitted. Accepts ValueFromPipeline and ValueFromPipelineByPropertyName.
.PARAMETER CommandlineSetting
0 = Do not allow command-line arguments, 1 = Allow any command-line arguments (not recommended), 2 = Always use the following command-line arguments
.PARAMETER CommandlineArguments
Command-line argument to be used when starting the new RemoteApp
.EXAMPLE
New-TSRemoteApp -Alias Notepad -Applicationpath "%windir%\\system32\\notepad.exe" -Displayname Notepad -ShowinRDWebAccess $false
.EXAMPLE
New-TSRemoteApp -Alias Calc -Applicationpath "%windir%\\system32\\calc.exe" -Displayname Calculator -CommandLineArgumentMode 2 -CommandlineArguments '/MyCustomParameter'
.NOTES
AUTHOR: Wizarden
LASTEDIT: 20.11.2010
SOURCE: Based on Script by Jan Egil Ring and Rebuilded for Windows 2008 Server
#>
[CmdletBinding()]
param (
[parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string]$Alias,
[parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string]$Applicationpath,
[parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string]$Displayname,
[parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[boolean]$ShowinRDWebAccess = $true,
[parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[int]$CommandlineSetting,
[parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
$CommandlineArguments
)
#Check Application for Existance
if ((Get-WmiObject -Namespace "root\\CIMV2\\TerminalServices" -Query "select * from Win32_TSPublishedApplication where alias = '$Alias'") -ne $null) {
Write-Warning "The application $alias already exist!"
return
}
#Create new Object
$newapp = ([wmiclass]"ROOT\\CIMV2\\TerminalServices:Win32_TSPublishedApplication").CreateInstance()
$newapp.Alias = $Alias
$newapp.Path = [System.Environment]::ExpandEnvironmentVariables($Applicationpath)
$newapp.VPath = $Applicationpath
#Configure RD Web Access visibility
$newapp.ShowInPortal = $ShowinRDWebAccess
#Configure Displayname
if ($Displayname) {
$newapp.Name = $Displayname
} else {
if (Test-Path $Applicationpath) {
if ((Get-Item $Applicationpath).VersionInfo.FileDescription -ne "") {
$newapp.Name = (Get-Item $Applicationpath).VersionInfo.FileDescription
} else {$newapp.Name = (Get-Item $Applicationpath).Name}
} else {$newapp.Name = [System.IO.Path]::GetFileNameWithoutExtension($Applicationpath)}
}
#Configure CommandLineSetting
if ($CommandlineSetting -ne $null -and $CommandlineSetting -ne 2) {
$newapp.CommandLineSetting = $CommandlineSetting
} else {$newapp.CommandLineSetting = 0}
#Configure CommandLineArguments
if ($CommandlineArguments -and ($CommandlineSetting -eq 2)) {
if ($CommandlineArguments.RequiredCommandline) {
$CommandlineArguments = $CommandlineArguments.RequiredCommandline
}
$newapp.CommandLineSetting = $CommandlineSetting
$newapp.RequiredCommandLine = $CommandlineArguments
}
#Configure Icons
$newapp.IconIndex = 0
$newapp.IconPath = $Applicationpath
#Create Default RDPFileContents
$newapp.RDPFileContents=(Get-WmiObject -Class "Win32_TSDeploymentSettings" -Namespace "root\\CIMV2\\TerminalServices").DeploymentRDPSettings
$newapp.RDPFileContents+="remoteapplicationmode:i:1"
$newapp.RDPFileContents+="alternate shell:s:||$Alias"
$newapp.RDPFileContents+="remoteapplicationprogram:s:||$Alias"
$newapp.RDPFileContents+="remoteapplicationname:s:$newapp.Name"
$newapp.RDPFileContents+="remoteapplicationcmdline:s:$newapp.CommandLineSetting"
#Create new RemoteApp
$newapp.Put() | Out-Null
if ($?) {Write-Host "The application $alias was succesfully created" -ForegroundColor yellow}
}
function Remove-TSRemoteApp {
<#
.SYNOPSIS
Removes the specified RemoteApp from the Windows 2008 Terminal Server.
.DESCRIPTION
Removes the specified RemoteApp from the Windows 2008 Terminal Server. One mandatory parameter: Alias
.PARAMETER Alias
The alias of the application to be removed
.EXAMPLE
Remove-TSRemoteApp -Alias Calc
Removes the Calc RemoteApp.
.EXAMPLE
Get-TSRemoteApp | Foreach-Object {Remove-TSRemoteApp $_.Alias}
Removes all RemoteApps.
.NOTES
AUTHOR: Wizarden
LASTEDIT: 20.11.2010
SOURCE: Based on Script by Jan Egil Ring and Rebuilded for Windows 2008 Server
#>
[CmdletBinding()]
param (
[parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string]$Alias
)
#Remove the specified RemoteApp
$Apps = Get-WmiObject -Class "Win32_TSPublishedApplication" -Namespace "root\\CIMV2\\TerminalServices" -Filter "Alias = '$Alias'"
if (-not $Apps) {
Write-Warning "The application $alias doesn't exist!";return
} else {
$Apps.Delete() | Out-Null
if (-not (Get-WmiObject -Class "Win32_TSPublishedApplication" -Namespace "root\\CIMV2\\TerminalServices" -Filter "Alias = '$Alias'")) {
Write-Host "The application $alias was successfully removed" -ForegroundColor yellow
}
}
}
function Get-TSRemoteApp {
<#
.SYNOPSIS
Retrieves info about the specified RemoteApp from the Windows 2008 Terminal Server.
.DESCRIPTION
Retrieves info about specified RemoteApp from the Windows 2008 Terminal Server. One optional parameter: Alias
If Alias is omitted, all RemoteApps are returned.
.PARAMETER Alias
The alias of the application to be retirived
.EXAMPLE
Get-TSRemoteApp -Alias Calc
.NOTES
AUTHOR: Wizarden
LASTEDIT: 20.11.2010
SOURCE: Based on Script by Jan Egil Ring and Rebuilded for Windows 2008 Server
#>
[CmdletBinding()]
param (
[parameter(Mandatory=$false)]
[string]$Alias
)
if ($Alias) {
if (-not (Get-WmiObject -Class "Win32_TSPublishedApplication" -Namespace "root\\CIMV2\\TerminalServices" -Filter "Alias = '$Alias'"))
{
Write-Warning "The application $alias doesn't exist!";return
}
Get-WmiObject -Class "Win32_TSPublishedApplication" -Namespace "root\\CIMV2\\TerminalServices" -Filter "Alias = '$Alias'" | Select-Object @{"Name"="Displayname";"Expression"={$_.Name}},@{"Name"="Alias";"Expression"={$_.Alias}},@{"Name"="Path";"Expression"={$_.VPath}}
} else {
Get-WmiObject -Class "Win32_TSPublishedApplication" -Namespace "root\\CIMV2\\TerminalServices" | Select-Object @{"Name"="Displayname";"Expression"={$_.Name}},@{"Name"="Alias";"Expression"={$_.Alias}},@{"Name"="Path";"Expression"={$_.VPath}}
}
}
function Import-TSRemoteAppsSet {
<#
.SYNOPSIS
Imports all TS RemoteApps Settings from the provided TSPUB-file.
.DESCRIPTION
Imports all TS RemoteApps from the provided TSPUB-file. Accepts ValueFromPipeline and ValueFromPipelineByPropertyName.
One mandatory parameter: Path
.PARAMETER Path
Path to the TSPUB-file to be imported. Accepts ValueFromPipeline and ValueFromPipelineByPropertyName.
Parameter Type: Mandatory
.PARAMETER Replace
Deletes all existing RemoteApps and insert new from file. Enabled by Default.
Parameter Type: Optional
.PARAMETER TSDeploymentSettings
Replace Terminal Server settings. Enabled by Default.
Parameter Type: Optional
.EXAMPLE
Import-TSRemoteApps -Path C:\\temp\\RemoteApps.tspub
Imports all RemoteApps from the specified TSPUB-file.
.NOTES
AUTHOR: Wizarden
LASTEDIT: 21.11.2010
#>
[CmdletBinding()]
param (
[parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string]$Path,
[parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[switch]$NotReplace = $true,
[parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[switch]$TSDeploymentSettings = $true
)
$ConfigFile = [xml](Get-Content $Path -Encoding UTF8)
if ($Replace) {
Get-WmiObject -Class "Win32_TSPublishedApplication" -Namespace "root\\CIMV2\\TerminalServices" | ForEach-Object {$_.Delete() | Out-Null}
}
if ($TSDeploymentSettings) {
$Win32_TSPublishedApplicationList = Get-WmiObject -Namespace "root\\CIMV2\\TerminalServices" -Class Win32_TSPublishedApplicationList
$Win32_TSPublishedApplicationList.Disabled = ($ConfigFile.RemotePrograms.UseAllowList -eq "No")
$Win32_TSPublishedApplicationList.Put() | Out-Null
$DeploymentSettings = Get-WmiObject -Class "Win32_TSDeploymentSettings" -Namespace "root\\CIMV2\\TerminalServices"
$DeploymentRDPSettings = $DeploymentSettings.DeploymentRDPSettings.Split("`n")
$values = @{}
ForEach ($val in $DeploymentRDPSettings) {
if ($val -ne "") {$values += @{([regex]::Match($val,"(^.+?:\\w?):(.*)")).groups[1].value = ([regex]::Match($val,"(^.+?:\\w?):(.*)")).groups[2].value}}
}
$values["server port:i"] = $ConfigFile.RemotePrograms.DeploymentSettings.Port
$values["full address:s"] = $ConfigFile.RemotePrograms.DeploymentSettings.FarmName
$values["gatewayhostname:s"] = $ConfigFile.RemotePrograms.DeploymentSettings.GatewaySettings.GatewayName
$values["gatewaycredentialssource:i"] = $ConfigFile.RemotePrograms.DeploymentSettings.GatewaySettings.GatewayAuthMode
$values["promptcredentialonce:i"] = [int][System.Convert]::ToBoolean($ConfigFile.RemotePrograms.DeploymentSettings.GatewaySettings.UseCachedCreds)
$values["allow font smoothing:i"] = [int][System.Convert]::ToBoolean($ConfigFile.RemotePrograms.DeploymentSettings.CertificateSettings.AllowFontSmoothing)
$values["session bpp:i"] = $ConfigFile.RemotePrograms.DeploymentSettings.CertificateSettings.ColorBitDepth
$values["use multimon:i"] = [int][System.Convert]::ToBoolean($ConfigFile.RemotePrograms.DeploymentSettings.CertificateSettings.UseMultimon)
$values["authentication level:i"] = $ConfigFile.RemotePrograms.DeploymentSettings.ServerAuth
switch ($ConfigFile.RemotePrograms.DeploymentSettings.GatewaySettings.GatewayUsage) {
0 {$values["gatewayusagemethod:i"] = 0;$values["gatewayprofileusagemethod:i"] = 1}
1 {$values["gatewayusagemethod:i"] = 2;$values["gatewayprofileusagemethod:i"] = 1}
2 {$values["gatewayusagemethod:i"] = 1;$values["gatewayprofileusagemethod:i"] = 1}
3 {$values["gatewayusagemethod:i"] = 2;$values["gatewayprofileusagemethod:i"] = 0}
default {$values["gatewayusagemethod:i"] = 0;$values["gatewayprofileusagemethod:i"] = 1}
}
switch ($ConfigFile.RemotePrograms.DeploymentSettings.CertificateSettings.RedirectionSettings) {
{$_ -band 1} {$values["redirectdrives:i"] = 1;$values["drivestoredirect:s"] = "*"}
{$_ -band 2} {$values["redirectprinters:i"] = 1}
{$_ -band 4} {$values["redirectclipboard:i"] = 1}
{$_ -band 8} {$values["devicestoredirect:s"] = "*"}
{$_ -band 16} {$values["redirectsmartcards:i"] = 1}
}
$DeploymentSettings.DeploymentRDPSettings = [string]::Join("`n",($values.Keys | ForEach-Object {$_ + ":" + $values[$_]}))
$DeploymentSettings.CustomRDPSettings = [System.Convert]::ToString($ConfigFile.RemotePrograms.DeploymentSettings.CertificateSettings.CustomRDPSettings)
$DeploymentSettings.CertificateExpiresOn = [int64]$ConfigFile.RemotePrograms.DeploymentSettings.CertificateSettings.CertificateExpiresOn
$DeploymentSettings.CertificateIssuedTo = [System.Convert]::ToString($ConfigFile.RemotePrograms.DeploymentSettings.CertificateSettings.CertificateIssuedTo)
$DeploymentSettings.CertificateIssuedBy = [System.Convert]::ToString($ConfigFile.RemotePrograms.DeploymentSettings.CertificateSettings.CertificateIssuedBy)
$DeploymentSettings.HasCertificate = [System.Convert]::ToBoolean($ConfigFile.RemotePrograms.DeploymentSettings.CertificateSettings.UseCertificate)
if ($ConfigFile.RemotePrograms.DeploymentSettings.CertificateSettings.Certificate){$DeploymentSettings.CertificateHash = @($ConfigFile.RemotePrograms.DeploymentSettings.CertificateSettings.Certificate -split '([a-f0-9]{2})' | foreach-object { if ($_) {[System.Convert]::ToByte($_,16)}})}
$DeploymentSettings.Put() | Out-Null
if ($?) {Write-Host "The settings was succesfully entered" -ForegroundColor yellow}
if ($ConfigFile.RemotePrograms.DeploymentSettings.CertificateSettings.UseCertificate.ShowRemoteDesktop) {
$newapp = ([wmiclass]"ROOT\\CIMV2\\TerminalServices:Win32_TSRemoteDesktop").CreateInstance()
$newapp.Alias = "TSRemoteDesktop"
$newapp.IconIndex = 0
$newapp.Name = "Remote Desktop"
$newapp.ShowInPortal = $true
$newapp.RDPFileContents=(Get-WmiObject -Class "Win32_TSDeploymentSettings" -Namespace "root\\CIMV2\\TerminalServices").DeploymentRDPSettings
$newapp.iconpath = "%SYSTEMDRIVE%\\Windows\\system32\\mstsc.exe"
$newapp.Put() | Out-Null
} else {Get-WmiObject -Class "Win32_TSRemoteDesktop" -Namespace "root\\CIMV2\\TerminalServices" | ForEach-Object {$_.Delete() | Out-Null}}
}
foreach ($Application in $ConfigFile.RemotePrograms.Application) {
if ((Get-WmiObject -Namespace "root\\CIMV2\\TerminalServices" -Query "select * from Win32_TSPublishedApplication where alias = '$Application.Alias'") -ne $null) {
Write-Warning "The application $Application.Alias already exist!"
continue
}
$newapp = ([wmiclass]"ROOT\\CIMV2\\TerminalServices:Win32_TSPublishedApplication").CreateInstance()
$newapp.Alias = $Application.Alias
$newapp.Path = $Application.Path
$newapp.VPath = $Application.VPath
$newapp.ShowInPortal = ($Application.ShowInTSWA -eq "Yes")
$newapp.Name = $Application.Name
$newapp.CommandLineSetting = $Application.CommandLineSetting
$newapp.RequiredCommandLine = $Application.RequiredCommandLine
$newapp.IconIndex = $Application.IconIndex
$newapp.IconPath = $Application.IconPath
$newapp.RDPFileContents = $Application.RDPContents
if ((Get-WmiObject -Class Win32_OperatingSystem).Version -ge 6.1){$newapp.SecurityDescriptor = $Application.SecurityDescriptor}
$newapp.Put() | Out-Null
if ($?) {Write-Host "The application $($Application.Alias) was succesfully created" -ForegroundColor yellow}
}
}
function Export-TSRemoteAppsSet {
<#
.SYNOPSIS
Exports all TS RemoteApps from the Windows 2008 Terminal Server.
.DESCRIPTION
Exports all TS RemoteApps from the Windows 2008 Terminal Server to a TSPUB-file.
One mandatory parameter: Path
.PARAMETER path
Path to the TSPUB-file to be exported
.EXAMPLE
Export-TSRemoteApps -Path C:\\temp\\RemoteApps.tspub
Exports all RemoteApps to the specified TSPUB-file.
.NOTES
AUTHOR: Wizarden
LASTEDIT: 22.11.2010
#>
[CmdletBinding()]
param (
[parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string]$Path
)
$xmldata = New-Object xml
$newelement = $xmldata.CreateXmlDeclaration("1.0", $null, $null)
$xmldata.AppendChild($newelement) | Out-Null
$newelement = $xmldata.CreateElement("RemotePrograms")
$newelement.InnerXml = "<UseAllowList />"
$Win32_TSPublishedApplicationList = Get-WmiObject -Namespace "root\\CIMV2\\TerminalServices" -Class Win32_TSPublishedApplicationList
if ($Win32_TSPublishedApplicationList.Disabled){$newelement.UseAllowList = "No"} else {$newelement.UseAllowList = "Yes"}
$xmldata.AppendChild($newelement) | Out-Null
$DeploymentSettingsElement = $xmldata.CreateElement("DeploymentSettings")
$GatewaySettingsElement = $xmldata.CreateElement("GatewaySettings")
$CertificateSettingsElement = $xmldata.CreateElement("CertificateSettings")
#$newelement.InnerXml = "<UseAllowList /><DeploymentSettings><Port /><FarmName /><GatewaySettings><GatewayName /><GatewayUsage /><GatewayAuthMode />
#<UseCachedCreds /></GatewaySettings><CertificateSettings><UseCertificate /><CertificateSize /><Certificate /><CertificateIssuedTo />
#<CertificateIssuedBy /><CertificateExpiresOn /><AllowFontSmoothing /><UseMultimon /><ColorBitDepth /><RedirectionSettings /><CustomRdpSettings />
#<ShowRemoteDesktop /><RemoteDesktopSecurityDescriptor /><UseMultimon /></CertificateSettings></DeploymentSettings>"
$DeploymentSettings = Get-WmiObject -Namespace "root\\CIMV2\\TerminalServices" -Class Win32_TSDeploymentSettings
if ($DeploymentSettings.Port){$DeploymentSettingsElement.InnerXml += "<Port />";$DeploymentSettingsElement.Port = $DeploymentSettings.Port.ToString()}
$DeploymentSettingsElement.InnerXml += "<ServerAuth />";$DeploymentSettingsElement.ServerAuth = [string][int[]]($DeploymentSettings.RequireServerAuth)
if ($DeploymentSettings.FarmName){$DeploymentSettingsElement.InnerXml += "<FarmName />";$DeploymentSettingsElement.FarmName = $DeploymentSettings.FarmName.ToString()}
if ($DeploymentSettings.GatewayName){$GatewaySettingsElement.InnerXml += "<GatewayName />";$GatewaySettingsElement.GatewayName = $DeploymentSettings.GatewayName.ToString()}
$GatewaySettingsElement.InnerXml += "<GatewayUsage />";$GatewaySettingsElement.GatewayUsage = $DeploymentSettings.GatewayUsage.ToString()
$GatewaySettingsElement.InnerXml += "<GatewayAuthMode />";$GatewaySettingsElement.GatewayAuthMode = $DeploymentSettings.GatewayAuthMode.ToString()
$GatewaySettingsElement.InnerXml += "<UseCachedCreds />";$GatewaySettingsElement.UseCachedCreds = $DeploymentSettings.GatewayUseCachedCreds.ToString()
$CertificateSettingsElement.InnerXml += "<UseCertificate />";$CertificateSettingsElement.UseCertificate = $DeploymentSettings.HasCertificate.ToString()
if ($DeploymentSettings.CertificateHash){
$CertificateSettingsElement.InnerXml += "<CertificateSize /><Certificate />"
$CertificateSettingsElement.CertificateSize = $DeploymentSettings.CertificateHash.Length.ToString()
$CertificateSettingsElement.Certificate = ([System.BitConverter]::ToString($DeploymentSettings.CertificateHash)).Replace("-","")
}
if ($DeploymentSettings.CertificateIssuedTo){$CertificateSettingsElement.InnerXml += "<CertificateIssuedTo />";$CertificateSettingsElement.CertificateIssuedTo = $DeploymentSettings.CertificateIssuedTo.ToString()}
if ($DeploymentSettings.CertificateIssuedBy){$CertificateSettingsElement.InnerXml += "<CertificateIssuedBy />";$CertificateSettingsElement.CertificateIssuedBy = $DeploymentSettings.CertificateIssuedBy.ToString()}
if ([int64]$DeploymentSettings.CertificateExpiresOn){$CertificateSettingsElement.InnerXml += "<CertificateExpiresOn />";$CertificateSettingsElement.CertificateExpiresOn = $DeploymentSettings.CertificateExpiresOn.ToString()}
$CertificateSettingsElement.InnerXml += "<AllowFontSmoothing />";$CertificateSettingsElement.AllowFontSmoothing = $DeploymentSettings.AllowFontSmoothing.ToString()
if ($DeploymentSettings.UseMultimon -ne $null){$CertificateSettingsElement.InnerXml += "<UseMultimon />";$CertificateSettingsElement.UseMultimon = $DeploymentSettings.UseMultimon.ToString()}
$CertificateSettingsElement.InnerXml += "<ColorBitDepth />";$CertificateSettingsElement.ColorBitDepth = $DeploymentSettings.ColorBitDepth.ToString()
$CertificateSettingsElement.InnerXml += "<RedirectionSettings />";$CertificateSettingsElement.RedirectionSettings = $DeploymentSettings.RedirectionOptions.ToString()
if ($DeploymentSettings.CustomRDPSettings){$CertificateSettingsElement.InnerXml += "<CustomRdpSettings />";$CertificateSettingsElement.CustomRdpSettings = $DeploymentSettings.CustomRDPSettings.ToString()}
$CertificateSettingsElement.InnerXml += "<ShowRemoteDesktop />";$CertificateSettingsElement.ShowRemoteDesktop = [string][bool](Get-WmiObject -Namespace "root\\CIMV2\\TerminalServices" -Class Win32_TSRemoteDesktop)
$CertificateSettingsElement.InnerXml += "<RemoteDesktopSecurityDescriptor />"
if ($GatewaySettingsElement.InnerXml -ne ""){$DeploymentSettingsElement.AppendChild($GatewaySettingsElement) | Out-Null}
if ($CertificateSettingsElement.InnerXml -ne ""){$DeploymentSettingsElement.AppendChild($CertificateSettingsElement) | Out-Null}
if ($DeploymentSettingsElement.InnerXml -ne ""){$xmldata.RemotePrograms.AppendChild($DeploymentSettingsElement) | Out-Null}
Write-Host "The settings was succesfully exported" -ForegroundColor yellow
Get-WmiObject -Namespace "root\\CIMV2\\TerminalServices" -Class Win32_TSPublishedApplication | ForEach-Object {
$newelement = $xmldata.CreateElement("Application")
# $newelement.InnerXml = "<Name /><Alias /><SecurityDescriptor /><Path /><VPath /><ShowInTSWA /><RequiredCommandLine /><IconPath /><IconIndex /><CommandLineSetting /><RDPContents />"
if ($_.Name){$newelement.InnerXml += "<Name />";$newelement.Name = $_.Name.ToString()}
if ($_.Alias){$newelement.InnerXml += "<Alias />";$newelement.Alias = $_.Alias.ToString()}
$newelement.InnerXml += "<SecurityDescriptor />";if ($_.SecurityDescriptor){$newelement.SecurityDescriptor = $_.SecurityDescriptor.ToString()}
if ($_.Path){$newelement.InnerXml += "<Path />";$newelement.Path = $_.Path.ToString()}
$newelement.InnerXml += "<VPath />";if ($_.VPath){$newelement.VPath = $_.VPath.ToString()}
if ($_.ShowInPortal){$newelement.InnerXml += "<ShowInTSWA />";$newelement.ShowInTSWA = "Yes"} else {$newelement.InnerXml += "<ShowInTSWA />";$newelement.ShowInTSWA = "No"}
$newelement.InnerXml += "<RequiredCommandLine />";if ($_.RequiredCommandLine){$newelement.RequiredCommandLine = $_.RequiredCommandLine.ToString()}
if ($_.IconPath){$newelement.InnerXml += "<IconPath />";$newelement.IconPath = $_.IconPath.ToString()}
$newelement.InnerXml += "<IconIndex />";$newelement.IconIndex = $_.IconIndex.ToString()
$newelement.InnerXml += "<CommandLineSetting />";$newelement.CommandLineSetting = $_.CommandLineSetting.ToString()
if ($_.RDPFileContents){$newelement.InnerXml += "<RDPContents />";$newelement.RDPContents = $_.RDPFileContents.ToString()}
$xmldata.RemotePrograms.AppendChild($newelement) | Out-Null
Write-Host "The $($newelement.Alias) was succesfully exported" -ForegroundColor yellow
}
$xmldata.Save($Path)
if ($?) {Write-Host "The $Path saved was succesfully" -ForegroundColor yellow}
}
|
PowerShellCorpus/PoshCode/Format-Hex.ps1
|
Format-Hex.ps1
|
##############################################################################\n##\n## Format-Hex\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\nOutputs a file or pipelined input as a hexadecimal display. To determine the\noffset of a character in the input, add the number at the far-left of the row\nwith the the number at the top of the column for that character.\n\n.EXAMPLE\n\n"Hello World" | Format-Hex\n\n 0 1 2 3 4 5 6 7 8 9 A B C D E F\n\n00000000 48 00 65 00 6C 00 6C 00 6F 00 20 00 57 00 6F 00 H.e.l.l.o. .W.o.\n00000010 72 00 6C 00 64 00 r.l.d.\n\n.EXAMPLE\n\nFormat-Hex c:\\temp\\example.bmp\n\n#>\n\n[CmdletBinding(DefaultParameterSetName = "ByPath")]\nparam(\n ## The file to read the content from\n [Parameter(ParameterSetName = "ByPath", Position = 0)]\n [string] $Path,\n\n ## The input (bytes or strings) to format as hexadecimal\n [Parameter(\n ParameterSetName = "ByInput", Position = 0,\n ValueFromPipeline = $true)]\n [Object] $InputObject\n)\n\nbegin\n{\n Set-StrictMode -Version Latest\n\n ## Create the array to hold the content. If the user specified the\n ## -Path parameter, read the bytes from the path.\n [byte[]] $inputBytes = $null\n if($Path) { $inputBytes = [IO.File]::ReadAllBytes((Resolve-Path $Path)) }\n\n ## Store our header, and formatting information\n $counter = 0\n $header = " 0 1 2 3 4 5 6 7 8 9 A B C D E F"\n $nextLine = "{0} " -f [Convert]::ToString(\n $counter, 16).ToUpper().PadLeft(8, '0')\n $asciiEnd = ""\n\n ## Output the header\n "`r`n$header`r`n"\n}\n\nprocess\n{\n ## If they specified the -InputObject parameter, retrieve the bytes\n ## from that input\n if(Test-Path variable:\\InputObject)\n {\n ## If it's an actual byte, add it to the inputBytes array.\n if($InputObject -is [Byte])\n {\n $inputBytes = $InputObject\n }\n else\n {\n ## Otherwise, convert it to a string and extract the bytes\n ## from that.\n $inputString = [string] $InputObject\n $inputBytes = [Text.Encoding]::Unicode.GetBytes($inputString)\n }\n }\n\n ## Now go through the input bytes\n foreach($byte in $inputBytes)\n {\n ## Display each byte, in 2-digit hexidecimal, and add that to the\n ## left-hand side.\n $nextLine += "{0:X2} " -f $byte\n\n ## If the character is printable, add its ascii representation to\n ## the right-hand side. Otherwise, add a dot to the right hand side.\n if(($byte -ge 0x20) -and ($byte -le 0xFE))\n {\n $asciiEnd += [char] $byte\n }\n else\n {\n $asciiEnd += "."\n }\n\n $counter++;\n\n ## If we've hit the end of a line, combine the right half with the\n ## left half, and start a new line.\n if(($counter % 16) -eq 0)\n {\n\n "$nextLine $asciiEnd"\n $nextLine = "{0} " -f [Convert]::ToString(\n $counter, 16).ToUpper().PadLeft(8, '0')\n $asciiEnd = "";\n }\n }\n}\n\nend\n{\n ## At the end of the file, we might not have had the chance to output\n ## the end of the line yet. Only do this if we didn't exit on the 16-byte\n ## boundary, though.\n if(($counter % 16) -ne 0)\n {\n while(($counter % 16) -ne 0)\n {\n $nextLine += " "\n $asciiEnd += " "\n $counter++;\n }\n "$nextLine $asciiEnd"\n }\n\n ""\n}
|
PowerShellCorpus/PoshCode/SQLite Read _ Write.ps1
|
SQLite Read _ Write.ps1
|
# Make sure SQLite.Interop.dll is in the same directory as System.Data.SQLite.dll
$scriptDir = "Path to your SQLite DLL"
Add-Type -Path "$scriptDir\\System.Data.SQLite.dll"
############### SAMPLE USAGE ###################
### Querying:
###
### $readQuery = "SELECT * FROM TABLE"
### $dataArray = $SQLite.querySQLite($readQuery)
###
### Writing:
###
### $writeQuery = "INSERT OR IGNORE INTO GAME VALUES ('12345', 'TEST');
### UPDATE GAME SET NAME = 'TEST1235' WHERE ID LIKE '12345';"
### $SQLite.writeSQLite($query)
###
################################################
################################################
###
### $catalog contains two properties ID and NAME
### foreach($item in $catalog ){
### $writeQuery = "INSERT OR IGNORE INTO GAME VALUES (`"$($item.ID)`", `"$($item.NAME)`");
### UPDATE GAME SET NAME = `"$($item.NAME)`" WHERE ID LIKE `"$($item.ID)`";"
### $SQLite.writeSQLite($writeQuery)
### }
$SQLite = New-Module {
Function querySQLite {
param([string]$query)
$datatSet = New-Object System.Data.DataSet
### declare location of db file. ###
$database = "$scriptDir\\data"
$connStr = "Data Source = $database"
$conn = New-Object System.Data.SQLite.SQLiteConnection($connStr)
$conn.Open()
$dataAdapter = New-Object System.Data.SQLite.SQLiteDataAdapter($query,$conn)
[void]$dataAdapter.Fill($datatSet)
$conn.close()
return $datatSet.Tables[0].Rows
}
Function writeSQLite {
param([string]$query)
$database = "$scriptDir\\data"
$connStr = "Data Source = $database"
$conn = New-Object System.Data.SQLite.SQLiteConnection($connStr)
$conn.Open()
$command = $conn.CreateCommand()
$command.CommandText = $query
$RowsInserted = $command.ExecuteNonQuery()
$command.Dispose()
}
Export-ModuleMember -Variable * -Function *
} -asCustomObject
|
PowerShellCorpus/PoshCode/Invoke-JQuery.ps1
|
Invoke-JQuery.ps1
|
function Invoke-JQuery
{
<#
.SYNOPSIS
Function to Invoke JQuery commands via IE COM
.DESCRIPTION
Invokes JQuery (or plain Javascript) commands via InternetExplorer.Application COM object,
after initial injection of JQuery reference in header section.
Useful to utilize JQuery selectors and functions for IE automation.
.PARAMETER IE
Initialized InternetExplorer.Application COM object
.PARAMETER Command
JQuery/Javascript to Invoke
.PARAMETER Function
Function to add in header section
.PARAMETER Initialize
Switch to initially inject JQuery in header section.
.EXAMPLE
$ie = new-object -com internetexplorer.application
$ie.visible = $true
$ie.navigate2("http://www.example.com")
# Wait for page load
while($ie.busy) {start-sleep 1}
#add addtional div to store results
$div="<div id='myResult'>"
$ie.Document.body.innerHTML += $div
#hide anchor tags
Invoke-JQuery $ie '$("a").hide();' -Initialize
#change innerhtml of div
Invoke-JQuery $ie 'var str=$("p:first").text();$("#myResult").html(str);'
#retrieve the value
$result = $ie.document.getElementById("myResult").innerHtml
$jFunc=@"
function SelectText(element) {
var text = document.getElementById(element);
var range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
}
"@
Invoke-JQuery $ie -Function $jFunc
Invoke-JQuery $ie 'SelectText("myResult");'
#>
[cmdletbinding()]
param(
[parameter(position=0, mandatory=$true)]
$IE,
[parameter(position=1,mandatory=$false)]
$Command,
[parameter()]
$Function,
[parameter()]
[switch]$Initialize
)
if ($Initialize -or $Function){
$url='http://code.jquery.com/jquery-1.4.2.min.js'
$document = $IE.document
$head = @($document.getElementsByTagName("head"))[0]
$script = $document.createElement('script')
$script.type = 'text/javascript'
}
if ($Initialize){
$script.src = $url
$head.appendChild($script) | Out-Null
}
if ($Command){$IE.document.parentWindow.execScript("$Command","javascript")}
if ($Function){
$script.text = $Function
$head.appendChild($script) | Out-Null
}
}
|
PowerShellCorpus/PoshCode/Add-ExcelAddins.ps1
|
Add-ExcelAddins.ps1
|
###########################################################################"
#
# NAME: Add-ExcelAddins.ps1
#
# AUTHOR: Jan Egil Ring
# EMAIL: jan.egil.ring@powershell.no
#
# COMMENT: This script will check if the specified Microsoft Office Excel Addins are loaded, and if not load them.
# Tested with PowerShell v2 and Microsoft Office Excel 2007, although it should work fine with PowerShell v1 and older
# versions of Microsoft Office Excel.
#
# 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 01.11.2009 - Initial release
#
###########################################################################"
$Addinfilename = 'Addin_01.xla'
$Addinfilepath = 'C:\\MyAddins\\'
$Excel = New-Object -ComObject excel.application
$ExcelWorkbook = $excel.Workbooks.Add()
if (($ExcelWorkbook.Application.AddIns | Where-Object {$_.name -eq $Addinfilename}) -eq $null) {
$ExcelAddin = $ExcelWorkbook.Application.AddIns.Add("$Addinfilepath$Addinfilename", $True)
$ExcelAddin.Installed = "True"
Write-Host "$Addinfilename added"}
else
{Write-Host "$Addinfilename already added"}
$Excel.Quit()
|
PowerShellCorpus/PoshCode/Get-DesktopResolution.ps.ps1
|
Get-DesktopResolution.ps.ps1
|
<#
.SYNOPSIS
Displays Desktop Size
.DESCRIPTION
This script is a re-write of an MSDN sample. It uses
the Win32_Desktop Monitor WMI class to obtain the
screen dimensions.
.NOTES
File Name : Get-DesktopResolution.ps1
Author : Thomas Lee - tfl@psp.co.uk
Requires : PowerShell V2 CTP3
.LINK
Script Posted To:
http://pshscripts.blogspot.com/2009/01/get-screensaverps1.html
Re-write of sample 3 at:
http://msdn.microsoft.com/en-us/library/aa394591(VS.85).aspx
.EXAMPLE
PS c:\\foo> .\\Get-DesktopResolution
There are 4 Desktops on UK0N055 as follows:
Desktop 1: Default Monitor
Screen Height : 1200
Screen Width : 1920
Desktop 2: Default Monitor
Screen Height :
Screen Width :
Desktop 3: Default Monitor
Screen Height :
Screen Width :
Desktop 4: Default Monitor
Screen Height :
Screen Width :
#>
##
# Start of script
##
# Get desktop information
$computer = "."
$desktops = Get-WmiObject -Class Win32_DesktopMonitor
$hostname = hostname
# Display desktop details
"There are {0} Desktops on {1} as follows:" -f $desktops.Count, $hostname
""
$i=1 # count of desktops on this system
foreach ($desktop in $desktops) {
"Desktop {0}: {1}" -f $i++, $Desktop.Caption
"Screen Height : {0}" -f $desktop.ScreenHeight
"Screen Width : {0}" -f $desktop.ScreenWidth
""
}
# End of Script
|
PowerShellCorpus/PoshCode/CertMgmt pack_4.ps1
|
CertMgmt pack_4.ps1
|
#####################################################################
# CertMgmtPack.ps1
# Version 0.51
#
# Digital certificate management pack
#
# Vadims Podans (c) 2009
# http://www.sysadmins.lv/
#####################################################################
#requires -Version 2.0
function Import-Certificate {
<#
.Synopsis
Imports digital certificates to Certificate Store from files
.Description
Improrts digital certificates to Certificate Store from various types of
certificates files, such .CER, .DER, .PFX (password required), .P7B.
.Parameter Path
Specifies the path to certificate file
.Parameter Password
Specifies password to PFX/PKCS#12 file only. For other certificate types
is not required.
Note: this parameter must be passed as SecureString.
.Parameter Storage
Specifies place in Sertificate Store for certificate. For user certificates
(default) you MAY specify 'User' and importing certificate will be stored
in CurrentUser Certificate Store. For computer certificates you MUST specify
'Computer' and importing certificates will be stored in LocalMachine Certificate
Store.
.Parameter Container
Specifies container within particular Certificate Store location. Container may
be one of AuthRoot/CA/Disallowed/My/REQUEST/Root/SmartCardRoot/Trust/TrustedPeople/
TrustedPublisher/UserDS. These containers represent MMC console containers
as follows:
AddressBook - AddressBook
AuthRoot - Third-Party Root CAs
CA - Intermediate CAs
Disallowed - Untrused Certificates
My - Personal
REQUEST - Certificate Enrollment Requests
Root - Trusted Root CAs
SmartCardRoot - Smart Card Trusted Roots
Trust - Enterprise Trust
TrustedPeople - Trusted People
TrustedPublishers - Trusted Publishers
UserDS - Active Directory User Object
.Parameter Exportable
Marks imported certificates private key as exportable. May be used only for PFX
files only. If this switch is not presented for PFX files, after importing you
will not be able to export this certificate with private key again.
.Parameter StrongProtection
Enables private key strong protection that requires user password each time
when certificate private key is used. Not available for computer certificates,
because computers certificates are used under LocalSystem account and here is
no UI for user to type password.
.Outputs
This command provide a simple message if the export is successful.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
[string]$Path,
[Parameter(Position = 1)]
[System.Security.SecureString]$Password,
[Parameter(Position = 2)]
[string][ValidateSet("CurrentUser", "LocalMachine")]$Storage = "CurrentUser",
[string][ValidateSet("AddressBook", "AuthRoot", "CA", "Disallowed", "My", "REQUEST",
"Root", "SmartCardRoot", "Trust", "TrustedPeople", "TrustedPublisher", "UserDS")]$Container = "My",
[switch]$Exportable,
[switch]$StrongProtection
)
if (!(Resolve-Path $Path)) {throw "Looks like your specified certificate file doesn't exist"}
$file = gi $Path -Force -ErrorAction Stop
$certs = New-Object system.security.cryptography.x509certificates.x509certificate2
switch ($Storage) {
"CurrentUser" {$flags = "UserKeySet"}
"LocalMachine" {$flags = "MachineKeySet"}
}
switch -regex ($file.Extension) {
".CER|.DER" {$certs.Import($file.FullName, $null, $flags)}
".PFX" {
if (!$password) {throw "For PFX files password is required."}
if ($StrongProtection -and $Storage -eq "Computer") {
throw "You cannot use Private Key Strong Protection for computer certificates!"
}
if ($Exportable) {$flags = $flags + ", Exportable"}
if ($StrongProtection) {$flags = $flags + ", UserProtected"}
$certs.Import($file.FullName, $password, $flags)
}
".P7B|.SST" {
$certs = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
$certs.Import([System.IO.File]::ReadAllBytes($file.FullName))
}
default {throw "Looks like your specified file is not a certificate file"}
}
$store = New-Object system.security.cryptography.X509Certificates.X509Store $Container, $Storage
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$certs | %{$store.Add($_)}
if ($?) {Write-Host -ForegroundColor Green Certificate file`: $file.fullname was successfully added to $Container container}
$store.Close()
}
function Export-Certificate {
<#
.Synopsis
Exports digital certificates to file Certificate Store.
.Description
Exports digital certificates from Certificate Store to various types of certificate
file such .CER, .DER, .PFX (password required), .P7B or .SST (serializd store).
.Parameter Path
Specifies the path to certificate storing folder
.Parameter Type
Specifies type of imported certificate. May be one of CERT/PFX/PKCS#12/P7B/PKCS#7.
.Parameter Password
Specifies a password for PFX files and used only if type is specified as PFX/PKCS#12.
Note: password must be supplied as SecureString.
.Parameter Storage
Specifies place in Sertificate Store for certificate. For user certificates
(default) you MAY specify 'User' to export certificates from CurrentUser Certificate Store.
For computer certificates you MUST specify 'Computer' to export certificates from
LocalMachine Certificate Store.
.Parameter Container
Specifies container within particular Certificate Store location. Container may
be one of AuthRoot/CA/Disallowed/My/REQUEST/Root/SmartCardRoot/Trust/TrustedPeople/
TrustedPublisher/UserDS. These containers represent MMC console containers
as follows:
AddressBook - AddressBook
AuthRoot - Third-Party Root CAs
CA - Intermediate CAs
Disallowed - Untrused Certificates
My - Personal
REQUEST - Certificate Enrollment Requests
Root - Trusted Root CAs
SmartCardRoot - Smart Card Trusted Roots
Trust - Enterprise Trust
TrustedPeople - Trusted People
TrustedPublishers - Trusted Publishers
UserDS - Active Directory User Object
.EXAMPLE
.Outputs
This command doesn't provide any output, except errors.
.Link
#>
[CmdletBinding()]
param (
[Parameter(Position = 0)]
[string]$Path,
[Parameter(Mandatory = $true, Position = 1)]
[string][ValidatePattern("Cert|Pfx|pkcs12|pkcs7|SST")]$Type,
[Parameter(Position = 2)]
[System.Security.SecureString]$Password,
[Parameter(Position = 3)]
[string][ValidateSet("CurrentUser", "LocalMachine")]$Storage = "CurrentUser",
[Parameter(ValueFromPipeline = $true, Position = 4)]
[string][ValidateSet("AddressBook", "AuthRoot", "CA", "Disallowed", "My", "REQUEST",
"Root", "SmartCardRoot", "Trust", "TrustedPeople", "TrustedPublisher", "UserDS")]$Container = "My",
[string]$Thumbprint,
[string]$Subject,
[string]$Issuer,
[string]$SerialNumber,
[string]$NotAfter,
[string]$NotBefore,
[switch]$DeleteKey,
[switch]$Recurse
)
if (!(Test-Path $Path)) {
New-Item -ItemType directory -Path $Path -Force -ErrorAction Stop
}
if ((Resolve-Path $Path).Provider.Name -ne "FileSystem") {
throw "Spicifed path is not recognized as filesystem path. Try again"
}
if ($Recurse) {
function dirx ($Storage) {
dir cert:\\$Storage -Recurse | ?{!$_.PsIsContainer}
}
} else {
function dirx ($Storage, $Container) {
dir cert:\\$Storage\\$Container
}
}
if ($Type -eq 'pkcs12') {$Type = "PFX"}
if ($Type -eq 'SST') {$Type = "SerializedStore"}
if ($Type -eq "PFX" -and !$Password) {throw "For PFX files password is required."}
$Type = [System.Security.Cryptography.X509Certificates.X509ContentType]::$Type
if ($NotAfter) {$NotAfter = [datetime]::ParseExact($NotAfter, "dd.MM.yyy", $null)}
if ($NotBefore) {$NotBefore = [datetime]::ParseExact($NotBefore, "dd.MM.yyy", $null)}
if ($Thumbprint) {$certs = @(dirx | ?{$_.Thumbprint -like "*$Thumbprint*"})}
elseif ($Subject) {$certs = @(dirx | ?{$_.Subject -like "*$Subject*"})}
elseif ($Issuer) {$certs = @(dirx | ?{$_.Issuer -like "*$Issuer*"})}
elseif ($SerialNumber) {$certs = @(dirx | ?{$_.SerialNumber -like "*$SerialNumber*"})}
elseif ($NotAfter -and !$NotBefore) {$certs = @(dirx | ?{$_.NotAfter -lt $NotAfter})}
elseif (!$NotAfter -and $NotBefore) {$certs = @(dirx | ?{$_.NotBefore -gt $NotBefore})}
elseif ($NotAfter -and $NotBefore) {$certs = @(dirx | ?{$_.NotAfter -lt $NotAfter `
-and $_.NotBefore -gt $NotBefore})}
else {$certs = @(dirx)}
if ($certs.Count -eq 0) {Write-Warning "Sorry, we unable to find certificates that correspond your filter :("; return}
switch -regex ($Type) {
"Cert" {
foreach ($cert in $certs) {
[void]($cert.Subject -match 'CN=([^,]+)')
$CN = $matches[1] -replace '[\\\\/:\\*?`"<>|]', ''
$bytes = $cert.Export($type)
$base64Data = [System.Convert]::ToBase64String($bytes)
Set-Content -LiteralPath $(Join-Path $Path ($CN + "_" + $cert.Thumbprint + ".cer")) -Value $base64Data
}
}
"PFX" {
foreach ($cert in $certs) {
[void]($cert.Subject -match 'CN=([^,]+)')
$CN = $matches[1] -replace '[\\\\/:\\*?`"<>|]', ''
$bytes = $cert.Export($Type, $Password)
[System.IO.File]::WriteAllBytes($(Join-Path $Path ($CN + "_" + $cert.Thumbprint + ".pfx")), $bytes)
if ($DeleteKey) {
$tempcert = $cert.Export("Cert")
$store = New-Object system.security.cryptography.X509Certificates.X509Store $container, $Storage
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$store.Remove($cert)
$store.Add($tempcert)
$store.Close()
}
}
}
"Pkcs7|SerializedStore" {
$certcol = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
$certs | %{[void]$certcol.Add($_)}
$bytes = $certcol.Export($Type)
if ($Type -eq "Pkcs7") {$ext = ".p7b"} else {$ext = ".sst"}
[System.IO.File]::WriteAllBytes($("ExportedCertificates" + $ext, $bytes))
}
}
}
|
PowerShellCorpus/PoshCode/connect-domain.ps1
|
connect-domain.ps1
|
function connect-domain_X {
BEGIN {$foregroundcolor= (get-host).ui.rawui.get_foregroundcolor()
Write-Host "";
"---------------------------------" ;
"Entering Nested Prompt for Quest connection to DOMAIN_X.";
"Type `"Exit`" when finished.";
"---------------------------------" ;
""
(get-host).ui.rawui.set_foregroundcolor("magenta")
$pw = Read-Host "Enter your DOMAIN_X password" -AsSecureString
}
PROCESS {connect-QADService -service 'domaincontroller' -ConnectionAccount 'domain_x\\username' -ConnectionPassword $pw
$host.enternestedprompt()
}
END {
(get-host).ui.rawui.set_foregroundcolor($foregroundcolor)
}
}
|
PowerShellCorpus/PoshCode/Memory helper functions.ps1
|
Memory helper functions.ps1
|
Function Add-SessionVariable()
{
param ([string[]]$VariableName=$null)
[string[]]$VariableNames = [AppDomain]::CurrentDomain.GetData('Variable')
$VariableNames += $VariableName
if ($input)
{
$VariableNames += $input
}
#To Not Waste Space, Remove Duplicates
$VariableNames = $VariableNames | Select-Object -Unique
[AppDomain]::CurrentDomain.SetData('Variable',$VariableNames)
}
Function Set-SessionVariableList()
{
$VariableNames = Get-Variable -scope global| ForEach-Object {$_.Name}
Add-SessionVariable $VariableNames
Write-Verbose 'Loaded Variable Names into AppDomain'
$counter = 1
Foreach ($Variable in $VariableNames)
{
Write-Verbose "`t $($counter): $Variable"
$counter++
}
}
Function Get-SessionVariableList()
{
[AppDomain]::CurrentDomain.GetData('Variable')
}
Function Remove-NewVariable()
{
$StartingMemory = (Get-Process -ID $PID).WS / 1MB
Write-Verbose "Current Memory Usage: $StartingMemory MB"
$VariableNames = Get-SessionVariableList
$VariableNames += 'StartingMemory'
Get-Variable -scope global | Where-Object {$VariableNames -notcontains $_.name} | Remove-Variable -scope global
[GC]::Collect()
$EndingMemory = (Get-Process -ID $PID).WS / 1MB
Write-Verbose "Ending Memory: $EndingMemory MB"
$Diff = $StartingMemory - $EndingMemory
Write-Verbose "Freed up: $Diff MB"
}
|
PowerShellCorpus/PoshCode/JSON 1.4.ps1
|
JSON 1.4.ps1
|
#requires -version 2.0
# Version History:
# v 0.5 - First Public version
# v 1.0 - Made ConvertFrom-Json work with arbitrary JSON
# - switched to xsl style sheets for ConvertTo-JSON
# v 1.1 - Changed ConvertFrom-Json to handle single item results
# v 1.2 - CodeSigned to make a fellow geek happy
# v 1.3 - Changed ConvertFrom-Json to handle zero item results (I hope)
# v 1.4 - Added -File parmeter set to ConvertFrom-Json
#
# There is no help (yet) because I'm still changing and renaming everything every time I mess with this code
# Full RoundTrip capability:
#
# > ls | ConvertTo-Json | ConvertFrom-Json
# > ps | ConvertTo-Json | Convert-JsonToXml | Convert-XmlToJson | convertFrom-Json
#
# You may frequently want to use the DEPTH or NoTypeInformation parameters:
#
# > ConvertTo-Json -Depth 2 -NoTypeInformation
#
# But then you have to specify the type when you reimport (and you can't do that for deep objects).
# This problem also occurs if you convert the result of a SELECT statement (ie: PSCustomObject).
# For Example:
#
# > PS | Select PM, WS, CPU, ID, ProcessName |
# >> ConvertTo-json -NoType |
# >> convertfrom-json -Type System.Diagnostics.Process
Add-Type -AssemblyName System.ServiceModel.Web, System.Runtime.Serialization
$utf8 = [System.Text.Encoding]::UTF8
function Write-String {
PARAM(
[Parameter()]$stream,
[Parameter(ValueFromPipeline=$true)]$string
)
PROCESS {
$bytes = $utf8.GetBytes($string)
$stream.Write( $bytes, 0, $bytes.Length )
}
}
function Convert-JsonToXml {
PARAM([Parameter(ValueFromPipeline=$true)][string[]]$json)
BEGIN {
$mStream = New-Object System.IO.MemoryStream
}
PROCESS {
$json | Write-String -stream $mStream
}
END {
$mStream.Position = 0
try
{
$jsonReader = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonReader($mStream,[System.Xml.XmlDictionaryReaderQuotas]::Max)
$xml = New-Object Xml.XmlDocument
$xml.Load($jsonReader)
$xml
}
finally
{
$jsonReader.Close()
$mStream.Dispose()
}
}
}
function Convert-XmlToJson {
PARAM([Parameter(ValueFromPipeline=$true)][Xml]$xml)
PROCESS {
$mStream = New-Object System.IO.MemoryStream
$jsonWriter = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonWriter($mStream)
try
{
$xml.Save($jsonWriter)
$bytes = $mStream.ToArray()
[System.Text.Encoding]::UTF8.GetString($bytes,0,$bytes.Length)
}
finally
{
$jsonWriter.Close()
$mStream.Dispose()
}
}
}
## Rather than rewriting ConvertTo-Xml ...
Function ConvertTo-Json {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,Position=1,ValueFromPipeline=$true)]$InputObject
,
[Parameter(Mandatory=$false)][Int]$Depth=1
,
[Switch]$NoTypeInformation
)
END {
## You must output ALL the input at once
## ConvertTo-Xml outputs differently if you just have one, so your results would be different
$input | ConvertTo-Xml -Depth:$Depth -NoTypeInformation:$NoTypeInformation -As Document | Convert-CliXmlToJson
}
}
Function Convert-CliXmlToJson {
PARAM(
[Parameter(ValueFromPipeline=$true)][Xml.XmlNode]$xml
)
BEGIN {
$xmlToJsonXsl = @'
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!--
CliXmlToJson.xsl
Copyright (c) 2006,2008 Doeke Zanstra
Copyright (c) 2009 Joel Bennett
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer. Redistributions in binary
form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with
the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
-->
<xsl:output indent="no" omit-xml-declaration="yes" method="text" encoding="UTF-8" media-type="text/x-json"/>
<xsl:strip-space elements="*"/>
<!--contant-->
<xsl:variable name="d">0123456789</xsl:variable>
<!-- ignore document text -->
<xsl:template match="text()[preceding-sibling::node() or following-sibling::node()]"/>
<!-- string -->
<xsl:template match="text()">
<xsl:call-template name="escape-string">
<xsl:with-param name="s" select="."/>
</xsl:call-template>
</xsl:template>
<!-- Main template for escaping strings; used by above template and for object-properties
Responsibilities: placed quotes around string, and chain up to next filter, escape-bs-string -->
<xsl:template name="escape-string">
<xsl:param name="s"/>
<xsl:text>"</xsl:text>
<xsl:call-template name="escape-bs-string">
<xsl:with-param name="s" select="$s"/>
</xsl:call-template>
<xsl:text>"</xsl:text>
</xsl:template>
<!-- Escape the backslash (\\) before everything else. -->
<xsl:template name="escape-bs-string">
<xsl:param name="s"/>
<xsl:choose>
<xsl:when test="contains($s,'\\')">
<xsl:call-template name="escape-quot-string">
<xsl:with-param name="s" select="concat(substring-before($s,'\\'),'\\\\')"/>
</xsl:call-template>
<xsl:call-template name="escape-bs-string">
<xsl:with-param name="s" select="substring-after($s,'\\')"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="escape-quot-string">
<xsl:with-param name="s" select="$s"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- Escape the double quote ("). -->
<xsl:template name="escape-quot-string">
<xsl:param name="s"/>
<xsl:choose>
<xsl:when test="contains($s,'"')">
<xsl:call-template name="encode-string">
<xsl:with-param name="s" select="concat(substring-before($s,'"'),'\\"')"/>
</xsl:call-template>
<xsl:call-template name="escape-quot-string">
<xsl:with-param name="s" select="substring-after($s,'"')"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="encode-string">
<xsl:with-param name="s" select="$s"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- Replace tab, line feed and/or carriage return by its matching escape code. Can't escape backslash
or double quote here, because they don't replace characters (� becomes \\t), but they prefix
characters (\\ becomes \\\\). Besides, backslash should be seperate anyway, because it should be
processed first. This function can't do that. -->
<xsl:template name="encode-string">
<xsl:param name="s"/>
<xsl:choose>
<!-- tab -->
<xsl:when test="contains($s,'	')">
<xsl:call-template name="encode-string">
<xsl:with-param name="s" select="concat(substring-before($s,'	'),'\\t',substring-after($s,'	'))"/>
</xsl:call-template>
</xsl:when>
<!-- line feed -->
<xsl:when test="contains($s,'
')">
<xsl:call-template name="encode-string">
<xsl:with-param name="s" select="concat(substring-before($s,'
'),'\\n',substring-after($s,'
'))"/>
</xsl:call-template>
</xsl:when>
<!-- carriage return -->
<xsl:when test="contains($s,'
')">
<xsl:call-template name="encode-string">
<xsl:with-param name="s" select="concat(substring-before($s,'
'),'\\r',substring-after($s,'
'))"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise><xsl:value-of select="$s"/></xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- number (no support for javascript mantise) -->
<xsl:template match="text()[not(string(number())='NaN' or
(starts-with(.,'0' ) and . != '0'))]">
<xsl:value-of select="."/>
</xsl:template>
<!-- boolean, case-insensitive -->
<xsl:template match="text()[translate(.,'TRUE','true')='true']">true</xsl:template>
<xsl:template match="text()[translate(.,'FALSE','false')='false']">false</xsl:template>
<!-- root object(s) -->
<xsl:template match="*" name="base">
<xsl:if test="not(preceding-sibling::*)">
<xsl:choose>
<xsl:when test="count(../*)>1"><xsl:text>[</xsl:text></xsl:when>
<xsl:otherwise><xsl:text>{</xsl:text></xsl:otherwise>
</xsl:choose>
</xsl:if>
<xsl:call-template name="escape-string">
<xsl:with-param name="s" select="name()"/>
</xsl:call-template>
<xsl:text>:</xsl:text>
<!-- check type of node -->
<xsl:choose>
<!-- null nodes -->
<xsl:when test="count(child::node())=0">null</xsl:when>
<!-- other nodes -->
<xsl:otherwise>
<xsl:apply-templates select="child::node()"/>
</xsl:otherwise>
</xsl:choose>
<!-- end of type check -->
<xsl:if test="following-sibling::*">,</xsl:if>
<xsl:if test="not(following-sibling::*)">
<xsl:choose>
<xsl:when test="count(../*)>1"><xsl:text>]</xsl:text></xsl:when>
<xsl:otherwise><xsl:text>}</xsl:text></xsl:otherwise>
</xsl:choose>
</xsl:if>
</xsl:template>
<!-- properties of objects -->
<xsl:template match="*[count(../*[name(../*)=name(.)])=count(../*) and count(../*)>1]">
<xsl:variable name="inArray" select="translate(local-name(),'OBJECT','object')='object' or ../@Type[starts-with(.,'System.Collections') or contains(.,'[]') or (contains(.,'[') and contains(.,']'))]"/>
<xsl:if test="not(preceding-sibling::*)">
<xsl:choose>
<xsl:when test="$inArray"><xsl:text>[</xsl:text></xsl:when>
<xsl:otherwise>
<xsl:text>{</xsl:text>
<xsl:if test="../@Type">
<xsl:text>"__type":</xsl:text>
<xsl:call-template name="escape-string">
<xsl:with-param name="s" select="../@Type"/>
</xsl:call-template>
<xsl:text>,</xsl:text>
</xsl:if>
</xsl:otherwise>
</xsl:choose>
</xsl:if>
<xsl:choose>
<xsl:when test="not(child::node())">
<xsl:call-template name="escape-string">
<xsl:with-param name="s" select="@Name"/>
</xsl:call-template>
<xsl:text>:null</xsl:text>
</xsl:when>
<xsl:when test="$inArray">
<xsl:apply-templates select="child::node()"/>
</xsl:when>
<!--
<xsl:when test="not(@Name) and not(@Type)">
<xsl:call-template name="escape-string">
<xsl:with-param name="s" select="local-name()"/>
</xsl:call-template>
<xsl:text>:</xsl:text>
<xsl:apply-templates select="child::node()"/>
</xsl:when>
-->
<xsl:when test="not(@Name)">
<xsl:call-template name="escape-string">
<xsl:with-param name="s" select="local-name()"/>
</xsl:call-template>
<xsl:text>:</xsl:text>
<xsl:apply-templates select="child::node()"/>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="escape-string">
<xsl:with-param name="s" select="@Name"/>
</xsl:call-template>
<xsl:text>:</xsl:text>
<xsl:apply-templates select="child::node()"/>
</xsl:otherwise>
</xsl:choose>
<xsl:if test="following-sibling::*">,</xsl:if>
<xsl:if test="not(following-sibling::*)">
<xsl:choose>
<xsl:when test="$inArray"><xsl:text>]</xsl:text></xsl:when>
<xsl:otherwise><xsl:text>}</xsl:text></xsl:otherwise>
</xsl:choose>
</xsl:if>
</xsl:template>
<!-- convert root element to an anonymous container -->
<xsl:template match="/">
<xsl:apply-templates select="node()"/>
</xsl:template>
</xsl:stylesheet>
'@
}
PROCESS {
if(Get-Member -InputObject $xml -Name root) {
Write-Verbose "Ripping to Objects"
$xml = $xml.root.Objects
} else {
Write-Verbose "Was already Objects"
}
Convert-Xml -Xml $xml -Xsl $xmlToJsonXsl
}
}
Function ConvertFrom-Xml {
[CmdletBinding(DefaultParameterSetName="AutoType")]
PARAM(
[Parameter(ValueFromPipeline=$true,Mandatory=$true,Position=1)]
[Xml.XmlNode]
$xml
,
[Parameter(Mandatory=$true,ParameterSetName="ManualType")]
[Type]$Type
,
[Switch]$ForceType
)
PROCESS{
if(Get-Member -InputObject $xml -Name root) {
return $xml.root.Objects |
} elseif(Get-Member -InputObject $xml -Name Objects) {
return $xml.Objects |
}
$propbag = @{}
foreach($name in Get-Member -InputObject $xml -MemberType Property | Where-Object{$_.Name -notmatch "^__|type"} | Select-Object -ExpandProperty name) {
Write-Verbose "$Name Type: $($xml.$Name.type)"
switch( $xml."$Name".type ) {
"object" {
$propbag."$Name" = ConvertFrom-Xml -Xml $xml."$Name"
break
}
"string" {
$propbag."$Name" = $xml."$Name".get_InnerText()
$MightBeADate = $xml."$Name".get_InnerText() -as [DateTime]
## Strings that are actually dates (*grumble* JSON is crap)
if($MightBeADate -and $propbag."$Name" -eq $MightBeADate.ToString("G")) {
$propbag."$Name" = $MightBeADate
}
break
}
"number" {
$number = $xml."$Name".get_InnerText()
if($number -eq ($number -as [int])) {
$propbag."$Name" = $number -as [int]
} elseif($number -eq ($number -as [double])) {
$propbag."$Name" = $number -as [double]
} else {
$propbag."$Name" = $number -as [decimal]
}
break
}
"boolean" {
$propbag."$Name" = [bool]::parse($xml."$Name".get_InnerText())
}
"null" {
$propbag."$Name" = $null
}
default {
$propbag."$Name" = $xml."$Name"
break
}
}
}
if(!$Type -and $xml.HasAttribute("__type")) { $Type = $xml.__Type }
if($ForceType -and $Type) {
try {
$output = New-Object $Type -Property $propbag
} catch {
$output = New-Object PSObject -Property $propbag
$output.PsTypeNames.Insert(0, $xml.__type)
}
} else {
$output = New-Object PSObject -Property $propbag
if($Type) {
$output.PsTypeNames.Insert(0, $Type)
}
}
Write-Output $output
}
}
Function ConvertFrom-Json {
[CmdletBinding(DefaultParameterSetName="StringInput")]
PARAM(
[Parameter(Mandatory=$true,Position=1,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,ParameterSetName="File")]
[Alias("PSPath")]
[string]$File
,
[Parameter(ValueFromPipeline=$true,Mandatory=$true,Position=1,ParameterSetName="StringInput")]
[string]$InputObject
,
[Parameter(Mandatory=$true,ParameterSetName="ManualType")]
[Type]$Type
,
[Switch]$ForceType
)
BEGIN {
[bool]$AsParameter = $PSBoundParameters.ContainsKey("File") -or $PSBoundParameters.ContainsKey("InputObject")
}
PROCESS {
if($PSCmdlet.ParameterSetName -eq "File") {
[string]$InputObject = @(Get-Content $File) -Join "`n"
$null = $PSBoundParameters.Remove("File")
}
else
{
$null = $PSBoundParameters.Remove("InputObject")
}
[Xml.XmlElement]$xml = (Convert-JsonToXml $InputObject).Root
if($xml) {
if($xml.Objects) {
$xml.Objects.Item.GetEnumerator() | ConvertFrom-Xml @PSBoundParameters
}elseif($xml.Item -and $xml.Item -isnot [System.Management.Automation.PSParameterizedProperty]) {
$xml.Item | ConvertFrom-Xml @PSBoundParameters
}else {
$xml | ConvertFrom-Xml @PSBoundParameters
}
} else {
Write-Error "Failed to parse JSON with JsonReader"
}
}
}
#########
### The JSON library is dependent on Convert-Xml from my Xml script module
function Convert-Node {
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[System.Xml.XmlReader]$XmlReader,
[Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)]
[System.Xml.Xsl.XslCompiledTransform]$StyleSheet
)
PROCESS {
$output = New-Object IO.StringWriter
$StyleSheet.Transform( $XmlReader, $null, $output )
Write-Output $output.ToString()
}
}
function Convert-Xml {
#.Synopsis
# The Convert-XML function lets you use Xslt to transform XML strings and documents.
#.Description
#.Parameter Content
# Specifies a string that contains the XML to search. You can also pipe strings to Select-XML.
#.Parameter Namespace
# Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}.
#.Parameter Path
# Specifies the path and file names of the XML files to search. Wildcards are permitted.
#.Parameter Xml
# Specifies one or more XML nodes to search.
#.Parameter Xsl
# Specifies an Xml StyleSheet to transform with...
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath")]
[String[]]$Path
,
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
[Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$Content
,
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[Alias("StyleSheet")]
[String[]]$Xslt
)
BEGIN {
$StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform
if(Test-Path @($Xslt)[0] -ErrorAction 0) {
Write-Verbose "Loading Stylesheet from $(Resolve-Path @($Xslt)[0])"
$StyleSheet.Load( (Resolve-Path @($Xslt)[0]) )
} else {
Write-Verbose "$Xslt"
$StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader ($Xslt -join "`n")))))
}
[Text.StringBuilder]$XmlContent = [String]::Empty
}
PROCESS {
switch($PSCmdlet.ParameterSetName) {
"Content" {
$null = $XmlContent.AppendLine( $Content -Join "`n" )
}
"Path" {
foreach($file in Get-ChildItem $Path) {
Convert-Node -Xml ([System.Xml.XmlReader]::Create((Resolve-Path $file))) $StyleSheet
}
}
"Xml" {
foreach($node in $Xml) {
Convert-Node -Xml (New-Object Xml.XmlNodeReader $node) $StyleSheet
}
}
}
}
END {
if($PSCmdlet.ParameterSetName -eq "Content") {
[Xml]$Xml = $XmlContent.ToString()
Convert-Node -Xml $Xml $StyleSheet
}
}
}
New-Alias fromjson ConvertFrom-Json
New-Alias tojson ConvertTo-Json
#New-Alias ipjs Import-Json
#New-Alias epjs Export-Json
#Import-Json, Export-Json,
Export-ModuleMember -Function ConvertFrom-Json, ConvertTo-Json, Convert-JsonToXml, Convert-XmlToJson, Convert-CliXmlToJson -Alias *
# SIG # Begin signature block
# MIIRDAYJKoZIhvcNAQcCoIIQ/TCCEPkCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUQEwDNGO0rcSlYCAALQChdbKr
# D4Oggg5CMIIHBjCCBO6gAwIBAgIBFTANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQG
# EwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERp
# Z2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2Vy
# dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDcxMDI0MjIwMTQ1WhcNMTIxMDI0MjIw
# MTQ1WjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzAp
# BgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRlIFNpZ25pbmcxODA2BgNV
# BAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJbnRlcm1lZGlhdGUgT2JqZWN0
# IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyiOLIjUemqAbPJ1J
# 0D8MlzgWKbr4fYlbRVjvhHDtfhFN6RQxq0PjTQxRgWzwFQNKJCdU5ftKoM5N4YSj
# Id6ZNavcSa6/McVnhDAQm+8H3HWoD030NVOxbjgD/Ih3HaV3/z9159nnvyxQEckR
# ZfpJB2Kfk6aHqW3JnSvRe+XVZSufDVCe/vtxGSEwKCaNrsLc9pboUoYIC3oyzWoU
# TZ65+c0H4paR8c8eK/mC914mBo6N0dQ512/bkSdaeY9YaQpGtW/h/W/FkbQRT3sC
# pttLVlIjnkuY4r9+zvqhToPjxcfDYEf+XD8VGkAqle8Aa8hQ+M1qGdQjAye8OzbV
# uUOw7wIDAQABo4ICfzCCAnswDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAQYwHQYD
# VR0OBBYEFNBOD0CZbLhLGW87KLjg44gHNKq3MIGoBgNVHSMEgaAwgZ2AFE4L7xqk
# QFulF2mHMMo0aEPQQa7yoYGBpH8wfTELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0
# YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRl
# IFNpZ25pbmcxKTAnBgNVBAMTIFN0YXJ0Q29tIENlcnRpZmljYXRpb24gQXV0aG9y
# aXR5ggEBMAkGA1UdEgQCMAAwPQYIKwYBBQUHAQEEMTAvMC0GCCsGAQUFBzAChiFo
# dHRwOi8vd3d3LnN0YXJ0c3NsLmNvbS9zZnNjYS5jcnQwYAYDVR0fBFkwVzAsoCqg
# KIYmaHR0cDovL2NlcnQuc3RhcnRjb20ub3JnL3Nmc2NhLWNybC5jcmwwJ6AloCOG
# IWh0dHA6Ly9jcmwuc3RhcnRzc2wuY29tL3Nmc2NhLmNybDCBggYDVR0gBHsweTB3
# BgsrBgEEAYG1NwEBBTBoMC8GCCsGAQUFBwIBFiNodHRwOi8vY2VydC5zdGFydGNv
# bS5vcmcvcG9saWN5LnBkZjA1BggrBgEFBQcCARYpaHR0cDovL2NlcnQuc3RhcnRj
# b20ub3JnL2ludGVybWVkaWF0ZS5wZGYwEQYJYIZIAYb4QgEBBAQDAgABMFAGCWCG
# SAGG+EIBDQRDFkFTdGFydENvbSBDbGFzcyAyIFByaW1hcnkgSW50ZXJtZWRpYXRl
# IE9iamVjdCBTaWduaW5nIENlcnRpZmljYXRlczANBgkqhkiG9w0BAQUFAAOCAgEA
# UKLQmPRwQHAAtm7slo01fXugNxp/gTJY3+aIhhs8Gog+IwIsT75Q1kLsnnfUQfbF
# pl/UrlB02FQSOZ+4Dn2S9l7ewXQhIXwtuwKiQg3NdD9tuA8Ohu3eY1cPl7eOaY4Q
# qvqSj8+Ol7f0Zp6qTGiRZxCv/aNPIbp0v3rD9GdhGtPvKLRS0CqKgsH2nweovk4h
# fXjRQjp5N5PnfBW1X2DCSTqmjweWhlleQ2KDg93W61Tw6M6yGJAGG3GnzbwadF9B
# UW88WcRsnOWHIu1473bNKBnf1OKxxAQ1/3WwJGZWJ5UxhCpA+wr+l+NbHP5x5XZ5
# 8xhhxu7WQ7rwIDj8d/lGU9A6EaeXv3NwwcbIo/aou5v9y94+leAYqr8bbBNAFTX1
# pTxQJylfsKrkB8EOIx+Zrlwa0WE32AgxaKhWAGho/Ph7d6UXUSn5bw2+usvhdkW4
# npUoxAk3RhT3+nupi1fic4NG7iQG84PZ2bbS5YxOmaIIsIAxclf25FwssWjieMwV
# 0k91nlzUFB1HQMuE6TurAakS7tnIKTJ+ZWJBDduUbcD1094X38OvMO/++H5S45Ki
# 3r/13YTm0AWGOvMFkEAF8LbuEyecKTaJMTiNRfBGMgnqGBfqiOnzxxRVNOw2hSQp
# 0B+C9Ij/q375z3iAIYCbKUd/5SSELcmlLl+BuNknXE0wggc0MIIGHKADAgECAgFR
# MA0GCSqGSIb3DQEBBQUAMIGMMQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRD
# b20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2ln
# bmluZzE4MDYGA1UEAxMvU3RhcnRDb20gQ2xhc3MgMiBQcmltYXJ5IEludGVybWVk
# aWF0ZSBPYmplY3QgQ0EwHhcNMDkxMTExMDAwMDAxWhcNMTExMTExMDYyODQzWjCB
# qDELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5ldyBZb3JrMRcwFQYDVQQHEw5XZXN0
# IEhlbnJpZXR0YTEtMCsGA1UECxMkU3RhcnRDb20gVmVyaWZpZWQgQ2VydGlmaWNh
# dGUgTWVtYmVyMRUwEwYDVQQDEwxKb2VsIEJlbm5ldHQxJzAlBgkqhkiG9w0BCQEW
# GEpheWt1bEBIdWRkbGVkTWFzc2VzLm9yZzCCASIwDQYJKoZIhvcNAQEBBQADggEP
# ADCCAQoCggEBAMfjItJjMWVaQTECvnV/swHQP0FTYUvRizKzUubGNDNaj7v2dAWC
# rAA+XE0lt9JBNFtCCcweDzphbWU/AAY0sEPuKobV5UGOLJvW/DcHAWdNB/wRrrUD
# dpcsapQ0IxxKqpRTrbu5UGt442+6hJReGTnHzQbX8FoGMjt7sLrHc3a4wTH3nMc0
# U/TznE13azfdtPOfrGzhyBFJw2H1g5Ag2cmWkwsQrOBU+kFbD4UjxIyus/Z9UQT2
# R7bI2R4L/vWM3UiNj4M8LIuN6UaIrh5SA8q/UvDumvMzjkxGHNpPZsAPaOS+RNmU
# Go6X83jijjbL39PJtMX+doCjS/lnclws5lUCAwEAAaOCA4EwggN9MAkGA1UdEwQC
# MAAwDgYDVR0PAQH/BAQDAgeAMDoGA1UdJQEB/wQwMC4GCCsGAQUFBwMDBgorBgEE
# AYI3AgEVBgorBgEEAYI3AgEWBgorBgEEAYI3CgMNMB0GA1UdDgQWBBR5tWPGCLNQ
# yCXI5fY5ViayKj6xATCBqAYDVR0jBIGgMIGdgBTQTg9AmWy4SxlvOyi44OOIBzSq
# t6GBgaR/MH0xCzAJBgNVBAYTAklMMRYwFAYDVQQKEw1TdGFydENvbSBMdGQuMSsw
# KQYDVQQLEyJTZWN1cmUgRGlnaXRhbCBDZXJ0aWZpY2F0ZSBTaWduaW5nMSkwJwYD
# VQQDEyBTdGFydENvbSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eYIBFTCCAUIGA1Ud
# IASCATkwggE1MIIBMQYLKwYBBAGBtTcBAgEwggEgMC4GCCsGAQUFBwIBFiJodHRw
# Oi8vd3d3LnN0YXJ0c3NsLmNvbS9wb2xpY3kucGRmMDQGCCsGAQUFBwIBFihodHRw
# Oi8vd3d3LnN0YXJ0c3NsLmNvbS9pbnRlcm1lZGlhdGUucGRmMIG3BggrBgEFBQcC
# AjCBqjAUFg1TdGFydENvbSBMdGQuMAMCAQEagZFMaW1pdGVkIExpYWJpbGl0eSwg
# c2VlIHNlY3Rpb24gKkxlZ2FsIExpbWl0YXRpb25zKiBvZiB0aGUgU3RhcnRDb20g
# Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgUG9saWN5IGF2YWlsYWJsZSBhdCBodHRw
# Oi8vd3d3LnN0YXJ0c3NsLmNvbS9wb2xpY3kucGRmMGMGA1UdHwRcMFowK6ApoCeG
# JWh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL2NydGMyLWNybC5jcmwwK6ApoCeGJWh0
# dHA6Ly9jcmwuc3RhcnRzc2wuY29tL2NydGMyLWNybC5jcmwwgYkGCCsGAQUFBwEB
# BH0wezA3BggrBgEFBQcwAYYraHR0cDovL29jc3Auc3RhcnRzc2wuY29tL3N1Yi9j
# bGFzczIvY29kZS9jYTBABggrBgEFBQcwAoY0aHR0cDovL3d3dy5zdGFydHNzbC5j
# b20vY2VydHMvc3ViLmNsYXNzMi5jb2RlLmNhLmNydDAjBgNVHRIEHDAahhhodHRw
# Oi8vd3d3LnN0YXJ0c3NsLmNvbS8wDQYJKoZIhvcNAQEFBQADggEBACY+J88ZYr5A
# 6lYz/L4OGILS7b6VQQYn2w9Wl0OEQEwlTq3bMYinNoExqCxXhFCHOi58X6r8wdHb
# E6mU8h40vNYBI9KpvLjAn6Dy1nQEwfvAfYAL8WMwyZykPYIS/y2Dq3SB2XvzFy27
# zpIdla8qIShuNlX22FQL6/FKBriy96jcdGEYF9rbsuWku04NqSLjNM47wCAzLs/n
# FXpdcBL1R6QEK4MRhcEL9Ho4hGbVvmJES64IY+P3xlV2vlEJkk3etB/FpNDOQf8j
# RTXrrBUYFvOCv20uHsRpc3kFduXt3HRV2QnAlRpG26YpZN4xvgqSGXUeqRceef7D
# dm4iTdHK5tIxggI0MIICMAIBATCBkjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoT
# DVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmlj
# YXRlIFNpZ25pbmcxODA2BgNVBAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJ
# bnRlcm1lZGlhdGUgT2JqZWN0IENBAgFRMAkGBSsOAwIaBQCgeDAYBgorBgEEAYI3
# AgEMMQowCKACgAChAoAAMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3AgEEMBwGCisG
# AQQBgjcCAQsxDjAMBgorBgEEAYI3AgEWMCMGCSqGSIb3DQEJBDEWBBQybJOKytsl
# 0qQUbi9ZGVemJ1YWUTANBgkqhkiG9w0BAQEFAASCAQBb0RGdp22rRJn1s0dAqzr4
# p4HjXhElzqfkoISZcw3jDonRZKm3lseub3FQYvBx8uUIhM8oExM3hO/PoF8TMBrw
# oX64F8+A/CD24AtjgDdtgFyuSCUCCev5p4BcP6yFOiQmwUwL2dwIJfr+6QlC0UYP
# NgTnT6ojU3WU6zvZoN6ouSTiwNW5qN+iFBOTpg0PfYVBnszuYoC33KL29W+BFlVY
# LK7pH4b/G1LddffE4gm0ZDJIMfP5OgXKA1GjpZuaoxi2xVW7hm8p/XaTdjDWmZB9
# OCMgSYtbrGKfw7Db1segy8gGq4ImvMQVNcYs+nXZ+hK7EgL+lWqXxNarIBoj9Imp
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Bootstrap psake w_ PsGet.ps1
|
Bootstrap psake w_ PsGet.ps1
|
function Get-MyModule {
param ([string] $name)
write-host "Is '$name' already imported? " -NoNewline -ForegroundColor Cyan
if (-not(Get-Module -name $name)) {
write-host "No." -ForegroundColor Red
write-host "Can we import '$name'? " -NoNewline
if (Get-Module -ListAvailable | Where-Object {$_.Name -eq $name}) {
write-host "Yes. Importing '$name'." -ForegroundColor Green
import-module -name $name
return $true
}
else {
write-host "No. It is not available locally." -ForegroundColor Cyan
return $false
}
}
else {
write-host "Yes." -ForegroundColor Green
return $true
}
}
function ContainsAny( [string]$s, [string[]] $items) {
$matches = @($items | where { $_.Contains( $s ) })
return [bool]$matches
}
# detect if psake is available
if (-not(Get-MyModule -name psake)) {
#detect if PsGet available
if (-not(Get-MyModule -name PsGet)) {
write-host "Downloading and installing PsGet from repository..." -ForegroundColor Yellow
(new-object Net.WebClient).DownloadString("http://psget.net/GetPsGet.ps1") | iex
import-module PsGet
}
write-host "Installing psake..." -ForegroundColor Yellow
install-module psake
}
import-module psake
$output = invoke-psake
if (ContainsAny "Cannot bind argument to parameter 'Path' because it is an empty string." $output) {
write-host "We need to patch psake.psm1... " -ForegroundColor Red -NoNewline
$psakePath = "~\\Documents\\WindowsPowerShell\\Modules\\psake\\psake.psm1"
(get-content $psakePath) | ForEach-Object { return $_.Replace("[Parameter(Position = 0, Mandatory = 0)][string] `$buildFile,", "[Parameter(Position = 0, Mandatory = 0)][string] `$buildFile = `"default.ps1`",")} | Set-Content $psakePath
import-module psake -Force
$output = invoke-psake
if (ContainsAny "Cannot bind argument to parameter 'Path' because it is an empty string." $output) {
write-host "patch was unsuccessful!" -ForegroundColor Red
}
else {
write-host "patch was successfully applied." -ForegroundColor Green
}
}
write-host "Invoke-Psake available as alias 'psake'" -ForegroundColor Cyan
new-alias psake invoke-psake -Scope "Global"
|
PowerShellCorpus/PoshCode/SearchZIP.psm1 Module Fi.ps1
|
SearchZIP.psm1 Module Fi.ps1
|
function SearchZIPfiles {
<#
.SYNOPSIS
Search for (filename) strings inside compressed ZIP or RAR files.
.DESCRIPTION
In any directory containing a large number of ZIP/RAR compressed Web Page files
this procedure will search each individual file name for simple text strings,
listing both the source RAR/ZIP file and the individual file name containing
the string. The relevant RAR/ZIP can then be subsequently opened in the usual
way.
Using the '-Table' switch will show the results with the Out-GridView display.
.EXAMPLE
extract -find 'library' -path d:\\scripts
Searching for 'library' - please wait... (Use CTRL+C to quit)
[Editor.zip] File: Windows 7 Library Procedures.mht
[Editor.rar] File: My Library collection from 1974 Idi Amin.html
[Test2.rar] File: Playlists from library - Windows 7 Forums.mht
[Test3.rar] File: Module library functions UserGroup.pdf
A total of 4 matches for 'library' found in folder 'D:\\Scripts'.
.EXAMPLE
extract -find 'backup' -path desktop
Searching for 'backup' - please wait... (Use CTRL+C to quit)
[Web.zip] File: How To Backup User and System Files.mht
[Pages.rar] File: Create an Image Backup.pdf
A total of 2 matches for 'backup' found in folder 'C:\\Users\\Sam\\Desktop'.
.NOTES
The first step will find any lines containing the selected pattern (which can
be anywhere in the line). Each of these lines will then be split into 2
headings: Source and Filename.
Note that there may be the odd occasion where a 'non-readable' character in the
returned string slips through the net!
.LINK
Web Address Http://www.SeaStarDevelopment.BraveHost.com
#>
[CmdletBinding()]
param([string][string][Parameter(Mandatory=$true)]$Find,
[string][ValidateNotNullOrEmpty()]$path = $pwd,
[switch]$table)
[int]$count = 0
if ($path -like 'desk*') {
$path = Join-Path $home 'desktop\\*'
}
else {
$path = Join-Path $path '*'
}
if (!(Test-path $path)) {
Write-Warning "Path '$($path.Replace('\\*',''))' is invalid - resubmit"
return
}
$folder = $path.Replace('*','')
$lines = @{}
$regex = '(?s)^(?<zip>.+?\\.(?:zip|rar)):(?:\\d+):.*\\\\(?<file>.*\\.(mht|html?|pdf))(.*)$'
Get-ChildItem $path -include '*.rar','*.zip' |
Select-String -SimpleMatch -Pattern $find |
foreach-Object `
-begin { Write-Host "Searching for '$find' - please wait... (Use CTRL+C to quit)" } `
-process {
$_ = $_ -replace '/','\\'
if ( $_ -match $regex ) {
$source = $matches.zip.Replace($folder,'')
$file = $matches.file
$file = $file -replace '\\s+',' ' #Single space words.
$file = $file -replace '\\p{S}',' ' #Remove some 'Dingbats'.
if ($table) {
$key = "{0:D4}" -f $count
$lines["$key $source"] = $file #Create a unique key.
}
else {
Write-Host "[$source] File: $file"
}
$count++
}
} `
-end {
$title = "A total of $($count) matches for '$find' found in host folder '$($path.Replace('\\*',''))'."
if ($table -and ($lines.count -gt 0)) {
$lines.GetEnumerator() |
Select-Object @{name = 'Source';expression = {$_.Key.SubString(5)}},
@{name = 'File' ;expression = {$_.Value}} |
Sort-Object File |
Out-GridView -Title $title
}
else {
Write-Host $title
}
}
} #End function.
New-Alias extract SearchZIPfiles -Description 'Find Web files inside ZIP/RAR'
Export-ModuleMember -Function SearchZIPfiles -Alias Extract
|
PowerShellCorpus/PoshCode/Copy files _1.ps1
|
Copy files _1.ps1
|
cls
<#
Writer: Ritesh P.
#>
# Core Declaration
$date = ((get-date).toString('MM-dd-yyyy'))
$time = ((Get-Date).toString('HH-mm-ss'))
#$what = "/COPYALL /S /B"
#$options = "/R:0 /W:0 /FP"
$NewDestinationPath = '\\\\'+'infra'+'\\c$\\data1\\'+$date+'-'+$time #
When I add $time to create Destination folder, Which protect
from folder duplication and also saved 8line of for loop code ;)
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++
$servers = 'infra'
foreach($Server in $Servers)
{
$sourceFolder = '\\\\'+$server+'\\c$\\data\\'
if (Test-Path $sourceFolder){
$desti=
$NewDestinationPath+'\\'+$Server
robocopy.exe
$sourceFolder $desti '*pub*.txt' /COPYALL /S /B /R:0 /W:0 /FP
/LOG:$date-$time-$server-'robocopy_log'.txt
#Write-output "Files
found:" on $sourceFolder __ | Out-File
$NewDestinationPath'\\'log_$date.txt -Append
}
else{
#"Files does not exist on $server " |
Out-File $NewDestinationPath'\\'Failed_BOS_$date.txt -Append
}
}
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++
# Email Declaration
#$file = c:\\scripts\\PublicFolderData\\log.txt
$smtpServer = “infra.al.com”
$msg = new-object Net.Mail.MailMessage
#$att = new-object Net.Mail.Attachment($file)
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = “BOS_Space_Report@al.com”
$msg.To.Add('riteshp@al.com')
$msg.Subject = “BOS Private Space Utilization Report”
#$msg.IsBodyHtml = $true
$msg.Body = "BOS Private Folder Utilization Space Report
Generated `n " + $desti
$msg.Body += "Log files located at
\\\\infra\\c$\\script\\publicfolderdata\\servername+date+robo_logfile.tx
t"
#$msg.Body = Get-Content "c:\\data\\body.txt"
#$msg.Attachments.Add($att)
$smtp.Send($msg)
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++
<#
"My pain may be the reason for
somebody's laugh
But my laugh must never be the
reason for somebody's pain"
-Charlie Chaplin
#>
|
PowerShellCorpus/PoshCode/Set-KeepAliveTime_1.ps1
|
Set-KeepAliveTime_1.ps1
|
<#
.SYNOPSIS
Change the setting for TCPIP KeepAliveTime on a server or several
servers.
.DESCRIPTION
Change the setting for TCPIP KeepAliveTime on a server or several
servers.
When moving mailboxes with large number of folders or very large number
of items it can take a very long time to enumerate the items. Sometimes
it takes over 2 hours and the connection times out.
We set the TCOPIP KeepAliveTime to it's max for the move or we reset
it back to normal after a move is complete.
.PARAMETER Name
A collection of servers to set, reset, or read the KeepAliveTime
registry setting.
.PARAMETER KeepAliveTime
The value to set KeepAliveTime. (A decimal number can be used.)
Default is '0x000dbba0' - 15 Minutes
0x000dbba0 ( 900000 decimal) 15 mnutes
0x006ddd00 (7200000 decimal) is the installed default setting of 2 hours
.PARAMETER ReadOnly
Read the KeepAliveTime setting for each server in the collection of
Servers
(should be a "get" but I am too lazy to write another script.)
.PARAMETER Hours
Set the collection of servers to TCPIP KeepAliveTime of <N> hours.
.PARAMETER Max
Set the collection of servers to the maximum TCPIP KeepAliveTime setting.
Defined as 0xffffffff - essentially "Forever"
.EXAMPLE
$Servers = Get-MailboxServer | ?{$_.AdminDisplayVersion -match "^Version 14"}
Set-KeepAliveTime -Name $Servers
Sets the KeepAliveTime on all the Mailbox servers to the Default setting.
.EXAMPLE
$servers = get-mailboxserver | ?{$_.AdminDisplayVersion -match "^Version 14"}
Set-KeepAliveTime -Name $Servers -Max
Sets the KeepAliveTime on all the Mailbox servers to the Maximum setting.
.EXAMPLE
$servers = Get-ExchangeServer |?{$_.ServerRole -ne "Mailbox" -and $_.AdminDisplayVersion -match "^Version 14"}
Set-KeepAliveTime -Name $Servers -Reset
Sets the KeepAliveTime on all the Exchamge 2010 Servers servers (CAS, HUB,
Mailbox)to the reset setting. Which can be different from default.
Suppose you find a setting of 4 hours is fine for moving large mailboxes.
Change the script to
The 21600000 for 6 hours
.NOTES
This script requires PSRemoteRegistry
http://psremoteregistry.codeplex.com/releases/view/65928
Explaination for TCPIP settings:
http://technet.microsoft.com/en-us/library/dd349797(v=WS.10).aspx
Microsoft recomends is 5 Minutes for KeepAliveTime (2/17/2010)
HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Services\\Tcpip\\Parameters\\
KeepAliveTime | Reg_DWORD | 0x000493e0 (300000)
Symantec recomends 15 minutes (July 15, 2011)
HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Services\\Tcpip\\Parameters\\
KeepAliveTime | Reg_DWORD | 0x000dbba0 (900000)
We use Symantic's recomendation as our default.
#>
[CmdletBinding()]
Param (
[Parameter(Position = 0, Mandatory = $true,ValueFromPipeLineByPropertyName=$true)]
[String[]]
$Name,
[Parameter(Position = 1, Mandatory = $false)]
[String]
$KeepAliveTime = '0x000dbba0',
[Parameter(Position = 3, Mandatory = $false)]
[ValidateRange(1,24)]
[Int]
$Hours = 0,
[Parameter(Position = 2, Mandatory = $false)]
[Switch]
$ReadOnly,
[Parameter(Position = 4, Mandatory = $false)]
[Switch]
$Max
)
#inorder to user PSRemoteRegistry Module you must be running from <server>
# this was to keep my helpers in check, of course, do whatever you need to do
if($(Hostname) -match '<server>') {
Import-Module PSRemoteRegistry
} Else {
Write-Warning "You must run this on <server> to work."
Exit
}
# Location of KeepAliveTime Value
$Key = 'System\\CurrentControlSet\\Services\\Tcpip\\Parameters\\'
$Value = 'KeepAliveTime'
if ($Name){
ForEach ($Server in $Name) {
if (Test-Connection -Count 1 -Quiet -ComputerName $Server){
if ($ReadOnly){
Write-Verbose "Checking Server: $($Server)"
Get-RegValue -ComputerName $Server -Key $key -Value $Value
} ElseIf ($Max){
$KeepAliveTime = '0xffffffff'
Write-Verbose "Set Max Server: $($Server)"
Set-RegDWord -ComputerName $Server -Key $Key -Value $Value -Data $KeepAliveTime -Force
} Else {
If ($Hours -gt 0){
$KeepAliveTime = 3600000*$Hours
Write-Verbose "Set Server: $($Server) to $($Hours) hours"
Set-RegDWord -ComputerName $Server -Key $Key -Value $Value -Data $KeepAliveTime -Force
} Else {
Set-RegDWord -ComputerName $Server -Key $Key -Value $Value -Data $KeepAliveTime -Force
}
}
} Else {
Write-Warning "Server $($Server) is not responding to pings."
}
}
} Else {
Write-Warning "Could not find any servers to process."
}
|
PowerShellCorpus/PoshCode/Script-Object_1.ps1
|
Script-Object_1.ps1
|
#Copyright (c) 2011 Justin Dearing
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in
#all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#THE SOFTWARE.
param(
[Parameter(Mandatory=$true, HelpMessage='The name of the stored procedure or user defined function to script')]
[string] $ProcedureName,
[string] $Path = "$($ProcedureName).sql",
[string] $ConnectionString = 'Data Source=.\\sqlexpress2k8R2;Initial Catalog=master;Integrated Security=SSPI;'
);
try {
[System.Data.SqlClient.SqlConnection] $cn = New-Object System.Data.SqlClient.SqlConnection (,$ConnectionString);
$cn.Open() > $null;
$cmd = $cn.CreateCommand();
$cmd.CommandType = [System.Data.CommandType]::StoredProcedure;
$cmd.CommandText = 'sp_helptext';
$cmd.Parameters.AddWithValue('@objname', $ProcedureName) > $null;
[System.Data.IDataReader] $rdr = $cmd.ExecuteReader();
[string] $sproc_text = '';
while ($rdr.Read()) {
$sproc_text += $rdr[0];
}
$rdr.Close();
$sproc_text | Out-File -FilePath $Path;
}
finally {
if ($cmd -ne $null) { $cmd.Dispose(); }
if ($cn -ne $null) { $cn.Dispose(); }
}
|
PowerShellCorpus/PoshCode/Show-ADObject.ps1
|
Show-ADObject.ps1
|
# Author: Steven Murawski http://www.mindofroot.com
# This script requires the modified Show-NetMap script (originally from Doug Finke)
# Show-NodeXLMap which can be found on http://poshcode.org/733
# and the NodeXL files
# These can be found at http://www.codeplex.com/NodeXL/Release/ProjectReleases.aspx?ReleaseId=20494
#
# Also required are the Quest AD Cmdlets.
#requires -pssnapin Quest.ActiveRoles.ADManagement
param ($ADClass, $MapLayout= "circular", [switch]$help, [switch]$ShowADClass, [switch]$Colorize, [switch]$NoTest)
function Write-Help()
{
$ExampleUsage = @'
To use this script, you will need the Show-Netmap script from Doug Finke,
along with the NodeXL DLLs.
Downloadable from http://www.codeplex.com/NodeXL/Release/ProjectReleases.aspx?ReleaseId=20494
Usage:
.\\Show-ADObject.ps1 -ADClass [(AD Type Name || Array of AD Type Names}] [-Colorize]
.\\Show-ADObject.ps1 -ShowADClasses
Example:
.\\Show-ADObject -ADClass group, organizationalunit -Colorize
'@
Write-Host $ExampleUsage
}
#Check to see if the required files are present to run the script.
function Test-Prerequisites()
{
$required = @{ShowNetMap = 'Show-NodeXLMap.ps1';
NetMapApp = 'Microsoft.NodeXL.ApplicationUtil.dll';
NetMapControl = 'Microsoft.NodeXL.Control.dll';
NetMapCore = 'Microsoft.NodeXL.Core.dll';
NetMapUtil = 'Microsoft.NodeXL.Util.dll';
NetMapVisual = 'Microsoft.NodeXL.Visualization.dll'
}
$report = @()
foreach ($key in $required.Keys)
{
$file = $required[$($key)]
if (Test-Path $file )
{
Write-Debug "Found $file"
}
else
{
$report += "Missing $file"
}
}
if ($report.count -eq 0)
{
Write-Debug "All prerequisites were found."
return $true
}
else
{
Write-Help
Write-Host "Missing files: "
$report | ForEach-Object { Write-Host "`tMissing $_" }
throw "Please move the needed files into the current directory!"
}
}
#If all the prereq's are in the local directory and the script was not run
#with the -help switch, load everything up!
if ($NoTest -or (Test-Prerequisites))
{
[Reflection.Assembly]::LoadWithPartialName("System.Drawing") | Out-Null
#This is just a helper function to find the parent of an object based on the parent's distinguished name
function Get-ParentFromDN()
{
PROCESS
{
$root = '^DC=(\\w+),DC=(\\w+)$'
$pattern = '^(OU|CN)=(\\w+?),.*?DC=\\w+?,DC=\\w+?$'
$dn = $_
if ($dn -notmatch $root)
{
$dn -replace $pattern, '$2'
}
else
{
$dn -replace $root, '$1.$2'
}
}
}
#This will return an array of all the Object Classes in your Active Directory
function Get-ADObjectClassName()
{
Get-QADObject -SizeLimit 0 | Select-Object -property @{name='Name';Expression={$_.type}} -unique | Sort-Object name
}
function Get-ColorList()
{
[System.Drawing.Color] | Get-Member -memberType property -static | foreach {$_.name}
}
function Get-RandomColor()
{
param($ListOfColors)
$count = $ListOfColors.count-1
$rand = New-Object System.Random
$value = $rand.next(0,$count)
$ListOfColors[$value]
}
function Get-ADMapObject()
{
param($TypesToMap=$(Throw 'One (or more object types as an array) are required to run this function'), [switch]$Color)
$script:ColorKey = @{}
if ($TypesToMap -is [string])
{
if ($color)
{
$MapColor = Get-RandomColor Get-ColorList
$script:ColorKey["$TypesToMap"] = $MapColor
Get-QADObject -Type $TypesToMap | select Name, @{name='Parent';Expression={$_.ParentContainerDN | Get-ParentFromDN}}, @{name='Color';Expression={$MapColor}}
}
else
{
Get-QADObject -Type $TypesToMap | select Name, @{name='Parent';Expression={$_.ParentContainerDN | Get-ParentFromDN}}
}
}
else
{
$colorList = Get-ColorList
foreach ( $type in $TypesToMap )
{
if ($color)
{
$MapColor = Get-RandomColor $colorList
$colorList = $colorList | ? {$_ -ne $MapColor}
$script:ColorKey["$type"] = $MapColor
Get-QADObject -Type $type | select Name, @{name='Parent';Expression={$_.ParentContainerDN | Get-ParentFromDN}}, @{name='Color';Expression={$MapColor}}
}
else
{
Get-QADObject -Type $type | select Name, @{name='Parent';Expression={$_.ParentContainerDN | Get-ParentFromDN}}
}
}
}
}
#Helper function stolen from Doug Finke and used to create the objects to feed to
#Show-Netmap
function New-SourceTarget ($s,$t,$c)
{
New-Object PSObject |
Add-Member -pass noteproperty source $s |
Add-Member -pass noteproperty target $t |
Add-Member -pass noteproperty color $c
}
if ($help)
{
Write-Help
}
else
{
if ($ShowADClass)
{
Get-ADObjectClassName
}
else
{
#Add the Show-Netmap functions from Doug Finke
. .\\Show-NodeXLMap.ps1
if ($Colorize)
{
$MapObjects = Get-ADMapObject -TypesToMap $ADClass -Color | % { New-SourceTarget $_.Name $_.Parent $_.Color }
Write-Host "Color Key: "
$ColorKey
}
else
{
$MapObjects = Get-ADMapObject -TypesToMap $ADClass | % { New-SourceTarget $_.Name $_.Parent }
}
$MapObjects | Show-NodeXLMap -layoutType $MapLayout
}
}
}
|
PowerShellCorpus/PoshCode/Get-ProcessCount_1.ps1
|
Get-ProcessCount_1.ps1
|
# Get-ProcessCount uses 2 main variables, server and process name.
# Process name is typically the end exe, such as "svchost.exe"
# Will accept unnamed args (Get-ProcessCount servername processname)
# or named args (Get-ProcessCount -Computer servername -Process processname)
Function Get-ProcessCount([string]$process, [string]$computer = "localhost", [switch]$guess) {
if($guess) {
$clause = [string]::Format("like '%{0}%'",$process)
}
else {
$clause = [string]::Format("='{0}'",$process)
}
#using string.Format can be vary to do variable substitution
$selectstring = [string]::Format("select * from Win32_Process where name {0}",
$clause)
$result = get-wmiobject -query $selectstring -ComputerName $computer
# I really like the group-object cmdlet for reporting stuff
@@ if($result) { $result | Group-Object Name }
else { Write "Process $process could not be found" }
}
|
PowerShellCorpus/PoshCode/SqlProxy_2.psm1.ps1
|
SqlProxy_2.psm1.ps1
|
# ---------------------------------------------------------------------------
### <Author>
### Chad Miller
### </Author>
### <Description>
### Based on functions in SQLPSX. SqlProxy.psm1 module is used for administering
### SQL Server logins, users, and roles. Designed to be used with PS Remoting.
### All actions audited to a custom Eventlog.
### See Write-SqlProxyLog for log setup details
### </Description>
# ---------------------------------------------------------------------------
try {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop}
catch {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo"}
try {add-type -AssemblyName "Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop; $smoVersion = 10}
catch {add-type -AssemblyName "Microsoft.SqlServer.Smo"; $smoVersion = 9}
try {add-type -AssemblyName "Microsoft.SqlServer.SqlEnum, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop; $smoVersion = 10}
catch {add-type -AssemblyName "Microsoft.SqlServer.SqlEnum"; $smoVersion = 9}
try
{
try {add-type -AssemblyName "Microsoft.SqlServer.SMOExtended, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop}
catch {add-type -AssemblyName "Microsoft.SqlServer.SMOExtended" -EA Stop}
}
catch {Write-Warning "SMOExtended not available"}
$EventID = @{
"Add-SqlDatabaseRoleMember"=0
"Add-SqlLogin"=1
"Add-SqlServerRoleMember"=2
"Add-SqlUser"=3
"Remove-SqlDatabaseRoleMember"=4
"Remove-SqlLogin"=5
"Remove-SqlServerRoleMember"=6
"Remove-SqlUser"=7
"Rename-SqlLogin"=8
"Set-SqlLogin"=9
"Set-SqlLoginDefaultDatabase"=10
}
#######################
<#
.SYNOPSIS
Gets a ServerConnection.
.DESCRIPTION
The Get-SqlConnection function gets a ServerConnection to the specified SQL Server.
.INPUTS
None
You cannot pipe objects to Get-SqlConnection
.OUTPUTS
Microsoft.SqlServer.Management.Common.ServerConnection
Get-SqlConnection returns a Microsoft.SqlServer.Management.Common.ServerConnection object.
.EXAMPLE
Get-SqlConnection "Z002\\sql2K8"
This command gets a ServerConnection to SQL Server Z002\\SQL2K8.
.EXAMPLE
Get-SqlConnection "Z002\\sql2K8" "sa" "Passw0rd"
This command gets a ServerConnection to SQL Server Z002\\SQL2K8 using SQL authentication.
.LINK
Get-SqlConnection
#>
function Get-SqlConnection
{
param(
[Parameter(Position=0, Mandatory=$true)] [string]$sqlserver,
[Parameter(Position=1, Mandatory=$false)] [string]$username,
[Parameter(Position=2, Mandatory=$false)] [string]$password
)
Write-Verbose "Get-SqlConnection $sqlserver"
try {
if($Username -and $Password)
{ $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $sqlserver,$username,$password }
else
{ $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $sqlserver }
$con.Connect()
Write-Output $con
}
catch { $message = $_.Exception.GetBaseException().Message
write-error $message
}
} #Get-ServerConnection
#######################
<#
.SYNOPSIS
Gets an SMO Server object.
.DESCRIPTION
The Get-SqlServer function gets a SMO Server object for the specified SQL Server.
.INPUTS
None
You cannot pipe objects to Get-SqlServer
.OUTPUTS
Microsoft.SqlServer.Management.Smo.Server
Get-SqlServer returns a Microsoft.SqlServer.Management.Smo.Server object.
.EXAMPLE
Get-SqlServer "Z002\\sql2K8"
This command gets an SMO Server object for SQL Server Z002\\SQL2K8.
.EXAMPLE
Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd"
This command gets a SMO Server object for SQL Server Z002\\SQL2K8 using SQL authentication.
.LINK
Get-SqlServer
#>
function Get-SqlServer
{
param(
[Parameter(Position=0, Mandatory=$true)] [string]$sqlserver,
[Parameter(Position=1, Mandatory=$false)] [string]$username,
[Parameter(Position=2, Mandatory=$false)] [string]$password,
[Parameter(Position=3, Mandatory=$false)] [string]$StatementTimeout=0
)
#When $sqlserver passed in from the SMO Name property, brackets
#are automatically inserted which then need to be removed
$sqlserver = $sqlserver -replace "\\[|\\]"
Write-Verbose "Get-SqlServer $sqlserver"
$con = Get-SqlConnection $sqlserver $Username $Password
$server = new-object ("Microsoft.SqlServer.Management.Smo.Server") $con
#Some operations might take longer than the default timeout of 600 seconnds (10 minutes). Set new default to unlimited
$server.ConnectionContext.StatementTimeout = $StatementTimeout
$server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.StoredProcedure], "IsSystemObject")
$server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.Table], "IsSystemObject")
$server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.View], "IsSystemObject")
$server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.UserDefinedFunction], "IsSystemObject")
#trap { "Check $SqlServer Name"; continue} $server.ConnectionContext.Connect()
Write-Output $server
} #Get-SqlServer
#######################
<#
.SYNOPSIS
Gets an SMO Database object.
.DESCRIPTION
The Get-SqlDatabase function gets an SMO Database object for the specified SQL Database or collection of Database objects.
.INPUTS
None
You cannot pipe objects to Get-SqlDatabase
.OUTPUTS
Microsoft.SqlServer.Management.Smo.Database
Get-SqlDatabase returns a Microsoft.SqlServer.Management.Smo.Database object.
.EXAMPLE
Get-SqlDatabase "Z002\\sql2K8"
This command gets a collection of SMO Database objects for SQL Server Z002\\SQL2K8.
.EXAMPLE
Get-SqlDatabase $(Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd") "pubs"
This command gets a SMO Database object for SQL database pubs on the SQL Server Z002\\SQL2K8 using SQL authentication.
.LINK
Get-SqlDatabase
#>
function Get-SqlDatabase
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$false)] [string]$dbname,
[Parameter(Position=2, Mandatory=$false)] [switch]$force
)
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Get-SqlDatabase:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Get-SqlDatabase $($server.Name) $dbname"
if ($dbname)
{ if ($server.Databases.Contains("$dbname") -and $server.Databases[$dbname].IsAccessible)
{$server.Databases[$dbname]}
else
{throw "Database $dname does not exist or is not accessible."}
}
elseif ($force)
{ $server.Databases | where {$_.IsAccessible -eq $true} }
#Skip systems databases
else
{ $server.Databases | where {$_.IsSystemObject -eq $false -and $_.IsAccessible -eq $true} }
} # Get-SqlDatabase
#######################
<#
.SYNOPSIS
Executes a query and returns an array of System.Data.DataRow.
.DESCRIPTION
The Get-SqlData function executes a query and returns an array of System.Data.DataRow.
.INPUTS
None
You cannot pipe objects to Get-SqlData
.OUTPUTS
System.Data.DataRow
Get-SqlData returns an array of System.Data.DataRow.
.EXAMPLE
Get-SqlData "Z002\\sql2K8" "pubs" "select * from authors"
This command executes the specified SQL query using Windows authentication.
.EXAMPLE
$server = Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd"
Get-SqlData $server "pubs" "select * from authors"
This command executes the specified SQL query using SQL authentication.
.LINK
Get-SqlData
#>
function Get-SqlData
{
param(
[Parameter(Position=0, Mandatory=$false)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] $dbname,
[Parameter(Position=2, Mandatory=$true)] [string]$qry
)
switch ($dbname.GetType().Name)
{
'String' { $database = Get-SqlDatabase $sqlserver $dbname }
'Database' { $database = $dbname }
default { throw "Get-SqlData:Param '`$dbname' must be a String or Database object." }
}
#Write-Verbose "Get-SqlData $($database.Parent.Name) $($database.Name) $qry"
Write-Verbose "Get-SqlData $($database.Parent.Name) $($database.Name)"
$ds = $database.ExecuteWithResults("$qry")
$ds.Tables | foreach { $_.Rows}
}# Get-SqlData
#######################
<#
.SYNOPSIS
Executes a query that does not return a result set.
.DESCRIPTION
The Set-SqlData function executes a query that does not return a result set.
.INPUTS
None
You cannot pipe objects to Set-SqlData
.OUTPUTS
None
Set-SqlData does not produce any output.
.EXAMPLE
Set-SqlData "Z002\\sql2K8" "pubs" "Update authors set au_lname = 'Brown' WHERE au_lname = 'White'"
This command executes the specified SQL query using Windows authentication.
.EXAMPLE
$server = Set-SqlServer "Z002\\sql2K8" "sa" "Passw0rd"
Set-SqlData $server "pubs" "Update authors set au_lname = 'Brown' WHERE au_lname = 'White'"
This command executes the specified SQL query using SQL authentication.
.LINK
Set-SqlData
#>
function Set-SqlData
{
param(
[Parameter(Position=0, Mandatory=$false)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$dbname,
[Parameter(Position=2, Mandatory=$true)] [string]$qry
)
switch ($dbname.GetType().Name)
{
'String' { $database = Get-SqlDatabase $sqlserver $dbname }
'Database' { $database = $dbname }
default { throw "Set-SqlData:Param '`$dbname' must be a String or Database object." }
}
#Write-Verbose "Set-SqlData $($database.Parent.Name) $($database.Name) $qry"
Write-Verbose "Set-SqlData $($database.Parent.Name) $($database.Name)"
$database.ExecuteNonQuery("$qry")
}# Set-SqlData
#######################
<#
.SYNOPSIS
Gets an SMO Login object.
.DESCRIPTION
The Get-SqlLogin function gets a collection of SMO Login objects for the specified SQL Server.
.INPUTS
None
You cannot pipe objects to Get-SqlLogin
.OUTPUTS
Microsoft.SqlServer.Management.Smo.Login
Get-SqlLogin returns a Microsoft.SqlServer.Management.Smo.Login object.
.EXAMPLE
Get-SqlLogin "Z002\\sql2K8"
This command gets a collection of SMO Login objects for SQL Server Z002\\SQL2K8.
.LINK
Get-SqlLogin
#>
function Get-SqlLogin
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver
)
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Get-SqlLogin:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Get-SqlLogin $($server.Name)"
foreach ($login in $server.Logins | where {$_.LoginType.ToString() -ne 'Certificate'})
{
#Return Login Object
$login
}
} # Get-SqlLogin
#######################
<#
.SYNOPSIS
Adds a login to a SQL Server.
.DESCRIPTION
The Add-SqlLogin function adds a new login to the specified SQL server.
.INPUTS
None
You cannot pipe objects to Add-SqlLogin
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Add-SqlLogin "Z002\\sql2k8" "TestPSUnit" "SQLPSXTesting" 'SqlLogin'
This command adds the TestPSUnit login to the Z002\\sql2k8 server.
.EXAMPLE
$server = Get-SqlServer "Z002\\sql2k8"
Add-SqlLogin $server "TestPSUnit" "SQLPSXTesting" 'SqlLogin'
This command adds the TestPSUnit login to the Z002\\sql2k8 server.
.LINK
Add-SqlLogin
#>
function Add-SqlLogin
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$name,
[Parameter(Position=2, Mandatory=$false)] [System.Security.SecureString]$password,
[Parameter(Position=3, Mandatory=$false)] [Microsoft.SqlServer.Management.Smo.LoginType]$logintype='WindowsUser',
[Parameter(Position=4, Mandatory=$false)] [string]$DefaultDatabase='master',
[Parameter(Position=5, Mandatory=$false)] [switch]$PasswordExpirationEnabled,
[Parameter(Position=6, Mandatory=$false)] [switch]$PasswordPolicyEnforced,
[Parameter(Position=7, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=8, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Add-SqlLogin:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Add-SqlLogin $($server.Name) $name"
$login = new-object ('Microsoft.SqlServer.Management.Smo.Login') $server, $name
$login.DefaultDatabase = $defaultDatabase
if ($logintype -eq 'SqlLogin')
{
$login.LoginType = $logintype
if ($server.Information.Version.Major -ne '8')
{
$login.PasswordExpirationEnabled = $($PasswordExpirationEnabled.IsPresent)
$login.PasswordPolicyEnforced = $($PasswordPolicyEnforced.IsPresent)
}
try {
$login.Create($password)
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
}
elseif ($logintype -eq 'WindowsUser' -or $logintype -eq 'WindowsGroup')
{
$login.LoginType = $logintype
try {
$login.Create()
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | % {"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
}
} #Add-SqlLogin
#######################
<#
.SYNOPSIS
Removes a login from a SQL Server.
.DESCRIPTION
The Remove-SqlLogin function removes a login from the specified SQL server.
.INPUTS
None
You cannot pipe objects to Remove-SqlLogin
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Remove-SqlLogin "Z002\\sql2k8" "TestPSUnit"
This command removes the TestPSUnit login from the Z002\\sql2k8 server.
.EXAMPLE
$server = Get-SqlServer "Z002\\sql2k8"
Remove-SqlLogin $server "TestPSUnit"
This command removes the TestPSUnit login from the Z002\\sql2k8 server.
.LINK
Remove-SqlLogin
#>
function Remove-SqlLogin
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$name,
[Parameter(Position=2, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=3, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Remove-SqlLogin:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Remove-SqlLogin $($server.Name) $name"
$login = Get-SqlLogin $server | where {$_.name -eq $name}
try {
if ($login) {
$login.Drop()
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "Login $name does not exist on server $($server.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
} #Remove-SqlLogin
#######################
<#
.SYNOPSIS
Removes a login from a SQL Server.
.DESCRIPTION
The Set-SqlLogin function changes a SQL Login Password.
.INPUTS
None
You cannot pipe objects to Set-SqlLogin
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
$pwd_secure_string = read-host "Enter a Password:" -assecurestring
Set-SqlLogin "Z002\\sql2k8" "TestPSUnit" $pwd_secure_string
This command sets the password for TestPSUnit login.
.LINK
Set-SqlLogin
#>
function Set-SqlLogin
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$name,
[Parameter(Position=2, Mandatory=$true)] [System.Security.SecureString]$password,
[Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=4, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Set-SqlLogin:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Set-SqlLogin $($server.Name) $name"
$login = Get-SqlLogin $server | where {$_.name -eq $name}
try {
if ($login) {
$login.ChangePassword($password,$true,$false)
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "Login $name does not exist on server $($server.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
} #Set-SqlLogin
#######################
<#
.SYNOPSIS
Removes a login from a SQL Server.
.DESCRIPTION
The Set-SqlLoginDefaultDatabase function changes a SQL Login default database.
.INPUTS
None
You cannot pipe objects to Set-SqlLoginDefaultDatabase
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Set-SqlLoginDefaultDatabase "Z002\\sql2k8" "TestPSUnit" 'master'
This command sets the default database for TestPSUnit login.
.LINK
Set-SqlLoginDefaultDatabase
#>
function Set-SqlLoginDefaultDatabase
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$name,
[Parameter(Position=2, Mandatory=$true)] [string]$DefaultDatabase,
[Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=4, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Set-SqlLoginDefaultDatabase:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Set-SqlLoginDefaultDatabase $($server.Name) $name"
$login = Get-SqlLogin $server | where {$_.name -eq $name}
try {
if ($login) {
$login.DefaultDatabase = $DefaultDatabase
$login.Alter()
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "Login $name does not exist on server $($server.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
} #Set-SqlLoginDefaultDatabase
#######################
<#
.SYNOPSIS
Removes a login from a SQL Server.
.DESCRIPTION
The Rename-SqlLogin function renames a SQL Login.
.INPUTS
None
You cannot pipe objects to Rename-SqlLogin
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Rename-SqlLogin "Z002\\sql2k8" "TestPSUnit" "CheckPSUnit"
This command renames the login TestPSUnit.
.LINK
Rename-SqlLogin
#>
function Rename-SqlLogin
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$name,
[Parameter(Position=2, Mandatory=$true)] [string]$newname,
[Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=4, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Rename-SqlLogin:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Rename-SqlLogin $($server.Name) $name $newname"
$login = Get-SqlLogin $server | where {$_.name -eq $name}
try {
if ($login) {
$login.Rename("$newName")
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "Login $name does not exist on server $($server.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
} #Rename-SqlLogin
#######################
<#
.SYNOPSIS
Adds a new user to a database.
.DESCRIPTION
The Add-SqlUser function adds a new user to the specified database.
.INPUTS
None
You cannot pipe objects to Add-SqlUser
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Add-SqlUser "Z002\\sql2k8" "pubs" "TestPSUnit"
This command adds the TestPSUnit login to the pubs database.
.EXAMPLE
$database = Get-SqlDatabase "Z002\\sql2k8" "pubs"
Add-SqlUser -dbname $database "TestPSUnit"
This command adds the TestPSUnit login to the pubs database.
.LINK
Add-SqlUser
#>
function Add-SqlUser
{
param(
[Parameter(Position=0, Mandatory=$false)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] $dbname,
[Parameter(Position=2, Mandatory=$true)] [string]$name,
[Parameter(Position=3, Mandatory=$false)] [string]$login=$name,
[Parameter(Position=4, Mandatory=$false)] [string]$defaultSchema='dbo',
[Parameter(Position=5, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=6, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($dbname.GetType().Name)
{
'String' { $database = Get-SqlDatabase $sqlserver $dbname }
'Database' { $database = $dbname }
default { throw "Add-SqlUser:Param '`$dbname' must be a String or Database object." }
}
Write-Verbose "Add-SqlUser $($database.Name) $name"
$user = new-object ('Microsoft.SqlServer.Management.Smo.User') $database, $name
$user.Login = $login
if ($db.parent.Information.Version.Major -ne '8')
{ $user.DefaultSchema = $defaultschema }
try {
$user.Create()
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
} #Add-SqlUser
#######################
<#
.SYNOPSIS
Removes a user from a database.
.DESCRIPTION
The Remove-SqlUser function removes a user from the specified database.
.INPUTS
None
You cannot pipe objects to Remove-SqlUser
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Remove-SqlUser "Z002\\sql2k8" "pubs" "TestPSUnit"
This command Removes the TestPSUnit user from the pubs database.
.EXAMPLE
$database = Get-SqlDatabase "Z002\\sql2k8" "pubs"
Remove-SqlUser -dbname $database "TestPSUnit"
This command Removes the TestPSUnit user from the pubs database.
.LINK
Remove-SqlUser
#>
function Remove-SqlUser
{
param(
[Parameter(Position=0, Mandatory=$false)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] $dbname,
[Parameter(Position=2, Mandatory=$true)] [string]$name,
[Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=4, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($dbname.GetType().Name)
{
'String' { $database = Get-SqlDatabase $sqlserver $dbname }
'Database' { $database = $dbname }
default { throw "Remove-SqlUser:Param '`$dbname' must be a String or Database object." }
}
Write-Verbose "Remove-SqlUser $($database.Name) $name"
$user = $database.Users[$name]
try {
if ($user) {
$user.Drop()
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "User $name does not exist in database $($database.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
} #Remove-SqlUser
#######################
<#
.SYNOPSIS
Gets an SMO ServerRole object.
.DESCRIPTION
The Get-SqlServerRole function gets a collection of SMO ServerRole objects for the specified SQL Server.
.INPUTS
None
You cannot pipe objects to Get-SqlServerRole
.OUTPUTS
Microsoft.SqlServer.Management.Smo.ServerRole
Get-SqlServerRole returns a Microsoft.SqlServer.Management.Smo.ServerRole object.
.EXAMPLE
Get-SqlServerRole "Z002\\sql2K8"
This command gets a collection of SMO ServerRole objects for SQL Server Z002\\SQL2K8.
.LINK
Get-SqlServerRole
#>
function Get-SqlServerRole
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver
)
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Get-SqlServerRole:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Get-SqlServerRole $($server.Name)"
foreach ($svrole in $server.Roles)
{
#Return ServerRole Object
$svrole
}
} #Get-SqlServerRole
#######################
<#
.SYNOPSIS
Adds a login to a server role.
.DESCRIPTION
The Add-SqlServerRoleMember function adds a login to the specified server role.
.INPUTS
None
You cannot pipe objects to Add-SqlServerRoleMember
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Add-SqlServerRoleMember "Z002\\sql2k8" "TestPSUnit" "bulkadmin"
This command adds the TestPSUnit login to the bulkadmin server role.
.EXAMPLE
$server = Get-SqlServer "Z002\\sql2k8"
Add-SqlServerRoleMember $server "TestPSUnit" "bulkadmin"
This command adds the TestPSUnit login to the bulkadmin server role.
.LINK
Add-SqlServerRoleMember
#>
function Add-SqlServerRoleMember
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$loginame,
[Parameter(Position=2, Mandatory=$true)] [string]$rolename,
[Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=4, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Add-SqlServerRoleMember:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Add-SqlServerRoleMember $($server.Name) $name"
if($server.Logins | where {$_.name -eq $loginame})
{
$svrole = Get-SqlServerRole $server | where {$_.name -eq $rolename}
try {
if ($svrole) {
$svrole.AddMember($loginame)
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "ServerRole $rolename does not exist on server $($server.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
}
else
{ throw "Login $loginame does not exist on server $($server.Name)." }
} #Add-SqlServerRoleMember
#######################
<#
.SYNOPSIS
Removes a login from a server role.
.DESCRIPTION
The Remove-SqlServerRoleMember function removes a login from the specified server role.
.INPUTS
None
You cannot pipe objects to Remove-SqlServerRoleMember
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Remove-SqlServerRoleMember "Z002\\sql2k8" "TestPSUnit" "bulkadmin"
This command Removes the TestPSUnit login from the bulkadmin server role.
.EXAMPLE
$server = Get-SqlServer "Z002\\sql2k8"
Remove-SqlServerRoleMember $server "TestPSUnit" "bulkadmin"
This command Removes the TestPSUnit login from the bulkadmin server role.
.LINK
Remove-SqlServerRoleMember
#>
function Remove-SqlServerRoleMember
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$loginame,
[Parameter(Position=2, Mandatory=$true)] [string]$rolename,
[Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=4, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Remove-SqlServerRoleMember:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Remove-SqlServerRoleMember $($server.Name) $name"
if($server.Logins | where {$_.name -eq $loginame})
{
$svrole = Get-SqlServerRole $server | where {$_.name -eq $rolename}
try {
if ($svrole) {
$svrole.DropMember($loginame)
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "ServerRole $rolename does not exist on server $($server.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
}
else
{ throw "Login $loginame does not exist on server $($server.Name)." }
} #Remove-SqlServerRoleMember
#######################
<#
.SYNOPSIS
Returns a SMO DatabaseRole object with additional properties.
.DESCRIPTION
The Get-SqlDatabaseRole function gets a collection of SMO DatabaseRole objects for the specified SQL Database.
.INPUTS
Microsoft.SqlServer.Management.Smo.Database
You can pipe database objects to Get-SqlDatabaseRole
.OUTPUTS
Microsoft.SqlServer.Management.Smo.DatabaseRole
Get-SqlDatabaseRole returns a Microsoft.SqlServer.Management.Smo.DatabaseRole object.
.EXAMPLE
Get-SqlDatabaseRole $(Get-SqlDatabase "Z002\\sql2K8" pubs)
This command gets a collection of SMO DatabaseRole objects for SQL Server Z002\\SQL2K8, pubs database.
.EXAMPLE
Get-SqlDatabase "Z002\\sql2K8" | Get-SqlDatabaseRole
This command gets a collection SMO DatabaseRole objects for all SQL databases on the SQL Server Z002\\SQL2K8.
.LINK
Get-SqlDatabaseRole
#>
function Get-SqlDatabaseRole
{
param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)] [Microsoft.SqlServer.Management.Smo.Database]$database
)
process
{
foreach ($role in $database.Roles)
{
#Return DatabaseRole Object
$role
}
}
} #Get-SqlDatabaseRole
#######################
<#
.SYNOPSIS
Adds a user or role to a database role.
.DESCRIPTION
The Add-SqlDatabaseRoleMember function adds a user or role to the specified database role.
.INPUTS
None
You cannot pipe objects to Add-SqlDatabaseRoleMember
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Add-SqlDatabaseRoleMember "Z002\\sql2k8" "pubs" "TestPSUnit" "TestPSUnitDBRole"
This command adds the TestUnit user to the TestPSUnitDBRole database role.
.EXAMPLE
$database = Get-SqlDatabase "Z002\\sql2k8" "pubs"
Add-SqlDatabaseRoleMember -dbname $database -name "TestPSUnit" -rolename "TestPSUnitDBRole"
This command adds the TestUnit user to the TestPSUnitDBRole database role.
.LINK
Add-SqlDatabaseRoleMember
#>
function Add-SqlDatabaseRoleMember
{
param(
[Parameter(Position=0, Mandatory=$false)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] $dbname,
[Parameter(Position=2, Mandatory=$true)] [string]$name,
[Parameter(Position=3, Mandatory=$true)] [string]$rolename,
[Parameter(Position=4, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=5, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($dbname.GetType().Name)
{
'String' { $database = Get-SqlDatabase $sqlserver $dbname }
'Database' { $database = $dbname }
default { throw "Add-SqlDatabaseRoleMember:Param '`$dbname' must be a String or Database object." }
}
Write-Verbose "Add-SqlDatabaseRoleMember $($database.Name) $name $rolename"
if(($database.Users | where {$_.name -eq $name}) -or ($database.Roles | where {$_.name -eq $name}))
{
$role = Get-SqlDatabaseRole $database | where {$_.name -eq $rolename}
try {
if ($role) {
$role.AddMember($name)
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "DatabaseRole $rolename does not exist in database $($database.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
}
else
{ throw "Role or User $name does not exist in database $($database.Name)." }
} #Add-SqlDatabaseRoleMember
#######################
<#
.SYNOPSIS
Removes a user or role from a database role.
.DESCRIPTION
The Remove-SqlDatabaseRoleMember function removes a user or role from the specified database role.
.INPUTS
None
You cannot pipe objects to Remove-SqlDatabaseRoleMember
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Remove-SqlDatabaseRoleMember "Z002\\sql2k8" "pubs" "TestPSUnit" "TestPSUnitDBRole"
This command removes the TestUnit user to the TestPSUnitDBRole database role.
.EXAMPLE
$database = Get-SqlDatabase "Z002\\sql2k8" "pubs"
Remove-SqlDatabaseRoleMember -dbname $database -name "TestPSUnit" -rolename "TestPSUnitDBRole"
This command removes the TestUnit user to the TestPSUnitDBRole database role.
.LINK
Remove-SqlDatabaseRoleMember
#>
function Remove-SqlDatabaseRoleMember
{
param(
[Parameter(Position=0, Mandatory=$false)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] $dbname,
[Parameter(Position=2, Mandatory=$true)] [string]$name,
[Parameter(Position=3, Mandatory=$true)] [string]$rolename,
[Parameter(Position=4, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=5, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($dbname.GetType().Name)
{
'String' { $database = Get-SqlDatabase $sqlserver $dbname }
'Database' { $database = $dbname }
default { throw "Remove-SqlDatabaseRoleMember:Param '`$dbname' must be a String or Database object." }
}
Write-Verbose "Remove-SqlDatabaseRoleMember $($database.Name) $name $rolename"
if(($database.Users | where {$_.name -eq $name}) -or ($database.Roles | where {$_.name -eq $name}))
{
$role = Get-SqlDatabaseRole $database | where {$_.name -eq $rolename}
try {
if ($role) {
$role.DropMember($name)
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "DatabaseRole $rolename does not exist in database $($database.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
}
else
{ throw "Role or User $name does not exist in database $($database.Name)." }
} #Remove-SqlDatabaseRoleMember
#######################
<#
.SYNOPSIS
Writes an entry to SqlProxy Log File.
.DESCRIPTION
The Write-SqlProxyLog function writes an entry to the SqlProxy Log File.
.INPUTS
None
You cannot pipe objects to Write-SqlProxyLog
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
$message = "PSUserName=$PSUserName`n" + $($psBoundParameters.GetEnumerator() | %{"$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message
This command writes a message to the SQLProxy Log
.NOTES
This must be run as administrator to create the new EventLog and EventLog Source!!!
New-EventLog -LogName SqlProxy -Source SqlProxy
.LINK
Write-SqlProxyLog
#>
function Write-SqlProxyLog
{
param(
[Parameter(Position=0, Mandatory=$true)] $EventID,
[Parameter(Position=1, Mandatory=$true)] $Message,
[Parameter(Position=2, Mandatory=$false)] $EntryType='SuccessAudit'
)
write-eventlog -logname SqlProxy -source SqlProxy -eventID $eventID -message $message -EntryType $EntryType
} #Write-SqlProxyLog
|
PowerShellCorpus/PoshCode/Create-Certificate.ps1
|
Create-Certificate.ps1
|
#####################################################################
# Create PowerShell cert.ps1
# Version 1.0
#
# Creates self-signed signing certificate and install it to certificate store
#
# Note: Requires at least Windows Vista. Windows XP/Windows Server 2003
# are not supported.
#
# Vadims Podans (c) 2010
# http://www.sysadmins.lv/
#####################################################################
#requires -Version 2.0
function New-SigningCert {
<#
.Synopsis
Creates self-signed signing certificate and install it to certificate store
.Description
This function generates self-signed certificate with some pre-defined and
user-definable settings. User may elect to perform complete certificate
installation, by installing generated certificate to Trusted Root Certification
Authorities and Trusted Publishers containers in *current user* store.
.Parameter Subject
Specifies subject for certificate. This parameter must be entered in X500
Distinguished Name format. Default is: CN=PowerShell User, OU=Test Signing Cert.
.Parameter KeyLength
Specifies private key length. Due of performance and security reasons, only
1024 and 2048 bit are supported. by default 1024 bit key length is used.
.Parameter NotBefore
Sets the date in local time on which a certificate becomes valid. By default
current date and time is used.
.Parameter NotAfter
Sets the date in local time after which a certificate is no longer valid. By
default certificate is valid for 365 days.
.Parameter Force
If Force switch is asserted, script will prepare certificate for use by adding
it to Trusted Root Certification Authorities and Trusted Publishers containers
in current user certificate store. During certificate installation you will be
prompted to confirm if you want to add self-signed certificate to Trusted Root
Certification Authorities container.
#>
[CmdletBinding()]
param (
[string]$Subject = "CN=PowerShell User, OU=Test Signing Cert",
[int][ValidateSet("1024", "2048")]$KeyLength = 1024,
[datetime]$NotBefore = [DateTime]::Now,
[datetime]$NotAfter = $NotBefore.AddDays(365),
[switch]$Force
)
$OS = (Get-WmiObject Win32_OperatingSystem).Version
if ($OS[0] -lt 6) {
Write-Warning "Windows XP, Windows Server 2003 and Windows Server 2003 R2 are not supported!"
return
}
# while all certificate fields MUST be encoded in ASN.1 DER format
# we will use CryptoAPI COM interfaces to generate and encode all necessary
# extensions.
# create Subject field in X.500 format using the following interface:
# http://msdn.microsoft.com/en-us/library/aa377051(VS.85).aspx
$SubjectDN = New-Object -ComObject X509Enrollment.CX500DistinguishedName
$SubjectDN.Encode($Subject, 0x0)
# define CodeSigning enhanced key usage (actual OID = 1.3.6.1.5.5.7.3.3) from OID
# http://msdn.microsoft.com/en-us/library/aa376784(VS.85).aspx
$OID = New-Object -ComObject X509Enrollment.CObjectID
$OID.InitializeFromValue("1.3.6.1.5.5.7.3.3")
# while IX509ExtensionEnhancedKeyUsage accept only IObjectID collection
# (to support multiple EKUs) we need to create IObjectIDs object and add our
# IObjectID object to the collection:
# http://msdn.microsoft.com/en-us/library/aa376785(VS.85).aspx
$OIDs = New-Object -ComObject X509Enrollment.CObjectIDs
$OIDs.Add($OID)
# now we create Enhanced Key Usage extension, add our OID and encode extension value
# http://msdn.microsoft.com/en-us/library/aa378132(VS.85).aspx
$EKU = New-Object -ComObject X509Enrollment.CX509ExtensionEnhancedKeyUsage
$EKU.InitializeEncode($OIDs)
# generate Private key as follows:
# http://msdn.microsoft.com/en-us/library/aa378921(VS.85).aspx
$PrivateKey = New-Object -ComObject X509Enrollment.CX509PrivateKey
$PrivateKey.ProviderName = "Microsoft Base Cryptographic Provider v1.0"
# private key is supposed for signature: http://msdn.microsoft.com/en-us/library/aa379409(VS.85).aspx
$PrivateKey.KeySpec = 0x2
$PrivateKey.Length = $KeyLength
# key will be stored in current user certificate store
$PrivateKey.MachineContext = 0x0
$PrivateKey.Create()
# now we need to create certificate request template using the following interface:
# http://msdn.microsoft.com/en-us/library/aa377124(VS.85).aspx
$Cert = New-Object -ComObject X509Enrollment.CX509CertificateRequestCertificate
$Cert.InitializeFromPrivateKey(0x1,$PrivateKey,"")
$Cert.Subject = $SubjectDN
$Cert.Issuer = $Cert.Subject
$Cert.NotBefore = $NotBefore
$Cert.NotAfter = $NotAfter
$Cert.X509Extensions.Add($EKU)
# completing certificate request template building
$Cert.Encode()
# now we need to process request and build end certificate using the following
# interface: http://msdn.microsoft.com/en-us/library/aa377809(VS.85).aspx
$Request = New-Object -ComObject X509Enrollment.CX509enrollment
# process request
$Request.InitializeFromRequest($Cert)
# retrievecertificate encoded in Base64.
$endCert = $Request.CreateRequest(0x1)
# install certificate to user store
$Request.InstallResponse(0x2,$endCert,0x1,"")
if ($Force) {
# convert Bas64 string to a byte array
[Byte[]]$bytes = [System.Convert]::FromBase64String($endCert)
foreach ($Container in "Root", "TrustedPublisher") {
# open Trusted Root CAs and TrustedPublishers containers and add
# certificate
$x509store = New-Object Security.Cryptography.X509Certificates.X509Store $Container, "CurrentUser"
$x509store.Open([Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$x509store.Add([Security.Cryptography.X509Certificates.X509Certificate2]$bytes)
# close store when operation is completed
$x509store.Close()
}
}
}
# SIG # Begin signature block
# MIIVAwYJKoZIhvcNAQcCoIIU9DCCFPACAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU0KtSTs5dBa+keiTXHCrRnHa1
# bU2gghDIMIIDejCCAmKgAwIBAgIQOCXX+vhhr570kOcmtdZa1TANBgkqhkiG9w0B
# AQUFADBTMQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xKzAp
# BgNVBAMTIlZlcmlTaWduIFRpbWUgU3RhbXBpbmcgU2VydmljZXMgQ0EwHhcNMDcw
# NjE1MDAwMDAwWhcNMTIwNjE0MjM1OTU5WjBcMQswCQYDVQQGEwJVUzEXMBUGA1UE
# ChMOVmVyaVNpZ24sIEluYy4xNDAyBgNVBAMTK1ZlcmlTaWduIFRpbWUgU3RhbXBp
# bmcgU2VydmljZXMgU2lnbmVyIC0gRzIwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJ
# AoGBAMS18lIVvIiGYCkWSlsvS5Frh5HzNVRYNerRNl5iTVJRNHHCe2YdicjdKsRq
# CvY32Zh0kfaSrrC1dpbxqUpjRUcuawuSTksrjO5YSovUB+QaLPiCqljZzULzLcB1
# 3o2rx44dmmxMCJUe3tvvZ+FywknCnmA84eK+FqNjeGkUe60tAgMBAAGjgcQwgcEw
# NAYIKwYBBQUHAQEEKDAmMCQGCCsGAQUFBzABhhhodHRwOi8vb2NzcC52ZXJpc2ln
# bi5jb20wDAYDVR0TAQH/BAIwADAzBgNVHR8ELDAqMCigJqAkhiJodHRwOi8vY3Js
# LnZlcmlzaWduLmNvbS90c3MtY2EuY3JsMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMI
# MA4GA1UdDwEB/wQEAwIGwDAeBgNVHREEFzAVpBMwETEPMA0GA1UEAxMGVFNBMS0y
# MA0GCSqGSIb3DQEBBQUAA4IBAQBQxUvIJIDf5A0kwt4asaECoaaCLQyDFYE3CoIO
# LLBaF2G12AX+iNvxkZGzVhpApuuSvjg5sHU2dDqYT+Q3upmJypVCHbC5x6CNV+D6
# 1WQEQjVOAdEzohfITaonx/LhhkwCOE2DeMb8U+Dr4AaH3aSWnl4MmOKlvr+ChcNg
# 4d+tKNjHpUtk2scbW72sOQjVOCKhM4sviprrvAchP0RBCQe1ZRwkvEjTRIDroc/J
# ArQUz1THFqOAXPl5Pl1yfYgXnixDospTzn099io6uE+UAKVtCoNd+V5T9BizVw9w
# w/v1rZWgDhfexBaAYMkPK26GBPHr9Hgn0QXF7jRbXrlJMvIzMIIDxDCCAy2gAwIB
# AgIQR78Zld+NUkZD99ttSA0xpDANBgkqhkiG9w0BAQUFADCBizELMAkGA1UEBhMC
# WkExFTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTEUMBIGA1UEBxMLRHVyYmFudmlsbGUx
# DzANBgNVBAoTBlRoYXd0ZTEdMBsGA1UECxMUVGhhd3RlIENlcnRpZmljYXRpb24x
# HzAdBgNVBAMTFlRoYXd0ZSBUaW1lc3RhbXBpbmcgQ0EwHhcNMDMxMjA0MDAwMDAw
# WhcNMTMxMjAzMjM1OTU5WjBTMQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNp
# Z24sIEluYy4xKzApBgNVBAMTIlZlcmlTaWduIFRpbWUgU3RhbXBpbmcgU2Vydmlj
# ZXMgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCpyrKkzM0grwp9
# iayHdfC0TvHfwQ+/Z2G9o2Qc2rv5yjOrhDCJWH6M22vdNp4Pv9HsePJ3pn5vPL+T
# rw26aPRslMq9Ui2rSD31ttVdXxsCn/ovax6k96OaphrIAuF/TFLjDmDsQBx+uQ3e
# P8e034e9X3pqMS4DmYETqEcgzjFzDVctzXg0M5USmRK53mgvqubjwoqMKsOLIYdm
# vYNYV291vzyqJoddyhAVPJ+E6lTBCm7E/sVK3bkHEZcifNs+J9EeeOyfMcnx5iIZ
# 28SzR0OaGl+gHpDkXvXufPF9q2IBj/VNC97QIlaolc2uiHau7roN8+RN2aD7aKCu
# FDuzh8G7AgMBAAGjgdswgdgwNAYIKwYBBQUHAQEEKDAmMCQGCCsGAQUFBzABhhho
# dHRwOi8vb2NzcC52ZXJpc2lnbi5jb20wEgYDVR0TAQH/BAgwBgEB/wIBADBBBgNV
# HR8EOjA4MDagNKAyhjBodHRwOi8vY3JsLnZlcmlzaWduLmNvbS9UaGF3dGVUaW1l
# c3RhbXBpbmdDQS5jcmwwEwYDVR0lBAwwCgYIKwYBBQUHAwgwDgYDVR0PAQH/BAQD
# AgEGMCQGA1UdEQQdMBukGTAXMRUwEwYDVQQDEwxUU0EyMDQ4LTEtNTMwDQYJKoZI
# hvcNAQEFBQADgYEASmv56ljCRBwxiXmZK5a/gqwB1hxMzbCKWG7fCCmjXsjKkxPn
# BFIN70cnLwA4sOTJk06a1CJiFfc/NyFPcDGA8Ys4h7Po6JcA/s9Vlk4k0qknTnqu
# t2FB8yrO58nZXt27K4U+tZ212eFX/760xX71zwye8Jf+K9M7UhsbOCf3P0owggSn
# MIIDj6ADAgECAgphnWDwAAAAAAACMA0GCSqGSIb3DQEBBQUAMH4xCzAJBgNVBAYT
# AkxWMRUwEwYDVQQKEwxTeXNhZG1pbnMgTFYxHDAaBgNVBAsTE0luZm9ybWF0aW9u
# IFN5c3RlbXMxOjA4BgNVBAMTMVN5c2FkbWlucyBMViBDbGFzcyAxIFJvb3QgQ2Vy
# dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAwNDE0MTc0MTE2WhcNMjAwNDE0MTYy
# NTU1WjByMQswCQYDVQQGEwJMVjEVMBMGA1UEChMMU3lzYWRtaW5zIExWMRwwGgYD
# VQQLExNJbmZvcm1hdGlvbiBTeXN0ZW1zMS4wLAYDVQQDEyVTeXNhZG1pbnMgTFYg
# SW50ZXJuYWwgQ2xhc3MgMSBTdWJDQS0xMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
# MIIBCgKCAQEAuHHw5SbkYZip0ZeLh2vKLXT6U5FHwKZDWGhqD5fFRKvMdwbhcDOj
# WDkMFLAGAOaut0nRsdtWn59vghcZxbHQGNaB1otcnL9cVgliGKaKiP/i3GbXwpOC
# RIOeVoldKpSOR1qlN8AWTXUXpjRBUp5Dgymi0Cnj7kKpn1w45Iea49oIHGUM8v64
# NHrpY6rv9EQDyE98/qjMMpHZkJlOAeGm+mL1bgyGWGg0kXyBYOZ/e7xCOia70u0+
# t5aUdWgAx2SSIuUholnyBStGMPcPrJtUVHk9Ygdc/W8Dg7bZQPFGDioPvYNI35v6
# fceKi7cSgtwj8xqRqG7cynfqx2lnqSLFjQIDAQABo4IBMTCCAS0wEAYJKwYBBAGC
# NxUBBAMCAQAwHQYDVR0OBBYEFBv6XnMtZxNcztMO5uh6qWCMC2P8MBkGCSsGAQQB
# gjcUAgQMHgoAUwB1AGIAQwBBMAsGA1UdDwQEAwIBhjAPBgNVHRMBAf8EBTADAQH/
# MB8GA1UdIwQYMBaAFE1IjcunX0Cos22iqY5OcfxPFhnUMDYGA1UdHwQvMC0wK6Ap
# oCeGJWh0dHA6Ly93d3cuc3lzYWRtaW5zLmx2L3BraS9yY2EtMS5jcmwwaAYIKwYB
# BQUHAQEEXDBaMDEGCCsGAQUFBzAChiVodHRwOi8vd3d3LnN5c2FkbWlucy5sdi9w
# a2kvcmNhLTEuY3J0MCUGCCsGAQUFBzABhhlodHRwOi8vb2NzcC5zeXNhZG1pbnMu
# bHYvMA0GCSqGSIb3DQEBBQUAA4IBAQCscUpz7yWwjkKRDmaolN9o0HjU6FvRfXAz
# EkL9JuymyDN/fvFfCHqqM49GNGAlh2ESemHisfS2Gf/dS0B8uSYSxiaNH8RSOOK1
# Tr8xvr+W/2vsVBiYFA0/SciJStBjBrcOKhwy2zW/dQMOEX86qPyEKqGAR1gsyNsO
# yABSBFCRsK3Tw+tlbRXldyj2pYBt1XxHuzPiZMA1Zz8O4rwcJRNLD6KNi49K49c7
# S1/9GEyT31TRTAx08VgLzLZ6kCSToGHM/mLeNUpW2ondzje6nqdBmxRHg++wrAKX
# 05DRuRri8MAVtaBwHxgQb+RO6KqZNoSVHZJ/0b7SSaZQgQW66zXXMIIE0zCCA7ug
# AwIBAgIKYTydVQAAAAAAEzANBgkqhkiG9w0BAQUFADByMQswCQYDVQQGEwJMVjEV
# MBMGA1UEChMMU3lzYWRtaW5zIExWMRwwGgYDVQQLExNJbmZvcm1hdGlvbiBTeXN0
# ZW1zMS4wLAYDVQQDEyVTeXNhZG1pbnMgTFYgSW50ZXJuYWwgQ2xhc3MgMSBTdWJD
# QS0xMB4XDTEwMDQxNTE3NDA1NloXDTE1MDQxNDE3NDA1NlowWjELMAkGA1UEBxMC
# TFYxFTATBgNVBAoTDFN5c2FkbWlucyBMVjEcMBoGA1UECxMTSW5mb3JtYXRpb24g
# U3lzdGVtczEWMBQGA1UEAxMNVmFkaW1zIFBvZGFuczCCASIwDQYJKoZIhvcNAQEB
# BQADggEPADCCAQoCggEBAIcw8V5Bjn11ZLAG/GhiQ+y7CEpYt/Z6alFQdkBNPSHu
# WMC+ebPUQgEky57JOeo9DeXUv8+rOxOt1thptEDEIZ5tJQHhSxLEfoxLSHQCkn4O
# mQXk6q/UZWfvktv73k2Rq+xdtvmMFTH4xqvhddVma6MeKEBWPu5URhT7wvnI+cGh
# 5TeE8kmErq/E2hVIOeZ1r85IC1naBiV4VxJMMQkePswBTYCAcjYCT1UU8GihEdgq
# 8dClNmsE2a/dYNoTktxIGUk2wFnP/ptSEtrlzhczKa5WDlGeuMx62lfRuTfzq+gO
# zk4JDleud6NPqqIijh/iYBS+qJ+4GexYPL0wZCdTPVUCAwEAAaOCAYEwggF9MDsG
# CSsGAQQBgjcVBwQuMCwGJCsGAQQBgjcVCJadTYWSsni9nzyF6Ox0gs7YRHqCqvdC
# h+fENgIBZAIBAzAfBgNVHSUEGDAWBgorBgEEAYI3CgMMBggrBgEFBQcDAzAOBgNV
# HQ8BAf8EBAMCB4AwKQYJKwYBBAGCNxUKBBwwGjAMBgorBgEEAYI3CgMMMAoGCCsG
# AQUFBwMDMB0GA1UdDgQWBBQsddpa07a5NYAClLLmLzGiK9dXmTAfBgNVHSMEGDAW
# gBQb+l5zLWcTXM7TDuboeqlgjAtj/DA3BgNVHR8EMDAuMCygKqAohiZodHRwOi8v
# d3d3LnN5c2FkbWlucy5sdi9wa2kvcGljYS0xLmNybDBpBggrBgEFBQcBAQRdMFsw
# MgYIKwYBBQUHMAKGJmh0dHA6Ly93d3cuc3lzYWRtaW5zLmx2L3BraS9waWNhLTEu
# Y3J0MCUGCCsGAQUFBzABhhlodHRwOi8vb2NzcC5zeXNhZG1pbnMubHYvMA0GCSqG
# SIb3DQEBBQUAA4IBAQBJ2bGbZu+3T+0ZJXOTSjQfXfAcBzzqHM+R16Up6qXkjUnQ
# gguINT/1Ktqr3y7SdPGkyHZytqz0ABwr/hgZ1bdl4WaV9xpy4oJni7wU4Gq6Mh8Q
# zvhGwrQmQifbRyumM/EKMzyYZU+KkD7TAHoN1CiEGhiEyK+9OVaQNxAxwO3jmWWN
# cj2Q86YrV7r+XzkAU/N6gSeVUXii5eGA30wQNnCWQd2cTzL9tHdNH8t4qKN9Lhij
# t0EoxGEZYGDniROmIYlIwZUj6nU/XsmeHyJ5vpcvBxu12AVQMNIUY+HzCLStKnCy
# Sd1htmJBemlaam0OPeYp7QSUKgwzm1+gK813GUzKMYIDpTCCA6ECAQEwgYAwcjEL
# MAkGA1UEBhMCTFYxFTATBgNVBAoTDFN5c2FkbWlucyBMVjEcMBoGA1UECxMTSW5m
# b3JtYXRpb24gU3lzdGVtczEuMCwGA1UEAxMlU3lzYWRtaW5zIExWIEludGVybmFs
# IENsYXNzIDEgU3ViQ0EtMQIKYTydVQAAAAAAEzAJBgUrDgMCGgUAoHgwGAYKKwYB
# BAGCNwIBDDEKMAigAoAAoQKAADAZBgkqhkiG9w0BCQMxDAYKKwYBBAGCNwIBBDAc
# BgorBgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQUin+n
# vVp8jJLwSWikhJbHlH09Hy4wDQYJKoZIhvcNAQEBBQAEggEAGtWm9io5wvAkVWs1
# 2cHs9S9aVXvfJCSLC+EmgdTIkjms/F4/XyiETdaZw5Klh4gTunXllVEUiGzgJY3v
# q7uIAqtfanu91ttSalsaj5PKHBHpmSRTgAIxZ+lsnXpwav9dOFGgcthUgVXKlsrb
# sgKOqBYeNPN8H2aYjEyhiHEcN+Jo7hYUmzGJzZ1LCwMEpHdWartzgYOB9bdEFBZx
# DOclp4NRgP+Gp/NncXJ/xuO3/PeEZzN2LvI4SgA+wa4+Bn3zu5OuQpNBbI2gJhOg
# GERJDOSN0GoVCKYMHHetA5m4K/zxUzNWzsQiyB2Oj/FXj7dBMbS48mDs1V9k4bUw
# 66FdlKGCAX8wggF7BgkqhkiG9w0BCQYxggFsMIIBaAIBATBnMFMxCzAJBgNVBAYT
# AlVTMRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5jLjErMCkGA1UEAxMiVmVyaVNpZ24g
# VGltZSBTdGFtcGluZyBTZXJ2aWNlcyBDQQIQOCXX+vhhr570kOcmtdZa1TAJBgUr
# DgMCGgUAoF0wGAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEHATAcBgkqhkiG9w0BCQUx
# DxcNMTAwNDE4MDg0MTE0WjAjBgkqhkiG9w0BCQQxFgQUWolmHMfK7jXucZQKpMkl
# ghPrawowDQYJKoZIhvcNAQEBBQAEgYANJxNrwTB2xRLj/edK+jJOGyH33jlrT3AI
# DVCgUvAQlC7uD25l8vxKqsowovDMRodGPZqdnNGE3oLz6K4sS3RrnDTrRr6jxPwK
# bnxTDJ6oCP2ZgcwFWnxHGzH6QeLzReuy5VmGXlambWCmQgdi6OYfvCQ0uE6Kl9/a
# SBQE1dd++Q==
# SIG # End signature block
|
PowerShellCorpus/PoshCode/JSON 1.2.ps1
|
JSON 1.2.ps1
|
#requires -version 2.0
# Version History:
# v 0.5 - First Public version
# v 1.0 - Made ConvertFrom-Json work with arbitrary JSON
# - switched to xsl style sheets for ConvertTo-JSON
# v 1.1 - Changed ConvertFrom-Json to handle single item results
# v 1.2 - CodeSigned to make a fellow geek happy
# There is no help (yet) because I'm still changing and renaming everything every time I mess with this code
# Full RoundTrip capability:
#
# > ls | ConvertTo-Json | ConvertFrom-Json
# > ps | ConvertTo-Json | Convert-JsonToXml | Convert-XmlToJson | convertFrom-Json
#
# You may frequently want to use the DEPTH or NoTypeInformation parameters:
#
# > ConvertTo-Json -Depth 2 -NoTypeInformation
#
# But then you have to specify the type when you reimport (and you can't do that for deep objects).
# This problem also occurs if you convert the result of a SELECT statement (ie: PSCustomObject).
# For Example:
#
# > PS | Select PM, WS, CPU, ID, ProcessName |
# >> ConvertTo-json -NoType |
# >> convertfrom-json -Type System.Diagnostics.Process
Add-Type -AssemblyName System.ServiceModel.Web, System.Runtime.Serialization
$utf8 = [System.Text.Encoding]::UTF8
function Write-String {
PARAM(
[Parameter()]$stream,
[Parameter(ValueFromPipeline=$true)]$string
)
PROCESS {
$bytes = $utf8.GetBytes($string)
$stream.Write( $bytes, 0, $bytes.Length )
}
}
function Convert-JsonToXml {
PARAM([Parameter(ValueFromPipeline=$true)][string[]]$json)
BEGIN {
$mStream = New-Object System.IO.MemoryStream
}
PROCESS {
$json | Write-String -stream $mStream
}
END {
$mStream.Position = 0
$jsonReader = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonReader($mStream,[System.Xml.XmlDictionaryReaderQuotas]::Max)
try
{
$xml = New-Object Xml.XmlDocument
$xml.Load($jsonReader)
$xml
}
finally
{
$jsonReader.Close()
$mStream.Dispose()
}
}
}
function Convert-XmlToJson {
PARAM([Parameter(ValueFromPipeline=$true)][Xml]$xml)
PROCESS {
$mStream = New-Object System.IO.MemoryStream
$jsonWriter = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonWriter($mStream)
try
{
$xml.Save($jsonWriter)
$bytes = $mStream.ToArray()
[System.Text.Encoding]::UTF8.GetString($bytes,0,$bytes.Length)
}
finally
{
$jsonWriter.Close()
$mStream.Dispose()
}
}
}
## Rather than rewriting ConvertTo-Xml ...
Function ConvertTo-Json {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,Position=1,ValueFromPipeline=$true)]$InputObject
,
[Parameter(Mandatory=$false)][Int]$Depth=1
,
[Switch]$NoTypeInformation
)
END {
## You must output ALL the input at once
## ConvertTo-Xml outputs differently if you just have one, so your results would be different
$input | ConvertTo-Xml -Depth:$Depth -NoTypeInformation:$NoTypeInformation -As Document | Convert-CliXmlToJson
}
}
Function Convert-CliXmlToJson {
PARAM(
[Parameter(ValueFromPipeline=$true)][Xml.XmlNode]$xml
)
BEGIN {
$xmlToJsonXsl = @'
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!--
CliXmlToJson.xsl
Copyright (c) 2006,2008 Doeke Zanstra
Copyright (c) 2009 Joel Bennett
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer. Redistributions in binary
form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with
the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
-->
<xsl:output indent="no" omit-xml-declaration="yes" method="text" encoding="UTF-8" media-type="text/x-json"/>
<xsl:strip-space elements="*"/>
<!--contant-->
<xsl:variable name="d">0123456789</xsl:variable>
<!-- ignore document text -->
<xsl:template match="text()[preceding-sibling::node() or following-sibling::node()]"/>
<!-- string -->
<xsl:template match="text()">
<xsl:call-template name="escape-string">
<xsl:with-param name="s" select="."/>
</xsl:call-template>
</xsl:template>
<!-- Main template for escaping strings; used by above template and for object-properties
Responsibilities: placed quotes around string, and chain up to next filter, escape-bs-string -->
<xsl:template name="escape-string">
<xsl:param name="s"/>
<xsl:text>"</xsl:text>
<xsl:call-template name="escape-bs-string">
<xsl:with-param name="s" select="$s"/>
</xsl:call-template>
<xsl:text>"</xsl:text>
</xsl:template>
<!-- Escape the backslash (\\) before everything else. -->
<xsl:template name="escape-bs-string">
<xsl:param name="s"/>
<xsl:choose>
<xsl:when test="contains($s,'\\')">
<xsl:call-template name="escape-quot-string">
<xsl:with-param name="s" select="concat(substring-before($s,'\\'),'\\\\')"/>
</xsl:call-template>
<xsl:call-template name="escape-bs-string">
<xsl:with-param name="s" select="substring-after($s,'\\')"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="escape-quot-string">
<xsl:with-param name="s" select="$s"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- Escape the double quote ("). -->
<xsl:template name="escape-quot-string">
<xsl:param name="s"/>
<xsl:choose>
<xsl:when test="contains($s,'"')">
<xsl:call-template name="encode-string">
<xsl:with-param name="s" select="concat(substring-before($s,'"'),'\\"')"/>
</xsl:call-template>
<xsl:call-template name="escape-quot-string">
<xsl:with-param name="s" select="substring-after($s,'"')"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="encode-string">
<xsl:with-param name="s" select="$s"/>
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- Replace tab, line feed and/or carriage return by its matching escape code. Can't escape backslash
or double quote here, because they don't replace characters (� becomes \\t), but they prefix
characters (\\ becomes \\\\). Besides, backslash should be seperate anyway, because it should be
processed first. This function can't do that. -->
<xsl:template name="encode-string">
<xsl:param name="s"/>
<xsl:choose>
<!-- tab -->
<xsl:when test="contains($s,'	')">
<xsl:call-template name="encode-string">
<xsl:with-param name="s" select="concat(substring-before($s,'	'),'\\t',substring-after($s,'	'))"/>
</xsl:call-template>
</xsl:when>
<!-- line feed -->
<xsl:when test="contains($s,'
')">
<xsl:call-template name="encode-string">
<xsl:with-param name="s" select="concat(substring-before($s,'
'),'\\n',substring-after($s,'
'))"/>
</xsl:call-template>
</xsl:when>
<!-- carriage return -->
<xsl:when test="contains($s,'
')">
<xsl:call-template name="encode-string">
<xsl:with-param name="s" select="concat(substring-before($s,'
'),'\\r',substring-after($s,'
'))"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise><xsl:value-of select="$s"/></xsl:otherwise>
</xsl:choose>
</xsl:template>
<!-- number (no support for javascript mantise) -->
<xsl:template match="text()[not(string(number())='NaN' or
(starts-with(.,'0' ) and . != '0'))]">
<xsl:value-of select="."/>
</xsl:template>
<!-- boolean, case-insensitive -->
<xsl:template match="text()[translate(.,'TRUE','true')='true']">true</xsl:template>
<xsl:template match="text()[translate(.,'FALSE','false')='false']">false</xsl:template>
<!-- root object(s) -->
<xsl:template match="*" name="base">
<xsl:if test="not(preceding-sibling::*)">
<xsl:choose>
<xsl:when test="count(../*)>1"><xsl:text>[</xsl:text></xsl:when>
<xsl:otherwise><xsl:text>{</xsl:text></xsl:otherwise>
</xsl:choose>
</xsl:if>
<xsl:call-template name="escape-string">
<xsl:with-param name="s" select="name()"/>
</xsl:call-template>
<xsl:text>:</xsl:text>
<!-- check type of node -->
<xsl:choose>
<!-- null nodes -->
<xsl:when test="count(child::node())=0">null</xsl:when>
<!-- other nodes -->
<xsl:otherwise>
<xsl:apply-templates select="child::node()"/>
</xsl:otherwise>
</xsl:choose>
<!-- end of type check -->
<xsl:if test="following-sibling::*">,</xsl:if>
<xsl:if test="not(following-sibling::*)">
<xsl:choose>
<xsl:when test="count(../*)>1"><xsl:text>]</xsl:text></xsl:when>
<xsl:otherwise><xsl:text>}</xsl:text></xsl:otherwise>
</xsl:choose>
</xsl:if>
</xsl:template>
<!-- properties of objects -->
<xsl:template match="*[count(../*[name(../*)=name(.)])=count(../*) and count(../*)>1]">
<xsl:variable name="inArray" select="translate(local-name(),'OBJECT','object')='object' or ../@Type[starts-with(.,'System.Collections') or contains(.,'[]') or (contains(.,'[') and contains(.,']'))]"/>
<xsl:if test="not(preceding-sibling::*)">
<xsl:choose>
<xsl:when test="$inArray"><xsl:text>[</xsl:text></xsl:when>
<xsl:otherwise>
<xsl:text>{</xsl:text>
<xsl:if test="../@Type">
<xsl:text>"__type":</xsl:text>
<xsl:call-template name="escape-string">
<xsl:with-param name="s" select="../@Type"/>
</xsl:call-template>
<xsl:text>,</xsl:text>
</xsl:if>
</xsl:otherwise>
</xsl:choose>
</xsl:if>
<xsl:choose>
<xsl:when test="not(child::node())">
<xsl:call-template name="escape-string">
<xsl:with-param name="s" select="@Name"/>
</xsl:call-template>
<xsl:text>:null</xsl:text>
</xsl:when>
<xsl:when test="$inArray">
<xsl:apply-templates select="child::node()"/>
</xsl:when>
<!--
<xsl:when test="not(@Name) and not(@Type)">
<xsl:call-template name="escape-string">
<xsl:with-param name="s" select="local-name()"/>
</xsl:call-template>
<xsl:text>:</xsl:text>
<xsl:apply-templates select="child::node()"/>
</xsl:when>
-->
<xsl:when test="not(@Name)">
<xsl:call-template name="escape-string">
<xsl:with-param name="s" select="local-name()"/>
</xsl:call-template>
<xsl:text>:</xsl:text>
<xsl:apply-templates select="child::node()"/>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="escape-string">
<xsl:with-param name="s" select="@Name"/>
</xsl:call-template>
<xsl:text>:</xsl:text>
<xsl:apply-templates select="child::node()"/>
</xsl:otherwise>
</xsl:choose>
<xsl:if test="following-sibling::*">,</xsl:if>
<xsl:if test="not(following-sibling::*)">
<xsl:choose>
<xsl:when test="$inArray"><xsl:text>]</xsl:text></xsl:when>
<xsl:otherwise><xsl:text>}</xsl:text></xsl:otherwise>
</xsl:choose>
</xsl:if>
</xsl:template>
<!-- convert root element to an anonymous container -->
<xsl:template match="/">
<xsl:apply-templates select="node()"/>
</xsl:template>
</xsl:stylesheet>
'@
}
PROCESS {
if(Get-Member -InputObject $xml -Name root) {
Write-Verbose "Ripping to Objects"
$xml = $xml.root.Objects
} else {
Write-Verbose "Was already Objects"
}
Convert-Xml -Xml $xml -Xsl $xmlToJsonXsl
}
}
Function ConvertFrom-Xml {
[CmdletBinding(DefaultParameterSetName="AutoType")]
PARAM(
[Parameter(ValueFromPipeline=$true,Mandatory=$true,Position=1)]
[Xml.XmlNode]
$xml
,
[Parameter(Mandatory=$true,ParameterSetName="ManualType")]
[Type]$Type
,
[Switch]$ForceType
)
PROCESS{
if(Get-Member -InputObject $xml -Name root) {
return $xml.root.Objects |
} elseif(Get-Member -InputObject $xml -Name Objects) {
return $xml.Objects |
}
$propbag = @{}
foreach($name in Get-Member -InputObject $xml -MemberType Property | Where-Object{$_.Name -notmatch "^__|type"} | Select-Object -ExpandProperty name) {
Write-Verbose "$Name Type: $($xml."$Name".type)"
switch( $xml."$Name".type ) {
"object" {
$propbag."$Name" = ConvertFrom-Xml -Xml $xml."$Name"
break
}
"string" {
$propbag."$Name" = $xml."$Name".get_InnerText()
$MightBeADate = $xml."$Name".get_InnerText() -as [DateTime]
## Strings that are actually dates (*grumble* JSON is crap)
if($MightBeADate -and $propbag."$Name" -eq $MightBeADate.ToString("G")) {
$propbag."$Name" = $MightBeADate
}
break
}
"number" {
$number = $xml."$Name".get_InnerText()
if($number -eq ($number -as [int])) {
$propbag."$Name" = $number -as [int]
} elseif($number -eq ($number -as [double])) {
$propbag."$Name" = $number -as [double]
} else {
$propbag."$Name" = $number -as [decimal]
}
break
}
"boolean" {
$propbag."$Name" = [bool]::parse($xml."$Name".get_InnerText())
}
"null" {
$propbag."$Name" = $null
}
default {
$propbag."$Name" = $xml."$Name"
break
}
}
}
if(!$Type -and $xml.HasAttribute("__type")) { $Type = $xml.__Type }
if($ForceType -and $Type) {
try {
$output = New-Object $Type -Property $propbag
} catch {
$output = New-Object PSObject -Property $propbag
$output.PsTypeNames.Insert(0, $xml.__type)
}
} else {
$output = New-Object PSObject -Property $propbag
if($Type) {
$output.PsTypeNames.Insert(0, $Type)
}
}
Write-Output $output
}
}
Function ConvertFrom-Json {
[CmdletBinding(DefaultParameterSetName="AutoType")]
PARAM(
[Parameter(ValueFromPipeline=$true,Mandatory=$true,Position=1)][string]$InputObject
,
[Parameter(Mandatory=$true,ParameterSetName="ManualType")][Type]$Type
,
[Switch]$ForceType
)
PROCESS {
$null = $PSBoundParameters.Remove("InputObject")
$xml = (Convert-JsonToXml $InputObject).Root
if($xml.Objects) {
$xml.Objects.Item.GetEnumerator() | ConvertFrom-Xml @PSBoundParameters
}elseif($xml.Item) {
$xml.Item | ConvertFrom-Xml @PSBoundParameters
}
}
}
#########
### The JSON library is dependent on Convert-Xml from my Xml script module
function Convert-Node {
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[System.Xml.XmlReader]$XmlReader,
[Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)]
[System.Xml.Xsl.XslCompiledTransform]$StyleSheet
)
PROCESS {
$output = New-Object IO.StringWriter
$StyleSheet.Transform( $XmlReader, $null, $output )
Write-Output $output.ToString()
}
}
function Convert-Xml {
#.Synopsis
# The Convert-XML function lets you use Xslt to transform XML strings and documents.
#.Description
#.Parameter Content
# Specifies a string that contains the XML to search. You can also pipe strings to Select-XML.
#.Parameter Namespace
# Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}.
#.Parameter Path
# Specifies the path and file names of the XML files to search. Wildcards are permitted.
#.Parameter Xml
# Specifies one or more XML nodes to search.
#.Parameter Xsl
# Specifies an Xml StyleSheet to transform with...
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath")]
[String[]]$Path
,
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
[Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$Content
,
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[Alias("StyleSheet")]
[String[]]$Xslt
)
BEGIN {
$StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform
if(Test-Path @($Xslt)[0] -ErrorAction 0) {
Write-Verbose "Loading Stylesheet from $(Resolve-Path @($Xslt)[0])"
$StyleSheet.Load( (Resolve-Path @($Xslt)[0]) )
} else {
Write-Verbose "$Xslt"
$StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader ($Xslt -join "`n")))))
}
[Text.StringBuilder]$XmlContent = [String]::Empty
}
PROCESS {
switch($PSCmdlet.ParameterSetName) {
"Content" {
$null = $XmlContent.AppendLine( $Content -Join "`n" )
}
"Path" {
foreach($file in Get-ChildItem $Path) {
Convert-Node -Xml ([System.Xml.XmlReader]::Create((Resolve-Path $file))) $StyleSheet
}
}
"Xml" {
foreach($node in $Xml) {
Convert-Node -Xml (New-Object Xml.XmlNodeReader $node) $StyleSheet
}
}
}
}
END {
if($PSCmdlet.ParameterSetName -eq "Content") {
[Xml]$Xml = $XmlContent.ToString()
Convert-Node -Xml $Xml $StyleSheet
}
}
}
New-Alias fromjson ConvertFrom-Json
New-Alias tojson ConvertTo-Json
#New-Alias ipjs Import-Json
#New-Alias epjs Export-Json
#Import-Json, Export-Json,
Export-ModuleMember -Function ConvertFrom-Json, ConvertTo-Json, Convert-JsonToXml, Convert-XmlToJson, Convert-CliXmlToJson -Alias *
# SIG # Begin signature block
# MIIIDQYJKoZIhvcNAQcCoIIH/jCCB/oCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUfmiIa5vfHY0pXkdWMbqjmY43
# ZR+gggUrMIIFJzCCBA+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
# BgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQUoUwjRzCv
# 3+BoGsB+b0S8utgrxNIwDQYJKoZIhvcNAQEBBQAEggEAuWvNn+zWBq99vDMSLtfF
# +8UIONZYIASIwWQXepjKqLbwmZsQaBDGFEDgXJCnpjK+1xbORJPREAPCPvEBXA4L
# HplhYl9HUQ/2GezBXc+D3AVkG34GoBWEIZzkud2jH+DMFIWDIQP8RJJ3YkYoUaL5
# 5qAsgeASTHkWI+8fG7Nume2EeGZVNuKLQK7vacSS4A+WkNXojtgYsLvlL1tVlGEA
# 7xURgoYqhfgU8NApViTDYKBE2ohXXtojb6CrDHN1DUF1QWxlAFQdODjDR05pdqq9
# sITi8drKtHcGz37q7MVkGSX0VX5FSvDE/Mr8BcIAQONET+zDOHr7tGB55DxT8ZIv
# 2A==
# SIG # End signature block
|
PowerShellCorpus/PoshCode/LetterDiamondOneliner v_2.ps1
|
LetterDiamondOneliner v_2.ps1
|
&{param([char]$c)[int]$s=65;$p=$c-$s;$r=,(' '*$p+[char]$s);$r+=@(do{"{0,$p} {1}{0}"-f([char]++$s),(' '*$f++)}until(!--$p));$r;$r[-2..-99]}Z
# trimmed 130 chars w/o arg
&{param([char]$c)$p=$c-($s=65);$r=,(' '*$p+[char]$s);do{$r+="{0,$p} {1}{0}"-f([char]++$s),(' '*$f++)}until(!--$p);$r;$r[-2..-99]}J
|
PowerShellCorpus/PoshCode/Format-TablePlus_1.ps1
|
Format-TablePlus_1.ps1
|
#requires -version 2.0
## Format-Table with wrapping and string trimming.
function Format-TablePlus() {
[CmdletBinding()]
param(
[Switch]
${AutoSize},
[Switch]
${HideTableHeaders},
[Switch]
${Wrap},
[Parameter(Position=0)]
[System.Object[]]
${Property},
[System.Object]
${GroupBy},
[System.String]
${View},
[Switch]
${ShowError},
[Switch]
${DisplayError},
[Switch]
${Force},
[ValidateSet('CoreOnly','EnumOnly','Both')]
[System.String]
${Expand},
[System.Int32]
${Width} = $Host.Ui.RawUI.BufferSize.Width,
[Switch]
${PadEnd},
[Parameter(ValueFromPipeline=$true)]
[System.Management.Automation.PSObject]
${InputObject}
)
begin
{
try {
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
# need to get rid of these before we pass this to the Format-Table cmdlet
$null = $PSBoundParameters.Remove("Width")
$null = $PSBoundParameters.Remove("TrimEnd")
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Format-Table', [System.Management.Automation.CommandTypes]::Cmdlet)
## I made the trimming optional, but defaulted it to on ;)
$scriptCmd = &{
if($PadEnd) {
{& $wrappedCmd @PSBoundParameters | Out-String -Stream -Width $Width }
} else {
{& $wrappedCmd @PSBoundParameters | Out-String -Stream -Width $Width | % { $_.TrimEnd() } }
}
}
$steppablePipeline = $scriptCmd.($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Format-Table
.ForwardHelpCategory Cmdlet
#>
}
|
PowerShellCorpus/PoshCode/Beginner event 10 .ps1
|
Beginner event 10 .ps1
|
#
# Summer 2009 Scripting games
# Beginner Event 10 - The 1,500-Meter race
# http://blogs.technet.com/heyscriptingguy/archive/2009/06/18/hey-scripting-guy-2009-scripting-games-event-10-details-beginner-and-advanced-1-500-meter-race.aspx
#
# ToDo: In this event, you must write a script that will count down from three minutes
# to zero seconds. When the three minutes have expired,
# display a message indicating that the given amount of time has elapsed.
#
# This solution uses the .Net System.Windows.Form and ...Drawing classes to produce a kind
# of GUI with a "stop-watch touch"
#
# The Start-Button starts the countdwon ... not very surpisingly :-)
# The countdown can be suspended by pressing the Stop-Button ... obviously
# You can Set the countdown timer in a range up to an hour ( 59:59 [mm:ss] )
# using the Set-Button. After entering a new valid mm:ss value press the Set-Button again
# to take these new values into effect
# I won't tell you, what the Exit-button might do for us :-)
#
# All the positioning and sizing has been done using the VS2008 designer too to avoid me
# having a heart attack trying to adjust pixelwise ...
# But I'm no artist, so I didn't spent too much time beautifying the layout!
#
# Klaus Schulte, 06/26/2009
# It'll be a three minutes countdown
$Script:countdownTime = 3*60
#
# This is the usual more a less VStudio 2008 designer generated "don't touch me" part of the code
# used to define the Form derived visual components
#
function InitializeComponent ()
{
# load the required additional GUI assemblies
[void][reflection.assembly]::LoadWithPartialName("System.Windows.Forms")
[void][reflection.assembly]::LoadWithPartialName("System.Drawing")
# We will have the form itself, a textbox displaying the remainig time,
# four buttons to control the countdown and ( surprise, surprise! ) a timer :-)
# It is good to have a timer for the heavy work that allows us to asynchronically
# react on timer events that would otherwise block the GUI and make it unresponsive
# if we use busy, active wait loops or a Sleep command to control the clock
$formCountdown = New-Object System.Windows.Forms.Form
$tbRemainingTime = New-Object System.Windows.Forms.TextBox
$btnStart = New-Object System.Windows.Forms.Button
$btnStop = New-Object System.Windows.Forms.Button
$btnSet = New-Object System.Windows.Forms.Button
$btnExit = New-Object System.Windows.Forms.Button
$timer1 = New-Object System.Windows.Forms.Timer
$formCountdown.SuspendLayout()
#
# tbRemainingTime
# I used the Algerian font, size 72 here, which you can easily change to your gusto
# The digits should be red on black background
# Only up to 5 chars can be entered into this textbox
#
$tbRemainingTime.BackColor = [System.Drawing.Color]::Black
$tbRemainingTime.Font = New-Object System.Drawing.Font "Algerian", 72
$tbRemainingTime.ForeColor = [System.Drawing.Color]::Red
$tbRemainingTime.Location = New-Object System.Drawing.Point(0, 0)
$tbRemainingTime.MaxLength = 5
$tbRemainingTime.Name = "tbRemainingTime"
$tbRemainingTime.Size = New-Object System.Drawing.Size(270, 134)
$tbRemainingTime.TabIndex = 0
#
# btnStart
# There is a lightgreen Start-button with a btnStart_Click eventhandler
#
$btnStart.BackColor = [System.Drawing.Color]::LightGreen
$btnStart.Font = New-Object System.Drawing.Font "Courier New", 12
$btnStart.Location = New-Object System.Drawing.Point(269, 0)
$btnStart.Name = "btnStart"
$btnStart.Size = New-Object System.Drawing.Size(82, 32)
$btnStart.TabIndex = 0
$btnStart.Text = "Start"
$btnStart.UseVisualStyleBackColor = $false
$btnStart.Add_Click({btnStart_Click})
#
# btnStop
# ... there is a salmon(lighted) Start-button with a btnStop_Click eventhandler
#
$btnStop.BackColor = [System.Drawing.Color]::Salmon
$btnStop.Enabled = $false
$btnStop.Font = New-Object System.Drawing.Font "Courier New", 12
$btnStop.Location = New-Object System.Drawing.Point(269, 32)
$btnStop.Name = "btnStop"
$btnStop.Size = New-Object System.Drawing.Size(82, 32)
$btnStop.TabIndex = 1
$btnStop.Text = "Stop"
$btnStop.UseVisualStyleBackColor = $false
$btnStop.Add_Click({btnStop_Click})
#
# btnSet
# ... there is a yellow Set-button with a btnSet_Click eventhandler
#
$btnSet.BackColor = [System.Drawing.Color]::Yellow
$btnSet.Font = New-Object System.Drawing.Font "Courier New", 12
$btnSet.Location = New-Object System.Drawing.Point(269, 64)
$btnSet.Name = "btnSet"
$btnSet.Size = New-Object System.Drawing.Size(82, 32)
$btnSet.TabIndex = 2
$btnSet.Text = "Set"
$btnSet.UseVisualStyleBackColor = $false
$btnSet.Add_Click({btnSet_Click})
#
# btnExit
# ... and a white Exit-button with a btnExit_Click eventhandler
#
$btnExit.BackColor = [System.Drawing.Color]::White
$btnExit.Font = New-Object System.Drawing.Font "Courier New", 12
$btnExit.Location = New-Object System.Drawing.Point(269, 96)
$btnExit.Name = "btnExit"
$btnExit.Size = New-Object System.Drawing.Size(82, 32)
$btnExit.TabIndex = 3
$btnExit.Text = "Exit"
$btnExit.UseVisualStyleBackColor = $false
$btnExit.Add_Click({btnExit_Click})
#
# timer1
# the timer has an eventhadler timer1_tick attached to it
#
$timer1.Add_Tick({timer1_Tick})
$timer1.Stop()
#
#
# frmCountdown
# The rest of the form is defined here
# and all the previously defined controls are added to it
#
$formCountdown.BackColor = [System.Drawing.Color]::Black
$formCountdown.ClientSize = New-Object System.Drawing.Size(349, 127)
# $formCountdown.ControlBox = $false
$formCountdown.Controls.Add($btnExit)
$formCountdown.Controls.Add($btnSet)
$formCountdown.Controls.Add($btnStop)
$formCountdown.Controls.Add($btnStart)
$formCountdown.Controls.Add($tbRemainingTime)
$formCountdown.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle
$formCountdown.MaximizeBox = $false
$formCountdown.MinimizeBox = $false
$formCountdown.Name = "formCountdown"
$formCountdown.SizeGripStyle = [System.Windows.Forms.SizeGripStyle]::Hide
$formCountdown.Text = "Countdown"
$formCountdown.ResumeLayout($false)
$formCountdown.PerformLayout()
$formCountdown.Load
#
# To have a well defined start state, we preset some properties of the controls here
#
$btnStart.Enabled = $true
$btnStop.Enabled = $false
$btnSet.Enabled = $true
$btnExit.Enabled = $true
$tbRemainingTime.ReadOnly = $true
DisplayCountdownTime($Script:countdownTime)
$formCountdown.ShowDialog()
}
#
# The Exit Button eventhandler just closes the form which shutsdown the application
# All the cleanup stuff could be done here especially if COM objects have been allocated
# you should release them somewhere before you shut the application down.
#
function btnExit_Click()
{
$formCountdown.Close()
}
#
# the Set Button event handler distinguishes between two "modes"
# depending on the readonly property of the (remaing countdowntime) textbox
# If you press the Set Button once, you enter edit mode to change the value
# of the countdown. Having changed the value you should hit the Set-button again
# to commit the changes. Before the commit is performed the string is checked
# against the regular expression $TimePattern to validate it. if it is invalid
# you are prompted with an error message and stay in set mode, otherwise the new
# value is used to start the countdown.
#
function btnSet_Click()
{
$TimePattern = "[0-5][0-9]:[0-5][0-9]"
if ($tbRemainingTime.ReadOnly)
{
$btnStart.Enabled = $false
$btnStop.Enabled = $false
$btnSet.Enabled = $true
$btnExit.Enabled = $true
$tbRemainingTime.ReadOnly = $false
$tbRemainingTime.BackColor = [System.Drawing.Color]::White
$tbRemainingTime.Focus
}
else
{
if (!([regex]::IsMatch($tbRemainingTime.Text, $TimePattern)))
{
[Windows.Forms.MessageBox]::Show("Please enter a time value in the form of 'mm:ss`r`n" `
+ "where 'mm' and 'ss' are less or equal to '59'")
return
}
$Script:countdownTime = 60 * [int]($tbRemainingTime.Text.Substring(0, 2)) +
[int]($tbRemainingTime.Text.Substring(3, 2))
DisplayCountdownTime($Script:countdownTime)
$btnStart.Enabled = $true
$btnStop.Enabled = $false
$btnSet.Enabled = $true
$btnExit.Enabled = $true
$tbRemainingTime.BackColor = [System.Drawing.Color]::Black
$tbRemainingTime.ReadOnly = $true
}
}
#
# Pressing the Stop-Button will pause the countdown
#
function btnStop_Click()
{
$timer1.Stop()
$btnStart.Enabled = $true
$btnStop.Enabled = $false
$btnSet.Enabled = $true
$btnExit.Enabled = $true
[Windows.Forms.MessageBox]::Show("Countdown paused!")
}
#
# Pressing the Start-Button will start the countdown
# The Timer interval is set to 1000 ms, which allows us to see a change of the countdown value
# each second
#
function btnStart_Click()
{
$btnStart.Enabled = $false
$btnStop.Enabled = $true
$btnSet.Enabled = $false
$btnExit.Enabled = $true
$timer1.Interval = 1000
$timer1.Start()
}
#
# just a helper function to convert an [int] to the display format: 'mm:ss'
# Values greater or equal to an hour are SilentlyIgnored :-)
#
function DisplayCountdownTime($seconds)
{
if ($seconds -lt 60*60)
{
$tbRemainingTime.Text = [string]::Format("{0:00}:{1:00}",
[Math]::floor($seconds / 60), $seconds % 60)
}
}
#
# this function just decrents the remaining time to countdown by one and displays the new value
# if the remaining time is greater than zero. If it is zero, the countdown is over and the requested
# message is displayed. The countdown could be restarted setting another value now.
#
function Countdown()
{
$Script:countdownTime--
DisplayCountdownTime($Script:countdownTime)
if ($Script:countdownTime -le 0)
{
$timer1.Stop()
$btnStart.Enabled = $false
$btnStop.Enabled = $false
$btnSet.Enabled = $true
$btnExit.Enabled = $true
[Windows.Forms.MessageBox]::Show("Countdown finished!")
}
}
#
# The timer event handler fires each second and calls Countdown to do the work
#
function timer1_Tick()
{
Countdown
}
#
# The main entry point to to what it is called ,..
#
InitializeComponent
|
PowerShellCorpus/PoshCode/Get-DominosOrderStatus.ps1
|
Get-DominosOrderStatus.ps1
|
# Get-DominosOrderStatus.psm1
# Author: xcud.com
#
# Inspired by Dana Merrick's Dominos Pizza Script
# http://shakti.trincoll.edu/~dmerrick/dominos.html
function Get-DominosOrderStatus($phone_number) {
$url = "http://trkweb.dominos.com/orderstorage/GetTrackerData?Phone=$phone_number"
[xml]$content = (new-object System.Net.WebClient).DownloadString($url);
$statii = select-xml -xml @($content) `
-Namespace @{dominos="http://www.dominos.com/message/"} `
-XPath descendant::dominos:OrderStatus
if($statii.Count -gt 0) { $statii | %{ $_.Node } }
else { "No orders" }
}
Export-ModuleMember Get-DominosOrderStatus
|
PowerShellCorpus/PoshCode/Set-ADUserRandomPassword_2.ps1
|
Set-ADUserRandomPassword_2.ps1
|
###########################################################################"
#
# NAME: Set-ADUserRandomPassword.ps1
#
# AUTHOR: Jan Egil Ring
# EMAIL: jan.egil.ring@powershell.no
#
# COMMENT: This script are used to set a random password for Active Directory users in a specified Organizational Unit. It stores the results in a csv-file.
# The background for this script is a school domain needing to set random passwords for new users, and exporting the passwords to a csv-# # file to let the teachers disribute the first-time passwords.
#
# 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 22.08.2009 - Initial release
#
###########################################################################"
#Requires: Quest.ActiveRoles.ADManagement
#Creating system.random object used to generate random numbers
$random = New-Object System.Random
#Creating an array to store user information in
$CSV = @()
#Get users
Get-QADUser -SearchRoot "domain.local/MyUserOU" -SizeLimit 0 | ForEach-Object {
#Generate a random password for each user
$password = "pwd"+($random.Next(1000,9999))
#Set the password for each user
Set-QADUser $_ -UserPassword $password
#Select what user information we want to export to the csv-file and storing it in a variable
$exportdata = Get-QADUser $_ | Select-Object name,samaccountname,company,department
#Add the password as a member to $exportdata
Add-Member -InputObject $exportdata -MemberType NoteProperty -Name Password -Value $password
#Add the user information to the $CSV array
$CSV += $exportdata
}
#Exporting all users to the csv-file
$CSV | Export-Csv -Path "C:\\export\\passwordlist.csv" -Encoding unicode -NoTypeInformation
|
PowerShellCorpus/PoshCode/Get-CompPartitionTable.ps1
|
Get-CompPartitionTable.ps1
|
param($computer,$instance,$database)
import-module sqlps -disablenamechecking
$path = "SQLSERVER:\\SQL\\$($computer)\\$($instance)\\Databases\\$($database)\\Tables"
SET-LOCATION $path
get-childitem | where {$_.HasCompressedPartitions -or $_.IsPartitioned} |
select @{n='ServerInstance';e={"$computer\\$instance"}},@{n='Database';e={$database}}, name, HasCompressedPartitions, IsPartitioned
cd $home
|
PowerShellCorpus/PoshCode/Get-Credential 1.2.ps1
|
Get-Credential 1.2.ps1
|
## Get-Credential
## An improvement over the default cmdlet which has no options ...
###################################################################################################
## History
## v 1.2 Refactor ShellIds key out to a variable, and wrap lines a bit
## v 1.1 Add -Console switch and set registry values accordingly (ouch)
## v 1.0 Add Title, Message, Domain, and UserName options to the Get-Credential cmdlet
###################################################################################################
function Get-Credential{
PARAM([String]$Title, [String]$Message, [String]$Domain, [String]$UserName, [switch]$Console)
$ShellIdKey = "HKLM:\\SOFTWARE\\Microsoft\\PowerShell\\1\\ShellIds"
## Carefully EA=SilentlyContinue because by default it's MISSING, not $False
$cp = (Get-ItemProperty $ShellIdKey ConsolePrompting -ea "SilentlyContinue")
## Compare to $True, because by default it's $null ...
$cp = $cp.ConsolePrompting -eq $True
if($Console -and !$cp) {
Set-ItemProperty $ShellIdKey ConsolePrompting $True
} elseif(!$Console -and $Console.IsPresent -and $cp) {
Set-ItemProperty $ShellIdKey ConsolePrompting $False
}
## Now call the Host.UI method ... if they don't have one, we'll die, yay.
$Host.UI.PromptForCredential($Title,$Message,$UserName,$Domain)
## BoyScouts: Leave everything better than you found it (I'm tempted to leave it = True)
Set-ItemProperty $ShellIdKey ConsolePrompting $cp
}
|
PowerShellCorpus/PoshCode/DNS functions.ps1
|
DNS functions.ps1
|
Param (
[Parameter(Mandatory=$true, Position=1)][string] $SourceServer,
[Parameter(Mandatory=$true, Position=2)][string] $SourceZone,
[Parameter(Mandatory=$true, Position=3)][string] $DestinationServer,
[Parameter(Mandatory=$true, Position=4)][string] $DestinationZone,
[string[]] $RRtypes = @("MicrosoftDNS_AType"),
[switch] $Copy,
[switch] $Clean,
[switch] $Help
)
# script variables
$nl = [Environment]::NewLine
If ($Help){
Write-Host -ForegroundColor Green "
NAME
DNS_Functions
SYNOPSIS
Copies and/or cleans DNS records from one forward zone to another
SYNTAX
.\\DNS_Functions SourceServer SourceZone DestinationServer DestinationZone Switches
EXAMPLES
Forward zone comparison report only:
.\\DNS_Functions $SourceServer $SourceZone $DestinationServer $DestinationZone
Forward source zone clean up for CNAME records:
.\\DNS_Functions.ps1 source_dnsserver source_zone.local destination_dnsserver destination_zone.local -RRtypes `"MicrosoftDNS_AType`",`"MicrosoftDNS_CNAMEType`" -Clean
DESCRIPTION
This script can both copy and clean DNS records by comparing any 2 DNS zones, either same or different FQDN
"
break
}
function GetDNSrecords($DNSserver, $DNSzone, $RRtype){
if ($RRtype -eq $null){$RRtype = "MicrosoftDNS_ResourceRecord"}
$DNSrecords = Get-WMIObject -Computer $DNSserver -Namespace "root\\MicrosoftDNS" -Class $RRtype -Filter "ContainerName='$DNSzone'"
if ($DNSrecords){
Switch ($RRtype){
MicrosoftDNS_AType {
foreach ($rec in $DNSrecords){
# add simple name of dns record as extra property for comparison routine
Add-Member -InputObject $rec -MemberType NoteProperty -Name SimpleVal -Value $rec.OwnerName.Replace(".$DNSzone","")
}
}
MicrosoftDNS_CNAMEType {
foreach ($rec in $DNSrecords){
# add simple name of dns record as extra property for comparison routine
Add-Member -InputObject $rec -MemberType NoteProperty -Name SimpleVal -Value $rec.OwnerName.Replace(".$DNSzone","")
}
}
MicrosoftDNS_ResourceRecord {
# to be implemented
}
}
}
return $DNSrecords
}
function GetDNSrecord ($DNSserver, $DNSzone, $name, $RRtype){
$DnSrecord = Get-WMIObject -Computer $DNSserver -Namespace "root\\MicrosoftDNS" -Class $RRtype -Filter "OwnerName='$name.$DNSzone'"
return $DNSrecord # returns the actual object for further processing
}
function GetDNSzones($DNSserver){
# server side filtering
$DNSzones = Get-WmiObject -ComputerName $DNSserver -Class MicrosoftDNS_Zone -Namespace root\\microsoftDNS -Filter "ZoneType = 1 or ZoneType = 2"
# client side filtering
#$destDNSzone = Get-WmiObject -ComputerName $destServer -Class MicrosoftDNS_Zone -Namespace root\\microsoftDNS | Where {$_.ZoneType -eq '1' -or $_.ZoneType -eq '2'}
return $DNSzones
}
function GetDNSzone ($DNSserver, $name){
$DnSzone = Get-WMIObject -Computer $DNSserver -Namespace "root\\MicrosoftDNS" -Class MicrosoftDNS_Zone -Filter "Name='$name'"
return $DnSzone # returns the actual object for further processing
}
# just for debugging and reference
function DNSrecordInfo($DNSrecord){
$objOutput = New-Object PSObject -Property @{
$class = $DNSrecord.__CLASS # A, CNAME, PTR, etc.
$ownerName = $DNSrecord.OwnerName # Name column in DNS GUI, FQDN
$containerName = $DNSrecord.ContainerName # Zone FQDN
$domainName = $DNSrecord.DomainName # Zone FQDN
$ttl = $DNSrecord.TTL # TTL
$recordClass = $DNSrecord.RecordClass # Usually 1 (IN)
$recordData = $DNSrecord.RecordData # Data column in DNS GUI, value
$simpleval = $ownerName.Replace(".$domainName","")
}
return $objOutput
}
function CopyRecords($DNSrecords){
Write-Output "$($nl)$('Copying') $($DNSrecords.count) $('records to') $($DestinationServer)$($nl)"
$Succ = $Fail = 0
foreach ($DnSrecord in $DNSrecords){
Switch ($DNSrecord.__CLASS) {
MicrosoftDNS_AType {
$destRec = [WmiClass]"\\\\$DestinationServer\\root\\MicrosoftDNS:MicrosoftDNS_AType"
if ($Copy){
if ($DnSrecord.SimpleVal -eq $SourceZone){
# skip (same as parent) A records
Write-Output "$('copy of A:') $($DNSrecord) $('skipped')"
break
}
try{
$newrec = $DNSrecord.SimpleVal + "." + $DestinationZone
$destRec.CreateInstanceFromPropertyData($DestinationServer, $DestinationZone, $newrec, 1, $DNSrecord.TTL, $DNSrecord.RecordData) | out-null
$Succ ++
Write-Output "$('copy of A:') $($newrec) $('on') $($DestinationServer)"
}
catch{
Write-Output "$('copy of A:') $($newrec) $('failed')"
Write-Output "$($error[0])"
$Fail ++
}
}
}
MicrosoftDNS_CNAMEType {
$destRec = [WmiClass]"\\\\$DestinationServer\\root\\MicrosoftDNS:MicrosoftDNS_CNAMEType"
if ($Copy){
try{
$newrec = $DNSrecord.SimpleVal + "." + $DestinationZone
$crec = $DNSrecord.RecordData.Replace(".$SourceZone",".$DestinationZone")
$destRec.CreateInstanceFromPropertyData($DestinationServer, $DestinationZone, $newrec, 1, $DNSrecord.TTL, $crec ) | out-null
$Succ ++
Write-Output "$('copy of CNAME:') $($newrec) $('on') $($DestinationServer)"
}
catch{
Write-Output "$('copy of CNAME') $($newrec) $('failed')"
Write-Output "$($error[0])"
$Fail ++
}
}
}
default{
Write-Output "$('copy of:') $($DNSrecord.SimpleVal) $('failed') $('due to unknown record class')"
$Fail ++
}
}
}
Write-Output "$($nl)$($Succ) $('records copied')"
Write-Output "$($Fail) $('records failed')$($nl)"
}
function ScavengeRecords($DNSrecords){
$Deleted = $Dead = $Live = 0
foreach ($DnSrecord in $DNSrecords){
if (Test-Connection -ComputerName $DNSrecord.OwnerName -count 1 -ea silentlycontinue) {
write-output "$($DNSrecord.SimpleVal) $('is still alive')"
$Live ++
}
else{
write-output "$($DNSrecord.SimpleVal) $('cannot be reached')"
$Dead ++
if ($Clean){
try{
$DNSrecord.delete()
$Deleted ++
}
catch{}
}
}
}
Write-Output "$($nl)$($Deleted) $('records scavenged')"
Write-Output "$($Live) $('records were live')"
Write-Output "$($Dead) $('records were dead')$($nl)"
}
function DedupDNSzone ($srcRecords, $dstRecords){
# return only records from reference (= source zone) found in both DNS zones
$Records2Dedup = compare-object $srcRecords $dstRecords -IncludeEqual -ExcludeDifferent -Property SimpleVal -PassThru
Write-Output "$($nl)$('deleting duplicate records from') $($SourceZone)"
try{
$Records2Dedup | %{ $_.delete() }
Write-Output "$($Records2Dedup.count) $('duplicate records processed')$($nl)"
}
catch{
Write-Output "$('failure deleting record(s)')$($nl)"
}
}
function CleanDNSzone($srcRecords, $dstRecords){
# return unique records in source zone only
$Records2Clean = compare-object $srcRecords $dstRecords -Property SimpleVal -PassThru | Where-Object { $_.SideIndicator -eq '<=' }
ScavengeRecords $Records2Clean
}
function CopyDNSzone ($srcRecords, $dstRecords){
# return unique records in source zone only
$Records2Copy = compare-object $srcRecords $dstRecords -Property SimpleVal -PassThru | Where-Object { $_.SideIndicator -eq '<=' }
CopyRecords $Records2Copy
}
function CompareDNSservers($srcDNSzone ,$destDNSzone){
$dest = $src = $equ = 0
$zones = compare-object $srcDNSzone $destDNSzone -Property name -IncludeEqual
if ($zones -ne $null){
foreach ($zone in $zones){
switch ($zone.SideIndicator){
'=>' {
write-output "$($zone.Name) $('only exists on destination:') $($DestinationServer)"
$dest ++
}
'<=' {
write-output "$($zone.Name) $('only exists on source:') $($SourceServer)"
$src ++
}
'==' {
write-output "$($zone.Name) $('exists on both source and destination')"
$equ ++
}
}
}
write-output "$($nl)$($dest) $('zones on') $($DestinationServer) $('only')"
write-output "$($src) $('zones on') $($SourceServer) $('only')"
write-output "$($equ) $('zones on both source and destination')$($nl)"
}
}
function CompareDNSzone($srcRecords, $dstRecords){
$dest = $src = $equ = 0
$records = compare-object $srcRecords $dstRecords -IncludeEqual -Property SimpleVal
if ($records -ne $null){
foreach ($record in $records){
switch ($record.SideIndicator){
'=>' {
write-output "$($record.SimpleVal) $('exists only in:') $($DestinationZone)"
$dest ++
}
'<=' {
write-output "$($record.SimpleVal) $('exists only in:') $($SourceZone)"
$src ++
}
'==' {
write-output "$($record.SimpleVal) $('exists in both zones')"
$equ ++
}
}
}
write-output "$($nl)$($dest) $('records in') $($DestinationZone) $('on') $($DestinationServer) $('only')"
write-output "$($src) $('records in') $($SourceZone) $('on') $($SourceServer) $('only')"
write-output "$($equ) $('records in both source and destination')$($nl)"
}
}
function GetRecordType($Class){
# return human readable record type :-)
Switch ($Class) {
MicrosoftDNS_AAAAType {return "AAAA"}
MicrosoftDNS_AFSDBType {return "AFSDB"}
MicrosoftDNS_ATMAType {return "ATMA"}
MicrosoftDNS_AType {return "A"}
MicrosoftDNS_CNAMEType {return "Cname"}
MicrosoftDNS_HINFOType {return "H Info"}
MicrosoftDNS_ISDNType {return "ISDN"}
MicrosoftDNS_KEYType {return "Key"}
MicrosoftDNS_MBType {return "MB"}
MicrosoftDNS_MDType {return "MD"}
MicrosoftDNS_MFType {return "MF"}
MicrosoftDNS_MGType {return "MG"}
MicrosoftDNS_MINFOType {return "M Info"}
MicrosoftDNS_MRType {return "MR"}
MicrosoftDNS_MXType {return "MX"}
MicrosoftDNS_NSType {return "NS"}
MicrosoftDNS_NXTType {return "NXT"}
MicrosoftDNS_PTRType {return "PTR"}
MicrosoftDNS_RPType {return "RP"}
MicrosoftDNS_RTType {return "RT"}
MicrosoftDNS_SIGType {return "SIG"}
MicrosoftDNS_SOAType {return "SOA"}
MicrosoftDNS_SRVType {return "SRV"}
MicrosoftDNS_TXTType {return "Text"}
MicrosoftDNS_WINSRType {return "Wins R"}
MicrosoftDNS_WINSType {return "Wins"}
MicrosoftDNS_WKSType {return "WKS"}
MicrosoftDNS_X25Type {return "X25"}
}
}
# actual script execution
write-output "$('Comparison between') $($SourceServer) $('and') $($DestinationServer) $('for all regular DNS zones')$($nl)"
if ($SourceServer -ne $DestinationServer){
# arrays of DNS zones to compare
$srcZones = GetDNSzones $SourceServer
$destZones = GetDNSzones $DestinationServer
# output of DNS zones found on both servers
CompareDNSservers $srcZones $destZones
# run thru loop for all DNS record types in script parameter
}
else{write-output "$('Source and Destination server are the same')$($nl)"}
foreach ($RRtype in $RRtypes){
if (!(GetRecordType $RRtype)){write-warning "$RRtype is not a valid DNS resource type";continue}
write-output "$('Comparison between') $($SourceZone) $('on') $($SourceServer) $('and') $($DestinationZone) $('on') $($DestinationServer) $('for') $(GetRecordType $RRtype) $('records')$($nl)"
# arrays of DNS records to compare
$sourceRecords = (GetDNSrecords $SourceServer $SourceZone $RRtype)
$destinRecords = (GetDNSrecords $DestinationServer $DestinationZone $RRtype)
# check for empty array(s)
if ($sourceRecords -and $destinRecords){
# output of DNS records found in both zones
CompareDNSzone $sourceRecords $destinRecords
# clean duplicate records on the source server
DedupDNSzone $sourceRecords $destinRecords
# copy unique records from source to destination server
CopyDNSzone $sourceRecords $destinRecords
#CleanDNSzone $sourceRecords $destinRecords
}
else{write-output "$('no') $(GetRecordType $RRtype) $('records in either DNS zone')$($nl)"}
}
write-output "$('end script')$($nl)"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.