full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PoshCode/Sort IE Favorites.ps1
|
Sort IE Favorites.ps1
|
$Results = gci $env:userprofile\\favorites -rec -inc *.url |
? {select-string -inp $_ -quiet "^URL=http"} |
select @{Name="Name"; Expression={[IO.Path]::GetFileNameWithoutExtension($_.FullName)}},
@{Name="URL"; Expression={get-content $_ | ? {$_ -match "^URL=http"} | % {$_.Substring(4)}}}
New-Item $env:userprofile\\favorites\\sorted -ItemType directory
foreach ($Result in $Results |Sort-Object -Property url)
{
$Url = [System.Uri]$Result.URL
if ($Url)
{
$Folders = $Url.Host.Split(".")
if ($url.Host -eq 'agoodman.com.au')
{
#break
}
if ($Folders.Count -eq 2)
{
$RootFolder = $Folders[0]
}
if ($Folders.Count -eq 3)
{
$RootFolder = $Folders[1]
if (($Folders[$Folders.Count-1]).Length -eq 2)
{
$RootFolder = $Folders[0]
}
}
if ($Folders.Count -gt 3)
{
if (($Folders[$Folders.Count-1]).Length -eq 3)
{
$RootFolder = ($Folders[$Folders.Count-3])
}
}
New-Item "$($env:userprofile)\\favorites\\sorted\\$($RootFolder)" -ItemType Directory -Force
$shell = New-Object -ComObject WScript.Shell
$FileName = $Result.Name.Trim() -replace "[^a-zA-Z0-9\\s]",""
$path = "$($env:userprofile)\\favorites\\sorted\\$($RootFolder)\\$($FileName).URL"
$ShortCut = $shell.CreateShortCut($path)
$ShortCut.TargetPath = $Result.URL
$ShortCut.Save()
}
}
|
PowerShellCorpus/PoshCode/Check PowerShell version.ps1
|
Check PowerShell version.ps1
|
#Check if PowerShell version 3 or higher is installed
if($host.Version.Major -lt 3)
{
Write-Host "PowerShell Version 3 or higher needs to be installed" -ForegroundColor Red
Write-Host "Windows Management Framework 3.0 - RC" -ForegroundColor Magenta
Write-Host "http://www.microsoft.com/en-us/download/details.aspx?id=29939" -ForegroundColor Magenta
Break
}
|
PowerShellCorpus/PoshCode/Function Run-Script_2.ps1
|
Function Run-Script_2.ps1
|
#################################################################################
# This function should be included in the PowerShell ISE profile.ps1 and it will
# display the start and end times of any scripts started by clicking 'Run Script'
# in the Add-ons Menu, or F2; additionally they will be logged to the Scripts
# Event Log (which needs creating first) and also to a text log file. This
# defaults to that created by the Windows Script Monitor Service (available from
# www.SeaStarDevelopment.Bravehost.com) which normally indicates the full command
# line used to start each script.
# V2.0 Use Try/Catch to trap (child) script errors & change Hotkey to F2.
#################################################################################
function Run-Script {
$script = $psISE.CurrentFile.DisplayName
if ($script.StartsWith("Untitled") -or $script.Contains("profile.") -or `
($host.Name -ne 'Windows PowerShell ISE Host' )) {
return
}
$psISE.CurrentFile.Save()
$logfile = "$env:programfiles\\Sea Star Development\\" +
"Script Monitor Service\\ScriptMon.txt" #Change to suit.
if (!(Test-Path env:\\JobCount)) {
$env:JobCount = 1 #This will work across multi Tab sessions.
}
$number = $env:JobCount.PadLeft(4,'0')
$startTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss"
$tag = "$startTime [$script] start. --> PSE $($myInvocation.Line)"
if (Test-Path $logfile) {
$tag | Out-File $logfile -encoding 'Default' -Append
}
"$startTime [$script] started."
Write-EventLog -Logname Scripts -Source Monitor -EntryType Information -EventID 2 -Category 002 -Message "Script Job: $script (PSE$number) started."
try {
Invoke-Command -Scriptblock { & $pwd\\$script }
}
catch {
Write-Host -ForegroundColor Red ">>> ERROR: $_"
}
$endTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss"
$tag = "$endTime [$script] ended. --> PSE $($myInvocation.Line)"
if (Test-Path $logfile) {
$tag | Out-File $logfile -encoding 'Default' -Append
}
"$endTime [$script] ended."
Write-Eventlog -Logname Scripts -Source Monitor -EntryType Information -EventID 1 -Category 001 -Message "Script Job: $script (PSE$number) ended."
$env:JobCount = [int]$env:JobCount+1
}
$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("Run Script",{Run-Script}, "F2") | Out-Null
|
PowerShellCorpus/PoshCode/Get-RemoteRegistry_4.ps1
|
Get-RemoteRegistry_4.ps1
|
## Get-RemoteRegistry
########################################################################################
## Version: 2.2
## + Added a feature that will return the (Default) values for a key.
## These are referenced as ."(Default)".
## I didn't want to use just "Default" as the property name because of name
## collision.## + Fixed a pasting bug
## + I added the "Properties" parameter so you can select specific registry values
## NOTE: you have to have access, and the remote registry service has to be running
########################################################################################
## USAGE:
## Get-RemoteRegistry $RemotePC "HKLM\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP"
## * Returns a list of subkeys (because this key has no properties)
## Get-RemoteRegistry $RemotePC "HKLM\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v2.0.50727"
## * Returns a list of subkeys and all the other "properties" of the key
## Get-RemoteRegistry $RemotePC "HKLM\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v2.0.50727\\Version"
## * Returns JUST the full version of the .Net SP2 as a STRING (to preserve prior behavior)
## Get-RemoteRegistry $RemotePC "HKLM\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v2.0.50727" Version
## * Returns a custom object with the property "Version" = "2.0.50727.3053" (your version)
## Get-RemoteRegistry $RemotePC "HKLM\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v2.0.50727" Version,SP
## * Returns a custom object with "Version" and "SP" (Service Pack) properties
##
## For fun, get all .Net Framework versions (2.0 and greater)
## and return version + service pack with this one command line:
##
## Get-RemoteRegistry $RemotePC "HKLM:\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP" |
## Select -Expand Subkeys | ForEach-Object {
## Get-RemoteRegistry $RemotePC "HKLM:\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\$_" Version,SP
## }
##
########################################################################################
# Function Get-RemoteRegistry {
param(
[string]$computer = $(Read-Host "Remote Computer Name")
,[string]$Path = $(Read-Host "Remote Registry Path (must start with HKLM,HKCU,etc)")
,[string[]]$Properties
,[switch]$Verbose
)
if ($Verbose) { $VerbosePreference = 2 } # Only affects this script.
$root, $last = $Path.Split("\\")
$last = $last[-1]
$Path = $Path.Substring($root.Length + 1,$Path.Length - ( $last.Length + $root.Length + 2))
$root = $root.TrimEnd(":")
#split the path to get a list of subkeys that we will need to access
# ClassesRoot, CurrentUser, LocalMachine, Users, PerformanceData, CurrentConfig, DynData
switch($root) {
"HKCR" { $root = "ClassesRoot"}
"HKCU" { $root = "CurrentUser" }
"HKLM" { $root = "LocalMachine" }
"HKU" { $root = "Users" }
"HKPD" { $root = "PerformanceData"}
"HKCC" { $root = "CurrentConfig"}
"HKDD" { $root = "DynData"}
default { return "Path argument is not valid" }
}
#Access Remote Registry Key using the static OpenRemoteBaseKey method.
Write-Verbose "Accessing $root from $computer"
$rootkey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($root,$computer)
if(-not $rootkey) { Write-Error "Can't open the remote $root registry hive" }
Write-Verbose "Opening $Path"
$key = $rootkey.OpenSubKey( $Path )
if(-not $key) { Write-Error "Can't open $($root + '\\' + $Path) on $computer" }
$subkey = $key.OpenSubKey( $last )
$output = new-object object
if($subkey -and $Properties -and $Properties.Count) {
foreach($property in $Properties) {
Add-Member -InputObject $output -Type NoteProperty -Name $property -Value $subkey.GetValue($property)
}
Write-Output $output
} elseif($subkey) {
Add-Member -InputObject $output -Type NoteProperty -Name "Subkeys" -Value @($subkey.GetSubKeyNames())
foreach($property in $subkey.GetValueNames()) {
if ( $property -eq "" ) {
Add-Member -InputObject $output -Type NoteProperty -Name "(Default)" -Value $subkey.GetValue($property)
} else {
Add-Member -InputObject $output -Type NoteProperty -Name $property -Value $subkey.GetValue($property)
}
}
Write-Output $output
}
else
{
$key.GetValue($last)
}
# }
|
PowerShellCorpus/PoshCode/Fill-ErUp.ps1
|
Fill-ErUp.ps1
|
function Fill-ErUp
{
<#
.Synopsis
The function will append random integers to a specified file through $Path until it reaches the $Size requirement.
.Description
Fills a file up with random integers until the file size is equal to the desired size. Used to increase file mememory size.
.Parameter FilePath
Path of the file that will be monitored
.Parameter Size
File size is monitored against this value. When file size is equal or greater than this value, function ceases to operate
.Example
Fill-ErUp -FilePath C:\\Test -Size 3MB
Fills up the file with random integers until a size of at least 3MB is reached
.Example
Fill-ErUp -FilePath C:\\Test -Size 3MB -ScriptString "Write-Output 'File filled to specified Size'"
After File is filled, the ScriptString is output to the terminal
.Notes
Author: Paul Kiri.
#>
param(
[Parameter(mandatory=$true,position=0)]
[string[]]$FilePath
,
[Parameter(mandatory=$true,position=1)]
[int]$Size
,
[Parameter(mandatory=$false)]
[string[]]$ScriptString
)
while((Get-ChildItem $FilePath).length -le $Size)
{
Add-Content $FilePath -Value (Get-Random)
}
Invoke-Command -ScriptBlock ([scriptblock]::Create($ScriptString))
}
|
PowerShellCorpus/PoshCode/CenturionPortal.ps1
|
CenturionPortal.ps1
|
## New-CodeSigningCert.ps1
########################################################################################################################
## Does the setup needed to self-sign PowerShell scripts ...
## Generates a "test" self-signed root Certificate Authority
## And then generates a code-signing certificate (and signs it with the CA certificate)
## OPTIONALLY (specify -import or -importall) imports the certificates to the store(s)
########################################################################################################################
## NOTE: Uses OpenSSL (because it's xcopy redistributable -- wake up Microsoft)
## In order for this to work you should KEEP the script in the folder with OpenSsl.exe
## Also, it is VERY important that you properly provide passwords and the locale data...
## You can obviously reorder the parameters however you like, and hard-code some of the values in the parameters, but
## you need to make sure that if you use this to generate multiple certificates, that you preserve all of the certs
## and keep track of all your passwords so you don't lock yourself out of any of them.
########################################################################################################################
## Usage:
## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Joel Bennett" Jaykul@HuddledMasses.org HuddledMasses.org Mystery Rochester "New York" US -importall -OpenSSLLocation C:\\Users\\Joel\\Documents\\WindowsPowershell\\PoshCerts\\bin -CAPassword MyCleverRootPassword -CodeSignPassword EvenMoreCleverPasswords
##
## If I hard-coded the company/dept/etc ... I could use this to generate certs for all my devs:
##
## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Mark Andreyovich" FakeEmail@Xerox.net -CAPassword MyCleverRootPassword -CodeSignPassword MarksPassword
## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Jesse Voller" FakeEmail2@Xerox.net -CAPassword MyCleverRootPassword -CodeSignPassword JessesPassword
##
## For the signed scripts to work, I just have to -import on the devices where the scripts need to run:
##
## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Jesse Voller" -import
## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Mark Andreyovich" -import
## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Joel Bennett" -import
##
## On the developers' workstations, I need to use Get-PfxCertificate to sign, or else run -importall
## That will load the codesigning cert in their "my" store, and will only require the password for the initial import
##
## \\\\Server\\PoshCerts\\New-CodeSigningCert.ps1 $pwd\\Certs "Joel Bennett" -importall -CodeSignPassword MyCodeSignPassword
########################################################################################################################
## History
## 1.0 - Initial public release
## 1.1 - Bug fix release to make it easier to use...
## 1.2 - Bug fix to get the ORG and COMMON NAME set correctly -- Major whoops!
##
Param(
$CertStorageLocation = (join-path (split-path $Profile) "Certs"),
$UserName = (Read-Host "User name")
, $email
, $company
, $department
, $city
, $state
, $country
, $RootCAName = "Self-Signed-Root-CA"
, $CodeSignName = "$UserName Code-Signing"
, $alias = "PoshCert",
[string]$keyBits = 4096,
[string]$days = 365,
[string]$daysCA = (365 * 5),
[switch]$forceNew = $false,
[switch]$importall = $false,
[switch]$import = ($false -or $importall),
## we ask you to specify the CA password and your codesign password
## You can leave these null when importing on end-user desktops
$CAPassword = $null,
$CodeSignPassword = $null,
## You really shouldn't pass these unless you know what you're doing
$OpenSSLLocation = $null,
$RootCAPassword = $Null,
$CodeSignCertPassword = $null
)
function Get-UserEmail {
if(!$script:email) {
$script:email = (Read-Host "Email address")
}
return $script:email
}
function Get-RootCAPassword {
if(!$script:RootCAPassword) {
if(!$script:CAPassword) {
$script:CAPassword = ((new-object System.Management.Automation.PSCredential "hi",(Read-Host -AsSecureString "Root CA Password")).GetNetworkCredential().Password)
}
## Then down here we calculate large passwords to actually use:
## This works as long as you keep the same company name and root ca name
$script:RootCAPassword = [Convert]::ToBase64String( (new-Object Security.Cryptography.PasswordDeriveBytes ([Text.Encoding]::UTF8.GetBytes($CaPassword)), ([Text.Encoding]::UTF8.GetBytes("$company$RootCAName")), "SHA1", 5).GetBytes(64) )
}
return $script:RootCAPassword
}
function Get-CodeSignPassword {
if(!$script:CodeSignCertPassword) {
if(!$script:CodeSignPassword) {
$script:CodeSignPassword = ((new-object System.Management.Automation.PSCredential "hi",(Read-Host -AsSecureString "Code Signing Password")).GetNetworkCredential().Password)
}
## This works as long as you keep the same PFX password and email address
$script:CodeSignCertPassword = ([Convert]::ToBase64String( (new-Object Security.Cryptography.PasswordDeriveBytes ([Text.Encoding]::UTF8.GetBytes($CodeSignPassword)), ([Text.Encoding]::UTF8.GetBytes((Get-UserEmail))), "SHA1", 5).GetBytes(64) ))
}
return $script:CodeSignCertPassword
}
function Get-SslConfig {
Param (
$keyBits,
$Country = (Read-Host "Country (2-Letter code)"),
$State = (Read-Host "State (Full Name, no intials)"),
$city = (Read-Host "City"),
$company = (Read-Host "Company Name (or Web URL)"),
$orgUnit = (Read-Host "Department (team, group, family)"),
$CommonName,
$email = (Read-Host "Email Address")
)
@"
# OpenSSL example configuration file for BATCH certificate generation
# This definition stops the following lines choking if HOME isn't defined.
HOME = .
RANDFILE = $($ENV::HOME)/.rnd
# To use this configuration with the "-extfile" option of the "openssl x509" utility
# name here the section containing the X.509v3 extensions to use:
#extensions = code_sign
####################################################################
[ req ]
default_bits = {0}
default_keyfile = privkey.pem
distinguished_name = req_distinguished_name
#attributes = req_attributes
x509_extensions = v3_ca # The extentions to add to the self signed cert
# req_extensions = v3_ca # Other extensions to add to a certificate request?
## Passwords for private keys could be specified here, instead of on the commandline
# input_password = secret
# output_password = secret
## Set the permitted string types...
## Some software crashes on BMPStrings or UTF8Strings, so we'll stick with
string_mask = nombstr
[ req_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = {1}
countryName_min = 2
countryName_max = 2
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = {2}
localityName = Locality Name (eg, city)
localityName_default = {3}
0.organizationName = Organization Name (eg, company)
0.organizationName_default = {4}
# we can do this but it is not usually needed
#1.organizationName = Second Organization Name (eg, company)
#1.organizationName_default = World Wide Web Pty Ltd
organizationalUnitName = Organizational Unit Name (eg, section)
organizationalUnitName_default = {5}
commonName = Common Name (eg, YOUR name)
commonName_default = {6}
commonName_max = 64
emailAddress = Email Address
emailAddress_default = {7}
emailAddress_max = 64
# SET-ex3 = SET extension number 3
# [ req_attributes ]
# challengePassword = A challenge password
# challengePassword_min = 4
# challengePassword_max = 20
# unstructuredName = An optional company name
[ v3_ca ]
## Extensions for a typical CA
## PKIX recommendations:
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer:always
## PKIX suggests we should include email address in subject alt name
# subjectAltName=email:copy
## But really they want it *only* there or the certs are "deprecated"
# subjectAltName=email:move
## And the issuer details
# issuerAltName=issuer:copy
## This is what PKIX recommends
basicConstraints = critical,CA:true
## some broken software chokes on critical extensions, so you could do this instead.
#basicConstraints = CA:true
## For a normal CA certificate you would want to specify this.
## But it will cause problems for our self-signed certificate.
# keyUsage = cRLSign, keyCertSign
## You might want the netscape-compatible stuff too
# nsCertType = sslCA, emailCA
[ code_sign ]
# These extensions are added when we get a code_signing cert
## PKIX recommendations:
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer
## PKIX suggests we should include email address in subject alt name
# subjectAltName=email:copy
## But really they want it *only* there or the certs are "deprecated"
# subjectAltName=email:move
## And the issuer details
# issuerAltName=issuer:copy
# This goes against PKIX guidelines but some CAs do it and some software
# requires this to avoid interpreting an end user certificate as a CA.
basicConstraints=CA:FALSE
# If nsCertType is omitted, the certificate can be used for anything *except* object signing.
# We just want to allow everything including object signing:
nsCertType = server, client, email, objsign
# This is the vital bit for code-signing
extendedKeyUsage = critical, serverAuth,clientAuth,codeSigning
# This is typical in keyUsage for a client certificate.
keyUsage = nonRepudiation, digitalSignature, keyEncipherment, dataEncipherment
# This will be displayed in Netscape's comment listbox.
nsComment = "OpenSSL Generated Certificate"
[ crl_ext ]
# CRL extensions.
# Only issuerAltName and authorityKeyIdentifier make any sense in a CRL.
# issuerAltName=issuer:copy
authorityKeyIdentifier=keyid:always,issuer:always
"@ -f $keyBits,$Country,$State,$city,$company,$orgUnit,$CommonName,$email
}
if(!$OpenSSLLocation) {
## You should be running the script from the OpenSsl folder
$OpenSSLLocation = Split-Path $MyInvocation.MyCommand.Path
Write-Debug "OpenSSL: $OpenSSLLocation"
}
if( Test-Path $OpenSslLocation ) {
## The OpenSslLoction needs to actually have OpenSsl in it ...
$files = ls (Join-Path $OpenSSLLocation "*.[de][lx][el]") -include libeay32.dll,ssleay32.dll,OpenSSL.exe # libssl32.dll,
if($files.count -lt 3) {
THROW "You need to configure a location where OpenSSL can be run from"
}
} else { THROW "You need to configure a location where OpenSSL can be run from" }
## Don't touch these
[string]$SslCnfPath = (join-path (Convert-Path $CertStorageLocation) PoshOpenSSL.config)
New-Alias OpenSsl (join-path $OpenSSLLocation OpenSSL.exe)
if( !(Test-Path $CertStorageLocation) ) {
New-Item -type directory -path $CertStorageLocation | Push-Location
$forceNew = $true
} else {
Push-Location $CertStorageLocation
}
Write-Debug "SslCnfPath: $SslCnfPath"
Write-Debug "OpenSsl: $((get-alias OpenSsl).Definition)"
## Process the CSR and generate a pfx file
if($forceNew -or (@(Test-Path "$CodeSignName.crt","$CodeSignName.pfx") -contains $false)) {
## Generate the private code-signing key and a certificate signing request (csr)
if($forceNew -or (@(Test-Path "$CodeSignName.key","$CodeSignName.csr") -contains $false)) {
## Generate the private root CA key and convert it into a self-signed certificate (crt)
if($forceNew -or (@(Test-Path "$RootCAName.key","$RootCAName.crt") -contains $false)) {
## Change configuration before -batch processing root key
$CommonName = "$company Certificate Authority"
$orgUnit = "$department Certificate Authority"
$email = Get-UserEmail
Set-Content $SslCnfPath (Get-SslConfig $keyBits $Country $State $city $company $orgUnit $CommonName $email) ## My special config file
OpenSsl genrsa -out "$RootCAName.key" -des3 -passout pass:$(Get-RootCAPassword) $keyBits
OpenSsl req -new -x509 -days $daysCA -key "$RootCAName.key" -out "$RootCAName.crt" -passin pass:$(Get-RootCAPassword) -config $SslCnfPath -batch
}
## Change configuration before -batch processing code-signing key
$CommonName = "$UserName"
$orgUnit = "$department"
$email = Get-UserEmail
Set-Content $SslCnfPath (Get-SslConfig $keyBits $Country $State $city $company $orgUnit $CommonName $email) ## My special config file
OpenSsl genrsa -out "$CodeSignName.key" -des3 -passout pass:$(Get-CodeSignPassword) $keyBits
OpenSsl req -new -key "$CodeSignName.key" -out "$CodeSignName.csr" -passin pass:$(Get-CodeSignPassword) -config $SslCnfPath -batch
}
## Use the root CA key to process the CSR and sign the code-signing key in one step...
OpenSsl x509 -req -days $days -in "$CodeSignName.csr" -CA "$RootCAName.crt" -CAcreateserial -CAkey "$RootCAName.key" -out "$CodeSignName.crt" -setalias $alias -extfile $SslCnfPath -extensions code_sign -passin pass:$(Get-RootCAPassword)
## Combine the signed certificate and the private key into a single file and specify a new password for it ...
OpenSsl pkcs12 -export -out "$CodeSignName.pfx" -inkey "$CodeSignName.key" -in "$CodeSignName.crt" -passin pass:$(Get-CodeSignPassword) -passout pass:$script:CodeSignPassword
}
Pop-Location
if($import) {
## Now we need to import the certificates to the computer so we can use them...
## Sadly, the PowerShell Certificate Provider is read-only, so we need to do this by hand
trap {
if($_.Exception.GetBaseException() -is [UnauthorizedAccessException]) {
write-error "Cannot import certificates as 'Root CA' or 'Trusted Publisher' except in an elevated console."
continue
}
}
## In order to be able to use scripts signed by these certs
## The root cert that signed the code-signing certs must be loaded into the "Root" store
$lm = new-object System.Security.Cryptography.X509certificates.X509Store "root", "LocalMachine"
$lm.Open("ReadWrite")
$lm.Add( (Get-PfxCertificate "$CertStorageLocation\\$RootCAName.crt") )
if($?) {
Write-Host "Successfully imported root certificate to trusted root store" -fore green
}
$lm.Close()
## In order to avoid the "untrusted publisher" prompt
## The public code-signing cert must be loaded into the "TrustedPublishers" store
$tp = new-object System.Security.Cryptography.X509certificates.X509Store "TrustedPublisher", "LocalMachine"
$tp.Open("ReadWrite")
$tp.Add( (Get-PfxCertificate "$CertStorageLocation\\$CodeSignName.crt") )
if($?) {
Write-Host "Successfully imported code-signing certificate to trusted publishers store" -fore green
}
$tp.Close()
if($importall) {
## It's a good practice to go ahead and put our private certificates in "OUR" store too
### Otherwise we have to load it each time from the pfx file using Get-PfxCertificate
##### $cert = Get-PfxCertificate "$CodeSignName.pfx"
##### Set-AuthenticodeSignature -Cert $cert -File Test-Script.ps1
$my = new-object System.Security.Cryptography.X509certificates.X509Store "My", "CurrentUser"
$my.Open( "ReadWrite" )
Get-CodeSignPassword
$my.Add((Get-PfxCertificate "$CertStorageLocation\\$CodeSignName.pfx")) #$script:CodeSignPassword, $DefaultStorage)
if($?) {
Write-Host "Successfully imported code-signing certificate to 'my' store" -fore yellow
}
$my.Close()
}
}
# SIG # Begin signature block
# MIILCQYJKoZIhvcNAQcCoIIK+jCCCvYCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUunVl0UTZlvAjOS219sL9EUT4
# EE6gggbgMIIG3DCCBMSgAwIBAgIJALPpqDj9wp7xMA0GCSqGSIb3DQEBBQUAMIHj
# MQswCQYDVQQGEwJVUzERMA8GA1UECBMITmV3IFlvcmsxEjAQBgNVBAcTCVJvY2hl
# c3RlcjEhMB8GA1UEChMYaHR0cDovL0h1ZGRsZWRNYXNzZXMub3JnMSgwJgYDVQQL
# Ex9TY3JpcHRpbmcgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MTcwNQYDVQQDEy5odHRw
# Oi8vSHVkZGxlZE1hc3Nlcy5vcmcgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MScwJQYJ
# KoZIhvcNAQkBFhhKYXlrdWxASHVkZGxlZE1hc3Nlcy5vcmcwHhcNMDkwMzE1MTkx
# OTE5WhcNMTAwMzE1MTkxOTE5WjCBqzELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5l
# dyBZb3JrMRIwEAYDVQQHEwlSb2NoZXN0ZXIxITAfBgNVBAoTGGh0dHA6Ly9IdWRk
# bGVkTWFzc2VzLm9yZzESMBAGA1UECxMJU2NyaXB0aW5nMRUwEwYDVQQDEwxKb2Vs
# IEJlbm5ldHQxJzAlBgkqhkiG9w0BCQEWGEpheWt1bEBIdWRkbGVkTWFzc2VzLm9y
# ZzCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAPfqxOG9TQN+qZjZ6KfM
# +zBK0YpjeyPL/cFgiGBhiIdYWTBtkbZydFr3IiERKRsUJ0/SKFbhf0C3Bvd/neTJ
# qiZjH4D6xkrfdLlWMmmSXXqjSt48jZp+zfCAIaF8K84e9//7lMicdVFE6VcgoATZ
# /eMKQky4JvphJpzDHYPLxLJQrKd0pjDDwspjdX5RedWkzeZBG7VfBnebLWUzgnMX
# IxRQKfFCMryQDP8weceOnJjfJEf2FYmdpsEg5EKKKbuHsQCMVTxfteKdPvh1oh05
# 1GWyPsvEPh4auJUT8pAVvrdxq+/O9KW/UV01UxjRYM1vdklNw8g7mkJTrrHjSjl7
# tuugCnJjt5kN6v/OaUtRRMR68O85bSTVGOxJGCHUKlyuuTx9tnfIgy4siFYX1Ve8
# xwaAdN3haTon3UkWzncHOq3reCIVF0luwRZu7u+TnOAnz2BRlt+rcT0O73GN20Fx
# gyN2f5VGBbw1KuS7T8XZ0TFCspUdgwAcmTGuEVJKGhVcGAvNlLx+KPc5dba4qEfs
# VZ0MssC2rALC1z61qWuucb5psHYhuD2tw1SrztywuxihIirZD+1+yKE4LsjkM1zG
# fQwDO/DQJwkdByjfB2I64p6mk36OlZAFxVfRBpXSCzdzbgKpuPsbtjkb5lGvKjE1
# JFVls1SHLJ9q80jHz6yW7juBAgMBAAGjgcgwgcUwHQYDVR0OBBYEFO0wLZyg+qGH
# Z4WO8ucEGNIdU1T9MB8GA1UdIwQYMBaAFN2N42ZweJLF1mz0j70TMxePMcUHMAkG
# A1UdEwQCMAAwEQYJYIZIAYb4QgEBBAQDAgTwMCoGA1UdJQEB/wQgMB4GCCsGAQUF
# BwMBBggrBgEFBQcDAgYIKwYBBQUHAwMwCwYDVR0PBAQDAgTwMCwGCWCGSAGG+EIB
# DQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTANBgkqhkiG9w0BAQUF
# AAOCAgEAmKihxd6KYamLG0YLvs/unUTVJ+NW3jZP16R28PpmidY/kaBFOPhYyMl2
# bBGQABe7LA5rpHFAs0F56gYETNoFk0qREVvaoz9u18VfLb0Uwqtnq0P68L4c7p2q
# V3nKmWjeI6H7BAyFuogxmMH5TGDfiqrrVSuh1LtPbkV2Wtto0SAxP0Ndyts2J8Ha
# vu/2rt0Ic5AkyD+RblFPtzkCC/MLVwSNAiDSKGRPRrLaiGxntEzR59GRyf2vwhGg
# oAXUqcJ/CVeHCP6qdSTM39Ut3RmMZHXz5qY8bvLgNYL6MtcJAx+EeUhW497alzm1
# jInXdbikIh0d/peTSDyLbjS8CPFFtS6Z56TDGMf+ouTpEA16otcWIPA8Zfjq+7n7
# iBHjeuy7ONoJ2VDNgqn9B+ft8UWRwnJbyB85T83OAGf4vyhCPz3Kg8kWxY30Bhnp
# Fayc6zQKCpn5o5T0/a0BBHwAyMfr7Lhav+61GpzzG1KfAw58N2GV8KCPKNEd3Zdz
# y07aJadroVkW5R+35mSafKRJp5pz20GDRwZQllqGH1Y/UJFEiI0Bme9ecbl2vzNp
# JjHyl/jLVzNVrBI5Zwb0lCLsykApgNY0yrwEqaiqwcxq5nkXFDhDPQvbdulihSo0
# u33fJreCm2fFyGbTuvR61goSksAvLQhvijLAzcKqWKG+laOtYpAxggOTMIIDjwIB
# ATCB8TCB4zELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5ldyBZb3JrMRIwEAYDVQQH
# EwlSb2NoZXN0ZXIxITAfBgNVBAoTGGh0dHA6Ly9IdWRkbGVkTWFzc2VzLm9yZzEo
# MCYGA1UECxMfU2NyaXB0aW5nIENlcnRpZmljYXRlIEF1dGhvcml0eTE3MDUGA1UE
# AxMuaHR0cDovL0h1ZGRsZWRNYXNzZXMub3JnIENlcnRpZmljYXRlIEF1dGhvcml0
# eTEnMCUGCSqGSIb3DQEJARYYSmF5a3VsQEh1ZGRsZWRNYXNzZXMub3JnAgkAs+mo
# OP3CnvEwCQYFKw4DAhoFAKB4MBgGCisGAQQBgjcCAQwxCjAIoAKAAKECgAAwGQYJ
# KoZIhvcNAQkDMQwGCisGAQQBgjcCAQQwHAYKKwYBBAGCNwIBCzEOMAwGCisGAQQB
# gjcCARUwIwYJKoZIhvcNAQkEMRYEFGPa+3yKeAOuG8MGktIPE98U9IQyMA0GCSqG
# SIb3DQEBAQUABIICACukiWmmkw/T3q/IukaKIIO4/jJLng9v52P60RViKwJn7TOZ
# C6Qcov2zO8/LBm8oIlY+kQil8MXqA3+5D7TGtFfYpyzoUh+Nwks1C9KAMWeRBKAL
# b3H6CVX0H5nRh9PLa2a4WxbYHM6IxCOa/Z8clH4veAZbs5Zq5mtjLV14u8PszAYM
# 4P/H0sXHMZYb9nj0vKjsZdxOlM0g6JHqUszE40tND/5dFuzdr3Tyu/aC6/j/ZFGZ
# jdyaM88kE88qAU9Bs2M18LsSUJx6GsdlXwDD4eCBRH59+QtAnQZB4HUL5KkF53DG
# J0WtRuI+wWmeMU9nNtDMQgSGJev0LVEJ2Ui+UsVA+RvWH04VCBrzlXi2TLzS9bCQ
# 5Fo/t/czCbC4m/WrXQyYNDoHtI/fXE2ctSPq2QQaDF9Bu65MuMGzWa3iFSFmq0uA
# nYivtHSlgyqhPBBmu8fspePkye7PzYoH2Gpykp17R5fBx+rQriKjTkZcGNdAGdQY
# j7SEC93e0KjtZRQA+ABxmVacmNrO6NGbMN2Zd8Pheham1T38V3aWjKvq2d94iUfh
# dgqvWhSu6zw0yE/NaJPTKnixN0j+up/Y7jSO9Cytvl4TNWJkFjDp+u0exl4s6eQ5
# cspbWHwWyYWyg7e0YaclbL7mPygvjxQDWOWgMN9cddvHCq8fiq6VPNTJqeLB
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Select-CLSCompliant_1.ps1
|
Select-CLSCompliant_1.ps1
|
function Select-CLSCompliant {
#.Synopsis
# Outputs the same as "Select-Object *" with basic error handling for properties that are not CLS Compliant
[CmdletBinding()]
param([Parameter(ValueFromPipeline=$true)]$InputObject)
process {
foreach($in in $InputObject) {
$In | Select-Object *
trap [System.Management.Automation.ExtendedTypeSystemException] {
$m = $_.Exception.Message
$matches = [regex]::Matches($m, 'The field/property: \\"(?<field>.*)\\" for type: \\"(?<Type>[^"]+)\\" .* Failed to use non CLS compliant type.')
$type = $matches[0].Groups["Type"].Value -as [Type]
$properties = $type.GetProperties()
$output = @{}
$properties | %{ $Output.($_.Name) = $_.GetValue( $In, $null ) }
$NewObject = new-Object PSObject -Property $Output
$NewObject.pstypenames.insert(0,"Selected." + ($matches[0].Groups["Type"].Value))
Write-Output $NewObject
continue
}
}
}}
|
PowerShellCorpus/PoshCode/ScheduledTasks.ps1
|
ScheduledTasks.ps1
|
# Windows Scheduled Tasks Management PowerShell Module
# http://powershell.codeplex.com
Function Get-ScheduledTasks
{
[CmdletBinding()]
param (
[ValidateNotNullOrEmpty()]
[string] $TaskName,
[string] $HostName )
process
{
if ( $HostName ) { $HostName = "/S $HostName" }
$ScheduledTasks = SCHTASKS.EXE /QUERY /FO CSV /NH $HostName
foreach ( $Item in $ScheduledTasks )
{
if ( $Item -ne "" )
{
$Item = $Item -replace("""|\\s","")
$SplitItem = $Item -split(",")
$ScheduledTaskName = $SplitItem[0]
$ScheduledTaskStatus = $SplitItem[3]
if ( $ScheduledTaskName -ne "" )
{
if ( $ScheduledTaskStatus -eq "" )
{
$ScheduledTaskStatus = "Not Running"
}
else
{
$ScheduledTaskStatus = "Running"
}
$objScheduledTaskName = New-Object System.Object
$objScheduledTaskName | Add-Member -MemberType NoteProperty -Name TaskName -Value $ScheduledTaskName
$objScheduledTaskName | Add-Member -MemberType NoteProperty -Name TaskStatus -Value $ScheduledTaskStatus
$objScheduledTaskName | Where-Object { $_.TaskName -match $TaskName }
}
}
}
}
}
Function Start-ScheduledTask
{
[CmdletBinding()]
param (
[ValidateNotNullOrEmpty()]
[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
[string] $TaskName,
[string] $HostName )
process
{
if ( $HostName ) { $HostName = "/S $HostName" }
SCHTASKS.EXE /RUN /TN $TaskName $HostName
}
}
Function Stop-ScheduledTask
{
[CmdletBinding()]
param (
[ValidateNotNullOrEmpty()]
[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
[string] $TaskName,
[string] $HostName )
process
{
if ( $HostName ) { $HostName = "/S $HostName" }
SCHTASKS.EXE /END /TN $TaskName $HostName
}
}
Export-ModuleMember Get-ScheduledTasks, Start-ScheduledTask, Stop-ScheduledTask
|
PowerShellCorpus/PoshCode/Out-AnsiGraph_1.ps1
|
Out-AnsiGraph_1.ps1
|
#
# Out-AnsiGraph.psm1
# Author: xcud
# History:
# v0.1 September 21, 2009 initial version
#
function Out-AnsiGraph($Parameter1=$null) {
BEGIN {
$q = new-object Collections.queue
}
PROCESS {
if($_) {
$name = $_.($Parameter1[0]);
$val = $_.($Parameter1[1])
if($max -lt $val) { $max = $val}
if($namewidth -lt $name.length) { $namewidth = $name.length }
$q.enqueue(@($name, $val))
}
}
END {
$q | %{
$graph = ""; 0..($_[1]/$max*20) | %{ $graph += "█" }
$name = "{0,$namewidth}" -f $_[0]
"$name $graph " + $_[1]
}
}
}
Export-ModuleMember Out-AnsiGraph
|
PowerShellCorpus/PoshCode/LibrarySqlData.ps1
|
LibrarySqlData.ps1
|
#######################
function Get-SqlData
{
param([string]$serverName=$(throw 'serverName is required.'), [string]$databaseName=$(throw 'databaseName is required.'),
[string]$query=$(throw 'query is required.'))
Write-Verbose "Get-SqlData serverName:$serverName databaseName:$databaseName query:$query"
$connString = "Server=$serverName;Database=$databaseName;Integrated Security=SSPI;"
$da = New-Object "System.Data.SqlClient.SqlDataAdapter" ($query,$connString)
$dt = New-Object "System.Data.DataTable"
[void]$da.fill($dt)
$dt
} #Get-SqlData
#######################
function Set-SqlData
{
param([string]$serverName=$(throw 'serverName is required.'), [string]$databaseName=$(throw 'databaseName is required.'),
[string]$query=$(throw 'query is required.'))
$connString = "Server=$serverName;Database=$databaseName;Integrated Security=SSPI;"
$conn = new-object System.Data.SqlClient.SqlConnection $connString
$conn.Open()
$cmd = new-object System.Data.SqlClient.SqlCommand("$query", $conn)
[void]$cmd.ExecuteNonQuery()
$conn.Close()
} #Set-SqlData
|
PowerShellCorpus/PoshCode/fc6a6ed7-a2a0-4a41-af75-9b06c4fba5de.ps1
|
fc6a6ed7-a2a0-4a41-af75-9b06c4fba5de.ps1
|
#========================================================================
# Code Generated By: SAPIEN Technologies, Inc., PowerShell Studio 2012 v3.1.15
# Generated On: 2/6/2013 2:58 AM
# Generated By: Manoj Nair
# Organization: Self
#========================================================================
#----------------------------------------------
#region Application Functions
#----------------------------------------------
function OnApplicationLoad {
#Note: This function is not called in Projects
#Note: This function runs before the form is created
#Note: To get the script directory in the Packager use: Split-Path $hostinvocation.MyCommand.path
#Note: To get the console output in the Packager (Windows Mode) use: $ConsoleOutput (Type: System.Collections.ArrayList)
#Important: Form controls cannot be accessed in this function
#TODO: Add snapins and custom code to validate the application load
return $true #return true for success or false for failure
}
function OnApplicationExit {
#Note: This function is not called in Projects
#Note: This function runs after the form is closed
#TODO: Add custom code to clean up and unload snapins when the application exits
$script:ExitCode = 0 #Set the exit code for the Packager
}
#endregion Application Functions
#----------------------------------------------
# Generated Form Function
#----------------------------------------------
function Call-CreateFolder_pff {
#----------------------------------------------
#region Import the Assemblies
#----------------------------------------------
[void][reflection.assembly]::Load("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
[void][reflection.assembly]::Load("System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
[void][reflection.assembly]::Load("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
[void][reflection.assembly]::Load("System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
[void][reflection.assembly]::Load("System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
[void][reflection.assembly]::Load("System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
[void][reflection.assembly]::Load("System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
[void][reflection.assembly]::Load("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
[void][reflection.assembly]::Load("System.ServiceProcess, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
#endregion Import Assemblies
#----------------------------------------------
#region Define SAPIEN Types
#----------------------------------------------
try{
$local:type = [ProgressBarOverlay]
}
catch
{
Add-Type -ReferencedAssemblies ('System.Windows.Forms', 'System.Drawing') -TypeDefinition @"
using System;
using System.Windows.Forms;
using System.Drawing;
namespace SAPIENTypes
{
public class ProgressBarOverlay : System.Windows.Forms.ProgressBar
{
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == 0x000F)// WM_PAINT
{
if (Style != System.Windows.Forms.ProgressBarStyle.Marquee || !string.IsNullOrEmpty(this.Text))
{
using (Graphics g = this.CreateGraphics())
{
using (StringFormat stringFormat = new StringFormat(StringFormatFlags.NoWrap))
{
stringFormat.Alignment = StringAlignment.Center;
stringFormat.LineAlignment = StringAlignment.Center;
if (!string.IsNullOrEmpty(this.Text))
g.DrawString(this.Text, this.Font, Brushes.Black, this.ClientRectangle, stringFormat);
else
{
int percent = (int)(((double)Value / (double)Maximum) * 100);
g.DrawString(percent.ToString() + "%", this.Font, Brushes.Black, this.ClientRectangle, stringFormat);
}
}
}
}
}
}
public string TextOverlay
{
get
{
return base.Text;
}
set
{
base.Text = value;
}
}
}
}
"@ | Out-Null
}
#endregion Define SAPIEN Types
#----------------------------------------------
#region Generated Form Objects
#----------------------------------------------
[System.Windows.Forms.Application]::EnableVisualStyles()
$formConsoleFolderCreator = New-Object 'System.Windows.Forms.Form'
$progressbaroverlay1 = New-Object 'SAPIENTypes.ProgressBarOverlay'
$button1Create = New-Object 'System.Windows.Forms.Button'
$datagridview2 = New-Object 'System.Windows.Forms.DataGridView'
$buttonBrowse = New-Object 'System.Windows.Forms.Button'
$textbox2 = New-Object 'System.Windows.Forms.TextBox'
$labelCSVFile = New-Object 'System.Windows.Forms.Label'
$labelProgress = New-Object 'System.Windows.Forms.Label'
$datagridview1 = New-Object 'System.Windows.Forms.DataGridView'
$buttonCreate = New-Object 'System.Windows.Forms.Button'
$combobox1 = New-Object 'System.Windows.Forms.ComboBox'
$textbox1 = New-Object 'System.Windows.Forms.TextBox'
$labelName = New-Object 'System.Windows.Forms.Label'
$openfiledialog1 = New-Object 'System.Windows.Forms.OpenFileDialog'
$InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
#endregion Generated Form Objects
#----------------------------------------------
# User Generated Script
#----------------------------------------------
$formConsoleFolderCreator_Load={
#TODO: Initialize Form Controls here
}
#region Control Helper Functions
function Load-DataGridView
{
<#
.SYNOPSIS
This functions helps you load items into a DataGridView.
.DESCRIPTION
Use this function to dynamically load items into the DataGridView control.
.PARAMETER DataGridView
The ComboBox control you want to add items to.
.PARAMETER Item
The object or objects you wish to load into the ComboBox's items collection.
.PARAMETER DataMember
Sets the name of the list or table in the data source for which the DataGridView is displaying data.
#>
Param (
[ValidateNotNull()]
[Parameter(Mandatory=$true)]
[System.Windows.Forms.DataGridView]$DataGridView,
[ValidateNotNull()]
[Parameter(Mandatory=$true)]
$Item,
[Parameter(Mandatory=$false)]
[string]$DataMember
)
$DataGridView.SuspendLayout()
$DataGridView.DataMember = $DataMember
if ($Item -is [System.ComponentModel.IListSource]`
-or $Item -is [System.ComponentModel.IBindingList] -or $Item -is [System.ComponentModel.IBindingListView] )
{
$DataGridView.DataSource = $Item
}
else
{
$array = New-Object System.Collections.ArrayList
if ($Item -is [System.Collections.IList])
{
$array.AddRange($Item)
}
else
{
$array.Add($Item)
}
$DataGridView.DataSource = $array
}
$DataGridView.ResumeLayout()
}
function Load-ComboBox
{
<#
.SYNOPSIS
This functions helps you load items into a ComboBox.
.DESCRIPTION
Use this function to dynamically load items into the ComboBox control.
.PARAMETER ComboBox
The ComboBox control you want to add items to.
.PARAMETER Items
The object or objects you wish to load into the ComboBox's Items collection.
.PARAMETER DisplayMember
Indicates the property to display for the items in this control.
.PARAMETER Append
Adds the item(s) to the ComboBox without clearing the Items collection.
.EXAMPLE
Load-ComboBox $combobox1 "Red", "White", "Blue"
.EXAMPLE
Load-ComboBox $combobox1 "Red" -Append
Load-ComboBox $combobox1 "White" -Append
Load-ComboBox $combobox1 "Blue" -Append
.EXAMPLE
Load-ComboBox $combobox1 (Get-Process) "ProcessName"
#>
Param (
[ValidateNotNull()]
[Parameter(Mandatory=$true)]
[System.Windows.Forms.ComboBox]$ComboBox,
[ValidateNotNull()]
[Parameter(Mandatory=$true)]
$Items,
[Parameter(Mandatory=$false)]
[string]$DisplayMember,
[switch]$Append
)
if(-not $Append)
{
$ComboBox.Items.Clear()
}
if($Items -is [Object[]])
{
$ComboBox.Items.AddRange($Items)
}
elseif ($Items -is [Array])
{
$ComboBox.BeginUpdate()
foreach($obj in $Items)
{
$ComboBox.Items.Add($obj)
}
$ComboBox.EndUpdate()
}
else
{
$ComboBox.Items.Add($Items)
}
$ComboBox.DisplayMember = $DisplayMember
}
function Load-ListBox
{
<#
.SYNOPSIS
This functions helps you load items into a ListBox or CheckedListBox.
.DESCRIPTION
Use this function to dynamically load items into the ListBox control.
.PARAMETER ListBox
The ListBox control you want to add items to.
.PARAMETER Items
The object or objects you wish to load into the ListBox's Items collection.
.PARAMETER DisplayMember
Indicates the property to display for the items in this control.
.PARAMETER Append
Adds the item(s) to the ListBox without clearing the Items collection.
.EXAMPLE
Load-ListBox $ListBox1 "Red", "White", "Blue"
.EXAMPLE
Load-ListBox $listBox1 "Red" -Append
Load-ListBox $listBox1 "White" -Append
Load-ListBox $listBox1 "Blue" -Append
.EXAMPLE
Load-ListBox $listBox1 (Get-Process) "ProcessName"
#>
Param (
[ValidateNotNull()]
[Parameter(Mandatory=$true)]
[System.Windows.Forms.ListBox]$ListBox,
[ValidateNotNull()]
[Parameter(Mandatory=$true)]
$Items,
[Parameter(Mandatory=$false)]
[string]$DisplayMember,
[switch]$Append
)
if(-not $Append)
{
$listBox.Items.Clear()
}
if($Items -is [System.Windows.Forms.ListBox+ObjectCollection])
{
$listBox.Items.AddRange($Items)
}
elseif ($Items -is [Array])
{
$listBox.BeginUpdate()
foreach($obj in $Items)
{
$listBox.Items.Add($obj)
}
$listBox.EndUpdate()
}
else
{
$listBox.Items.Add($Items)
}
$listBox.DisplayMember = $DisplayMember
}
#endregion
$combobox1_SelectedIndexChanged={
#TODO: Place custom script here
}
$buttonCreate_Click={
#TODO: Place custom script here
switch ($combobox1.SelectedItem) {
"Package Folder" {
$global:ObjectType = 2
}
"Application Folder" {
$global:ObjectType = 6000
}
value3 {
$global:ObjectType = 2
}
default {
$global:ObjectType = 2
}
}
$Arguments = @{Name = $textbox1.Text; ObjectType = $ObjectType; ParentContainerNodeId = 0}
$StoreResults = @{}
Set-WmiInstance -Namespace "Root\\SMS\\Site_P01" -Class "SMS_ObjectContainerNode" -Arguments $Arguments -OutVariable StoreResults
if($Error)
{
$labelProgress.Text = $Error[0].Exception.Message
}
Else {
$labelProgress.Text = "Folder Created Successfully. Results will be displayed soon...."
}
Load-DataGridView -DataGridView $datagridview1 -Item $StoreResults
}
$datagridview1_CellContentClick=[System.Windows.Forms.DataGridViewCellEventHandler]{
#Event Argument: $_ = [System.Windows.Forms.DataGridViewCellEventArgs]
#TODO: Place custom script here
}
$buttonBrowse_Click={
#TODO: Place custom script here
$openfiledialog1.ShowDialog()
$textbox2.Text = $OpenFileDialog1.FileName
$script:CSVFileName = $openfiledialog1.FileName
}
$openfiledialog1_FileOk=[System.ComponentModel.CancelEventHandler]{
#Event Argument: $_ = [System.ComponentModel.CancelEventArgs]
#TODO: Place custom script here
}
$datagridview2_CellContentClick=[System.Windows.Forms.DataGridViewCellEventHandler]{
#Event Argument: $_ = [System.Windows.Forms.DataGridViewCellEventArgs]
#TODO: Place custom script here
}
$button1Create_Click={
#TODO: Place custom script here
$MultipleCreate = Import-Csv $CSVFileName
$TotalUserCount = $MultipleCreate.Count
for ($i=0;$i -lt $TotalUserCount;$i++) {
$Arguments = @{Name = $MultipleCreate[$i].Name; ObjectType = $MultipleCreate[$i].ObjectType; ParentContainerNodeId = $MultipleCreate[$i].ParentContainerNodeId}
Set-WmiInstance -Namespace "Root\\SMS\\Site_P01" -Class "SMS_ObjectContainerNode" -Arguments $Arguments
$script:CustomObject2 = @{}
$CustomObject2[$i] = [pscustomobject]@{Name=$MultipleCreate[$i].Name; Created="True"}
$progressbaroverlay1.Increment(($i + 1)/$TotalUserCount * 100)
$progressbaroverlay1.PerformStep()
}
Load-DataGridView -DataGridView $datagridview2 -Item $CustomObject2
}
$progressbaroverlay1_Click={
#TODO: Place custom script here
}
# --End User Generated Script--
#----------------------------------------------
#region Generated Events
#----------------------------------------------
$Form_StateCorrection_Load=
{
#Correct the initial state of the form to prevent the .Net maximized form issue
$formConsoleFolderCreator.WindowState = $InitialFormWindowState
}
$Form_Cleanup_FormClosed=
{
#Remove all event handlers from the controls
try
{
$progressbaroverlay1.remove_Click($progressbaroverlay1_Click)
$button1Create.remove_Click($button1Create_Click)
$datagridview2.remove_CellContentClick($datagridview2_CellContentClick)
$buttonBrowse.remove_Click($buttonBrowse_Click)
$datagridview1.remove_CellContentClick($datagridview1_CellContentClick)
$buttonCreate.remove_Click($buttonCreate_Click)
$combobox1.remove_SelectedIndexChanged($combobox1_SelectedIndexChanged)
$formConsoleFolderCreator.remove_Load($formConsoleFolderCreator_Load)
$openfiledialog1.remove_FileOk($openfiledialog1_FileOk)
$formConsoleFolderCreator.remove_Load($Form_StateCorrection_Load)
$formConsoleFolderCreator.remove_FormClosed($Form_Cleanup_FormClosed)
}
catch [Exception]
{ }
}
#endregion Generated Events
#----------------------------------------------
#region Generated Form Code
#----------------------------------------------
#
# formConsoleFolderCreator
#
$formConsoleFolderCreator.Controls.Add($progressbaroverlay1)
$formConsoleFolderCreator.Controls.Add($button1Create)
$formConsoleFolderCreator.Controls.Add($datagridview2)
$formConsoleFolderCreator.Controls.Add($buttonBrowse)
$formConsoleFolderCreator.Controls.Add($textbox2)
$formConsoleFolderCreator.Controls.Add($labelCSVFile)
$formConsoleFolderCreator.Controls.Add($labelProgress)
$formConsoleFolderCreator.Controls.Add($datagridview1)
$formConsoleFolderCreator.Controls.Add($buttonCreate)
$formConsoleFolderCreator.Controls.Add($combobox1)
$formConsoleFolderCreator.Controls.Add($textbox1)
$formConsoleFolderCreator.Controls.Add($labelName)
$formConsoleFolderCreator.ClientSize = '522, 603'
$formConsoleFolderCreator.Name = "formConsoleFolderCreator"
$formConsoleFolderCreator.Text = "Console Folder Creator"
$formConsoleFolderCreator.add_Load($formConsoleFolderCreator_Load)
#
# progressbaroverlay1
#
$progressbaroverlay1.Location = '29, 387'
$progressbaroverlay1.Name = "progressbaroverlay1"
$progressbaroverlay1.Size = '464, 27'
$progressbaroverlay1.TabIndex = 11
$progressbaroverlay1.add_Click($progressbaroverlay1_Click)
#
# button1Create
#
$button1Create.Location = '169, 558'
$button1Create.Name = "button1Create"
$button1Create.Size = '152, 27'
$button1Create.TabIndex = 10
$button1Create.Text = "Create"
$button1Create.UseVisualStyleBackColor = $True
$button1Create.add_Click($button1Create_Click)
#
# datagridview2
#
$datagridview2.ColumnHeadersHeightSizeMode = 'AutoSize'
$datagridview2.Location = '30, 425'
$datagridview2.Name = "datagridview2"
$datagridview2.Size = '464, 121'
$datagridview2.TabIndex = 9
$datagridview2.add_CellContentClick($datagridview2_CellContentClick)
#
# buttonBrowse
#
$buttonBrowse.Location = '421, 347'
$buttonBrowse.Name = "buttonBrowse"
$buttonBrowse.Size = '73, 21'
$buttonBrowse.TabIndex = 8
$buttonBrowse.Text = "Browse"
$buttonBrowse.UseVisualStyleBackColor = $True
$buttonBrowse.add_Click($buttonBrowse_Click)
#
# textbox2
#
$textbox2.Location = '83, 348'
$textbox2.Name = "textbox2"
$textbox2.Size = '319, 20'
$textbox2.TabIndex = 7
#
# labelCSVFile
#
$labelCSVFile.Location = '27, 352'
$labelCSVFile.Name = "labelCSVFile"
$labelCSVFile.Size = '71, 27'
$labelCSVFile.TabIndex = 6
$labelCSVFile.Text = "CSV File :"
#
# labelProgress
#
$labelProgress.Location = '26, 107'
$labelProgress.Name = "labelProgress"
$labelProgress.Size = '468, 29'
$labelProgress.TabIndex = 5
#
# datagridview1
#
$datagridview1.AutoSizeColumnsMode = 'ColumnHeader'
$datagridview1.ColumnHeadersHeightSizeMode = 'AutoSize'
$datagridview1.Location = '24, 154'
$datagridview1.Name = "datagridview1"
$datagridview1.Size = '471, 150'
$datagridview1.TabIndex = 4
$datagridview1.add_CellContentClick($datagridview1_CellContentClick)
#
# buttonCreate
#
$buttonCreate.Location = '408, 57'
$buttonCreate.Name = "buttonCreate"
$buttonCreate.Size = '88, 21'
$buttonCreate.TabIndex = 3
$buttonCreate.Text = "&Create"
$buttonCreate.UseVisualStyleBackColor = $True
$buttonCreate.add_Click($buttonCreate_Click)
#
# combobox1
#
$combobox1.FormattingEnabled = $True
[void]$combobox1.Items.Add("Package Folder")
[void]$combobox1.Items.Add("Query Folder")
[void]$combobox1.Items.Add("Software Metering Folder")
[void]$combobox1.Items.Add("Operating System Installer Folder")
[void]$combobox1.Items.Add("Application Folder")
$combobox1.Location = '220, 57'
$combobox1.Name = "combobox1"
$combobox1.Size = '182, 21'
$combobox1.TabIndex = 2
$combobox1.add_SelectedIndexChanged($combobox1_SelectedIndexChanged)
#
# textbox1
#
$textbox1.Location = '60, 58'
$textbox1.Name = "textbox1"
$textbox1.Size = '154, 20'
$textbox1.TabIndex = 1
$textbox1.Text = "Enter the Name of the Folder"
#
# labelName
#
$labelName.Location = '18, 62'
$labelName.Name = "labelName"
$labelName.Size = '47, 19'
$labelName.TabIndex = 0
$labelName.Text = "Name"
#
# openfiledialog1
#
$openfiledialog1.FileName = "openfiledialog1"
$openfiledialog1.Filter = "CSV Files | *.csv"
$openfiledialog1.InitialDirectory = "C:\\Scripts\\Forms"
$openfiledialog1.add_FileOk($openfiledialog1_FileOk)
#endregion Generated Form Code
#----------------------------------------------
#Save the initial state of the form
$InitialFormWindowState = $formConsoleFolderCreator.WindowState
#Init the OnLoad event to correct the initial state of the form
$formConsoleFolderCreator.add_Load($Form_StateCorrection_Load)
#Clean up the control events
$formConsoleFolderCreator.add_FormClosed($Form_Cleanup_FormClosed)
#Show the Form
return $formConsoleFolderCreator.ShowDialog()
} #End Function
#Call OnApplicationLoad to initialize
if((OnApplicationLoad) -eq $true)
{
#Call the form
Call-CreateFolder_pff | Out-Null
#Perform cleanup
OnApplicationExit
}
|
PowerShellCorpus/PoshCode/Check e-mail access type.ps1
|
Check e-mail access type.ps1
|
$ErrorActionPreference = "silentlycontinue"
$login = read-host -prompt "Type the user login"
$Status = @( Get-ADuser $login | select SamAccountName).count
If($Status -eq 0) {
Write-Host No such user exists! -FOREGROUNDCOLOR RED
./the_script_name.ps1
} Else {Write-Host Working on it! -FOREGROUNDCOLOR GREEN
}
Get-Mailbox $login | Get-CASMailbox
|
PowerShellCorpus/PoshCode/Firefox Bookmarks By Key.ps1
|
Firefox Bookmarks By Key.ps1
|
if (!( gmo ShowUI)) {ipmo showui}
if(!(Get-Command DataGrid -ErrorAction SilentlyContinue)) {
Add-UIFunction -Type System.Windows.Controls.DataGrid
}
if(!(Get-Command DataGridTextColumn -ErrorAction SilentlyContinue)) {
Add-UIFunction -Type System.Windows.Controls.DataGridTextColumn
}
if(!(Get-Command DataGridHyperlinkColumn -ErrorAction SilentlyContinue)) {
Add-UIFunction -Type System.Windows.Controls.DataGridHyperlinkColumn
}
# Attention this uses WPF 4.0 cf. http://stackoverflow.com/questions/2094694/launch-powershell-under-net-4/5069146#5069146
# Firefox Bookmarks http://stackoverflow.com/questions/464516/firefox-bookmarks-sqlite-structure
# System.Data.SQLite Download http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki
# Currently DONT INSTALL IT IN GAC http://system.data.sqlite.org/index.html/tktview?name=54e52d4c6f
if (! $sqlitedll)
{
$sqlitedll = [System.Reflection.Assembly]::LoadFrom("C:\\Program Files\\System.Data.SQLite\\bin\\System.Data.SQLite.dll")
}
# copy your firefox bookmarks and tell youe system where to find the copy
$ConnectionString = "Data Source=C:\\Var\\sqlite_ff4\\places.sqlite"
$conn = new-object System.Data.SQLite.SQLiteConnection
$conn.ConnectionString = $ConnectionString
$conn.Open()
# $sql = "SELECT * from moz_bookmarks t1 where parent = 4 and t1.title = 'sqlite' or t1.title = 'sql'"
function Invoke-sqlite
{
param( [string]$sql,
[System.Data.SQLite.SQLiteConnection]$connection
)
$cmd = new-object System.Data.SQLite.SQLiteCommand($sql,$connection)
$ds = New-Object system.Data.DataSet
$da = New-Object System.Data.SQLite.SQLiteDataAdapter($cmd)
$da.fill($ds) | Out-Null
return $ds.tables[0]
}
function Invoke-sqlite2
{
param( [string]$sql,
[System.Data.SQLite.SQLiteConnection]$connection
)
$cmd = new-object System.Data.SQLite.SQLiteCommand($sql,$connection)
$ds = New-Object system.Data.DataSet
$da = New-Object System.Data.SQLite.SQLiteDataAdapter($cmd)
$da.fill($ds) | Out-Null
$ds.tables[0]
}
# $o1 = Invoke-sqlite $sql $conn
# $o2 = Invoke-sqlite2 $sql $conn
function Show-Bockmarks ($conn) {
Show -Parameters $conn -width 1600 -top 100 -left 10 -height 300 -maxheight 900 {
Param(
$conn
)
$useDataGrid = $true
$global:UIInputWindow = $this
GridPanel -ColumnDefinitions @(
ColumnDefinition -Width 900*
) -RowDefinitions @(
RowDefinition -Height 30
RowDefinition -Height 600*
) {
StackPanel -Orientation horizontal -Grid-Column 0 -Grid-Row 0 -Children {
Label '1. Keyword'
TextBox -Name tag1 -width 200
Label '2. Keyword'
TextBox -Name tag2 -width 200
Label '3. Keyword'
TextBox -Name tag3 -width 200
Button -Name Search "search" -On_Click {
$text1 = Select-UIElement $global:UIInputWindow Tag1
$tag1 = $text1.Text
$text2 = Select-UIElement $global:UIInputWindow Tag2
$tag2 = $text2.Text
$text3 = Select-UIElement $global:UIInputWindow Tag3
$tag3 = $text3.Text
if ( $tag2 -ne '') {
$clause2 = @"
join moz_bookmarks l2 on b.fk = l2.fk and b.id <> l2.id
join moz_bookmarks t2 on l2.parent = t2.id and t2.parent = 4 and upper(t2.title) = upper('$tag2')
"@
} else { $clause2 = '' }
if ( $tag3 -ne '') {
$clause3 = @"
join moz_bookmarks l3 on b.fk = l3.fk and b.id <> l3.id
join moz_bookmarks t3 on l3.parent = t3.id and t3.parent = 4 and upper(t3.title) = upper('$tag3')
"@
} else { $clause3 = '' }
$ff_sql = @"
SELECT b.title, datetime (b.dateAdded / 1000000, 'unixepoch', 'localtime') dateAdded , p.url
from moz_bookmarks b
join moz_bookmarks l1 on b.fk = l1.fk and b.id <> l1.id
join moz_bookmarks t1 on l1.parent = t1.id and t1.parent = 4 and upper(t1.title) = upper('$tag1')
join moz_places p on b.fk = p.id $clause2 $clause3
where b.title is not null and b.type = 1
order by b.dateAdded
"@
Write-Host $ff_sql
$global:UIInputWindow.Title = "$($conn.database) Database Browser"
$dg = Select-UIElement $global:UIInputWindow TableView
$dg.ItemsSource = @(Invoke-sqlite -sql $ff_sql -connection $conn)
# $TableView.DataContext = @(Invoke-sqlite -sql $ff_sql -connection $conn)
}
Button -Name Cancel "Close" -On_Click {$global:UIInputWindow.Close()}
}
If ($useDataGrid)
{
DataGrid -Grid-Column 0 -Grid-Row 1 `
-Name TableView `
-columns {
DataGridTextColumn -width 500* -Header "title" -Binding { Binding -Path "title" }
DataGridTextColumn -width 100* -Header "dateAdded" -Binding { Binding -Path "dateAdded" }
DataGridHyperlinkColumn -width 500* -Header "url" -Binding { Binding -Path "url" } `
-ContentBinding { Binding -Path "url" }
# -On_HyperlinkClick {
# Write-Host $this
# }
} -On_SelectionChanged {
start $this.selecteditem.url
}
} else {
ListView -Grid-Column 0 -Grid-Row 1 -Name TableView -View {
GridView -AllowsColumnReorder -Columns {
GridViewColumn -Header "title" -DisplayMemberBinding { Binding -Path "title" }
GridViewColumn -Header "dateAdded" -DisplayMemberBinding { Binding -Path "dateAdded" }
GridViewColumn -Header "url" -DisplayMemberBinding { Binding -Path "url" }
}
} -On_SelectionChanged {
start $this.selecteditem.url
}
}
}
}
}
Show-Bockmarks $conn
$conn.close()
|
PowerShellCorpus/PoshCode/PowerOAuth Beta 2.ps1
|
PowerOAuth Beta 2.ps1
|
if(@(Import-ConstructorFunctions -Path "$PSScriptRoot\\Types_Generated").Count -lt 3) {
Add-ConstructorFunction -T Hammock.Authentication.OAuth.OAuthCredentials, Hammock.RestClient, Hammock.RestRequest -Path "$PSScriptRoot\\Types_Generated"
}
$RequestToken = "request_token"
$AccessToken = "access_token"
$Authorize = "authorize"
# $Yammer = @{
# Authority = "https://www.yammer.com/oauth"
# ConsumerKey = 'aaaaaaaaaaaaaaaaaaaa'
# ConsumerSecret = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
# }
# $Twitter = new-object PSObject -Property @{
# Authority = 'https://api.twitter.com/oauth/'
# ConsumerKey = 'aaaaaaaaaaaaaaaaaaaaa'
# ConsumerSecret = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
# } | Get-OAuthCredentials
function Get-OAuthCredentials {
#.Synopsis
# Get verified OAuth credentials from an OAuth service
#.Description
# Gets verified OAuth credentials from an OAuth service using the desktop "Verified App" system
[CmdletBinding()]
param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[string]$Authority
,
[Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias('Key')]
[string]$ConsumerKey
,
[Parameter(Position=2, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias('Secret')]
[string]$ConsumerSecret
)
process {
$CachePath = Join-Path $PSScriptRoot "$(($Authority -as [Uri]).Authority).clixml"
if(Test-Path $CachePath) {
return Import-CliXml $CachePath
}
##############################################
### STEP 1: Request a user token
$cred1 = New-OAuthCredentials -Type RequestToken -SignatureMethod HmacSha1 -ConsumerKey $ConsumerKey -ConsumerSecret $ConsumerSecret
$client = New-RestClient -Cred $cred1 -Authority $Authority
# $client.AddField( "format", "xml" ) ## this doesn't work for some reason
$request = New-RestRequest -Path $RequestToken
$RequestResponse = $client.Request( $request )
##############################################
### STEP 2: Get the user to verify that token
$RequestAuth = [System.Web.HttpUtility]::ParseQueryString($RequestResponse.Content)
$AuthURL = "{0}/{1}?oauth_token={2}" -f $Authority.TrimEnd('/'), $Authorize, $RequestAuth['oauth_token']
Start $AuthURL
$AccessVerifier = Read-Host "Please enter the token from the web site: $AuthURL"
##############################################
### STEP 3: Get an access token
$cred2 = New-OAuthCredentials -Type AccessToken -SignatureMethod HmacSha1 -Verifier $AccessVerifier `
-ConsumerKey $ConsumerKey -ConsumerSecret $ConsumerSecret `
-Token $RequestAuth['oauth_token'] -TokenSecret $RequestAuth['oauth_token_secret']
$client = New-RestClient -Cred $cred2 -Authority $Authority
# $client.AddField( "format", "xml" ) ## this doesn't work for some reason
$request = New-RestRequest -Path $AccessToken
$AccessResponse = $client.Request( $request )
$AccessAuth = [System.Web.HttpUtility]::ParseQueryString($AccessResponse.Content)
##############################################
### STEP 4: Now stash that stuff somewhere!
$credentials = New-OAuthCredentials -Type AccessToken -SignatureMethod HmacSha1 `
-ConsumerKey $ConsumerKey -ConsumerSecret $ConsumerSecret `
-Token $RequestAuth['oauth_token'] -TokenSecret $RequestAuth['oauth_token_secret']
Export-CliXml $CachePath -Input $Credentials
return $credentials
}}
|
PowerShellCorpus/PoshCode/New-RDP.ps1
|
New-RDP.ps1
|
########################################################################################################################
# NAME
# New-RDP
#
# SYNOPSIS
# Creates a new RDP file to store Remote Desktop connection settings.
#
# SYNTAX
# Start-RDP [-Path] <string> [[-Server] <string>] [-PassThru] [-Force]
#
# DETAILED DESCRIPTION
# The New-RDP cmdlet creates a new, blank RDP file with required settings.
#
# PARAMETERS
# -Path <string>
# Specifies the path to save the new RDP file at.
#
# Required? true
# Position? 1
# Default value
# Accept pipeline input? false
# Accept wildcard characters? false
#
# -Server <string>
# Specifies the name of the server to connect to. May also include an IP address, domain, and/or port.
#
# Required? false
# Position? 2
# Default value
# Accept pipeline input? false
# Accept wildcard characters? false
#
# -PassThru <SwitchParameter>
# Passes thru an object that represents the new RDP file to the pipeline. By default, this cmdlet does
# not pass any objects through the pipeline.
#
# Required? false
# Position? named
# Default value false
# Accept pipeline input? false
# Accept wildcard characters? false
#
# -Force <SwitchParameter>
# Overrides restrictions that prevent the command from succeeding.
#
# Required? false
# Position? named
# Default value false
# Accept pipeline input? false
# Accept wildcard characters? false
#
# INPUT TYPE
#
#
# RETURN TYPE
# System.IO.FileInfo
#
# NOTES
#
# -------------------------- EXAMPLE 1 --------------------------
#
# C:\\PS>New-RDP -Path C:\\myserver.rdp -Server myserver
#
#
# This command creates a new RDP file to connect to the server named "myserver".
#
#
#Function global:New-RDP {
param(
[string]$Path = $(throw "A path to the new RDP file is required."),
[string]$Server = "",
[switch]$PassThru,
[switch]$Force
)
if (!(Test-Path $path) -or $force) {
Set-Content -Path $path -Value "full address:s:$server" -Force
if ($passthru) {
Get-ChildItem -Path $path
}
} else {
throw "Path already exists, use the -Force switch."
}
#}
|
PowerShellCorpus/PoshCode/6bdd2502-383e-47c0-9f8c-f6424b6ba672.ps1
|
6bdd2502-383e-47c0-9f8c-f6424b6ba672.ps1
|
# Connect-VIServer <vCenter server>
# Uncomment the next line to test this script
# $WhatIfPreference = $true
if (-not (Get-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue)) {
Add-PSSnapin VMware.VimAutomation.Core
}
if (-not (Get-PSSnapin Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue)) {
Add-PSSnapin Quest.ActiveRoles.ADManagement
}
$VMs = Get-Cluster -Name <Cluster name> | Get-VM | Sort Name
$VM = $VMs | Select -First 1
If (-not $vm.CustomFields.ContainsKey("CreatedBy")) {
Write-Host "Creating CreatedBy Custom field for all VM's"
New-CustomAttribute -TargetType VirtualMachine -Name CreatedBy | Out-Null
}
If (-not $vm.CustomFields.ContainsKey("CreatedOn")) {
Write-Host "Creating CreatedOn Custom field for all VM's"
New-CustomAttribute -TargetType VirtualMachine -Name CreatedOn | Out-Null
}
Foreach ($VM in $VMs){
If ($vm.CustomFields["CreatedBy"] -eq $null -or $vm.CustomFields["CreatedBy"] -eq ""){
Write-Host "Finding creator for $vm"
$Event = $VM | Get-VIEvent -Types Info | Where { $_.Gettype().Name -eq "VmBeingDeployedEvent" -or $_.Gettype().Name -eq "VmCreatedEvent" -or $_.Gettype().Name -eq "VmRegisteredEvent" -or $_.Gettype().Name -eq "VmClonedEvent"}
If (($Event | Measure-Object).Count -eq 0){
$User = "Unknown"
$Created = "Unknown"
} Else {
If ($Event.Username -eq "" -or $Event.Username -eq $null) {
$User = "Unknown"
} Else {
$User = (Get-QADUser -Identity $Event.Username).DisplayName
if ($User -eq $null -or $User -eq ""){
$User = $Event.Username
}
$Created = $Event.CreatedTime
}
}
Write "Adding info to $($VM.Name)"
Write-Host -ForegroundColor Yellow "CreatedBy $User"
$VM | Set-Annotation -CustomAttribute "CreatedBy" -Value $User | Out-Null
Write-Host -ForegroundColor Yellow "CreatedOn $Created"
$VM | Set-Annotation -CustomAttribute "CreatedOn" -Value $Created | Out-Null
}
}
|
PowerShellCorpus/PoshCode/Get-FileEncoding_5.ps1
|
Get-FileEncoding_5.ps1
|
<#
.SYNOPSIS
Gets file encoding.
.DESCRIPTION
The Get-FileEncoding function determines encoding by looking at Byte Order Mark (BOM).
Based on port of C# code from http://www.west-wind.com/Weblog/posts/197245.aspx
.EXAMPLE
Get-ChildItem *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {$_.Encoding -ne 'ASCII'}
This command gets ps1 files in current directory where encoding is not ASCII
.EXAMPLE
Get-ChildItem *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {$_.Encoding -ne 'ASCII'} | foreach {(get-content $_.FullName) | set-content $_.FullName -Encoding ASCII}
Same as previous example but fixes encoding using set-content
#>
function Get-FileEncoding
{
[CmdletBinding()] Param (
[Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] [string]$Path
)
[byte[]]$byte = get-content -Encoding byte -ReadCount 4 -TotalCount 4 -Path $Path
if ($byte.count -ge 0)
{
if ( $byte[0] -eq 0xef -and $byte[1] -eq 0xbb -and $byte[2] -eq 0xbf )
{ Write-Output 'UTF8' }
elseif ($byte[0] -eq 0xfe -and $byte[1] -eq 0xff)
{ Write-Output 'BigEndianUnicode' }
elseif ($byte[0] -eq 0xff -and $byte[1] -eq 0xfe)
{ Write-Output 'Unicode' }
elseif ($byte[0] -eq 0 -and $byte[1] -eq 0 -and $byte[2] -eq 0xfe -and $byte[3] -eq 0xff)
{ Write-Output 'UTF32' }
elseif ($byte[0] -eq 0x2b -and $byte[1] -eq 0x2f -and $byte[2] -eq 0x76)
{ Write-Output 'UTF7'}
else
{ Write-Output 'ASCII' }
}
}
|
PowerShellCorpus/PoshCode/LibraryMSCS_4.ps1
|
LibraryMSCS_4.ps1
|
# ------------------------------------------------------------------------
### <Script>
### <Author>
### Chad Miller
### </Author>
### <Description>
### Defines functions for working with Microsoft Cluster Service (MSCS)
### Updated 8/3/2011
### Added Authentication PacketPrivacy to fix Access Denied errorson
### Windows 2008/2008 R2 clusters
### </Description>
### <Usage>
### . ./LibraryMSCS.ps1
### </Usage>
### </Script>
# ------------------------------------------------------------------------
#######################
function Get-Cluster
{
param($cluster)
gwmi -class "MSCluster_Cluster" -namespace "root\\mscluster" -computername $cluster -Authentication PacketPrivacy
} #Get-Cluster
#######################
function Get-ClusterName
{
param($cluster)
Get-Cluster $cluster | select -ExpandProperty name
} #Get-ClusterName
#######################
function Get-ClusterNode
{
param($cluster)
gwmi -class MSCluster_Node -namespace "root\\mscluster" -computername $cluster -Authentication PacketPrivacy | add-member -pass NoteProperty Cluster $cluster
} #Get-ClusterNode
#######################
function Get-ClusterSQLVirtual
{
param($cluster)
gwmi -class "MSCluster_Resource" -namespace "root\\mscluster" -computername $cluster -Authentication PacketPrivacy | where {$_.type -eq "SQL Server"} | Select @{n='Cluster';e={$cluster}}, Name, State, @{n='VirtualServerName';e={$_.PrivateProperties.VirtualServerName}}, @{n='InstanceName';e={$_.PrivateProperties.InstanceName}}, `
@{n='ServerInstance';e={("{0}\\{1}" -f $_.PrivateProperties.VirtualServerName,$_.PrivateProperties.InstanceName).TrimEnd('\\')}}, `
@{n='Node';e={$(gwmi -namespace "root\\mscluster" -computerName $cluster -Authentication PacketPrivacy -query "ASSOCIATORS OF {MSCluster_Resource.Name='$($_.Name)'} WHERE AssocClass = MSCluster_NodeToActiveResource" | Select -ExpandProperty Name)}}
} #Get-ClusterSQLVirtual
#######################
function Get-ClusterNetworkName
{
param($cluster)
gwmi -class "MSCluster_Resource" -namespace "root\\mscluster" -computername $cluster -Authentication PacketPrivacy | where {$_.type -eq "Network Name"} | Select @{n='Cluster';e={$cluster}}, Name, State, @{n='NetworkName';e={$_.PrivateProperties.Name}}, `
@{n='Node';e={$(gwmi -namespace "root\\mscluster" -computerName $cluster -Authentication PacketPrivacy -query "ASSOCIATORS OF {MSCluster_Resource.Name='$($_.Name)'} WHERE AssocClass = MSCluster_NodeToActiveResource" | Select -ExpandProperty Name)}}
} #Get-ClusterNetworkName
#######################
function Get-ClusterResource
{
param($cluster)
gwmi -ComputerName $cluster -Authentication PacketPrivacy -Namespace "root\\mscluster" -Class MSCluster_Resource | add-member -pass NoteProperty Cluster $cluster |
add-member -pass ScriptProperty Node `
{ gwmi -namespace "root\\mscluster" -computerName $this.Cluster -Authentication PacketPrivacy -query "ASSOCIATORS OF {MSCluster_Resource.Name='$($this.Name)'} WHERE AssocClass = MSCluster_NodeToActiveResource" | Select -ExpandProperty Name } |
add-member -pass ScriptProperty Group `
{ gwmi -ComputerName $this.Cluster -Authentication PacketPrivacy -Namespace "root\\mscluster" -query "ASSOCIATORS OF {MSCluster_Resource.Name='$($this.Name)'} WHERE AssocClass = MSCluster_ResourceGroupToResource" | Select -ExpandProperty Name }
} #Get-ClusterResource
#######################
function Get-ClusterGroup
{
param($cluster)
gwmi -class MSCluster_ResourceGroup -namespace "root\\mscluster" -computername $cluster -Authentication PacketPrivacy | add-member -pass NoteProperty Cluster $cluster |
add-member -pass ScriptProperty Node `
{ gwmi -namespace "root\\mscluster" -computerName $this.Cluster -Authentication PacketPrivacy -query "ASSOCIATORS OF {MSCluster_ResourceGroup.Name='$($this.Name)'} WHERE AssocClass = MSCluster_NodeToActiveGroup" | Select -ExpandProperty Name } |
add-member -pass ScriptProperty PreferredNodes `
{ @(,(gwmi -namespace "root\\mscluster" -computerName $this.Cluster -Authentication PacketPrivacy -query "ASSOCIATORS OF {MSCluster_ResourceGroup.Name='$($this.Name)'} WHERE AssocClass = MSCluster_ResourceGroupToPreferredNode" | Select -ExpandProperty Name)) }
} #Get-ClusterGroup
|
PowerShellCorpus/PoshCode/Invoke-ExecuteTSQL .ps1
|
Invoke-ExecuteTSQL .ps1
|
#######################
<#
.SYNOPSIS
Execute T-SQL Statments and return messages from SQL Server (print).
.DESCRIPTION
Execute T-SQL Statments and return messages from SQL Server (print).
.INPUTS
None
You cannot pipe objects to Invoke-ExecuteTSQL
.OUTPUTS
PSObject :
Boolean Exitcode = $True or $False indicating if the query ran successfully
String ErrorMessage = The ErrorMessage if not ran successfully
String Message = Messages from SQL Server (print)
.EXAMPLE
Invoke-ExecuteTSQL -SQLInstanceName . -DatabaseName YourDB -UserName YourUserName -PassWord YourPassword -Query $Query -verbose
This command runs a T-SQL Query using UserName and Password
.EXAMPLE
Invoke-ExecuteTSQL -SQLInstanceName . -DatabaseName YourDB -Query $Query -verbose
This command runs a T-SQL Query using TrustedConnection
.LINK
Invoke-ExecuteTSQL
#>
function Invoke-ExecuteTSQL {
[cmdletbinding()]
Param(
[Parameter(Position=0,Mandatory = $true)]
[ValidateNotNullorEmpty()]
[string]$SQLInstanceName,
[Parameter(Position=1,Mandatory = $true)]
[ValidateNotNullorEmpty()]
[string]$DatabaseName,
[Parameter(Position=2)]
[string]$UserName,
[Parameter(Position=3)]
[string]$PassWord,
[Parameter(Position=4,Mandatory = $true)]
[ValidateNotNullorEmpty()]
[string]$Query
)
function Get-SQLConnectionEvent($EventID) {
write-output (Get-Event -SourceIdentifier $EventID -ErrorAction SilentlyContinue |
Select -ExpandProperty SourceEventArgs |
Select -ExpandProperty message)
Remove-Event -SourceIdentifier $EventID -ErrorAction SilentlyContinue
}
try {
if($Username -and $Password) {
Write-Verbose "Connecting to SQL Server using trusted connection"
$SqlConnection.ConnectionString = "Server=$($SQLInstanceName);Database=$($DatabaseName);Integrated Security=True"
} else {
Write-Verbose "Connecting to SQL Server using Username and Password"
$SqlConnection.ConnectionString = "Server=$($SQLInstanceName);Database=$($DatabaseName);UID=$($Username);PWD=$($Password)"
}
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=localhost;Database=confio;Integrated Security=True"
$eventID = "SQLConnectionEvent$(Get-date -format 'yyyyMMddhhmmss')";
write-verbose "Registering the event $eventID"
Register-ObjectEvent -inputObject $SqlConnection -eventName InfoMessage -sourceIdentifier $eventID
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.Connection = $SqlConnection
$SqlCmd.CommandTimeout = 0
$SqlCmd.Connection.Open()
write-verbose "Running the Query"
$SqlCmd.CommandText = $Query
$SqlCmd.ExecuteNonQuery() | Out-Null
$ExitCode = $true
$Message = Get-SQLConnectionEvent $eventID
$ErroMessage = ""
} catch {
$ExitCode = $false
$Message = ""
$ErroMessage = $_.exception
}
Finally {
if ($SqlCmd.Connection.State -eq [System.Data.ConnectionState]::Open) {
write-verbose "Closing Connection"
$SqlCmd.Connection.Close()
$SqlCmd.Connection.Dispose()
}
}
Write-Output (New-Object psobject -Property @{ 'ExitCode' = $ExitCode
'Message' = $Message
'ErrorMessage' =$ErroMessage})
}
|
PowerShellCorpus/PoshCode/Get-Credential 2.6.ps1
|
Get-Credential 2.6.ps1
|
## Get-Credential
## An improvement over the default cmdlet which has no options ...
###################################################################################################
## History
## v 2.6 Put back support for passing in the domain when getting credentials without prompting
## v 2.5 Added examples for the help
## v 2.4 Fix a bug in -Store when the UserName isn't passed in as a parameter
## v 2.3 Add -Store switch and support putting credentials into the file system
## v 2.1 Fix the comment help and parameter names to agree with each other (whoops)
## v 2.0 Rewrite for v2 to replace the default Get-Credential
## v 1.2 Refactor ShellIds key out to a variable, and wrap lines a bit
## v 1.1 Add -Console switch and set registry values accordingly (ouch)
## v 1.0 Add Title, Message, Domain, and UserName options to the Get-Credential cmdlet
###################################################################################################
function Get-Credential {
## .Synopsis
## Gets a credential object based on a user name and password.
## .Description
## The Get-Credential function creates a credential object for a specified username and password, with an optional domain. You can use the credential object in security operations.
##
## The function accepts more parameters to customize the security prompt than the default Get-Credential cmdlet (including forcing the call through the console if you're in the native PowerShell.exe CMD console), but otherwise functions identically.
## .Example
## Get-Credential -user key -pass secret -store | % { $_.GetNetworkCredential() } | fl *
##
## Demonstrates the ability to store passwords securely, and pass them in on the command line
## .Example
## Get-Credential key
##
## If you haven't stored the password for "key", you'll be prompted with the regular PowerShell credential prompt, otherwise it will read the stored password and return credentials without prompting
## .Example
## Get-Credential -inline
##
## Will prompt for credentials inline in the host instead of in a popup dialog
[CmdletBinding(DefaultParameterSetName="Prompted")]
PARAM(
# A default user name for the credential prompt, or a pre-existing credential (would skip all prompting)
[Parameter(ParameterSetName="Prompted",Position=1,Mandatory=$false)]
[Parameter(ParameterSetName="Promptless",Position=1,Mandatory=$true)]
[Parameter(ParameterSetName="StoreCreds",Position=1,Mandatory=$true)]
[Parameter(ParameterSetName="Flush",Position=1,Mandatory=$true)]
[Alias("Credential")]
[PSObject]$UserName=$null
,
# Allows you to override the default window title of the credential dialog/prompt
#
# You should use this to allow users to differentiate one credential prompt from another. In particular, if you're prompting for, say, Twitter credentials, you should put "Twitter" in the title somewhere. If you're prompting for domain credentials. Being specific not only helps users differentiate and know what credentials to provide, but also allows tools like KeePass to automatically determine it.
[Parameter(ParameterSetName="Prompted",Position=2,Mandatory=$false)]
[string]$Title=$null
,
# Allows you to override the text displayed inside the credential dialog/prompt.
#
# You can use this for things like presenting an explanation of what you need the credentials for.
[Parameter(ParameterSetName="Prompted",Position=3,Mandatory=$false)]
[string]$Message=$null
,
# Specifies the default domain to use if the user doesn't provide one (by default, this is null)
[Parameter(ParameterSetName="Prompted",Position=4,Mandatory=$false)]
[Parameter(ParameterSetName="Promptless",Position=4,Mandatory=$false)]
[string]$Domain=$null
,
# The Get-Credential cmdlet forces you to always return DOMAIN credentials (so even if the user provides just a plain user name, it prepends "\\" to the user name). This switch allows you to override that behavior and allow generic credentials without any domain name or the leading "\\".
[Parameter(ParameterSetName="Prompted",Mandatory=$false)]
[switch]$GenericCredentials
,
# Forces the credential prompt to occur inline in the console/host using Read-Host -AsSecureString (not implemented properly in PowerShell ISE)
[Parameter(ParameterSetName="Prompted",Mandatory=$false)]
[switch]$Inline
,
# Store the credential in the file system (and overwrite them)
[Parameter(ParameterSetName="Prompted",Mandatory=$false)]
[Parameter(ParameterSetName="Promptless",Mandatory=$false)]
[Parameter(ParameterSetName="StoreCreds",Mandatory=$true)]
[switch]$Store
,
# Remove stored credentials from the file system
[Parameter(ParameterSetName="Prompted",Mandatory=$false)]
[Parameter(ParameterSetName="Promptless",Mandatory=$false)]
[Parameter(ParameterSetName="Flush",Mandatory=$true)]
[switch]$Flush
,
# Allows you to override the path to store credentials in
[Parameter(ParameterSetName="Prompted",Mandatory=$false)]
[Parameter(ParameterSetName="Promptless",Mandatory=$false)]
[Parameter(ParameterSetName="StoreCreds",Mandatory=$false)]
$CredentialFolder = $(Join-Path ${Env:APPDATA} Credentials)
,
# The password
[Parameter(ParameterSetName="Promptless",Position=5,Mandatory=$true)]
$Password = $(
if($UserName -and (Test-Path "$(Join-Path $CredentialFolder $UserName).cred")) {
if($Flush) {
Remove-Item "$(Join-Path $CredentialFolder $UserName).cred"
} else {
Get-Content "$(Join-Path $CredentialFolder $UserName).cred" | ConvertTo-SecureString
}
})
)
process {
[PSCredential]$Credential = $null
if( $UserName -is [System.Management.Automation.PSCredential]) {
$Credential = $UserName
} elseif($UserName -ne $null) {
$UserName = $UserName.ToString()
}
if($Password) {
if($Password -isnot [System.Security.SecureString]) {
[char[]]$Chars = $Password.ToString().ToCharArray()
$Password = New-Object System.Security.SecureString
foreach($c in $chars) { $Password.AppendChar($c) }
}
if($Domain) {
$Credential = New-Object System.Management.Automation.PSCredential ${Domain}\\${UserName}, ${Password}
} else {
$Credential = New-Object System.Management.Automation.PSCredential ${UserName}, ${Password}
}
}
if(!$Credential) {
if($Inline) {
if($Title) { Write-Host $Title }
if($Message) { Write-Host $Message }
if($Domain) {
if($UserName -and $UserName -notmatch "[@\\\\]") {
$UserName = "${Domain}\\${UserName}"
}
}
if(!$UserName) {
$UserName = Read-Host "User"
if(($Domain -OR !$GenericCredentials) -and $UserName -notmatch "[@\\\\]") {
$UserName = "${Domain}\\${UserName}"
}
}
$Credential = New-Object System.Management.Automation.PSCredential $UserName,$(Read-Host "Password for user $UserName" -AsSecureString)
}
if($GenericCredentials) { $Type = "Generic" } else { $Type = "Domain" }
## Now call the Host.UI method ... if they don't have one, we'll die, yay.
## BugBug? PowerShell.exe (v2) disregards the last parameter
$Credential = $Host.UI.PromptForCredential($Title, $Message, $UserName, $Domain, $Type, "Default")
}
if($Store) {
$CredentialFile = "$(Join-Path $CredentialFolder $Credential.UserName).cred"
if(!(Test-Path $CredentialFolder)) {
mkdir $CredentialFolder | out-null
}
$Credential.Password | ConvertFrom-SecureString | Set-Content $CredentialFile
}
return $Credential
}
}
|
PowerShellCorpus/PoshCode/http___bestfreeipadgames.ps1
|
http___bestfreeipadgames.ps1
|
A man is not old as long as he is seeking something. A man is not old until regrets take the place of dreams.
-----------------------------------
|
PowerShellCorpus/PoshCode/Test-VM_1.ps1
|
Test-VM_1.ps1
|
Function Test-VM
{
[cmdletbinding()]
Param
(
[Parameter(Mandatory=$true,Position=1)]
[string[]]$Name,
[Parameter(Mandatory=$true,Position=2)]
[string[]]$ComputerName
)
Process
{
$results = @()
foreach ($cName in $ComputerName) {
foreach ($vName in $Name) {
$result = New-Object System.Management.Automation.PSObject
$result | Add-Member -NotePropertyName ComputerName -NotePropertyValue $cName
$result | Add-Member -NotePropertyName Name -NotePropertyValue $vName
Try
{
$vm = Get-VM -ComputerName $cName -Name $vName -ErrorAction Stop
if ($vm -ne $null) {
$Existence = $true
} else {
$Existence = $false
}
}
Catch
{
#Display an error message
}
$result | Add-Member -NotePropertyName Existence -NotePropertyValue $Existence
$results += $result
}
}
return $results
}
}
|
PowerShellCorpus/PoshCode/Set Active Sync DeviceID_1.ps1
|
Set Active Sync DeviceID_1.ps1
|
# Requires a connection to Exchange Server, or Exchange Management Shell
$s = New-PSSession -ConfigurationName Microsoft.Exchange -Name ExchMgmt -ConnectionUri http://ex14.domain.local/PowerShell/ -Authentication Kerberos
Import-PSSession $s
# Get all Client Access Server properties for all mailboxes with an ActiveSync Device Partnership
$Mailboxes = Get-CASMailbox -Filter {HasActivesyncDevicePartnership -eq $true} -ResultSize Unlimited
# Get DeviceID for all mailboxes
$EASMailboxes = $Mailboxes | Select-Object PrimarySmtpAddress,@{N='DeviceID';E={Get-ActiveSyncDeviceStatistics -Mailbox $_.Identity | Select-Object –ExpandProperty DeviceID}}
# Set the ActiveSyncAllowedDeviceIDs attribute of all Mailboxes
$EASMailboxes | foreach {Set-CASMailbox $_.PrimarySmtpAddress -ActiveSyncAllowedDeviceIDs $_.DeviceID}
|
PowerShellCorpus/PoshCode/Test-CommandValidation.ps1
|
Test-CommandValidation.ps1
|
#############################################################
#
# PS II> Test-CommandValidation -command get-process | fl
# VerbNounConvention : True
# ReservedKeyWords : True
# VerbConvention : True
#
# author: Walid Toumi
#############################################################
function Test-CommandValidation {
param($Command,[switch]$SimpleForm)
$keys = man key |
Select-String "(\\S+)(?=\\s{5,}about_*)" |
select -expand Matches |
select -expand value
$verbNounConvention = $verbconvention = $reservedkeywords = $false
$verb,$noun = $Command.Split('-')
if($noun) {
$verbNounConvention = $true
if( (get-verb $verb) ) { $verbconvention = $true }
if($keys -contains $noun) { $reservedkeywords = $true }
}
else {
$reservedkeywords = $verbconvention = $null
}
$objPS=new-object PSObject -prop @{
VerbNounConvention = $verbNounConvention
VerbConvention = $verbconvention
ReservedKeyWords = $reservedkeywords
}
if($SimpleForm) {
switch($objPS) {
{!$_.ReservedKeyWords -and $_.VerbConvention -and $_.VerbNounConvention}
{Write-Host "PASS !!" -ForegroundColor green}
{!$_.VerbConvention -and !$_.VerbConvention -and !$_.VerbNounConvention}
{Write-Host "FAIL !!" -ForegroundColor red}
default
{ Write-Host "MAYBE !!" -ForegroundColor DarkYellow }
}
} else {
$objPS
}
}
|
PowerShellCorpus/PoshCode/RoboCopyWrapper.ps1
|
RoboCopyWrapper.ps1
|
# Robocopy example code for more info see the series on my blog
# http://thepowershellguy.com/blogs/posh/archive/tags/robocopy/default.aspx
#############################################################################################
## Make RoboCopy Help Object
#############################################################################################
$RoboHelp = robocopy /? | Select-String '::'
$r = [regex]'(.*)::(.*)'
$RoboHelpObject = $RoboHelp | select `
@{Name='Parameter';Expression={ $r.Match( $_).groups[1].value.trim()}},
@{Name='Description';Expression={ $r.Match( $_).groups[2].value.trim()}}
$RoboHelpObject = $RoboHelpObject |% {$Cat = 'General'} {
if ($_.parameter -eq '') { if ($_.Description -ne ''){
$cat = $_.description -replace 'options :',''}
} else {
$_ | select @{Name='Category';Expression={$cat}},parameter,description
}
}
#############################################################################################
## Robocopy example command :
#############################################################################################
robocopy 'c:\\test1' c:\\PowerShellRoboTest /r:2 /w:5 /s /v /np |
Tee-Object -Variable RoboLog
#############################################################################################
## Process the Output
#############################################################################################
$null,$StartBegin,$StartEnd,$StopBegin = $RoboLog | Select-String "----" |% {$_.linenumber}
$RoboStatus = New-Object object
# Start information
$robolog[$StartBegin..$StartEnd] | % {
Switch -regex ($_) {
'Started :(.*)' {
Add-Member -InputObject $RoboStatus -Name StartTime `
-Value ([datetime]::ParseExact($matches[1].trim(),'ddd MMM dd HH:mm:ss yyyy',$null)) `
-MemberType NoteProperty
}
'Source :(.*)' {
Add-Member -InputObject $RoboStatus -Name Source `
-Value ($matches[1].trim()) -MemberType NoteProperty
}
'Dest :(.*)' {
Add-Member -InputObject $RoboStatus -Name Destination `
-Value ($matches[1].trim()) -MemberType NoteProperty
}
'Files :(.*)' {
Add-Member -InputObject $RoboStatus -Name FileName `
-Value ($matches[1].trim()) -MemberType NoteProperty
}
'Options :(.*)' {
Add-Member -InputObject $RoboStatus -Name Options `
-Value ($matches[1].trim()) -MemberType NoteProperty
}
}
}
# Stop Information
$robolog[$StopBegin..( $RoboLog.Count -1)] |% {
Switch -regex ($_) {
'Ended :(.*)' {
Add-Member -InputObject $RoboStatus -Name StopTime `
-Value ([datetime]::ParseExact($matches[1].trim(),'ddd MMM dd HH:mm:ss yyyy',$null))`
-MemberType NoteProperty
}
'Speed :(.*) Bytes' {
Add-Member -InputObject $RoboStatus -Name BytesSecond `
-Value ($matches[1].trim()) -MemberType NoteProperty
}
'Speed :(.*)MegaBytes' {
Add-Member -InputObject $RoboStatus -Name MegaBytesMinute `
-Value ($matches[1].trim()) -MemberType NoteProperty
}
'(Total.*)' {
$cols = $_.Split() |? {$_}
}
'Dirs :(.*)' {
$fields = $matches[1].Split() |? {$_}
$dirs = new-object object
0..5 |% {
Add-Member -InputObject $Dirs -Name $cols[$_] -Value $fields[$_] -MemberType NoteProperty
Add-Member -InputObject $Dirs -Name 'toString' -MemberType ScriptMethod `
-Value {[string]::Join(" ",($this.psobject.Properties |
% {"$($_.name):$($_.value)"}))} -force
}
Add-Member -InputObject $RoboStatus -Name Directories -Value $dirs -MemberType NoteProperty
}
'Files :(.*)' {
$fields = $matches[1].Split() |? {$_}
$Files = new-object object
0..5 |% {
Add-Member -InputObject $Files -Name $cols[$_] -Value $fields[$_] -MemberType NoteProperty
Add-Member -InputObject $Files -Name 'toString' -MemberType ScriptMethod -Value `
{[string]::Join(" ",($this.psobject.Properties |% {"$($_.name):$($_.value)"}))} -force
}
Add-Member -InputObject $RoboStatus -Name files -Value $files -MemberType NoteProperty
}
'Bytes :(.*)' {
$fields = $matches[1].Split() |? {$_}
$fields = $fields |% {$new=@();$i = 0 } {
if ($_ -match '\\d') {$new += $_;$i++} else {$new[$i-1] = ([double]$new[$i-1]) * "1${_}B" }
}{$new}
$Bytes = new-object object
0..5 |% {
Add-Member -InputObject $Bytes -Name $cols[$_] `
-Value $fields[$_] -MemberType NoteProperty
Add-Member -InputObject $Bytes -Name 'toString' -MemberType ScriptMethod `
-Value {[string]::Join(" ",($this.psobject.Properties |
% {"$($_.name):$($_.value)"}))} -force
}
Add-Member -InputObject $RoboStatus -Name bytes -Value $bytes -MemberType NoteProperty
}
}
}
# Process the details log
$re = New-Object regex('(.*)\\s{2}([\\d\\.]*\\s{0,1}\\w{0,1})\\s(.*)')
$RoboDetails = $robolog[($StartEnd +1)..($stopbegin -3)] |? {$_.StartsWith([char]9)} | select `
@{Name='Action';Expression={$re.Match($_) |% {$_.groups[1].value.trim()}}},
@{Name='Size';Expression={$re.Match($_) |% {$_.groups[2] |% {$_.value.trim()}}}},
@{Name='Directory';Expression={if(!($re.Match($_) |% {$_.groups[1].value.trim()})){
'-';$Script:dir = $re.Match($_) |% {$_.groups[3] |
% {$_.value.trim()}} }else {$script:dir}}},
@{Name='Name';Expression={$re.Match($_) |% {$_.groups[3] |% {$_.value.trim()}}}}
# convert all values to bytes (but is also possible switch on robocopy )
0..($RoboDetails.count -1) |% {
if ($Robodetails[$_].Directory -eq '-') {
$Robodetails[$_].Action = 'Directory'
$Robodetails[$_].Directory = split-path $Robodetails[$_].Name
}
if ($Robodetails[$_].size -match '[mg]') {
$Robodetails[$_].size = [double]($roboDetails[$_].size.trim('mg ')) * 1mb
}
}
#Add-Member -InputObject $RoboDetails -Name 'toString' -MemberType ScriptMethod `
-Value {"Details : " + $this.count} -force
Add-Member -InputObject $RoboStatus -Name Details `
-Value $RoboDetails -MemberType NoteProperty
# Process warnings and errors
$reWarning = New-Object regex('(.*)(ERROR.*)(\\(.*\\))(.*)\\n(.*)')
$roboWarnings = $reWarning.matches(($robolog | out-string)) | Select `
@{Name='Time';Expression={[datetime]$_.groups[1].value.trim()}},
@{Name='Error';Expression={$_.groups[2].value.trim()}},
@{Name='Code';Expression={$_.groups[3].value.trim()}},
@{Name='Message';Expression={$_.groups[5].value.trim()}},
@{Name='Info';Expression={$_.groups[4].value.trim()}}
#Add-Member -InputObject $RoboWarnigs -Name 'toString' `
-MemberType ScriptMethod -Value {"Details : " + $this.count} -force
Add-Member -InputObject $RoboStatus -Name Warnings `
-Value $roboWarnings -MemberType NoteProperty
$reErrors = New-Object regex('\\) (.*)\\n(.*)\\nERROR:(.*)')
$roboErrors = $reErrors.matches(($robolog |? {$_}| out-string)) | Select `
@{Name='Error';Expression={$_.groups[3].value.trim()}},
@{Name='Message';Expression={$_.groups[2].value.trim()}},
@{Name='Info';Expression={$_.groups[1].value.trim()}}
#Add-Member -InputObject $RoboErrors -Name 'toString' `
-MemberType ScriptMethod -Value {"Details : " + $this.count} -force
Add-Member -InputObject $RoboStatus -Name Errors `
-Value $RoboErrors -MemberType NoteProperty
#############################################################################################
## Use $roboStatus Object created to get and format the statistics :
#############################################################################################
# check status
$RoboStatus
# Calculate time running
"Time elapsed : $($RoboStatus.StopTime - $RoboStatus.StartTime)"
# Get Help for Options given
$RoboStatus.Options.split()[1..100] |
% { $par = $_ ;$RoboHelpObject |? {$_.parameter -eq $par} } | ft -a
# Details on files and directories (to string overruled!) :
$RoboStatus.files
$RoboStatus.Directories
# Group Details
$RoboStatus.Details | group action
# List Errors and Warnings
$RoboStatus.Errors | fl
$RoboStatus.Warnings
# Get count of warnings
$RoboStatus.Warnings |group info | ft count,Name -a
# Only warnings that resoved in a failed copy
$RoboStatus.Warnings |
select *, @{name='Failed';e={($RoboStatus.errors |% {$_.info}) -contains $_.info}}
# Action Details with warnings
$RoboStatus.details |? {$_.action} | select *,
@{name='Failed';e={$d = $_;($RoboStatus.errors |
% {$_.info}) -match '\\\\'+([regex]::escape($d.name))}} |? {$_.failed} |
group action,directory,name | ft -a name,count
# Count of warnings per error
$RoboStatus.Errors |
select *,@{name='Warnings';e={$e = $_;($robostatus.warnings |? {$_.info -eq $e.info}).count}}
# List of Warnings per error
$RoboStatus.Errors |
select *,@{name='Warnings';e={$e = $_;($robostatus.warnings |? {$_.info -eq $e.info})}} |% {
$_ | fl error,Info ;$_.warnings | sort -u info,message | ft [tecm]* -a
}
|
PowerShellCorpus/PoshCode/Get-FailingDrive_1.ps1
|
Get-FailingDrive_1.ps1
|
Function Get-FailingDrive {
<#
.SYNOPSIS
Checks for any potentially failing drives and reports back drive information.
.DESCRIPTION
Checks for any potentially failing drives and reports back drive information. This only works
against local hard drives using SMART technology. Reason values and their meanings can be found
here: http://en.wikipedia.org/wiki/S.M.A.R.T#Known_ATA_S.M.A.R.T._attributes
.PARAMETER Computer
Remote or local computer to check for possible failed hard drive.
.PARAMETER Credential
Provide alternate credential to perform query.
.NOTES
Author: Boe Prox
Version: 1.0
http://learn-powershell.net
.EXAMPLE
Get-FailingDrive
WARNING: ST9320320AS ATA Device may fail!
MediaType : Fixed hard disk media
InterFace : IDE
DriveName : ST9320320AS ATA Device
Reason : 1
SerialNumber : 202020202020202020202020533531584e5a4d50
FailureImminent : True
Description
-----------
Command ran against the local computer to check for potential failed hard drive.
#>
[cmdletbinding()]
Param (
[parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
[string[]]$Computername,
[parameter()]
[System.Management.Automation.PSCredential]$Credential
)
Begin {
$queryhash = @{}
$BadDriveHash = @{}
}
Process {
ForEach ($Computer in $Computername) {
If ($PSBoundParameters['Computer']) {
$queryhash['Computername'] = $Computer
$BadDriveHash['Computername'] = $Computer
} Else {
$queryhash['Computername'] = $Env:Computername
$BadDriveHash['Computername'] = $Env:Computername
}
If ($PSBoundParameters['Credential']) {
$queryhash['Credential'] = $Credential
$BadDriveHash['Credential'] = $Credential
}
Write-Verbose "Creating SplatTable"
$queryhash['NameSpace'] = 'root\\wmi'
$queryhash['Class'] = 'MSStorageDriver_FailurePredictStatus'
$queryhash['Filter'] = "PredictFailure='False'"
$queryhash['ErrorAction'] = 'Stop'
$BadDriveHash['Class'] = 'win32_diskdrive'
$BadDriveHash['ErrorAction'] = 'Stop'
[regex]$regex = "(?<DriveName>\\w+\\\\[A-Za-z0-9_]*)\\w+"
Try {
Write-Verbose "Checking for failed drives"
Get-WmiObject @queryhash | ForEach {
$drive = $regex.Matches($_.InstanceName) | ForEach {$_.Groups['DriveName'].value}
Write-Verbose "Gathering more information about failing drive"
$BadDrive = gwmi @BadDriveHash | Where {$_.PNPDeviceID -like "$drive*"}
If ($BadDrive) {
Write-Warning "$($BadDriveHash['Computername']): $($BadDrive.Model) may fail!"
New-Object PSObject -Property @{
DriveName = $BadDrive.Model
FailureImminent = $_.PredictFailure
Reason = $_.Reason
MediaType = $BadDrive.MediaType
SerialNumber = $BadDrive.SerialNumber
InterFace = $BadDrive.InterfaceType
Partitions = $BadDrive.Partitions
Size = $BadDrive.Size
Computer = $BadDriveHash['Computername']
}
}
}
} Catch {
Write-Warning "$($Error[0])"
}
}
}
}
|
PowerShellCorpus/PoshCode/Test-VmMigration.ps1
|
Test-VmMigration.ps1
|
$vv = get-vm testsql17b | get-view
$si = Get-View ServiceInstance -Server $global:DefaultVIServers[1]
$hs = get-vmhost infesx52*
$hv = $hs | Get-View
$pool = $vv.ResourcePool
$vmMoRef = $vv.MoRef
$hsMoRef = $hv.MoRef
$si = Get-View ServiceInstance -Server $global:DefaultVIServers[1] # this turned out to be futile, later line returns multi objects anyway...
$VmProvCheck = get-view $si.Content.VmProvisioningChecker # don't know why it grabbed multiple objs, one for each vCenter
$RavVmProvCheck = $VmProvCheck[0] # This is the object we need for the VC instance in question
$results = $RavVmProvCheck.CheckMigrate( $vmMoRef, $hsMoRef, $pool, $null, $null )
|
PowerShellCorpus/PoshCode/New-IseFile.ps1
|
New-IseFile.ps1
|
function New-IseFile ($path = 'tmp_default.ps1')
{
$count = $psise.CurrentPowerShellTab.Files.count
$null = $psIse.CurrentPowerShellTab.Files.Add()
$Newfile = $psIse.CurrentPowerShellTab.Files[$count]
$NewFile.SaveAs($path)
$NewFile.Save([Text.Encoding]::default)
$Newfile
}
|
PowerShellCorpus/PoshCode/ConvertTo-MultiArray.ps1
|
ConvertTo-MultiArray.ps1
|
function ConvertTo-MultiArray {
<#
.Notes
NAME: ConvertTo-MultiArray
AUTHOR: Tome Tanasovski
Website: http://powertoe.wordpress.com
Twitter: http://twitter.com/toenuff
Version: 1.0
CREATED: 11/5/2010
LASTEDIT:
11/5/2010 1.0
Initial Release
.Synopsis
Converts a collection of PowerShell objects into a multi-dimensional array
.Description
Converts a collection of PowerShell objects into a multi-dimensional array. The first row of the array contains the property names. Each additional row contains the values for each object.
This cmdlet was created to act as an intermediary to importing PowerShell objects into a range of cells in Exchange. By using a multi-dimensional array you can greatly speed up the process of adding data to Excel through the Excel COM objects.
.Parameter InputObject
Specifies the objects to export into the multi dimensional array. Enter a variable that contains the objects or type a command or expression that gets the objects. You can also pipe objects to ConvertTo-MultiArray.
.Parameter Array
Takes a reference to an object. The object will be formatted as a new multi-dimensional array of the appropriate size for the InputObject passed to the cmdlet.
.Inputs
System.Management.Automation.PSObject
You can pipe any .NET Framework object to ConvertTo-MultiArray
.Outputs
$Null & Object[,]
There is no direct output from this cmdlet, however, the object passed as a reference in the -Array parameter will contain a new multi-dimensional array.
.Example
$array = $null
get-process |Convertto-MultiArray ([ref]$array)
.Example
$array = $null
$dir = Get-ChildItem c:\\
Convertto-MultiArray -InputObject $dir -Array ([ref]$array)
.LINK
http://powertoe.wordpress.com
#>
param(
[Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true)]
[PSObject[]]$InputObject,
[Parameter(Mandatory=$true, Position=0)]
[ref] $Array
)
BEGIN {
$objects = @()
}
Process {
$objects += $InputObject
}
END {
$properties = $objects[0].psobject.properties |%{$_.name}
$array.Value = New-Object 'object[,]' ($objects.Count+1),$properties.count
# i = row and j = column
$j = 0
$properties |%{
$array.Value[0,$j] = $_
$j++
}
$i = 1
$objects |% {
$item = $_
$j = 0
$properties | % {
$array.value[$i,$j] = $item.($_)
$j++
}
$i++
}
}
}
|
PowerShellCorpus/PoshCode/MIFParser.ps1
|
MIFParser.ps1
|
param ($fileName, $computerName=$env:ComputerName)
#######################
function ConvertTo-MIFXml
{
param ($mifFile)
$mifText = gc $mifFile |
#Remove illegal XML characters
% { $_ -replace "&", "&" } |
% { $_ -replace"'", "'" } |
% { $_ -replace "<", "<" } |
% { $_ -replace ">", ">" } |
#Create Component attribute
% { $_ -replace 'Start Component','<Component' } |
#Create Group attribute
% { $_ -replace 'Start Group','><Group' } |
#Create Attribute attribute
% { $_ -replace 'Start Attribute','><Attribute' } |
#Create closing tags
% { $_ -replace 'End Attribute','></Attribute>' } |
% { $_ -replace 'End Group','</Group>' } |
% { $_ -replace 'End Component','</Component>'} |
#Remove all quotes
% { $_ -replace '"' } |
#Remove MIF comments. MIF Comments start with //
% { $_ -replace "(\\s*//\\s*.*)" } |
#Extract name/value and quote value
% { $_ -replace "\\s*([^\\s]+)\\s*=\\s*(.+$)",'$1="$2"' } |
#Replace tabs with spaces
% { $_ -replace "\\t", " " } |
#Replace 2 spaces with 1
% { $_ -replace "\\s{2,}", " " }
#Join the array, cleanup some spacing and extra > signs
[xml]$mifXml = [string]::Join(" ", $mifText) -replace ">\\s*>",">" -replace "\\s+>",">"
return $mifXml
} #ConvertTo-MIFXml
#######################
ConvertTo-MIFXml $fileName | foreach {$_.component} | foreach {$_.Group} | foreach {$_.Attribute} | select @{n='SystemName';e={$computerName}}, `
@{n='Component';e={$($_.psbase.ParentNode).psbase.ParentNode.name}}, @{n='Group';e={$_.psbase.ParentNode.name}}, `
@{n='FileName';e={[System.IO.Path]::GetFileName($FileName)}}, ID, Name, Value
|
PowerShellCorpus/PoshCode/Expand-ZipFile.ps1
|
Expand-ZipFile.ps1
|
function Expand-ZipFile {
param {
$zipPath,
$destination,
[switch] $quiet
}
$shellApplication = new-object -com shell.application
$zipPackage = $shellApplication.NameSpace($zipPath)
$destinationFolder = $shellApplication.NameSpace($destination)
# CopyHere vOptions Flag # 4 - Do not display a progress dialog box.
# 16 - Respond with "Yes to All" for any dialog box that is displayed.
#$destinationFolder.CopyHere($zipPackage.Items(),20)
$total = $zipPackage.Items().Count
$progress = 1;
foreach ($zipFile in $zipPackage.Items()) {
if(!$quiet) {
Write-Progress "Extracting $zipPath" "Extracting $($zipFile.Name)" -id 0 -percentComplete (($progress/$total)*100)
}
$destinationFolder.CopyHere($zipFile,20)
$progress++
}
if(!$quiet) {
Write-Progress "Extracted $zipPath" "Extracted $total items" -id 0
}
}
|
PowerShellCorpus/PoshCode/ConvertTo-Function.ps1
|
ConvertTo-Function.ps1
|
## ConvertTo-Function
## By Steven Murawski (http://www.mindofroot.com / http://blog.usepowershell.com)
###################################################################################################
## Usage:
## ./ConvertTo-Function Get-Server.ps1
## dir *.ps1 | ./convertto-Function
###################################################################################################
param ($filename)
PROCESS
{
if ($_ -ne $Null)
{
$filename = $_
}
if ($filename -is [System.IO.FileInfo])
{
$filename = $filename.Name
}
if (Test-Path $filename)
{
$name = (Resolve-Path $filename | Split-Path -Leaf) -replace '\\.ps1'
$scriptblock = get-content $filename | Out-String
if (Test-Path function:global:$name)
{
Set-Item -Path function:global:$name -Value $scriptblock
Get-Item -Path function:global:$name
}
else
{
New-Item -Path function:global:$name -Value $scriptblock
}
}
else
{
throw 'Either a valid path or a FileInfo object'
}
}
|
PowerShellCorpus/PoshCode/whoami_3.ps1
|
whoami_3.ps1
|
function Get-UserStatus {
<#
.Synopsis
Get extended information about local user.
.Description
There is no input arguments, just specify Get-UserStatus or his alias whoami.
.Link
http://msdn.microsoft.com/en-us/library/system.security.principal.aspx
http://poshcode.org/3979
#>
$usr = [Security.Principal.WindowsIdentity]::GetCurrent()
$res = (New-Object Security.Principal.WindowsPrincipal $usr).IsInRole(
[Security.Principal.WindowsBuiltInRole]::Administrator
)
"{0, 9}: {1}" -f "User", $usr.Name
"{0, 9}: {1}" -f "SID", $usr.Owner.Value
"{0, 9}: {1}" -f "IsAdmin", $res
"{0, 9}:" -f "Groups"
$usr.Groups | % {"`t " + $_.Translate([Security.Principal.NTAccount]).Value} | sort
""
}
Set-Alias whoami Get-UserStatus
|
PowerShellCorpus/PoshCode/Invoke-ScriptBlockClosur.ps1
|
Invoke-ScriptBlockClosur.ps1
|
##############################################################################\n##\n## Invoke-ScriptBlockClosure\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nDemonstrates the GetNewClosure() method on a script block that pulls variables\nin from the user's session (if they are defined.)\n\n.EXAMPLE\n\nPS >$name = "Hello There"\nPS >Invoke-ScriptBlockClosure { $name }\nHello There\nHello World\nHello There\n\n#>\n\nparam(\n ## The scriptblock to invoke\n [ScriptBlock] $ScriptBlock\n)\n\nSet-StrictMode -Version Latest\n\n## Create a new script block that pulls variables\n## from the user's scope (if defined.)\n$closedScriptBlock = $scriptBlock.GetNewClosure()\n\n## Invoke the script block normally. The contents of\n## the $name variable will be from the user's session.\n& $scriptBlock\n\n## Define a new variable\n$name = "Hello World"\n\n## Invoke the script block normally. The contents of\n## the $name variable will be "Hello World", now from\n## our scope.\n& $scriptBlock\n\n## Invoke the "closed" script block. The contents of\n## the $name variable will still be whatever was in the user's session\n## (if it was defined.)\n& $closedScriptBlock
|
PowerShellCorpus/PoshCode/Get-NaCifs.ps1
|
Get-NaCifs.ps1
|
# Glenn Sizemore www . Get-Admin . Com
# Requires the NetApp OnTap SDK v3.5
#
# Will connect to the destination Filer and retrieve detailed information on every
# Cifs share. This function will not retrieve permissions.
#
# Usage:
# Connect to the filler
# $Filer = 'TOASTER'
# $NetApp = New-Object NetApp.Manage.NaServer($filer,1,0)
# $NetApp.SetAdminUser(UserName,Password)
#
# Call the function
# Get-NaCifs -Server $NetApp
Function Get-NaCifs {
Param(
[NetApp.Manage.NaServer]$Server
)
Process {
# Establish a connection and prepair to iterate through all shares.
$NaElement = New-Object NetApp.Manage.NaElement("cifs-share-list-iter-start")
$results = $Server.InvokeElem($naelement)
$Tag = $results.GetChildContent("tag")
$RecordReturned = $results.GetChildContent("records")
$processing=$true
$increment = 50 #How many records should we process at a time
# Loop until we get all shares
While ($processing) {
$NaElement = New-Object NetApp.Manage.NaElement("cifs-share-list-iter-next")
$NaElement.AddNewChild("maximum",$increment)
$NaElement.AddNewChild("tag",$Tag)
$results = $Server.InvokeElem($naelement)
$RecordReturned = $results.GetChildContent("records")
IF ($RecordReturned -eq 0) {
break
} else {
Foreach ($share in $results.GetChildByName("cifs-shares").GetChildren()) {
$S = "" | Select @{
N='Name'
E={$share.GetChildContent("share-name")}
}, @{
N='Path'
E={$share.GetChildContent("mount-point")}
}
# From here on out we'll use add-member because default shares
# Won't contain any of these properties.
switch($share) {
{$_.GetChildByName("caching")}
{
$S|Add-Member 'NoteProperty' 'Caching' $_.GetChildContent("caching")
}
{$_.GetChildByName("description")}
{
$S|Add-Member 'NoteProperty' 'Description' $_.GetChildContent("description")
}
{$_.GetChildByName("dir-umask")}
{
$S|Add-Member 'NoteProperty' 'DirUmask' $_.GetChildContent("dir-umask")
}
{$_.GetChildByName("file-umask")}
{
$S|Add-Member 'NoteProperty' 'FileUmask' $_.GetChildContent("file-umask")
}
{$_.GetChildByName("forcegroup")}
{
$S|Add-Member 'NoteProperty' 'Forcegroup' $_.GetChildContent("forcegroup")
}
{$_.GetChildByName("is-access-based-enum")}
{
$S|Add-Member 'NoteProperty' 'ABE' $true
}
{$_.GetChildByName("is-symlink-strict-security")}
{
if ($_.GetChildContent("is-symlink-strict-security") -eq "false") {
$S|Add-Member 'NoteProperty' 'SymlinkStrictSecurity' $False
}
}
{$_.GetChildByName("is-vol-offline")}
{
IF ($_.GetChildContent("is-vol-offline") -eq "true") {
$S|Add-Member 'NoteProperty' 'VolOffline' $true
}
}
{$_.GetChildByName("is-vscan")}
{
IF ($_.GetChildContent("is-vscan") -eq "true") {
$S|Add-Member 'NoteProperty' 'VirusScanOnOpen' $True
}
}
{$_.GetChildByName("is-vscanread")}
{
IF ($_.GetChildContent("is-vscanread") -eq "true") {
$S|Add-Member 'NoteProperty' 'VirusScanOnRead' $True
}
}
{$_.GetChildByName("is-widelink")}
{
IF ($_.GetChildContent("is-widelink") -eq "true") {
$S|Add-Member 'NoteProperty' 'WideLink' $True
}
}
{$_.GetChildByName("maxusers")}
{
$S|Add-Member 'NoteProperty' 'MaxUsers' $_.GetChildContent("maxusers")
}
{$_.GetChildByName("umask")}
{
$S|Add-Member 'NoteProperty' 'Umask' $_.GetChildContent("umask")
}
}
Write-Output $S
}
}
}
$NaElement = New-Object NetApp.Manage.NaElement("cifs-share-list-iter-end")
$NaElement.AddNewChild("tag",$Tag)
[VOID]$Server.InvokeElem($naelement)
}
}
|
PowerShellCorpus/PoshCode/Findup_5.ps1
|
Findup_5.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 FileInfo FI { get; private set; }
public bool Checked { get; set; }
public string SHA512_1st1K { get; set; }
public string SHA512_All { get; set; }
}
class Recurse // Add FileInfoExt objects of files matching filenames, file specifications (IE: *.*), 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 Program
{
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;
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(" ");
Console.WriteLine("Examples: findup.exe c:\\\\finances -recurse");
Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data -recurse -delete -noprompt");
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;
}
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;
}
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 (fs[i].FI.FullName == fs[c].FI.FullName) // don't count the same file as a match.
continue;
if (fs[i].SHA512_1st1K == null) // check/hash first 1K first.
fs[i].SHA512_1st1K = ComputeInitialHash(fs[i].FI.FullName);
if (fs[c].SHA512_1st1K == null)
fs[c].SHA512_1st1K = ComputeInitialHash(fs[c].FI.FullName);
if (fs[i].SHA512_1st1K != fs[c].SHA512_1st1K) // if the 1st 1K has the same hash..
continue;
if (fs[i].SHA512_1st1K == null) // if hash error, then skip to next file.
continue;
if (fs[i].FI.Length > 1024) // skip hashing the file again if < 1024 bytes.
{
if (fs[i].SHA512_All == null) // check/hash the rest of the files.
fs[i].SHA512_All = ComputeFullHash(fs[i].FI.FullName);
if (fs[c].SHA512_All == null)
fs[c].SHA512_All = ComputeFullHash(fs[c].FI.FullName);
if (fs[i].SHA512_All != fs[c].SHA512_All)
continue;
if (fs[i].SHA512_All == null) // check for hash fail before declairing a duplicate.
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 readonly byte[] readBuf = new byte[1024];
private static string ComputeInitialHash(string path)
{
try
{
using (var stream = File.OpenRead(path))
{
var length = stream.Read(readBuf, 0, readBuf.Length);
var hash = SHA512.Create().ComputeHash(readBuf, 0, length);
return BitConverter.ToString(hash);
}
}
catch (Exception e)
{
Console.WriteLine("Hash Error: " + e.Message);
return (null);
}
}
private static string ComputeFullHash(string path)
{
try
{
using (var stream = File.OpenRead(path))
{
return BitConverter.ToString(SHA512.Create().ComputeHash(stream));
}
}
catch (Exception e)
{
Console.WriteLine("Hash error: " + e.Message);
return (null);
}
}
}
}
|
PowerShellCorpus/PoshCode/Publish-File_1.ps1
|
Publish-File_1.ps1
|
# Note that this version will not descend directories.
function Publish-File {
param (
[parameter( Mandatory = $true, HelpMessage="URL pointing to a SharePoint document library (omit the '/forms/default.aspx' portion)." )]
[System.Uri]$Url,
[system.Management.Automation.PSCredential]$Credential,
[parameter( Mandatory = $true, ValueFromPipeline = $true, HelpMessage="One or more files to publish. Use 'dir' to produce correct object type." )]
[System.IO.FileInfo[]]$FileName
)
Add-Type -AssemblyName System.Web
$wc = new-object System.Net.WebClient
if ( $Credential ) { $wc.Credentials = $Credential }
else { $wc.UseDefaultCredentials = $true }
$FileName | ForEach-Object {
$DestUrl = [system.Web.HttpUtility]::UrlPathEncode( ( "{0}{1}{2}" -f $Url.ToString().TrimEnd("/"), "/", $_.Name ) )
Write-Verbose "$( get-date -f s ): Uploading file: $_"
Write-Verbose "url: $DestUrl"
$wc.UploadFile( $DestUrl , "PUT", $_.FullName )
Write-Verbose "$( get-date -f s ): Upload completed"
}
}
# Example:
# dir c:\\path\\files* | Publish-File -Url "https://mysharepointsite.com/personal/userID/Personal%20Documents"
|
PowerShellCorpus/PoshCode/e17dfa3f-0ecd-4124-a650-54cdf6ae6041.ps1
|
e17dfa3f-0ecd-4124-a650-54cdf6ae6041.ps1
|
Get-WmiObject -Class Win32_MountPoint |
where {$_.Directory -like ‘Win32_Directory.Name="D:\\\\MDBDATA*"’} |
foreach {
$vol = $_.Volume
Get-WmiObject -Class Win32_Volume | where {$_.__RELPATH -eq $vol} |
Select @{Name="Folder"; Expression={$_.Caption}},
@{Name="Server"; Expression={$_.SystemName}},
@{Name="Size"; Expression={"{0:F3}" -f $($_.Capacity / 1GB)}},
@{Name="Free"; Expression={"{0:F3}" -f $($_.FreeSpace / 1GB)}},
@{Name="% Free"; Expression={"{0:F2}" -f $(($_.FreeSpace/$_.Capacity)*100)}}
} |Format-Table -AutoSize
|
PowerShellCorpus/PoshCode/Shaped WPF Windows.ps1
|
Shaped WPF Windows.ps1
|
$window = show -minw 300 -minh 300 -width 400 -height 400 -AllowsTransparency -WindowStyle none -Background transparent {
grid {
viewbox -stretch Uniform {
Path -Fill "#80D0E0FF" -stroke red -strokethickness 4 `
-horizontalalign center -verticalalign center `
-data "M79,3L65,82 17,91 50,138 96,157 104,192 175,154 190,167 218,78 156,76 157,9 111,39z"
}
Button -Margin 150 "Click Me"
}
} -On_MouseLeftButtonDown {
$this.DragMove()
} -On_Deactivated {
$this.Opacity = .5
} -On_Activated {
$this.Opacity = 1
} -async -passthru
## Later, you can mess with the window in various ways from the host, because we did -async -passthru:
invoke-uiwindow $window { $this.Opacity = 1 }
|
PowerShellCorpus/PoshCode/Convert File Encoding.ps1
|
Convert File Encoding.ps1
|
cd c:\\windows\\temp\\common
foreach($File in get-childitem | where-object{($_.Extension -ieq '.PS1') -or ($_.Extension -ieq '.PSM1')})
{
$FileName = $File.Name
$TempFile = "$($File.Name).ASCII"
@@ get-content $FileName | out-file $TempFile -Encoding ASCII
remove-item $FileName
rename-item $TempFile $FileName
}
|
PowerShellCorpus/PoshCode/Set-Computername_10.ps1
|
Set-Computername_10.ps1
|
function Set-ComputerName {
param( [switch]$help,
[string]$originalPCName=$(read-host "Please specify the current name of the computer"),
[string]$computerName=$(read-host "Please specify the new name of the computer"))
$usage = "set-ComputerName -originalPCname CurrentName -computername AnewName"
if ($help) {Write-Host $usage;break}
$computer = Get-WmiObject Win32_ComputerSystem -OriginalPCname OriginalName -computername $originalPCName
$computer.Rename($computerName)
}
|
PowerShellCorpus/PoshCode/finddupe_1.ps1
|
finddupe_1.ps1
|
param($dir = '.')
function Get-MD5([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]'))
{
$stream = $null;
$cryptoServiceProvider = [System.Security.Cryptography.MD5CryptoServiceProvider];
$hashAlgorithm = new-object $cryptoServiceProvider
$stream = $file.OpenRead();
$hashByteArray = $hashAlgorithm.ComputeHash($stream);
$stream.Close();
## We have to be sure that we close the file stream if any exceptions are thrown.
trap
{
if ($stream -ne $null)
{
$stream.Close();
}
break;
}
foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }}
return [string]$result;
}
$matches = 0 # initialize number of matches for summary.
$files = (dir $dir -recurse | ? {$_.psiscontainer -ne $true})
for ($i=0;$i -ne $files.count; $i++) # Cycle thru all files
{
if ($files[$i] -eq $null) {continue}
$md5 = $null
$filecheck = $files[$i]
$files[$i] = $null
for ($c=0;$c -ne $files.count; $c++)
{
if ($files[$c] -eq $null) {continue}
# write-host "Comparing $filecheck and $($files[$c]) `r" -nonewline
if ($filecheck.length -eq $files[$c].length)
{
#write-host "Comparing MD5 of $($filecheck.fullname) and $($files[$c].fullname) `r" -nonewline
if ($md5 -eq $null) {$md5 = (get-md5 $filecheck)}
if ($md5 -eq (get-md5 $files[$c]))
{
"Size and MD5 match: {0} and {1}" -f $filecheck.fullname, $files[$c].fullname
$matches++
$files[$c] = $null
}
}
}
}
write-host ""
write-host "Number of Files checked: $($files.count)." # Display useful info; files checked and matches found.
write-host "Number of matches found: $($matches)."
write-host ""
|
PowerShellCorpus/PoshCode/TimeSyn HyperV Settings.ps1
|
TimeSyn HyperV Settings.ps1
|
<#Time Synchronization Status#>
Write-Host "Time Synchronization Status" -ForegroundColor Yellow
Write-Host "_______________________________" -ForegroundColor Yellow
Write-Host
$VMhost = Get-ItemProperty "HKLM:\\SOFTWARE\\Microsoft\\Virtual Machine\\Guest\\Parameters" | select -ExpandProperty physicalhostname
$VirtualMachineName = Get-ItemProperty "HKLM:\\SOFTWARE\\Microsoft\\Virtual Machine\\Guest\\Parameters" | select -ExpandProperty VirtualMachineName
$session = New-PSSession -ComputerName $vmhost
Invoke-Command -Session $session {
param($vmname)
$MgmtSvc = gwmi -namespace root\\virtualization MSVM_VirtualSystemManagementService
$VM = gwmi -namespace root\\virtualization MSVM_ComputerSystem |?{$_.elementname -match $vmname}
$TimeSyncComponent = gwmi -query "associators of {$VM} where ResultClass = Msvm_TimeSyncComponent" -namespace root\\virtualization
$TimeSyncSetting = gwmi -query "associators of {$TimeSyncComponent} where ResultClass = Msvm_TimeSyncComponentSettingData" -namespace root\\virtualization
# Disable = 3; Enable = 2
if ($TimeSyncSetting.EnabledState -eq 3 ){
Write-Host "Time Synchronzation Disabled" -ForegroundColor Green
}
else{ Write-Host "Time Synchronzation Enabled" -ForegroundColor Red }
} -Args $VirtualMachineName
Get-PSSession | Remove-PSSession
|
PowerShellCorpus/PoshCode/Out-LogFile Module.ps1
|
Out-LogFile Module.ps1
|
function Out-LogFile {
<#
.SYNOPSIS
Output to log file.
.DESCRIPTION
Output to formatted log file.
Default fomatting is:
SEVERITY: dd-MM-yyyy HH:mm:ss: Message
e.g. I: 25-06-2010 17:09:10: Started Processing
.PARAMETER BackgroundColor
Specifies the background colour when using -WriteHost. There is no default.
.PARAMETER BlankLine
Write 1 or more blank lines to the log file (default 0).
When used with -Message the blank lines are written after the message.
.PARAMETER DateFormat
Date formating string (default "dd-MM-yyyy HH:mm:ss").
See Get-Date -Format
.PARAMETER DontFormat
Don't format the message and write the input directly to the log file.
.PARAMETER Encoding
Specifies the type of character encoding used in the file (default Unicode).
Valid values are "Unicode", "UTF7", "UTF8", "UTF32", "ASCII", "BigEndianUnicode", "Default", and "OEM".
"Default" uses the encoding of the system's current ANSI code page.
"OEM" uses the current original equipment manufacturer code page identifier for the operating system.
.PARAMETER Force
Overwrite an existing read-only file.
.PARAMETER ForegroundColor
Specifies the text colour when using -WriteHost. There is no default.
.PARAMETER LogFile
Path to the log file (default $global:DefaultLogFile).
Set the global variable $global:DefaultLogFile to use the default setting.
.PARAMETER Message
Input object or text message to write to the log file.
.PARAMETER Severity
Message severity flag (default I).
Any string can be used as a flag such as I, W, E or INFO, WARNING, ERROR etc.
.PARAMETER Title
Write unformatted string to the log file with blank lines either side.
This is the equivilent of:
Out-LogFile -BlankLine 1
Out-LogFile -Message "Message" -BlankLine 1 -DontFormat
-Title is processed before -Message so the two can be combined in a single call:
Out-LogFile -Title "Today's Report" -Message "Started Processing"
.PARAMETER WriteHost
Writes -Message or -Title to the host (default $global:WriteHostPreference).
Set the global variable $global:WriteHostPreference to $true to enable -WriteHost by default.
To override the default set -WriteHost or -WriteHost:$false.
.EXAMPLE
$global:WriteHostPreference = $true
$global:DefaultLogFile = "C:\\Logs\\MyLog.LOG"
Out-LogFile "Simple Example"
I: 25-06-2010 18:07:00: Simple Example
Write "Simple Example" to the default log specified by $global:DefaultLogPath and the host.
.EXAMPLE
Out-LogFile "Another Example" -WriteHost -ForgroundColor Green -LogFile C:\\Logs\\MyLog.LOG -Severity E
E: 25-06-2010 18:10:00: Another Example
Write "Another Example" to C:\\Logs\\MyLog.LOG and to the host with green text setting the severity flag to 'E'.
.EXAMPLE
Daily-Report | Out-LogFile -Title "Todays Report" -DontFormat -BlankLine 1
Write the log title "Daily Report" followed by the output from Daily-Report to the default log file without formatting. A single blank line is added at the end.
.INPUTS
Object
.OUTPUTS
None
.NOTES
Author: Mike Ling
Histroy:
v2.1 - 13/02/2012 - Added support for: $global:DefaultLogFile and $global:WriteHostPreference
v2.0 - 07/02/2012 - Added support for: Pipleline, CmdletBinding, ParameterSets, Encoding, WriteHost Colour.
v1.0 - 25/06/2010 - First release.
.LINK
Out-File
#>
[CmdletBinding(DefaultParameterSetName='Message')]
param(
[Parameter(ParameterSetName='Message',
Position=0,
ValueFromPipeline=$true)]
[object[]]$Message,
[Parameter(ParameterSetName='Message')]
[string]$LogFile = $global:DefaultLogPath,
[Parameter(ParameterSetName='Message')]
[int]$BlankLine = 0,
[switch]$WriteHost = $global:WriteHostPreference,
[string]$Severity = "I",
[Parameter(ParameterSetName='Message')]
[switch]$DontFormat,
[Parameter(ParameterSetName='Message')]
[string]$DateFormat = "dd-MM-yyyy HH:mm:ss",
#[Parameter(ParameterSetName='Title',Position=0,Mandatory=$true)]
[string]$Title,
[System.ConsoleColor]$ForegroundColor = $host.UI.RawUI.ForegroundColor,
[System.ConsoleColor]$BackgroundColor = $host.UI.RawUI.BackgroundColor,
[ValidateSet('unicode', 'utf7', 'utf8', 'utf32', 'ascii', 'bigendianunicode', 'default', 'oem')]
[string]$Encoding = 'Unicode',
[switch]$Force
)
begin {
Write-Verbose "Log File: $LogFile"
if ( -not $LogFile ) { Write-Error "The -LogFile parameter must be defined or $global:LogFile must be set."; break}
if ( -not (Test-Path $LogFile) ) { New-Item -Path $LogFile -ItemType File -Force | Out-Null }
if ( -not (Test-Path $LogFile) ) { Write-Error "Log file can not be found: $LogFile."; break}
if ( $Title ) {
$text = $Title
$Title = $null
Out-LogFile -BlankLine 1 -LogFile $LogFile -WriteHost:$WriteHost -Force:$Force -Encoding $Encoding
Out-LogFile -Message $text -BlankLine 1 -DontFormat -LogFile $LogFile -WriteHost:$WriteHost -Force:$Force -Encoding $Encoding
}
}
process {
if ( $Message ) {
$text = $Message
foreach ( $text in $Message ) {
if ( -not $DontFormat ) { $text = "$(($Severity).ToUpper()): $(Get-Date -Format `"$DateFormat`")" + ": $text" }
if ($WriteHost) { Write-Host $text -BackgroundColor $BackgroundColor -ForegroundColor $ForegroundColor}
$text | Out-File -FilePath $LogFile -Force:$Force -Encoding $Encoding -Append
}
}
if ( $BlankLine -gt 0 ){
for ($i = 0; $i -lt $BlankLine; $i++ ) {
"" | Out-File -FilePath $LogFile -Force:$Force -Encoding $Encoding -Append
if ($WriteHost) { Write-Host "" -BackgroundColor $BackgroundColor -ForegroundColor $ForegroundColor }
}
}
}
end {
}
}
|
PowerShellCorpus/PoshCode/SMS_2.psm1.ps1
|
SMS_2.psm1.ps1
|
<#
.Synopsis
Functions for managing SMS and SCCM.
.Notes
NAME: SMS.psm1
AUTHOR: Tim Johnson <tojo2000@tojo2000.com>
#>
#Requires -version 2.0
[string]$default_wmi_provider_server = 'myserver'
[string]$default_site = 'S00'
function Get-SmsWmi {
<#
.Synopsis
A function for accessing the SMS WMI classes from the SMS Provider.
.Description
This function wraps Get-WmiObject in order to provide an easy way to access
the SMS Provider and the classes it provides. This function keeps you from
having to keep entering in the long namespace and the name of the provider
server every time you want to query the provider.
Valid class nicknames include:
Nickname WMI Class
==============================================================================
AddRemovePrograms => SMS_G_System_ADD_REMOVE_PROGRAMS
AdStatus => SMS_ClientAdvertisementStatus
Advertisement => SMS_Advertisement
Collection => SMS_Collection
ComputerSystem => SMS_G_System_COMPUTER_SYSTEM
DistributionPoint => SMS_DistributionPoint
LogicalDisk => SMS_G_System_LOGICAL_DISK
MembershipRule => SMS_CollectionMembershipRule
NetworkAdapter => SMS_G_System_NETWORK_ADAPTER
NetworkAdapterConfiguration => SMS_G_System_NETWORK_ADAPTER_CONFIGURATION
OperatingSystem => SMS_G_System_OPERATING_SYSTEM
Package => SMS_Package
PkgStatus => SMS_PackageStatus
Program => SMS_Program
Query => SMS_Query
Server => SMS_SystemResourceList
Service => SMS_G_System_SERVICE
Site => SMS_Site
StatusMessage => SMS_StatusMessage
System => SMS_R_System
WorkstationStatus => SMS_G_System_WORKSTATION_STATUS
User => SMS_R_User
.Parameter class
The class or class nickname to be returned.
.Parameter computername
The server with the SMS Provider installed. Note: May not be the site server.
.Parameter site
The site code of the site being accessed.
.Example
# Get all server clients
PS> Get-SmsWmi sys 'OperatingSystemNameAndVersion like "%serv%" and client = 1'
.Example
# Get the PackageID for all packages on Distribution Point Server1
PS> Get-SmsWmi dist 'ServerNALPath like "%Server1%"' | select PackageID
.Example
# Get the ResourceID for all systems with a HW Scan after 2009-03-31
PS> Get-SmsWmi work 'LastHardwareScan > "2009-03-31"' | select ResourceID
.ReturnValue
System.Management.ManagementObject objects of the corresponding class.
.Link
Documentation on the SMS WMI objects can be found in the SCCM SDK:
http://www.microsoft.com/downloads/details.aspx?familyid=064a995f-ef13-4200-81ad-e3af6218edcc&displaylang=en
.Notes
NAME: Get-SmsWmi
AUTHOR: Tim Johnson <tojo2000@tojo2000.com>
FILE: SMS.psm1
#>
param([Parameter(Position = 0)]
[string]$class = $(Throw @"
`t
ERROR: You must enter a class name or nickname.
`t
Valid nicknames are:
`t
Nickname WMI Class
==============================================================================
AddRemovePrograms => SMS_G_System_ADD_REMOVE_PROGRAMS
AdStatus => SMS_ClientAdvertisementStatus
Advertisement => SMS_Advertisement
Collection => SMS_Collection
ComputerSystem => SMS_G_System_COMPUTER_SYSTEM
DistributionPoint => SMS_DistributionPoint
LogicalDisk => SMS_G_System_LOGICAL_DISK
MembershipRule => SMS_CollectionMembershipRule
NetworkAdapter => SMS_G_System_NETWORK_ADAPTER
NetworkAdapterConfiguration => SMS_G_System_NETWORK_ADAPTER_CONFIGURATION
OperatingSystem => SMS_G_System_OPERATING_SYSTEM
Package => SMS_Package
PkgStatus => SMS_PackageStatus
Program => SMS_Program
Query => SMS_Query
Server => SMS_SystemResourceList
Service => SMS_G_System_SERVICE
Site => SMS_Site
StatusMessage => SMS_StatusMessage
System => SMS_R_System
WorkstationStatus => SMS_G_System_WORKSTATION_STATUS
User => SMS_R_User
`t
Note: You only need to type as many characters as needed to be unambiguous.
`t
"@),
[Parameter(Position = 1)]
[string]$filter = $null,
[Parameter(Position = 2)]
[string]$computername = $default_wmi_provider_server,
[Parameter(Position = 3)]
[string]$site = $default_site)
$classes = @{'collection' = 'SMS_Collection';
'package' = 'SMS_Package';
'program' = 'SMS_Program';
'system' = 'SMS_R_System';
'server' = 'SMS_SystemResourceList';
'advertisement' = 'SMS_Advertisement';
'query' = 'SMS_Query';
'membershiprule' = 'SMS_CollectionMembershipRule';
'statusmessage' = 'SMS_StatusMessage';
'site' = 'SMS_Site';
'user' = 'SMS_R_User';
'pkgstatus' = 'SMS_PackageStatus';
'addremoveprograms' = 'SMS_G_System_ADD_REMOVE_PROGRAMS';
'computersystem' = 'SMS_G_System_COMPUTER_SYSTEM';
'operatingsystem' = 'SMS_G_System_OPERATING_SYSTEM';
'service' = 'SMS_G_System_SERVICE';
'workstationstatus' = 'SMS_G_System_WORKSTATION_STATUS';
'networkadapter' = 'SMS_G_System_NETWORK_ADAPTER';
'networkadapterconfiguration' = ('SMS_G_System_NETWORK_' +
'ADAPTER_CONFIGURATION');
'logicaldisk' = 'SMS_G_System_LOGICAL_DISK';
'distributionpoint' = 'SMS_DistributionPoint';
'adstatus' = 'SMS_ClientAdvertisementStatus'}
$matches = @();
foreach ($class_name in @($classes.Keys | sort)) {
if ($class_name.StartsWith($class.ToLower())) {
$matches += $classes.($class_name)
}
}
if ($matches.Count -gt 1) {
Write-Error @"
`t
Warning: Class provided matches more than one nickname.
`t
Type 'Get-SMSWmi' with no parameters to see a list of nicknames.
`t
"@
$class = $matches[0]
} elseif ($matches.Count -eq 1) {
$class = $matches[0]
}
$query = "Select * from $class"
if ($filter) {
$query += " Where $filter"
}
# Now that we have our parameters, let's execute the command.
$namespace = 'root\\sms\\site_' + $site
gwmi -ComputerName $computerName -Namespace $namespace -Query $query
}
function Find-SmsID {
<#
.Synopsis
Look up SMS WMI objects from the SMS Provider by SMS ID.
.Description
This function makes it easy to look up a System Resource, Advertisement,
Package, or Collection by ID. The SMS Provider is queried, and the WMI object
that matches the ID is returned.
.Parameter AdvertisementID
A switch indicating that the $ID is an AdvertisementID.
.Parameter CollectionID
A switch indicating that the $ID is a CollectionID.
.Parameter PackageID
A switch indicating that the $ID is a PackageID.
.Parameter ResourceID
A switch indicating that the $ID is a ResourceID.
.Parameter ID
A string with the ID to look up.
.Parameter computername
The server with the SMS Provider installed. Note: May not be the site server.
.Parameter site
The site code of the site being accessed.
.Example
# Look up PackageID S000003D
PS> Find-SmsID -PackageID S000003D
.ReturnValue
A System.Management.ManagementObject object of the corresponding class.
.Link
Documentation on the SMS WMI objects can be found in the SCCM SDK:
http://www.microsoft.com/downloads/details.aspx?familyid=064a995f-ef13-4200-81ad-e3af6218edcc&displaylang=en
.Notes
NAME: Find-SmsID
AUTHOR: Tim Johnson <tojo2000@tojo2000.com>
FILE: SMS.psm1
#>
param([switch]$AdvertisementID,
[switch]$CollectionID,
[switch]$ResourceID,
[switch]$PackageID,
[string]$ID,
[string]$computername = $default_wmi_provider_server,
[string]$site = $default_site)
$class = ''
$Type = ''
if ($AdvertisementID) {
$Type = 'AdvertisementID'
$class = 'SMS_Advertisement'
} elseif ($CollectionID) {
$Type = 'CollectionID'
$class = 'SMS_Collection'
} elseif ($PackageID) {
$Type = 'PackageID'
$class = 'SMS_Package'
} elseif ($ResourceID) {
$Type = 'ResourceID'
$class = 'SMS_R_System'
} else {
Throw @"
`t
You must specify an ID type. Valid switches are:
`t
`t-AdvertisementID
`t-CollectionID
`t-PackageID
`t-ResourceID
`t
USAGE: Find-SmsID <Type> <ID> [-computername <computer>] [-site <site>]
`t
"@
}
if ($ResourceID) {
trap [System.Exception] {
Write-Output "`nERROR: Invalid Input for ResourceID!`n"
break
}
$Type = 'ResourceID'
$class = 'System'
[int]$ID = $ID
} else{
if ($ID -notmatch '^[a-zA-Z0-9]{8}$') {
Throw "`n`t`nERROR: Invalid ID format.`n`t`n"
}
}
Get-SmsWmi -class $class -filter "$Type = `"$ID`"" `
-computername $computername `
-site $site
}
function Get-SmsCollectionTree {
<#
.Synopsis
Inspired by tree.com from DOS, it creates a tree of all collections in SMS.
.Description
This function iterates recursively through all collections, showing which
collections are under which other collections, and what their CollectionIDs
are.
.Parameter root
The CollectionID of the collection to start with (default COLLROOT).
.Parameter indent
The indent level of the current interation.
.Parameter computername
The hostname of the server with the SMS Provider
.Parameter site
The site code of the target SMS site.
.Link
Documentation on the SMS WMI objects can be found in the SCCM SDK:
http://www.microsoft.com/downloads/details.aspx?familyid=064a995f-ef13-4200-81ad-e3af6218edcc&displaylang=en
.Notes
NAME: Get-SmsCollectionTree
AUTHOR: Tim Johnson <tojo2000@tojo2000.com>
FILE: SMS.psm1
#>
param([string]$root = 'COLLROOT',
[int]$indent = 0,
[string]$computername = $default_wmi_provider_server,
[string]$site = $default_site)
Get-SmsWmi -class SMS_CollectToSubCollect `
-filter "parentCollectionID = '$root'" `
-computername $computername `
-site $site |
% {$name = (Find-SmsID -c $_.subCollectionID).Name
Add-Member -InputObject $_ -Name 'sub_name' NoteProperty $name
$_} |
sort sub_name |
% {Write-Host ((' ' * $indent) +
"+ $($_.sub_name) : $($_.subCollectionID)")
Get-SmsCollectionTree -root $_.subCollectionID `
-indent ($indent + 1) `
-computername $computername `
-site $site}
}
function Approve-Client {
<#
.Synopsis
Approves a list of resources or all clients in a collection.
.Description
Marks one or more clients as Approved in the SCCM DB. A list of resources
or a CollectionID may be passed.
.Parameter resource_list
A list of ResourceIDs to be approved.
.Parameter collection_id
A CollectionID whose members will be approved.
.Parameter computername
The server with the SMS Provider installed. Note: May not be the site server.
.Parameter site
The site code of the site being accessed.
.Example
# Approve two systems by ResourceID
PS> Approve-Client -resource_list 33217, 4522
.Example
# Approve all members of collection S000023C
PS> Approve-Client -collection_id S000023C
.ReturnValue
An integer with the number of clients approved.
.Link
Documentation on the SMS WMI objects can be found in the SCCM SDK:
http://www.microsoft.com/downloads/details.aspx?familyid=064a995f-ef13-4200-81ad-e3af6218edcc&displaylang=en
.Notes
NAME: Approve-Client
AUTHOR: Tim Johnson <tojo2000@tojo2000.com>
FILE: SMS.psm1
#>
param([string[]]$resource_list,
[string]$collection_id,
[string]$computername = $default_wmi_provider_server,
[string]$site = $default_site)
$clients = @()
$coll_class = [wmiclass]('\\\\{0}\\root\\sms\\site_{1}:SMS_Collection' `
-f $computername, $site)
if ($resource_list.Count) {
$clients = $resource_list
}elseif ($collection_id){
$clients = @(Get-SmsWmi SMS_CollectionMember_a `
-filter "CollectionID = '$($collection_id)'" |
%{$_.ResourceID})
}
if ($clients.Count -eq 0) {
Write-Error ('Error: You must supply at least one client.`n' +
' (Did you enter an empty or invalid collection?)')
break
}
return ($coll_class.ApproveClients($clients)).ReturnValue
}
|
PowerShellCorpus/PoshCode/Inventory_2.ps1
|
Inventory_2.ps1
|
##############################################################################\n##\n## Inventory\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\nServes as the configuration script for a custom remoting endpoint that\nexposes only the Get-Inventory custom command.\n\n.EXAMPLE\n\nPS >Register-PsSessionConfiguration Inventory `\n -StartupScript 'C:\\Program Files\\Endpoints\\Inventory.ps1'\nPS >Enter-PsSession leeholmes1c23 -ConfigurationName Inventory\n\n[leeholmes1c23]: [Inventory] > Get-Command\n\nCommandType Name Definition\n----------- ---- ----------\nFunction Exit-PSSession [CmdletBinding()]...\nFunction Get-Command [CmdletBinding()]...\nFunction Get-FormatData [CmdletBinding()]...\nFunction Get-Help [CmdletBinding()]...\nFunction Get-Inventory ...\nFunction Measure-Object [CmdletBinding()]...\nFunction Out-Default [CmdletBinding()]...\nFunction prompt ...\nFunction Select-Object [CmdletBinding()]...\n\n[leeholmes1c23]: [Inventory] > Get-Inventory\n\nSystemDirectory : C:\\Windows\\system32\nOrganization :\nBuildNumber : 6002\nRegisteredUser : Lee Holmes\nSerialNumber : 89580-433-1295803-71477\nVersion : 6.0.6002\n\n[leeholmes1c23]: [Inventory] > 1+1\nThe syntax is not supported by this runspace. This might be because it is\nin no-language mode.\n + CategoryInfo :\n + FullyQualifiedErrorId : ScriptsNotAllowed\n\n[leeholmes1c23]: [Inventory] > Exit-PsSession\nPS >\n\n#>\n\nSet-StrictMode -Off\n\n## Create a new function to get inventory\nfunction Get-Inventory\n{\n Get-WmiObject Win32_OperatingSystem\n}\n\n## Customize the prompt\nfunction Prompt\n{\n "[Inventory] > "\n}\n\n## Remember which functions we want to expose to the user\n$exportedCommands = "Get-Inventory","Prompt"\n\n## The System.Management.Automation.Runspaces.InitialSessionState class\n## has a CreateRestricted() method that creates a default locked-down\n## secure configuration for a remote session. This configuration only\n## supports the bare minimum required for interactive remoting.\n$issType = [System.Management.Automation.Runspaces.InitialSessionState]\n$iss = $issType::CreateRestricted("RemoteServer")\n\n## Add the commands to a hashtable so that we can access them easily\n$issHashtable = @{}\nforeach($command in $iss.Commands)\n{\n $issHashtable[$command.Name + "-" + $command.CommandType] = $command\n}\n\n## Go through all of functions built into the restricted runspace and add\n## them to this session. These are proxy functions to limit the functionality\n## of commands that we need (such as Get-Command, Select-Object, etc.)\nforeach($function in $iss.Commands |\n Where-Object { $_.CommandType -eq "Function" })\n{\n Set-Content "function:\\$($function.Name)" -Value $function.Definition\n}\n\n## Go through all of the commands in this session\nforeach($command in Get-Command)\n{\n ## If it was one of our exported commands, keep it Public\n if($exportedCommands -contains $command.Name) { continue }\n\n ## If the current command is defined as Private in the initial session\n ## state, mark it as private here as well.\n $issCommand = $issHashtable[$command.Name + "-" + $command.CommandType]\n if((-not $issCommand) -or ($issCommand.Visibility -ne "Public"))\n {\n $command.Visibility = "Private"\n }\n}\n\n## Finally, prevent all access to the PowerShell language\n$executionContext.SessionState.Scripts.Clear()\n$executionContext.SessionState.Applications.Clear()\n$executionContext.SessionState.LanguageMode = "NoLanguage"
|
PowerShellCorpus/PoshCode/Set-Computername_1.ps1
|
Set-Computername_1.ps1
|
function Set-ComputerName {
param( [switch]$help,
@@ [string]$originalPCName=$(read-host "Please specify the current name of the computer"),
[string]$computerName=$(read-host "Please specify the new name of the computer"))
$usage = "set-ComputerName -computername AnewName"
if ($help) {Write-Host $usage;break}
@@ $computer = Get-WmiObject Win32_ComputerSystem -computername $originalPCName
$computer.Rename($computerName)
}
|
PowerShellCorpus/PoshCode/NIC Performance_1.ps1
|
NIC Performance_1.ps1
|
$cat = New-Object system.Diagnostics.PerformanceCounterCategory("Network Interface")
$inst = $cat.GetInstanceNames()
foreach ( $nic in $inst ) {
$a = $cat.GetCounters( $nic )
$a | ft CounterName, { $_.NextValue() } -AutoSize
}
|
PowerShellCorpus/PoshCode/Ayth_1.ps1
|
Ayth_1.ps1
|
# ========================================================================
#
# Microsoft PowerShell Source File -- Created with PowerShell Plus Professional
#
# NAME: Disable-MassMailPF.ps1
#
# AUTHOR: Darrin Henshaw , Ignition IT Canada Ltd.
# DATE : 8/13/2008
#
# COMMENT: Used to disable mail on an imported list of public folders.
#
# ========================================================================
param($csv = $Args[0])
$Preference = $ConfirmPreference
$ConfirmPreference = 'none'
# Import the list of the public folders to the variable $pflist
$pflist = Import-Csv -path $csv
# Loop through allt he public folder names in the variable we created above.
foreach ($pf in $pflist)
# For all of them, we get their properties and examine as to whether they are mail enabled already. If they are we disable the mail on them.
{Get-PublicFolder -identity $pf.Identity |Where-Object {$_.MailEnabled -eq $true}|Disable-MailPublicFolder -Server hfxignvmexpf1}
$ConfirmPreference = $Preference
|
PowerShellCorpus/PoshCode/Import-BufferBox.ps1
|
Import-BufferBox.ps1
|
###################################################################################################
##### BUFFER UTILITIES SCRIPT FUNCTIONS AND SETUP
###################################################################################################
## A bunch of script functions for creating a simple in-console split-view with output above and an
## input line below. It allows scripts to sort-of simulate accepting input while they output text.
## It's still pretty fragile and occasionally does weird things while you're typing, because it's
## not really multi-threaded and the $Host doesn't have a "LineAvailable" method ... and if you
## pause a script, you can't see output from typing, so the whole things is well and truly a hack.
## But it works!
##
## NOTE: there's a demo script you can call by passing "DEMO" when you invoke this file
## USAGE NOTE: When you execute this script file, all functions become global
###################################################################################################
$global:_RECTANGLE_ = "system.management.automation.host.rectangle"
$global:_BLANKCELL_ = new-object System.Management.Automation.Host.BufferCell(' ','Black','Black','complete')
Function global:New-BufferBox ($Height, $Width, $Title="") {
$box = &{"¯¯$Title$('¯'*($Width-($Title.Length+2)))";
1..($Height - 2) | % {(' ' * $Width)};
('_' * $Width);
1..2 | % {(' ' * $Width)};
}
$boxBuffer = $Host.UI.RawUI.NewBufferCellArray($box,'Green','Black')
,$boxBuffer
}
Function global:Move-BufferBox ($Origin,$Width,$Height,$Scroll=-1){
$re = new-object $_RECTANGLE_ $origin.x, $origin.y, ($origin.x + $width-2), ($origin.y + $height)
$origin.Y += $Scroll
$Host.UI.RawUI.ScrollBufferContents($re, $origin, $re, $_BLANKCELL_)
}
Function global:Write-Message ($Message,$Foreground = 'White',$Background = 'Black',[switch]$noscroll) {
if ( -not $NoScroll) {
Move-BufferBox $ContentPos ($WindowSize.Width -2) ($WindowSize.Height -5)
}
# "{0},{1} {2},{3} -{4}" -f $script:pos.X, $script:pos.Y, $MessagePos.X, $MessagePos.Y, $message
$host.ui.rawui.SetBufferContents(
$MessagePos,
$Host.UI.RawUI.NewBufferCellArray(
@($message.PadRight($WindowSize.Width)),
$Foreground,
$Background)
)
}
Function global:Clear-PromptBox {
$Host.UI.RawUI.SetBufferContents( $PromptPos, $prompt )
}
Function global:Initialize-BufferBox($Title) {
###################################################################################################
##### Initialize a lot of settings
###################################################################################################
$script:WindowSize = $Host.UI.RawUI.WindowSize;
"`n" * $WindowSize.Height
$script:ContentPos = $Host.UI.RawUI.WindowPosition;
$Host.UI.RawUI.SetBufferContents($ContentPos, (New-BufferBox ($WindowSize.Height - 2) $WindowSize.Width $title))
$ContentPos.X += 2 # 2 cell left padding on output
$ContentPos.Y += 1 # leave the top row with the title in it
# The Message is written into the very last line of the ContentBox
$script:MessagePos = $ContentPos
$MessagePos.Y += ($WindowSize.Height - 5)
$script:PromptPos = $ContentPos
$PromptPos.X = 0
$PromptPos.Y += $WindowSize.Height - 3
$script:prompt = $Host.UI.RawUI.NewBufferCellArray( @(&{" " * $WindowSize.Width;" " * $WindowSize.Width}), "Yellow", "Black")
}
Function Test-BufferBox {
$fore = $Host.UI.RawUI.ForegroundColor
$back = $Host.UI.RawUI.BackgroundColor
$Host.UI.RawUI.ForegroundColor = "Yellow"
$Host.UI.RawUI.BackgroundColor = "Black"
Initialize-BufferBox "Testing BufferBox"
Write-Message 'Welcome to the BufferBox script by Joel "Jaykul" Bennett'
Write-Message "With great inspiration from /\\/\\o\\/\\/ http://ThePowerShellGuy.com"
Write-Message "You're about to see text fly by up here in the top of the window"
Write-Message "But while it's flying, you can still type down in the bottom!"
Write-Message "Try it out. Press any key to start."
$Host.UI.RawUI.ReadKey( "IncludeKeyDown" ) | out-null
[string]$line=""
Get-Content $MyInvocation.ScriptName | foreach {
Write-Message $_
while($Host.UI.RawUI.KeyAvailable) {
$k = $Host.UI.RawUI.ReadKey( "IncludeKeyUp" )
if($k.VirtualKeyCode -eq 13 )
{
Write-Message $line -fore red -back yellow
$line=""
Clear-PromptBox
}
elseif($k.VirtualKeyCode -eq 8 )
{
$line = $line.SubString(0,$($line.Length-2))
}
elseif($k.Character -ne 0)
{
$line += $k.Character
}
}
1..10 | % {[System.Threading.Thread]::Sleep(20)}
}
Write-Message "Thanks for playing..."
[System.Threading.Thread]::Sleep(1000)
$Host.UI.RawUI.ForegroundColor = $fore
$Host.UI.RawUI.BackgroundColor = $back
$Host.UI.RawUI.FlushInputBuffer()
}
if($args.Count -gt 0) { Test-BufferBox }
|
PowerShellCorpus/PoshCode/Quest Dynamic Group 001.ps1
|
Quest Dynamic Group 001.ps1
|
<#
2012.07.06
Information will be uploaded shortly.
#>
|
PowerShellCorpus/PoshCode/Get-DiskSizeInfo.ps1
|
Get-DiskSizeInfo.ps1
|
Function Get-DiskSizeInfo {
<#
.DESCRIPTION
Check the Disk(s) Size and remaining freespace.
.PARAMETER ComputerName
Specify the computername(s)
.INPUTS
System.String
.OUTPUTS
System.Management.Automation.PSObject
.EXAMPLE
Get-DiskSizeInfo
Get the drive(s), Disk(s) space, and the FreeSpace (GB and Percentage)
.EXAMPLE
Get-DiskSizeInfo -ComputerName SERVER01,SERVER02
Get the drive(s), Disk(s) space, and the FreeSpace (GB and Percentage) on the Computers SERVER01 and SERVER02
.EXAMPLE
Get-Content Computers.txt | Get-DiskSizeInfo
Get the drive(s), Disk(s) space, and the FreeSpace (GB and Percentage) for each computers listed in Computers.txt
.NOTES
NAME : Get-DiskSizeInfo
AUTHOR: Francois-Xavier Cat
EMAIL : fxcat@LazyWinAdmin.com
DATE : 2013/02/05
.LINK
http://lazywinadmin.com
#>
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$True)]
[string[]]$ComputerName = $env:COMPUTERNAME
)
BEGIN {# Setup
}
PROCESS {
Foreach ($Computer in $ComputerName) {
Write-Verbose -Message "ComputerName: $Computer - Getting Disk(s) information..."
try {
# Set all the parameters required for our query
$params = @{'ComputerName'=$Computer;
'Class'='Win32_LogicalDisk';
'Filter'="DriveType=3";
'ErrorAction'='SilentlyContinue'}
$TryIsOK = $True
# Run the query against the current $Computer
$Disks = Get-WmiObject @params
}#Try
Catch {
"$Computer" | Out-File -Append -FilePath c:\\Errors.txt
$TryIsOK = $False
}#Catch
if ($TryIsOK) {
Write-Verbose -Message "ComputerName: $Computer - Formating information for each disk(s)"
foreach ($disk in $Disks) {
# Prepare the Information output
Write-Verbose -Message "ComputerName: $Computer - $($Disk.deviceid)"
$output = @{'ComputerName'=$computer;
'Drive'=$disk.deviceid;
'FreeSpace(GB)'=("{0:N2}" -f($disk.freespace/1GB));
'Size(GB)'=("{0:N2}" -f($disk.size/1GB));
'PercentFree'=("{0:P2}" -f(($disk.Freespace/1GB) / ($disk.Size/1GB)))}
# Create a new PowerShell object for the output
$object = New-Object -TypeName PSObject -Property $output
$object.PSObject.TypeNames.Insert(0,'Report.DiskSizeInfo')
# Output the disk information
Write-Output -InputObject $object
}#foreach ($disk in $disks)
}#if ($TryIsOK)
}#Foreach ($Computer in $ComputerName)
}#PROCESS
END {# Cleanup
}
}#Function Get-DiskSizeInfo
|
PowerShellCorpus/PoshCode/RegEx Quick Reference.ps1
|
RegEx Quick Reference.ps1
|
# get-regex.ps1
#
# Displays .NET/C#/Powershell Regular Expression Quick Reference
#
# Author: Robbie Foust (rfoust@duke.edu)
#
# For best visual results, run "get-regex | ft -auto"
function global:get-regex ([switch]$CharRep, [switch]$CharClass, [switch]$Anchors, [switch]$Comments, [switch]$Grouping, [switch]$Replacement)
{
$CharRepDesc = "Character representations"
$CharClassDesc = "Character classes and class-like constructs"
$AnchorsDesc = "Anchors and other zero-width tests"
$CommentsDesc = "Comments and mode modifiers"
$GroupingDesc = "Grouping, capturing, conditional, and control"
$ReplacementDesc = "Replacement sequences"
if (!$CharRep -and !$CharClass -and !$Anchors -and !$Comments -and !$Grouping -and !$Replacement)
{
$all = $true
}
else
{
$all = $false
}
if ($CharRep -or $all)
{
$CharRepObj = @()
$CharRepObj += new-object psobject | add-member noteproperty "Sequence" "\\a" -pass |
add-member noteproperty "Meaning" "Alert (bell), x07." -pass |
add-member noteproperty "Table" $CharRepDesc -pass
$CharRepObj += new-object psobject | add-member noteproperty "Sequence" "\\b" -pass |
add-member noteproperty "Meaning" "Backspace, x08, supported only in character class." -pass |
add-member noteproperty "Table" $CharRepDesc -pass
$CharRepObj += new-object psobject | add-member noteproperty "Sequence" "\\e" -pass |
add-member noteproperty "Meaning" "ESC character, x1B." -pass |
add-member noteproperty "Table" $CharRepDesc -pass
$CharRepObj += new-object psobject | add-member noteproperty "Sequence" "\\n" -pass |
add-member noteproperty "Meaning" "Newline, x0A." -pass |
add-member noteproperty "Table" $CharRepDesc -pass
$CharRepObj += new-object psobject | add-member noteproperty "Sequence" "\\r" -pass |
add-member noteproperty "Meaning" "Carriage return, x0D." -pass |
add-member noteproperty "Table" $CharRepDesc -pass
$CharRepObj += new-object psobject | add-member noteproperty "Sequence" "\\f" -pass |
add-member noteproperty "Meaning" "Form feed, x0C." -pass |
add-member noteproperty "Table" $CharRepDesc -pass
$CharRepObj += new-object psobject | add-member noteproperty "Sequence" "\\t" -pass |
add-member noteproperty "Meaning" "Horizontal tab, x09." -pass |
add-member noteproperty "Table" $CharRepDesc -pass
$CharRepObj += new-object psobject | add-member noteproperty "Sequence" "\\v" -pass |
add-member noteproperty "Meaning" "Vertical tab, x0B." -pass |
add-member noteproperty "Table" $CharRepDesc -pass
$CharRepObj += new-object psobject | add-member noteproperty "Sequence" "\\0octal" -pass |
add-member noteproperty "Meaning" "Character specified by a two-digit octal code." -pass |
add-member noteproperty "Table" $CharRepDesc -pass
$CharRepObj += new-object psobject | add-member noteproperty "Sequence" "\\xhex" -pass |
add-member noteproperty "Meaning" "Character specified by a two-digit hexadecimal code." -pass |
add-member noteproperty "Table" $CharRepDesc -pass
$CharRepObj += new-object psobject | add-member noteproperty "Sequence" "\\uhex" -pass |
add-member noteproperty "Meaning" "Character specified by a four-digit hexadecimal code." -pass |
add-member noteproperty "Table" $CharRepDesc -pass
$CharRepObj += new-object psobject | add-member noteproperty "Sequence" "\\cchar" -pass |
add-member noteproperty "Meaning" "Named control character." -pass |
add-member noteproperty "Table" $CharRepDesc -pass
$CharRepObj
}
if ($CharClass -or $all)
{
$CharClassObj = @()
$CharClassObj += new-object psobject | add-member noteproperty "Sequence" "[...]" -pass |
add-member noteproperty "Meaning" "A single character listed or contained within a listed range." -pass |
add-member noteproperty "Table" $CharClassDesc -pass
$CharClassObj += new-object psobject | add-member noteproperty "Sequence" "[^...]" -pass |
add-member noteproperty "Meaning" "A single character not listed and not contained within a listed range." -pass |
add-member noteproperty "Table" $CharClassDesc -pass
$CharClassObj += new-object psobject | add-member noteproperty "Sequence" "." -pass |
add-member noteproperty "Meaning" "Any character, except a line terminator (unless single-line mode, s)." -pass |
add-member noteproperty "Table" $CharClassDesc -pass
$CharClassObj += new-object psobject | add-member noteproperty "Sequence" "\\w" -pass |
add-member noteproperty "Meaning" "Word character." -pass |
add-member noteproperty "Table" $CharClassDesc -pass
$CharClassObj += new-object psobject | add-member noteproperty "Sequence" "\\W" -pass |
add-member noteproperty "Meaning" "Non-word character." -pass |
add-member noteproperty "Table" $CharClassDesc -pass
$CharClassObj += new-object psobject | add-member noteproperty "Sequence" "\\d" -pass |
add-member noteproperty "Meaning" "Digit." -pass |
add-member noteproperty "Table" $CharClassDesc -pass
$CharClassObj += new-object psobject | add-member noteproperty "Sequence" "\\D" -pass |
add-member noteproperty "Meaning" "Non-digit." -pass |
add-member noteproperty "Table" $CharClassDesc -pass
$CharClassObj += new-object psobject | add-member noteproperty "Sequence" "\\s" -pass |
add-member noteproperty "Meaning" "Whitespace character." -pass |
add-member noteproperty "Table" $CharClassDesc -pass
$CharClassObj += new-object psobject | add-member noteproperty "Sequence" "\\S" -pass |
add-member noteproperty "Meaning" "Non-whitespace character." -pass |
add-member noteproperty "Table" $CharClassDesc -pass
$CharClassObj += new-object psobject | add-member noteproperty "Sequence" "\\p{prop}" -pass |
add-member noteproperty "Meaning" "Character contained by given Unicode block or property." -pass |
add-member noteproperty "Table" $CharClassDesc -pass
$CharClassObj += new-object psobject | add-member noteproperty "Sequence" "\\P{prop}" -pass |
add-member noteproperty "Meaning" "Character not contained by given Unicode block or property." -pass |
add-member noteproperty "Table" $CharClassDesc -pass
$CharClassObj
}
if ($Anchors -or $all)
{
$AnchorsObj = @()
$AnchorsObj += new-object psobject | add-member noteproperty "Sequence" "^" -pass |
add-member noteproperty "Meaning" "Start of string, or after any newline if in MULTILINE mode." -pass |
add-member noteproperty "Table" $AnchorsDesc -pass
$AnchorsObj += new-object psobject | add-member noteproperty "Sequence" "\\A" -pass |
add-member noteproperty "Meaning" "Beginning of string, in all match modes." -pass |
add-member noteproperty "Table" $AnchorsDesc -pass
$AnchorsObj += new-object psobject | add-member noteproperty "Sequence" "$" -pass |
add-member noteproperty "Meaning" "End of string, or before any newline if in MULTILINE mode." -pass |
add-member noteproperty "Table" $AnchorsDesc -pass
$AnchorsObj += new-object psobject | add-member noteproperty "Sequence" "\\Z" -pass |
add-member noteproperty "Meaning" "End of string but before any final line terminator, in all match modes." -pass |
add-member noteproperty "Table" $AnchorsDesc -pass
$AnchorsObj += new-object psobject | add-member noteproperty "Sequence" "\\z" -pass |
add-member noteproperty "Meaning" "End of string, in all match modes." -pass |
add-member noteproperty "Table" $AnchorsDesc -pass
$AnchorsObj += new-object psobject | add-member noteproperty "Sequence" "\\b" -pass |
add-member noteproperty "Meaning" "Boundary between a \\w character and a \\W character." -pass |
add-member noteproperty "Table" $AnchorsDesc -pass
$AnchorsObj += new-object psobject | add-member noteproperty "Sequence" "\\B" -pass |
add-member noteproperty "Meaning" "Not-word-boundary." -pass |
add-member noteproperty "Table" $AnchorsDesc -pass
$AnchorsObj += new-object psobject | add-member noteproperty "Sequence" "\\G" -pass |
add-member noteproperty "Meaning" "End of the previous match." -pass |
add-member noteproperty "Table" $AnchorsDesc -pass
$AnchorsObj += new-object psobject | add-member noteproperty "Sequence" "(?=...)" -pass |
add-member noteproperty "Meaning" "Positive lookahead." -pass |
add-member noteproperty "Table" $AnchorsDesc -pass
$AnchorsObj += new-object psobject | add-member noteproperty "Sequence" "(?!...)" -pass |
add-member noteproperty "Meaning" "Negative lookahead." -pass |
add-member noteproperty "Table" $AnchorsDesc -pass
$AnchorsObj += new-object psobject | add-member noteproperty "Sequence" "(?<=...)" -pass |
add-member noteproperty "Meaning" "Positive lookbehind." -pass |
add-member noteproperty "Table" $AnchorsDesc -pass
$AnchorsObj += new-object psobject | add-member noteproperty "Sequence" "(?<!...)" -pass |
add-member noteproperty "Meaning" "Negative lookbehind." -pass |
add-member noteproperty "Table" $AnchorsDesc -pass
$AnchorsObj
}
if ($Comments -or $all)
{
$CommentsObj = @()
$CommentsObj += new-object psobject | add-member noteproperty "Sequence" "Singleline (s)" -pass |
add-member noteproperty "Meaning" "Dot (.) matches any character, including a line terminator." -pass |
add-member noteproperty "Table" $CommentsDesc -pass
$CommentsObj += new-object psobject | add-member noteproperty "Sequence" "Multiline (m)" -pass |
add-member noteproperty "Meaning" "^ and $ match next to embedded line terminators." -pass |
add-member noteproperty "Table" $CommentsDesc -pass
$CommentsObj += new-object psobject | add-member noteproperty "Sequence" "IgnorePatternWhitespace (x)" -pass |
add-member noteproperty "Meaning" "Ignore whitespace and allow embedded comments starting with #." -pass |
add-member noteproperty "Table" $CommentsDesc -pass
$CommentsObj += new-object psobject | add-member noteproperty "Sequence" "IgnoreCase (i)" -pass |
add-member noteproperty "Meaning" "Case-insensitive match based on characters in the current culture." -pass |
add-member noteproperty "Table" $CommentsDesc -pass
$CommentsObj += new-object psobject | add-member noteproperty "Sequence" "CultureInvariant (i)" -pass |
add-member noteproperty "Meaning" "Culture-insensitive match." -pass |
add-member noteproperty "Table" $CommentsDesc -pass
$CommentsObj += new-object psobject | add-member noteproperty "Sequence" "ExplicitCapture (n)" -pass |
add-member noteproperty "Meaning" "Allow named capture groups, but treat parentheses as non-capturing groups." -pass |
add-member noteproperty "Table" $CommentsDesc -pass
$CommentsObj += new-object psobject | add-member noteproperty "Sequence" "Compiled" -pass |
add-member noteproperty "Meaning" "Compile regular expression." -pass |
add-member noteproperty "Table" $CommentsDesc -pass
$CommentsObj += new-object psobject | add-member noteproperty "Sequence" "RightToLeft" -pass |
add-member noteproperty "Meaning" "Search from right to left, starting to the left of the start position." -pass |
add-member noteproperty "Table" $CommentsDesc -pass
$CommentsObj += new-object psobject | add-member noteproperty "Sequence" "ECMAScript" -pass |
add-member noteproperty "Meaning" "Enables ECMAScript compliance when used with IgnoreCase or Multiline." -pass |
add-member noteproperty "Table" $CommentsDesc -pass
$CommentsObj += new-object psobject | add-member noteproperty "Sequence" "(?imnsx-imnsx)" -pass |
add-member noteproperty "Meaning" "Turn match flags on or off for rest of pattern." -pass |
add-member noteproperty "Table" $CommentsDesc -pass
$CommentsObj += new-object psobject | add-member noteproperty "Sequence" "(?imnsx-imnsx:...)" -pass |
add-member noteproperty "Meaning" "Turn match flags on or off for the rest of the subexpression." -pass |
add-member noteproperty "Table" $CommentsDesc -pass
$CommentsObj += new-object psobject | add-member noteproperty "Sequence" "(?#...)" -pass |
add-member noteproperty "Meaning" "Treat substring as a comment." -pass |
add-member noteproperty "Table" $CommentsDesc -pass
$CommentsObj += new-object psobject | add-member noteproperty "Sequence" "#..." -pass |
add-member noteproperty "Meaning" "Treat rest of line as a comment in /x mode." -pass |
add-member noteproperty "Table" $CommentsDesc -pass
$CommentsObj
}
if ($Grouping -or $all)
{
$GroupingObj = @()
$GroupingObj += new-object psobject | add-member noteproperty "Sequence" "(...)" -pass |
add-member noteproperty "Meaning" "Grouping. Submatches fill \\1,\\2,... and `$1,`$2,...." -pass |
add-member noteproperty "Table" $GroupingDesc -pass
$GroupingObj += new-object psobject | add-member noteproperty "Sequence" "\\n" -pass |
add-member noteproperty "Meaning" "In a regular expression, match what was matched by the nth earlier submatch." -pass |
add-member noteproperty "Table" $GroupingDesc -pass
$GroupingObj += new-object psobject | add-member noteproperty "Sequence" "`$n" -pass |
add-member noteproperty "Meaning" "In a replacement string, contains the nth earlier submatch." -pass |
add-member noteproperty "Table" $GroupingDesc -pass
$GroupingObj += new-object psobject | add-member noteproperty "Sequence" "(?<name>...)" -pass |
add-member noteproperty "Meaning" "Captures matched substring into group, 'name'." -pass |
add-member noteproperty "Table" $GroupingDesc -pass
$GroupingObj += new-object psobject | add-member noteproperty "Sequence" "(?:...)" -pass |
add-member noteproperty "Meaning" "Grouping-only parentheses, no capturing." -pass |
add-member noteproperty "Table" $GroupingDesc -pass
$GroupingObj += new-object psobject | add-member noteproperty "Sequence" "(?>...)" -pass |
add-member noteproperty "Meaning" "Disallow backtracking for subpattern." -pass |
add-member noteproperty "Table" $GroupingDesc -pass
$GroupingObj += new-object psobject | add-member noteproperty "Sequence" "...|..." -pass |
add-member noteproperty "Meaning" "Alternation; match one or the other." -pass |
add-member noteproperty "Table" $GroupingDesc -pass
$GroupingObj += new-object psobject | add-member noteproperty "Sequence" "*" -pass |
add-member noteproperty "Meaning" "Match 0 or more times." -pass |
add-member noteproperty "Table" $GroupingDesc -pass
$GroupingObj += new-object psobject | add-member noteproperty "Sequence" "+" -pass |
add-member noteproperty "Meaning" "Match 1 or more times." -pass |
add-member noteproperty "Table" $GroupingDesc -pass
$GroupingObj += new-object psobject | add-member noteproperty "Sequence" "?" -pass |
add-member noteproperty "Meaning" "Match 1 or 0 times." -pass |
add-member noteproperty "Table" $GroupingDesc -pass
$GroupingObj += new-object psobject | add-member noteproperty "Sequence" "{n}" -pass |
add-member noteproperty "Meaning" "Match exactly n times." -pass |
add-member noteproperty "Table" $GroupingDesc -pass
$GroupingObj += new-object psobject | add-member noteproperty "Sequence" "{n,}" -pass |
add-member noteproperty "Meaning" "Match at least n times." -pass |
add-member noteproperty "Table" $GroupingDesc -pass
$GroupingObj += new-object psobject | add-member noteproperty "Sequence" "{x,y}" -pass |
add-member noteproperty "Meaning" "Match at least x times, but no more than y times." -pass |
add-member noteproperty "Table" $GroupingDesc -pass
$GroupingObj += new-object psobject | add-member noteproperty "Sequence" "*?" -pass |
add-member noteproperty "Meaning" "Match 0 or more times, but as few times as possible." -pass |
add-member noteproperty "Table" $GroupingDesc -pass
$GroupingObj += new-object psobject | add-member noteproperty "Sequence" "+?" -pass |
add-member noteproperty "Meaning" "Match 1 or more times, but as few times as possible." -pass |
add-member noteproperty "Table" $GroupingDesc -pass
$GroupingObj += new-object psobject | add-member noteproperty "Sequence" "??" -pass |
add-member noteproperty "Meaning" "Match 0 or 1 times, but as few times as possible." -pass |
add-member noteproperty "Table" $GroupingDesc -pass
$GroupingObj += new-object psobject | add-member noteproperty "Sequence" "{n,}?" -pass |
add-member noteproperty "Meaning" "Match at least n times, but as few times as possible." -pass |
add-member noteproperty "Table" $GroupingDesc -pass
$GroupingObj += new-object psobject | add-member noteproperty "Sequence" "{x,y}?" -pass |
add-member noteproperty "Meaning" "Match at least x times, no more than y times, but as few times as possible." -pass |
add-member noteproperty "Table" $GroupingDesc -pass
$GroupingObj
}
if ($Replacement -or $all)
{
$ReplacementObj = @()
$ReplacementObj += new-object psobject | add-member noteproperty "Sequence" "`$1, `$2, ..." -pass |
add-member noteproperty "Meaning" "Captured submatches." -pass |
add-member noteproperty "Table" $ReplacementDesc -pass
$ReplacementObj += new-object psobject | add-member noteproperty "Sequence" "`${name}" -pass |
add-member noteproperty "Meaning" "Matched text of a named capture group." -pass |
add-member noteproperty "Table" $ReplacementDesc -pass
$ReplacementObj += new-object psobject | add-member noteproperty "Sequence" "`$'" -pass |
add-member noteproperty "Meaning" "Text before match." -pass |
add-member noteproperty "Table" $ReplacementDesc -pass
$ReplacementObj += new-object psobject | add-member noteproperty "Sequence" "`$&" -pass |
add-member noteproperty "Meaning" "Text of match." -pass |
add-member noteproperty "Table" $ReplacementDesc -pass
$ReplacementObj += new-object psobject | add-member noteproperty "Sequence" "`$'" -pass |
add-member noteproperty "Meaning" "Text after match." -pass |
add-member noteproperty "Table" $ReplacementDesc -pass
$ReplacementObj += new-object psobject | add-member noteproperty "Sequence" "`$+" -pass |
add-member noteproperty "Meaning" "Last parenthesized match." -pass |
add-member noteproperty "Table" $ReplacementDesc -pass
$ReplacementObj += new-object psobject | add-member noteproperty "Sequence" "`$_" -pass |
add-member noteproperty "Meaning" "Copy of original input string." -pass |
add-member noteproperty "Table" $ReplacementDesc -pass
$ReplacementObj
}
}
|
PowerShellCorpus/PoshCode/Set-OutlookSignature.ps1
|
Set-OutlookSignature.ps1
|
###########################################################################"
#
# NAME: Set-OutlookSignature.ps1
#
# AUTHOR: Jan Egil Ring
#
# COMMENT: Script to create an Outlook signature based on user information from Active Directory.
# Adjust the variables in the "Custom variables"-section
# Create an Outlook-signature from an Outlook-client based on your company template (logo, fonts etc) and copy this signature to the path defined in the $SigSource variable
# See the following blog-post for more information: http://blog.crayon.no/blogs/janegil/archive/2010/01/09/outlook-signature-based-on-user-information-from-active-directory.aspx
#
# Tested on Office 2003,2007 and 2010 beta
#
# You have a royalty-free right to use, modify, reproduce, and
# distribute this script file in any way you find useful, provided that
# you agree that the creator, owner above has no warranty, obligations,
# or liability for such use.
#
# VERSION HISTORY:
# 1.0 09.01.2010 - Initial release
#
###########################################################################"
#Custom variables
$CompanyName = 'Company Name'
$DomainName = 'domain.local'
$SigVersion = '1.0' #When the version number are updated the local signature are re-created
$SigSource = "\\\\$DomainName\\netlogon\\sig_files\\$CompanyName"
$ForceSignatureNew = '1' #When the signature are forced the signature are enforced as default signature for new messages the next time the script runs. 0 = no force, 1 = force
$ForceSignatureReplyForward = '0' #When the signature are forced the signature are enforced as default signature for reply/forward messages the next time the script runs. 0 = no force, 1 = force
#Environment variables
$AppData=(Get-Item env:appdata).value
$SigPath = '\\Microsoft\\Signatures'
$LocalSignaturePath = $AppData+$SigPath
#Get Active Directory information for current user
$UserName = $env:username
$Filter = "(&(objectCategory=User)(samAccountName=$UserName))"
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.Filter = $Filter
$ADUserPath = $Searcher.FindOne()
$ADUser = $ADUserPath.GetDirectoryEntry()
$ADDisplayName = $ADUser.DisplayName
$ADEmailAddress = $ADUser.mail
$ADTitle = $ADUser.title
$ADTelePhoneNumber = $ADUser.TelephoneNumber
#Setting registry information for the current user
$CompanyRegPath = "HKCU:\\Software\\"+$CompanyName
if (Test-Path $CompanyRegPath)
{}
else
{New-Item -path "HKCU:\\Software" -name $CompanyName}
if (Test-Path $CompanyRegPath'\\Outlook Signature Settings')
{}
else
{New-Item -path $CompanyRegPath -name "Outlook Signature Settings"}
$ForcedSignatureNew = (Get-ItemProperty $CompanyRegPath'\\Outlook Signature Settings').ForcedSignatureNew
$ForcedSignatureReplyForward = (Get-ItemProperty $CompanyRegPath'\\Outlook Signature Settings').ForcedSignatureReplyForward
$SignatureVersion = (Get-ItemProperty $CompanyRegPath'\\Outlook Signature Settings').SignatureVersion
Set-ItemProperty $CompanyRegPath'\\Outlook Signature Settings' -name SignatureSourceFiles -Value $SigSource
$SignatureSourceFiles = (Get-ItemProperty $CompanyRegPath'\\Outlook Signature Settings').SignatureSourceFiles
#Forcing signature for new messages if enabled
if ($ForcedSignatureNew -eq '1')
{
#Set company signature as default for New messages
$MSWord = New-Object -com word.application
$EmailOptions = $MSWord.EmailOptions
$EmailSignature = $EmailOptions.EmailSignature
$EmailSignatureEntries = $EmailSignature.EmailSignatureEntries
$EmailSignature.NewMessageSignature=$CompanyName
$MSWord.Quit()
}
#Forcing signature for reply/forward messages if enabled
if ($ForcedSignatureReplyForward -eq '1')
{
#Set company signature as default for Reply/Forward messages
$MSWord = New-Object -com word.application
$EmailOptions = $MSWord.EmailOptions
$EmailSignature = $EmailOptions.EmailSignature
$EmailSignatureEntries = $EmailSignature.EmailSignatureEntries
$EmailSignature.ReplyMessageSignature=$CompanyName
$MSWord.Quit()
}
#Copying signature sourcefiles and creating signature if signature-version are different from local version
if ($SignatureVersion -eq $SigVersion){}
else
{
#Copy signature templates from domain to local Signature-folder
Copy-Item "$SignatureSourceFiles\\*" $LocalSignaturePath -Recurse -Force
#Insert variables from Active Directory to rtf signature-file
$MSWord = New-Object -com word.application
$MSWord.Documents.Open($LocalSignaturePath+'\\'+$CompanyName+'.rtf')
($MSWord.ActiveDocument.Bookmarks.Item("DisplayName")).Select()
$MSWord.Selection.Text=$ADDisplayName
($MSWord.ActiveDocument.Bookmarks.Item("Title")).Select()
$MSWord.Selection.Text=$ADTitle
($MSWord.ActiveDocument.Bookmarks.Item("TelephoneNumber")).Select()
$MSWord.Selection.Text=$ADTelePhoneNumber
($MSWord.ActiveDocument.Bookmarks.Item("EmailAddress")).Select()
$MSWord.Selection.Text=$ADEmailAddress
($MSWord.ActiveDocument).Save()
($MSWord.ActiveDocument).Close()
$MSWord.Quit()
#Insert variables from Active Directory to htm signature-file
$MSWord = New-Object -com word.application
$MSWord.Documents.Open($LocalSignaturePath+'\\'+$CompanyName+'.htm')
($MSWord.ActiveDocument.Bookmarks.Item("DisplayName")).Select()
$MSWord.Selection.Text=$ADDisplayName
($MSWord.ActiveDocument.Bookmarks.Item("Title")).Select()
$MSWord.Selection.Text=$ADTitle
($MSWord.ActiveDocument.Bookmarks.Item("TelephoneNumber")).Select()
$MSWord.Selection.Text=$ADTelePhoneNumber
($MSWord.ActiveDocument.Bookmarks.Item("EmailAddress")).Select()
$MSWord.Selection.Text=$ADEmailAddress
($MSWord.ActiveDocument).Save()
($MSWord.ActiveDocument).Close()
$MSWord.Quit()
#Insert variables from Active Directory to txt signature-file
(Get-Content $LocalSignaturePath'\\'$CompanyName'.txt') | Foreach-Object {$_ -replace "DisplayName", $ADDisplayName -replace "Title", $ADTitle -replace "TelePhoneNumber", $ADTelePhoneNumber -replace "EmailAddress", $ADEmailAddress} | Set-Content $LocalSignaturePath'\\'$CompanyName'.txt'
}
#Stamp registry-values for Outlook Signature Settings if they doesn`t match the initial script variables. Note that these will apply after the second script run when changes are made in the "Custom variables"-section.
if ($ForcedSignatureNew -eq $ForceSignatureNew){}
else
{Set-ItemProperty $CompanyRegPath'\\Outlook Signature Settings' -name ForcedSignatureNew -Value $ForceSignatureNew}
if ($ForcedSignatureReplyForward -eq $ForceSignatureReplyForward){}
else
{Set-ItemProperty $CompanyRegPath'\\Outlook Signature Settings' -name ForcedSignatureReplyForward -Value $ForceSignatureReplyForward}
if ($SignatureVersion -eq $SigVersion){}
else
{Set-ItemProperty $CompanyRegPath'\\Outlook Signature Settings' -name SignatureVersion -Value $SigVersion}
|
PowerShellCorpus/PoshCode/Test-Port_6.ps1
|
Test-Port_6.ps1
|
function Test-Port{
<#
.SYNOPSIS
Tests port on computer.
.DESCRIPTION
Tests port on computer.
.PARAMETER computer
Name of server to test the port connection on.
.PARAMETER port
Port to test
.PARAMETER tcp
Use tcp port
.PARAMETER udp
Use udp port
.PARAMETER UDPTimeOut
Sets a timeout for UDP port query. (In milliseconds, Default is 1000)
.PARAMETER TCPTimeOut
Sets a timeout for TCP port query. (In milliseconds, Default is 1000)
.NOTES
Name: Test-Port.ps1
Author: Boe Prox
DateCreated: 18Aug2010
List of Ports: http://www.iana.org/assignments/port-numbers
To Do:
Add capability to run background jobs for each host to shorten the time to scan.
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Test-Port -computer 'server' -port 80
Checks port 80 on server 'server' to see if it is listening
.EXAMPLE
'server' | Test-Port -port 80
Checks port 80 on server 'server' to see if it is listening
.EXAMPLE
Test-Port -computer @("server1","server2") -port 80
Checks port 80 on server1 and server2 to see if it is listening
.EXAMPLE
Test-Port -comp dc1 -port 17 -udp -UDPtimeout 10000
Server : dc1
Port : 17
TypePort : UDP
Open : True
Notes : "My spelling is Wobbly. It's good spelling but it Wobbles, and the letters
get in the wrong places." A. A. Milne (1882-1958)
Description
-----------
Queries port 17 (qotd) on the UDP port and returns whether port is open or not
.EXAMPLE
@("server1","server2") | Test-Port -port 80
Checks port 80 on server1 and server2 to see if it is listening
.EXAMPLE
(Get-Content hosts.txt) | Test-Port -port 80
Checks port 80 on servers in host file to see if it is listening
.EXAMPLE
Test-Port -computer (Get-Content hosts.txt) -port 80
Checks port 80 on servers in host file to see if it is listening
.EXAMPLE
Test-Port -computer (Get-Content hosts.txt) -port @(1..59)
Checks a range of ports from 1-59 on all servers in the hosts.txt file
#>
[cmdletbinding(
DefaultParameterSetName = '',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = '',
ValueFromPipeline = $True)]
[array]$computer,
[Parameter(
Position = 1,
Mandatory = $True,
ParameterSetName = '')]
[array]$port,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[int]$TCPtimeout=1000,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[int]$UDPtimeout=1000,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[switch]$TCP,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[switch]$UDP
)
Begin {
If (!$tcp -AND !$udp) {$tcp = $True}
#Typically you never do this, but in this case I felt it was for the benefit of the function
#as any errors will be noted in the output of the report
$ErrorActionPreference = "SilentlyContinue"
$report = @()
}
Process {
ForEach ($c in $computer) {
ForEach ($p in $port) {
If ($tcp) {
#Create temporary holder
$temp = "" | Select Server, Port, TypePort, Open, Notes
#Create object for connecting to port on computer
$tcpobject = new-Object system.Net.Sockets.TcpClient
#Connect to remote machine's port
$connect = $tcpobject.BeginConnect($c,$p,$null,$null)
#Configure a timeout before quitting
$wait = $connect.AsyncWaitHandle.WaitOne($TCPtimeout,$false)
#If timeout
If(!$wait) {
#Close connection
$tcpobject.Close()
Write-Verbose "Connection Timeout"
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "TCP"
$temp.Open = "False"
$temp.Notes = "Connection to Port Timed Out"
} Else {
$error.Clear()
$tcpobject.EndConnect($connect) | out-Null
#If error
If($error[0]){
#Begin making error more readable in report
[string]$string = ($error[0].exception).message
$message = (($string.split(":")[1]).replace('"',"")).TrimStart()
$failed = $true
}
#Close connection
$tcpobject.Close()
#If unable to query port to due failure
If($failed){
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "TCP"
$temp.Open = "False"
$temp.Notes = "$message"
} Else{
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "TCP"
$temp.Open = "True"
$temp.Notes = ""
}
}
#Reset failed value
$failed = $Null
#Merge temp array with report
$report += $temp
}
If ($udp) {
#Create temporary holder
$temp = "" | Select Server, Port, TypePort, Open, Notes
#Create object for connecting to port on computer
$udpobject = new-Object system.Net.Sockets.Udpclient
#Set a timeout on receiving message
$udpobject.client.ReceiveTimeout = $UDPTimeout
#Connect to remote machine's port
Write-Verbose "Making UDP connection to remote server"
$udpobject.Connect("$c",$p)
#Sends a message to the host to which you have connected.
Write-Verbose "Sending message to remote host"
$a = new-object system.text.asciiencoding
$byte = $a.GetBytes("$(Get-Date)")
[void]$udpobject.Send($byte,$byte.length)
#IPEndPoint object will allow us to read datagrams sent from any source.
Write-Verbose "Creating remote endpoint"
$remoteendpoint = New-Object system.net.ipendpoint([system.net.ipaddress]::Any,0)
Try {
#Blocks until a message returns on this socket from a remote host.
Write-Verbose "Waiting for message return"
$receivebytes = $udpobject.Receive([ref]$remoteendpoint)
[string]$returndata = $a.GetString($receivebytes)
If ($returndata) {
Write-Verbose "Connection Successful"
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "UDP"
$temp.Open = "True"
$temp.Notes = $returndata
$udpobject.close()
}
} Catch {
If ($Error[0].ToString() -match "\\bRespond after a period of time\\b") {
#Close connection
$udpobject.Close()
#Make sure that the host is online and not a false positive that it is open
If (Test-Connection -comp $c -count 1 -quiet) {
Write-Verbose "Connection Open"
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "UDP"
$temp.Open = "True"
$temp.Notes = ""
} Else {
<#
It is possible that the host is not online or that the host is online,
but ICMP is blocked by a firewall and this port is actually open.
#>
Write-Verbose "Host maybe unavailable"
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "UDP"
$temp.Open = "False"
$temp.Notes = "Unable to verify if port is open or if host is unavailable."
}
} ElseIf ($Error[0].ToString() -match "forcibly closed by the remote host" ) {
#Close connection
$udpobject.Close()
Write-Verbose "Connection Timeout"
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "UDP"
$temp.Open = "False"
$temp.Notes = "Connection to Port Timed Out"
} Else {
$udpobject.close()
}
}
#Merge temp array with report
$report += $temp
}
}
}
}
End {
#Generate Report
$report
}
}
|
PowerShellCorpus/PoshCode/Windows Startup Script_2.ps1
|
Windows Startup Script_2.ps1
|
<#======================================================================================
File Name : Startup.ps1
Original Author : Kenneth C. Mazie
:
Description : This is a Windows startup script with pop-up notification and checks to
: assure things are not exectuted if already running or set. It can be run
: as a personal startup script or as a domain startup (with some editing).
: It is intended to be executed from the Start Menu "All Programs\\Startup" folder.
:
: The script will Start programs, map shares, set routes, and can email the results
: if desired. The email subroutine is commented out. You'll need to edit it yourself.
: When run with the "debug" variable set to TRUE it also displays staus in the
: PowerShell command window. Other wise all operation statuses are displayed in pop-up
: ballons near the system tray.
:
: To call the script use the following in a shortcut or in the RUN registry key.
: "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -WindowStyle Hidden –Noninteractive -NoLogo -Command "&{C:\\Startup.ps1}"
: Change the script name and path as needed to suit your environment.
:
: Be sure to edit all sections to suit your needs before executing. Be sure to
: enable sections you wish to run by uncommenting them at the bottom of the script.
:
: Route setting is done as a function of selecting a specific Network Adapter with the intent
: of manually altering your routes for hardline or WiFi connectivity. This section you will
: need to customize to suit your needs or leave commented out. This allowed me to
: alter the routing for my office (Wifi) or lab (hardline) by detecting whether my
: laptop was docked or not. The hardline is ALWAYS favored as written.
:
: To identify process names to use run "get-process" by itself to list process
: names that PowerShell will be happy with, just make sure each app you want to
: identify a process name for is already running first.
:
: A 2 second sleep delay is added to smooth out processing but can be removed if needed.
:
Notes : Sample script is safe to run as written, it will only load taskmanager and firefox.
: In general, I did not write this script for ease of readability. Most commands are
: one-liner style, sorry if that causes you grief.
:
Warnings : Drive mapping passwords are clear text within the script.
:
:
Last Update by : Kenneth C. Mazie (kcmjr)
Version History : v1.0 - 05-03-12 - Original
Change History : v2.0 - 11-15-12 - Minor edits
: v3.0 - 12-10-12 - Converted application commands to arrays
: v4.0 - 02-14-13 - Converted all other sections to arrays
:
=======================================================================================#>
clear-host
$Debug = $True
$CloudStor = $False
$ScriptName = "Startup Script"
#--[ Prep Pop-up Notifications ]--
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$Icon = [System.Drawing.SystemIcons]::Information
$Notify = new-object system.windows.forms.notifyicon
$Notify.icon = $Icon #--[ NOTE: Available tooltip icons are = warning, info, error, and none
$Notify.visible = $true
#--[ Force to execute with admin priviledge ]--
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = new-object Security.Principal.WindowsPrincipal $identity
if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -eq $false) {$Args = '-noprofile -nologo -executionpolicy bypass -file "{0}"' -f $MyInvocation.MyCommand.Path;Start-Process -FilePath 'powershell.exe' -ArgumentList $Args -Verb RunAs;exit}
if ($debug){write-host "`n------[ Running with Admin Privileges ]------`n" -ForegroundColor DarkCyan}
$Notify.ShowBalloonTip(2500,$ScriptName,"Script is running with full admin priviledges",[system.windows.forms.tooltipicon]::Info)
if ($debug){write-host "Running in DEBUG Mode..." -ForegroundColor DarkCyan}
function Pause-Host { #--[ Only use if you need a countdown timer ]--
param($Delay = 10)
$counter = 0;
While(!$host.UI.RawUI.KeyAvailable -and ($Delay-- -ne $counter )) #--count down
#While(!$host.UI.RawUI.KeyAvailable -and ($counter++ -lt $Delay )) #--count up
{
clear-host
if ($debug){Write-Host "testing... $Delay"} #--count down
#Write-Host "testing... $counter" #--count up
[Threading.Thread]::Sleep(1000)
}
}
Function SetRoutes { #--[ Array consists of Network, Mask ]--
$RouteArray = @()
$RouteArray += , @("10.0.0.0","255.0.0.0")
$RouteArray += , @("172.1.0.0","255.255.0.0")
$RouteArray += , @("192.168.1.0","255.255.255.0")
#--[ Add more route entries here... ]--
$Index = 0
Do {
$RouteNet = $ShareArray[$Index][0]
$RouteMask = $ShareArray[$Index][1]
iex "route delete $RouteNet"
Sleep (2)
iex "route add $RouteNet mask $RouteMask $IP"
Sleep (2)
$Index++
}
While ($Index -lt $RouteArray.length)
}
Function SetMappings { #--[ Array consists of Drive Letter, Path, User, and Password ]--
$ShareArray = @()
$ShareArray += , @("J:","\\\\192.168.1.250\\Share1","username","password")
$ShareArray += , @("K:","\\\\192.168.1.250\\Share2","username","password")
#--[ Add more mapping entries here... ]--
$Index = 0
Do {
$MapDrive = $ShareArray[$Index][0]
$MapPath = $ShareArray[$Index][1]
$MapUser = $ShareArray[$Index][2]
$MapPassword = $ShareArray[$Index][3]
$net = $(New-Object -Com WScript.Network)
if ( Exists-Drive $MapDrive){$Notify.ShowBalloonTip(2500,$ScriptName,"Drive $MapDrive is already mapped...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "Drive $MapDrive already mapped" -ForegroundColor DarkRed}}else{if (test-path $MapPath){$net.MapNetworkDrive($MapDrive, $MapPath, "False",$MapUser,$MapPassword);$Notify.ShowBalloonTip(2500,$ScriptName,"Mapping Drive $MapDrive...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "Mapping Drive $MapDrive" -ForegroundColor DarkGreen}}else{$Notify.ShowBalloonTip(2500,$ScriptName,"Cannot Map Drive $MapDrive - Target Not Found...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "Cannot Map Drive $MapDrive - Target Not Found" -ForegroundColor DarkRed}}}
Sleep (2)
$Index++
}While ($Index -lt $ShareArray.length)
}
Function Exists-Drive {
param($driveletter)
(New-Object System.IO.DriveInfo($driveletter)).DriveType -ne 'NoRootDirectory'
}
Function LoadApps { #--[ Array consists of Process Name, File Path, Arguements, Title ]--
$AppArray = @()
$AppArray += , @("firefox","C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe","https://www.google.com","FireFox")
#--[ Add more app entries here... ]--
#--[ Cloud Storage Provider Subsection ]--
if (!$CloudStor ){$Notify.ShowBalloonTip(2500,$ScriptName,"Cloud Providers Bypassed...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "Cloud Providers Bypassed..." -ForegroundColor Magenta;}}
else
{
$AppArray += , @("googledrivesync","C:\\Program Files (x86)\\Google\\Drive\\googledrivesync.exe","/autostart","GoogleDrive")
#--[ Add more cloud entries here... ]--
}
$AppArray += , @("taskmgr","C:\\Windows\\System32\\taskmgr.exe"," ","Task Manager")
#--[ Add more app entries here... ]--
$Index = 0
Do {
$AppProcess = $AppArray[$Index][0]
$AppExe = $AppArray[$Index][1]
$AppArgs = $AppArray[$Index][2]
$AppName = $AppArray[$Index][3]
If((get-process -Name $AppProcess -ea SilentlyContinue) -eq $Null){start-process -FilePath $AppExe -ArgumentList $AppArgs ;$Notify.ShowBalloonTip(2500,$ScriptName,"$AppName is loading...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "Loading" $AppName "..." -ForegroundColor DarkGreen}}else{$Notify.ShowBalloonTip(2500,$ScriptName,"$AppName is already running...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "$AppName Already Running..." -ForegroundColor DarkRed } }
Sleep (2)
$Index++
}
While ($Index -lt $AppArray.length)
}
<#
function SendMail {
#param($strTo, $strFrom, $strSubject, $strBody, $smtpServer)
param($To, $From, $Subject, $Body, $smtpServer)
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = $From
$msg.To.Add($To)
$msg.Subject = $Subject
$msg.IsBodyHtml = 1
$msg.Body = $Body
$smtp.Send($msg)
}
#>
Function IdentifyNics {
$Domain1 = "LabDomain.com"
$Domain2 = "OfficeDomain.com"
#--[ Detect Network Adapters ]--
$Wired = get-wmiobject -class "Win32_NetworkAdapterConfiguration" | where {$_.IPAddress -like "192.168.1.*" }
#--[ Alternate detection methods]--
#$Wired = get-wmiobject -class "Win32_NetworkAdapterConfiguration" | where {$_.IPAddress -like "192.168.1.*" } | where {$_.DNSDomainSuffixSearchOrder -match $Domain2}
#$Wired = get-wmiobject -class "Win32_NetworkAdapterConfiguration" | where {$_.Description -like "Marvell Yukon 88E8056 PCI-E Gigabit Ethernet Controller" }
$WiredIP = ([string]$Wired.IPAddress).split(" ")
$WiredDesc = $Wired.Description
if ($debug){
write-host "Name: " $Wired.Description`n"DNS Domain: " $Wired.DNSDomainSuffixSearchOrder`n"IPv4: " $WiredIP[0]`n"IPv6: " $WiredIP[1]`n""
if ($WiredIP[0]){$Notify.ShowBalloonTip(2500,$ScriptName,"Detected $WiredDesc",[system.windows.forms.tooltipicon]::Info)}else{$Notify.ShowBalloonTip(2500,$ScriptName,"Hardline not detected",[system.windows.forms.tooltipicon]::Info)}
}
sleep (2)
$WiFi = get-wmiobject -class "Win32_NetworkAdapterConfiguration" | where {$_.Description -like "Intel(R) Centrino(R) Advanced-N 6250 AGN" }
$WiFiIP = ([string]$WiFi.IPAddress).split(" ")
$WiFiDesc = $WiFi.Description
write-host "Name: " $WiFi.Description`n"DNS Domain: " $WiFi.DNSDomainSuffixSearchOrder`n"IPv4: " $WiFiIP[0]`n"IPv6: " $WiFiIP[1]
if ($WiFiIP[0]){$Notify.ShowBalloonTip(2500,$ScriptName,"Detected $WiFiDesc",[system.windows.forms.tooltipicon]::Info)}else{$Notify.ShowBalloonTip(2500,$ScriptName,"WiFi not detected",[system.windows.forms.tooltipicon]::Info)}
sleep (2)
#--[ Set Routes ]--
if ($WiredIP[0]) { #--[ The hardline is connected. Favor the hardline if both connected ]--
$IP = $WiredIP[0]
if ($Wired.DNSDomainSuffixSearchOrder -like $Domain1 -or $Wired.DNSDomainSuffixSearchOrder -like $Domain2) { #--[ the hardline is connected ]--
write-host ""`n"Setting routes for hardline"`n""
$Notify.ShowBalloonTip(2500,$ScriptName,"Setting routes for hardline...",[system.windows.forms.tooltipicon]::Info)
#SetRoutes $IP
}
} else {
if ($WiFiIP[0]) {
if ($WiFi.DNSDomainSuffixSearchOrder -like $Domain2) { #--[ The wifi is connected --]
$IP = $WiFiIP[0]
write-host ""`n"Setting routes for wifi"`n""
$Notify.ShowBalloonTip(2500,$ScriptName,"Setting routes for wifi...",[system.windows.forms.tooltipicon]::Info)
#SetRoutes $IP
}
}
}
}
#Write-Host $IP
#IdentifyNics
#SetMappings
#Pause-Host
LoadApps
If ($debug){write-host "Completed All Operations..." -ForegroundColor DarkCyan}
|
PowerShellCorpus/PoshCode/LibraryProperties.ps1
|
LibraryProperties.ps1
|
##############################################################################\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\nfilter Get-PropertyValue($property)\n{\n $_.$property\n}
|
PowerShellCorpus/PoshCode/Watch-Process_2.ps1
|
Watch-Process_2.ps1
|
Function Watch-Process {
<#
.DESCRIPTION
Creates an event handler for monitoring either process creation or deletion. This requires to be run as administrator.
.SYNOPSIS
Watches for process creation or deletion.
.PARAMETER computerName
Name of the remote computer. Make sure you have privileges to access remote WMI namespaces.
The default value is local computer.
.PARAMETER Name
Name of the process to monitor.
.PARAMETER Id
Processs ID of the process to monitor.
.PARAMETER Creation
Switch Parameter. Use this to start process creation monitor.
.PARAMETER Deletion
Switch Parameter. Use this to start process deletion monitor.
.PARAMETER Timeout
By default there is no timeout. The process monitor will wait forever. You can specify the maximum timeout period in seconds.
.OUTPUTS
Returns a process object in case of process creation
and returns process exit status in case of process deletion
.EXAMPLE
Watch-Process -computerName TestServer01 -Name "Notepad.exe" -Creation
Description
-----------
The above example demonstrates to how to start a process creation monitor for a remote process
.EXAMPLE
Watch-Process -computerName TestServer01 -Name "notepad.exe" -Deletion
Watch-Process -computerName TestServer01 -Id 3123 -Deletion
Description
-----------
The above creates process deletion monitor for notepad.exe on computer TestServer01 and also creates a process deletion monitor for process ID 3123 on the remote computer.
.LINK
Online version: http://www.ravichaganti.com/blog
#>
[CmdletBinding()]
param (
[Parameter(ParameterSetName="pCreation",Mandatory=$false)]
[Parameter(ParameterSetName="pDeletion",Mandatory=$false)]
[String]$computerName=".",
[Parameter(ParameterSetName="pCreation",Mandatory=$true)]
[Parameter(ParameterSetName="pDeletion",Mandatory=$false)]
[String]$name,
[Parameter(ParameterSetName="pDeletion",Mandatory=$false)]
[int]$Id,
[Parameter(ParameterSetName="pCreation",Mandatory=$false)]
[Switch]$creation,
[Parameter(ParameterSetName="pDeletion",Mandatory=$false)]
[Switch]$deletion,
[Parameter(ParameterSetName="pDeletion",Mandatory=$false)]
[Parameter(ParameterSetName="pCreation",Mandatory=$false)]
[int]$timeout=-1
)
if ($deletion) {
if (($PSBoundParameters.Keys -contains "Name") -and ($PSBoundParameters.Keys -Contains "Id")) {
Write-Error "Both Name and Id parameters are specified. Specify any of these parameters."
return
} elseif ($name) {
$query = "SELECT * FROM Win32_ProcessStopTrace WHERE ProcessName='$($name)'"
Write-Verbose $query
} elseif ($id) {
$query = "SELECT * FROM Win32_ProcessStopTrace WHERE ProcessID='$($Id)'"
Write-Verbose $query
} else {
Write-Error "Neither -Name nor -Id provided. You must provide one of these parameters."
return
}
} elseif ($creation) {
$query = "SELECT * FROM Win32_ProcessStartTrace WHERE ProcessName='$($name)'"
Write-Verbose $query
} else {
Write-Error "You must specify an event to monitor. The valid parameters are -deletion or -creation"
return
}
if ($query) {
$srcId = [guid]::NewGuid()
#Register a WMI event for process creation or deletion
Write-Verbose "Registering a WMI event"
Register-WmiEvent -ComputerName $computerName -Query $query -SourceIdentifier $srcID
#Wait for the event to trigger
Wait-Event -SourceIdentifier $srcID -Timeout $timeout
#Unregister the event. We don't need it anymore
Write-Verbose "Unregistering a WMI event"
Unregister-Event -SourceIdentifier $srcID
}
}
|
PowerShellCorpus/PoshCode/sqlps2.ps1
|
sqlps2.ps1
|
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Resources;
using System.Globalization;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Reflection;
[assembly:RunspaceConfigurationType("Community.CustomRunspaceConfiguration")]
namespace Community
{
/// <summary>
/// CustomRunspaceConfiguration implements runspace configuration for current
/// minishell.
/// </summary>
public class CustomRunspaceConfiguration : RunspaceConfiguration
{
/// <summary>
/// Constructor is made private intentionally so that each instance of
/// CustomRunspaceConfiguration will be created through Create() function
/// </summary>
private CustomRunspaceConfiguration()
{
}
/// <summary>
/// This is the static function to create an instance of this type.
/// </summary>
/// <returns>runspace configuration instance created</returns>
public new static RunspaceConfiguration Create()
{
CustomRunspaceConfiguration runspaceConfig = new CustomRunspaceConfiguration();
return runspaceConfig;
}
private const string _shellId = "Community.sqlps2";
/// <summary>
/// Shell Id
/// </summary>
/// <value>Shell Id</value>
public override string ShellId
{
get
{
return _shellId;
}
}
#region Cmdlets, Providers, Assemblies
private CmdletConfigurationEntry[] _cmdletConfigurationEntries = new CmdletConfigurationEntry[] { new CmdletConfigurationEntry("Invoke-Sqlcmd", typeof(Microsoft.SqlServer.Management.PowerShell.GetScriptCommand), "Microsoft.SqlServer.Management.PSSnapins.dll-Help.xml"),
new CmdletConfigurationEntry("Invoke-PolicyEvaluation", typeof(Microsoft.SqlServer.Management.PowerShell.InvokePolicyEvaluationCommand), "Microsoft.SqlServer.Management.PSSnapins.dll-Help.xml"),
new CmdletConfigurationEntry("Encode-SqlName", typeof(Microsoft.SqlServer.Management.PowerShell.EncodeSqlName), "Microsoft.SqlServer.Management.PSProvider.dll-Help.xml"),
new CmdletConfigurationEntry("Decode-SqlName", typeof(Microsoft.SqlServer.Management.PowerShell.DecodeSqlName), "Microsoft.SqlServer.Management.PSProvider.dll-Help.xml"),
new CmdletConfigurationEntry("Convert-UrnToPath", typeof(Microsoft.SqlServer.Management.PowerShell.ConvertUrnToPath), "Microsoft.SqlServer.Management.PSProvider.dll-Help.xml"),
new CmdletConfigurationEntry("Start-Transcript", typeof(Microsoft.PowerShell.Commands.StartTranscriptCommand), "Microsoft.PowerShell.ConsoleHost.dll-Help.xml"),
new CmdletConfigurationEntry("Stop-Transcript", typeof(Microsoft.PowerShell.Commands.StopTranscriptCommand), "Microsoft.PowerShell.ConsoleHost.dll-Help.xml"),
new CmdletConfigurationEntry("Get-Command", typeof(Microsoft.PowerShell.Commands.GetCommandCommand), "System.Management.Automation.dll-Help.xml"),
new CmdletConfigurationEntry("Get-Help", typeof(Microsoft.PowerShell.Commands.GetHelpCommand), "System.Management.Automation.dll-Help.xml"),
new CmdletConfigurationEntry("Get-History", typeof(Microsoft.PowerShell.Commands.GetHistoryCommand), "System.Management.Automation.dll-Help.xml"),
new CmdletConfigurationEntry("Invoke-History", typeof(Microsoft.PowerShell.Commands.InvokeHistoryCommand), "System.Management.Automation.dll-Help.xml"),
new CmdletConfigurationEntry("Add-History", typeof(Microsoft.PowerShell.Commands.AddHistoryCommand), "System.Management.Automation.dll-Help.xml"),
new CmdletConfigurationEntry("ForEach-Object", typeof(Microsoft.PowerShell.Commands.ForEachObjectCommand), "System.Management.Automation.dll-Help.xml"),
new CmdletConfigurationEntry("Where-Object", typeof(Microsoft.PowerShell.Commands.WhereObjectCommand), "System.Management.Automation.dll-Help.xml"),
new CmdletConfigurationEntry("Set-PSDebug", typeof(Microsoft.PowerShell.Commands.SetPSDebugCommand), "System.Management.Automation.dll-Help.xml"),
new CmdletConfigurationEntry("Add-Content", typeof(Microsoft.PowerShell.Commands.AddContentCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Clear-Content", typeof(Microsoft.PowerShell.Commands.ClearContentCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Clear-ItemProperty", typeof(Microsoft.PowerShell.Commands.ClearItemPropertyCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Join-Path", typeof(Microsoft.PowerShell.Commands.JoinPathCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Convert-Path", typeof(Microsoft.PowerShell.Commands.ConvertPathCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Copy-ItemProperty", typeof(Microsoft.PowerShell.Commands.CopyItemPropertyCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Get-EventLog", typeof(Microsoft.PowerShell.Commands.GetEventLogCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Get-ChildItem", typeof(Microsoft.PowerShell.Commands.GetChildItemCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Get-Content", typeof(Microsoft.PowerShell.Commands.GetContentCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Get-ItemProperty", typeof(Microsoft.PowerShell.Commands.GetItemPropertyCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Get-WmiObject", typeof(Microsoft.PowerShell.Commands.GetWmiObjectCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Move-ItemProperty", typeof(Microsoft.PowerShell.Commands.MoveItemPropertyCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Get-Location", typeof(Microsoft.PowerShell.Commands.GetLocationCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Set-Location", typeof(Microsoft.PowerShell.Commands.SetLocationCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Push-Location", typeof(Microsoft.PowerShell.Commands.PushLocationCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Pop-Location", typeof(Microsoft.PowerShell.Commands.PopLocationCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("New-PSDrive", typeof(Microsoft.PowerShell.Commands.NewPSDriveCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Remove-PSDrive", typeof(Microsoft.PowerShell.Commands.RemovePSDriveCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Get-PSDrive", typeof(Microsoft.PowerShell.Commands.GetPSDriveCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Get-Item", typeof(Microsoft.PowerShell.Commands.GetItemCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("New-Item", typeof(Microsoft.PowerShell.Commands.NewItemCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Set-Item", typeof(Microsoft.PowerShell.Commands.SetItemCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Remove-Item", typeof(Microsoft.PowerShell.Commands.RemoveItemCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Move-Item", typeof(Microsoft.PowerShell.Commands.MoveItemCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Rename-Item", typeof(Microsoft.PowerShell.Commands.RenameItemCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Copy-Item", typeof(Microsoft.PowerShell.Commands.CopyItemCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Clear-Item", typeof(Microsoft.PowerShell.Commands.ClearItemCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Invoke-Item", typeof(Microsoft.PowerShell.Commands.InvokeItemCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Get-PSProvider", typeof(Microsoft.PowerShell.Commands.GetPSProviderCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("New-ItemProperty", typeof(Microsoft.PowerShell.Commands.NewItemPropertyCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Split-Path", typeof(Microsoft.PowerShell.Commands.SplitPathCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Test-Path", typeof(Microsoft.PowerShell.Commands.TestPathCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Get-Process", typeof(Microsoft.PowerShell.Commands.GetProcessCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Stop-Process", typeof(Microsoft.PowerShell.Commands.StopProcessCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Remove-ItemProperty", typeof(Microsoft.PowerShell.Commands.RemoveItemPropertyCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Rename-ItemProperty", typeof(Microsoft.PowerShell.Commands.RenameItemPropertyCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Resolve-Path", typeof(Microsoft.PowerShell.Commands.ResolvePathCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Get-Service", typeof(Microsoft.PowerShell.Commands.GetServiceCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Stop-Service", typeof(Microsoft.PowerShell.Commands.StopServiceCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Start-Service", typeof(Microsoft.PowerShell.Commands.StartServiceCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Suspend-Service", typeof(Microsoft.PowerShell.Commands.SuspendServiceCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Resume-Service", typeof(Microsoft.PowerShell.Commands.ResumeServiceCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Restart-Service", typeof(Microsoft.PowerShell.Commands.RestartServiceCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Set-Service", typeof(Microsoft.PowerShell.Commands.SetServiceCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("New-Service", typeof(Microsoft.PowerShell.Commands.NewServiceCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Set-Content", typeof(Microsoft.PowerShell.Commands.SetContentCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Set-ItemProperty", typeof(Microsoft.PowerShell.Commands.SetItemPropertyCommand), "Microsoft.PowerShell.Commands.Management.dll-Help.xml"),
new CmdletConfigurationEntry("Format-Default", typeof(Microsoft.PowerShell.Commands.FormatDefaultCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Format-List", typeof(Microsoft.PowerShell.Commands.FormatListCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Format-Custom", typeof(Microsoft.PowerShell.Commands.FormatCustomCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Format-Table", typeof(Microsoft.PowerShell.Commands.FormatTableCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Format-Wide", typeof(Microsoft.PowerShell.Commands.FormatWideCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Out-Null", typeof(Microsoft.PowerShell.Commands.OutNullCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Out-Default", typeof(Microsoft.PowerShell.Commands.OutDefaultCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Out-Host", typeof(Microsoft.PowerShell.Commands.OutHostCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Out-File", typeof(Microsoft.PowerShell.Commands.OutFileCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Out-Printer", typeof(Microsoft.PowerShell.Commands.OutPrinterCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Out-String", typeof(Microsoft.PowerShell.Commands.OutStringCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Out-LineOutput", typeof(Microsoft.PowerShell.Commands.OutLineOutputCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Add-Member", typeof(Microsoft.PowerShell.Commands.AddMemberCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Compare-Object", typeof(Microsoft.PowerShell.Commands.CompareObjectCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("ConvertTo-Html", typeof(Microsoft.PowerShell.Commands.ConvertToHtmlCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Export-Csv", typeof(Microsoft.PowerShell.Commands.ExportCsvCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Import-Csv", typeof(Microsoft.PowerShell.Commands.ImportCsvCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Export-Alias", typeof(Microsoft.PowerShell.Commands.ExportAliasCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Invoke-Expression", typeof(Microsoft.PowerShell.Commands.InvokeExpressionCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Get-Alias", typeof(Microsoft.PowerShell.Commands.GetAliasCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Get-Culture", typeof(Microsoft.PowerShell.Commands.GetCultureCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Get-Date", typeof(Microsoft.PowerShell.Commands.GetDateCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Get-Host", typeof(Microsoft.PowerShell.Commands.GetHostCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Get-Member", typeof(Microsoft.PowerShell.Commands.GetMemberCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Get-UICulture", typeof(Microsoft.PowerShell.Commands.GetUICultureCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Get-Unique", typeof(Microsoft.PowerShell.Commands.GetUniqueCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Import-Alias", typeof(Microsoft.PowerShell.Commands.ImportAliasCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Select-String", typeof(Microsoft.PowerShell.Commands.SelectStringCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Measure-Object", typeof(Microsoft.PowerShell.Commands.MeasureObjectCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("New-Alias", typeof(Microsoft.PowerShell.Commands.NewAliasCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("New-TimeSpan", typeof(Microsoft.PowerShell.Commands.NewTimeSpanCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Read-Host", typeof(Microsoft.PowerShell.Commands.ReadHostCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Set-Alias", typeof(Microsoft.PowerShell.Commands.SetAliasCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Set-Date", typeof(Microsoft.PowerShell.Commands.SetDateCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Start-Sleep", typeof(Microsoft.PowerShell.Commands.StartSleepCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Tee-Object", typeof(Microsoft.PowerShell.Commands.TeeObjectCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Measure-Command", typeof(Microsoft.PowerShell.Commands.MeasureCommandCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Update-TypeData", typeof(Microsoft.PowerShell.Commands.UpdateTypeDataCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Update-FormatData", typeof(Microsoft.PowerShell.Commands.UpdateFormatDataCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Write-Host", typeof(Microsoft.PowerShell.Commands.WriteHostCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Write-Progress", typeof(Microsoft.PowerShell.Commands.WriteProgressCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("New-Object", typeof(Microsoft.PowerShell.Commands.NewObjectCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Select-Object", typeof(Microsoft.PowerShell.Commands.SelectObjectCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Group-Object", typeof(Microsoft.PowerShell.Commands.GroupObjectCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Sort-Object", typeof(Microsoft.PowerShell.Commands.SortObjectCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Get-Variable", typeof(Microsoft.PowerShell.Commands.GetVariableCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("New-Variable", typeof(Microsoft.PowerShell.Commands.NewVariableCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Set-Variable", typeof(Microsoft.PowerShell.Commands.SetVariableCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Remove-Variable", typeof(Microsoft.PowerShell.Commands.RemoveVariableCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Clear-Variable", typeof(Microsoft.PowerShell.Commands.ClearVariableCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Export-Clixml", typeof(Microsoft.PowerShell.Commands.ExportClixmlCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Import-Clixml", typeof(Microsoft.PowerShell.Commands.ImportClixmlCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Write-Debug", typeof(Microsoft.PowerShell.Commands.WriteDebugCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Write-Verbose", typeof(Microsoft.PowerShell.Commands.WriteVerboseCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Write-Warning", typeof(Microsoft.PowerShell.Commands.WriteWarningCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Write-Error", typeof(Microsoft.PowerShell.Commands.WriteErrorCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Write-Output", typeof(Microsoft.PowerShell.Commands.WriteOutputCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Get-TraceSource", typeof(Microsoft.PowerShell.Commands.GetTraceSourceCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Set-TraceSource", typeof(Microsoft.PowerShell.Commands.SetTraceSourceCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Trace-Command", typeof(Microsoft.PowerShell.Commands.TraceCommandCommand), "Microsoft.PowerShell.Commands.Utility.dll-Help.xml"),
new CmdletConfigurationEntry("Get-Acl", typeof(Microsoft.PowerShell.Commands.GetAclCommand), "Microsoft.PowerShell.Security.dll-Help.xml"),
new CmdletConfigurationEntry("Set-Acl", typeof(Microsoft.PowerShell.Commands.SetAclCommand), "Microsoft.PowerShell.Security.dll-Help.xml"),
new CmdletConfigurationEntry("Get-PfxCertificate", typeof(Microsoft.PowerShell.Commands.GetPfxCertificateCommand), "Microsoft.PowerShell.Security.dll-Help.xml"),
new CmdletConfigurationEntry("Get-Credential", typeof(Microsoft.PowerShell.Commands.GetCredentialCommand), "Microsoft.PowerShell.Security.dll-Help.xml"),
new CmdletConfigurationEntry("Get-ExecutionPolicy", typeof(Microsoft.PowerShell.Commands.GetExecutionPolicyCommand), "Microsoft.PowerShell.Security.dll-Help.xml"),
new CmdletConfigurationEntry("Set-ExecutionPolicy", typeof(Microsoft.PowerShell.Commands.SetExecutionPolicyCommand), "Microsoft.PowerShell.Security.dll-Help.xml"),
new CmdletConfigurationEntry("Get-AuthenticodeSignature", typeof(Microsoft.PowerShell.Commands.GetAuthenticodeSignatureCommand), "Microsoft.PowerShell.Security.dll-Help.xml"),
new CmdletConfigurationEntry("Set-AuthenticodeSignature", typeof(Microsoft.PowerShell.Commands.SetAuthenticodeSignatureCommand), "Microsoft.PowerShell.Security.dll-Help.xml"),
new CmdletConfigurationEntry("ConvertFrom-SecureString", typeof(Microsoft.PowerShell.Commands.ConvertFromSecureStringCommand), "Microsoft.PowerShell.Security.dll-Help.xml"),
new CmdletConfigurationEntry("ConvertTo-SecureString", typeof(Microsoft.PowerShell.Commands.ConvertToSecureStringCommand), "Microsoft.PowerShell.Security.dll-Help.xml") };
private RunspaceConfigurationEntryCollection<CmdletConfigurationEntry> _cmdlets;
/// <summary>
/// Cmdlets for this minishell
/// </summary>
/// <value>a collection of cmdlet configuration entries</value>
public override RunspaceConfigurationEntryCollection<CmdletConfigurationEntry> Cmdlets
{
get
{
if (_cmdlets == null)
{
_cmdlets = new RunspaceConfigurationEntryCollection<CmdletConfigurationEntry>(_cmdletConfigurationEntries);
}
return _cmdlets;
}
}
private ProviderConfigurationEntry[] _providerConfigurationEntries = new ProviderConfigurationEntry[] { new ProviderConfigurationEntry("SqlServer", typeof(Microsoft.SqlServer.Management.PowerShell.SqlServerProvider), "Microsoft.SqlServer.Management.PSProvider.dll-Help.xml"),
new ProviderConfigurationEntry("Alias", typeof(Microsoft.PowerShell.Commands.AliasProvider), "System.Management.Automation.dll-Help.xml"),
new ProviderConfigurationEntry("Environment", typeof(Microsoft.PowerShell.Commands.EnvironmentProvider), "System.Management.Automation.dll-Help.xml"),
new ProviderConfigurationEntry("FileSystem", typeof(Microsoft.PowerShell.Commands.FileSystemProvider), "System.Management.Automation.dll-Help.xml"),
new ProviderConfigurationEntry("Function", typeof(Microsoft.PowerShell.Commands.FunctionProvider), "System.Management.Automation.dll-Help.xml"),
new ProviderConfigurationEntry("Registry", typeof(Microsoft.PowerShell.Commands.RegistryProvider), "System.Management.Automation.dll-Help.xml"),
new ProviderConfigurationEntry("Variable", typeof(Microsoft.PowerShell.Commands.VariableProvider), "System.Management.Automation.dll-Help.xml"),
new ProviderConfigurationEntry("Certificate", typeof(Microsoft.PowerShell.Commands.CertificateProvider), "Microsoft.PowerShell.Security.dll-Help.xml") };
private RunspaceConfigurationEntryCollection<ProviderConfigurationEntry> _providers;
/// <summary>
/// Providers for this minishell
/// </summary>
/// <value>a collection of provider configuration entries</value>
public override RunspaceConfigurationEntryCollection<ProviderConfigurationEntry> Providers
{
get
{
if (_providers == null)
{
_providers = new RunspaceConfigurationEntryCollection<ProviderConfigurationEntry>(_providerConfigurationEntries);
}
return _providers;
}
}
private AssemblyConfigurationEntry[] _assemblyConfigurationEntries = new AssemblyConfigurationEntry[] { new AssemblyConfigurationEntry("Microsoft.SqlServer.Management.PSSnapins, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91", "Microsoft.SqlServer.Management.PSSnapins.dll"),
new AssemblyConfigurationEntry("Microsoft.SqlServer.Management.PSProvider, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91", "Microsoft.SqlServer.Management.PSProvider.dll"),
new AssemblyConfigurationEntry("Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91", "Microsoft.SqlServer.Smo.dll"),
new AssemblyConfigurationEntry("Microsoft.SqlServer.Dmf, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91", "Microsoft.SqlServer.Dmf.dll"),
new AssemblyConfigurationEntry("Microsoft.SqlServer.SqlWmiManagement, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91", "Microsoft.SqlServer.SqlWmiManagement.dll"),
new AssemblyConfigurationEntry("Microsoft.SqlServer.ConnectionInfo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91", "Microsoft.SqlServer.ConnectionInfo.dll"),
new AssemblyConfigurationEntry("Microsoft.SqlServer.SmoExtended, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91", "Microsoft.SqlServer.SmoExtended.dll"),
new AssemblyConfigurationEntry("Microsoft.SqlServer.Management.Sdk.Sfc, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91", "Microsoft.SqlServer.Management.Sdk.Sfc.dll"),
new AssemblyConfigurationEntry("Microsoft.SqlServer.SqlEnum, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91", "Microsoft.SqlServer.SqlEnum.dll"),
new AssemblyConfigurationEntry("Microsoft.SqlServer.RegSvrEnum, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91", "Microsoft.SqlServer.RegSvrEnum.dll"),
new AssemblyConfigurationEntry("Microsoft.SqlServer.WmiEnum, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91", "Microsoft.SqlServer.WmiEnum.dll"),
new AssemblyConfigurationEntry("Microsoft.SqlServer.ServiceBrokerEnum, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91", "Microsoft.SqlServer.ServiceBrokerEnum.dll"),
new AssemblyConfigurationEntry("Microsoft.SqlServer.ConnectionInfoExtended, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91", "Microsoft.SqlServer.ConnectionInfoExtended.dll"),
new AssemblyConfigurationEntry("Microsoft.SqlServer.Management.Collector, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91", "Microsoft.SqlServer.Management.Collector.dll"),
new AssemblyConfigurationEntry("Microsoft.SqlServer.Management.CollectorEnum, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91", "Microsoft.SqlServer.Management.CollectorEnum.dll"),
new AssemblyConfigurationEntry("Microsoft.PowerShell.ConsoleHost, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", "Microsoft.PowerShell.ConsoleHost.dll"),
new AssemblyConfigurationEntry("System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", "System.Management.Automation.dll"),
new AssemblyConfigurationEntry("Microsoft.PowerShell.Commands.Management, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", "Microsoft.PowerShell.Commands.Management.dll"),
new AssemblyConfigurationEntry("Microsoft.PowerShell.Commands.Utility, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", "Microsoft.PowerShell.Commands.Utility.dll"),
new AssemblyConfigurationEntry("Microsoft.PowerShell.Security, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", "Microsoft.PowerShell.Security.dll") };
private RunspaceConfigurationEntryCollection<AssemblyConfigurationEntry> _assemblies;
/// <summary>
/// Type resolution assemblies for this minishell
/// </summary>
/// <value>a collection of assembly configuration entries</value>
public override RunspaceConfigurationEntryCollection<AssemblyConfigurationEntry> Assemblies
{
get
{
if (_assemblies == null)
{
_assemblies = new RunspaceConfigurationEntryCollection<AssemblyConfigurationEntry>(_assemblyConfigurationEntries);
}
return _assemblies;
}
}
#endregion
#region Types and Formats
private TypeConfigurationEntry[] _typeConfigurationEntries = new TypeConfigurationEntry[] { new TypeConfigurationEntry(@"SQLProvider.Types.ps1xml"), new TypeConfigurationEntry(@"types.ps1xml") };
private RunspaceConfigurationEntryCollection<TypeConfigurationEntry> _types;
/// <summary>
/// Types for this minishell
/// </summary>
/// <value>a collection of type configuration entries</value>
public override RunspaceConfigurationEntryCollection<TypeConfigurationEntry> Types
{
get
{
if (_types == null)
{
_types = new RunspaceConfigurationEntryCollection<TypeConfigurationEntry>(_typeConfigurationEntries);
}
return _types;
}
}
private FormatConfigurationEntry[] _formatConfigurationEntries = new FormatConfigurationEntry[] { new FormatConfigurationEntry(@"SQLProvider.Format.ps1xml"), new FormatConfigurationEntry(@"DotNetTypes.format.ps1xml"), new FormatConfigurationEntry(@"PowerShellCore.format.ps1xml"), new FormatConfigurationEntry(@"PowerShellTrace.format.ps1xml"), new FormatConfigurationEntry(@"FileSystem.format.ps1xml"), new FormatConfigurationEntry(@"Registry.format.ps1xml"), new FormatConfigurationEntry(@"Certificate.format.ps1xml"), new FormatConfigurationEntry(@"Help.format.ps1xml") };
private RunspaceConfigurationEntryCollection<FormatConfigurationEntry> _formats;
/// <summary>
/// Formats for this minishell
/// </summary>
/// <value>a collection of format configuration entries</value>
public override RunspaceConfigurationEntryCollection<FormatConfigurationEntry> Formats
{
get
{
if (_formats == null)
{
_formats = new RunspaceConfigurationEntryCollection<FormatConfigurationEntry>(_formatConfigurationEntries);
}
return _formats;
}
}
#endregion
#region scripts and initscript
private RunspaceConfigurationEntryCollection<ScriptConfigurationEntry> _scripts;
/// <summary>
/// Pre-defined scripts for this minishell
/// </summary>
/// <value>a collection of script configuration entries</value>
public override RunspaceConfigurationEntryCollection<ScriptConfigurationEntry> Scripts
{
get
{
if (_scripts == null)
{
_scripts = new RunspaceConfigurationEntryCollection<ScriptConfigurationEntry>();
string[] scriptNames = null;
string[] scripts = null;
GetResources(ScriptResourceName, ref scriptNames, ref scripts);
if (scripts != null)
{
for (int i = 0; i < scripts.Length; i++)
{
ScriptConfigurationEntry data = new ScriptConfigurationEntry(scriptNames[i], scripts[i]);
_scripts.Append(data);
}
}
}
return _scripts;
}
}
private RunspaceConfigurationEntryCollection<ScriptConfigurationEntry> _initializationScripts;
/// <summary>
/// Initialization scripts to be run at minishell start up.
/// </summary>
/// <value>a collection of initialization scripts</value>
public override RunspaceConfigurationEntryCollection<ScriptConfigurationEntry> InitializationScripts
{
get
{
if (_initializationScripts == null)
{
_initializationScripts = new RunspaceConfigurationEntryCollection<ScriptConfigurationEntry>();
Dictionary<string, object> profile = GetResources(ProfileResourceName, CultureInfo.InvariantCulture);
if (profile == null)
return null;
if (profile != null && profile.ContainsKey(ProfileResourceName))
{
_initializationScripts.Append(new ScriptConfigurationEntry(ProfileResourceName, (string)profile[ProfileResourceName]));
}
}
return _initializationScripts;
}
}
#endregion
#region Minishell Help
static private string _shellHelp = null;
static private string ShellHelp
{
get
{
if(_shellHelp == null)
LoadHelpResource();
return _shellHelp;
}
}
static private string _shellBanner = null;
static private string ShellBanner
{
get
{
if(_shellBanner == null)
LoadHelpResource();
return _shellBanner;
}
}
static private void LoadHelpResource()
{
Dictionary<string,object> helpResources = GetResources(HelpResourceName, CultureInfo.CurrentUICulture);
if(helpResources != null)
{
if(helpResources.ContainsKey(ShellHelpResourceKey))
{
_shellHelp = (string) helpResources[ShellHelpResourceKey];
}
if(helpResources.ContainsKey(ShellBannerResourceKey))
{
_shellBanner = (string) helpResources[ShellBannerResourceKey];
}
}
return;
}
#endregion
#region Resource Loading
private const string ScriptResourceName = "script";
private const string ProfileResourceName = "initialization";
private const string HelpResourceName = "help";
private const string ShellHelpResourceKey = "ShellHelp";
private const string ShellBannerResourceKey = "ShellBanner";
private const string ResourceListKey = "__resourceList__";
/// <summary>
/// Return all resources in ordered name/value pairs. Order of resources are
/// defined in resourceListKey. This will look for resources for invariant
/// culture.
/// </summary>
private static void GetResources(string resourceType, ref string[] names, ref string[] values)
{
names = null;
values = null;
Dictionary<string, object> resources = GetResources(resourceType, CultureInfo.InvariantCulture);
if(resources == null)
return;
if(!resources.ContainsKey(ResourceListKey))
{
return;
}
names = (string[])resources[ResourceListKey];
if(names == null || names.Length == 0)
return;
values = new string[names.Length];
for (int i = 0; i < names.Length; i++)
{
values[i] = (string)resources[names[i]];
}
return;
}
/// <summary>
/// Return all resources in defined in current assembly in the format of a string/object dictionary.
/// </summary>
private static Dictionary<string, object> GetResources(string resourceType, CultureInfo culture)
{
ResourceManager resMgr = new ResourceManager(resourceType, Assembly.GetExecutingAssembly());
if (resMgr == null)
return null;
ResourceSet resSet = null;
try
{
resSet = resMgr.GetResourceSet(culture, true, true);
}
catch (MissingManifestResourceException)
{
return null;
}
if (resSet == null)
return null;
Dictionary<string, object> result = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
IDictionaryEnumerator id = resSet.GetEnumerator();
while (id.MoveNext())
{
result[(string)id.Key] = id.Value;
}
return result;
}
#endregion
/// <summary>
/// This is the main function for minishell. It will start msh console shell with
/// a runspace configuration instance for current minishell.
/// </summary>
/// <param name="args">args to main</param>
/// <returns>minishell execution status</returns>
[LoaderOptimization(LoaderOptimization.MultiDomain)]
public static int Main(string[] args)
{
RunspaceConfiguration configuration = Create();
return Microsoft.PowerShell.ConsoleShell.Start(configuration, ShellBanner, ShellHelp, args);
}
}
}
|
PowerShellCorpus/PoshCode/Copy-Function.ps1
|
Copy-Function.ps1
|
#Requires -Version 2.0
<#
.Synopsis
Copy a function from the current session to another session
.Description
Copies a function deffinition from the current session into any other session
.Parameter Session
The session(s) you want to define the function in
.Parameter Name
The Name of the function to copy
.Parameter Definition
The optional definition of the function. This is used to allow copying via the pipeline.
.Parameter Force
Overwrite existing functions in the session.
.Parameter Passthru
Output the FunctionInfo from the session
.Example
Copy-Function -Session $Session1 -Name Prompt -Force
Copies the prompt function from the current session into the specified session, overwriting the existing prompt function.
.Example
Get-Command -Type Function | Copy-Function $Session1
Copies all of the functions from the current session into the new session.
.Notes
#>
function Copy-Function {
[CmdletBinding(SupportsShouldProcess=$true)]
Param(
[Parameter(Mandatory=$true, Position=0)]
[System.Management.Automation.Runspaces.PSSession[]]
$Session,
[Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true,Position=1)]
[String]
$name,
[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$false)]
[String]
$Definition,
[Switch]
$Force,
[Switch]
$Passthru
)
Process {
if( $PSCmdlet.ShouldProcess("Copied function $Name to sessions: $(($Session|select -expand Name) -join ', ')","Copy function `"$Name`"?","Copying functions to sessions: $(($Session|select -expand Name) -join ', ')") ) {
if(!$Definition){ $Definition = (gcm -type function $name).Definition }
If(!$Passthru) {
Invoke-Command {
Param($name, $value, $force)
$null = new-item function:"$name" -value $value -force:$force
} -Session $Session -ArgumentList $Name,$Definition,$Force
} else {
Invoke-Command {
Param($name, $value, $force)
new-item function:"$name" -value $value -force:$force
} -Session $Session -ArgumentList $Name,$Definition,$Force
}
}
}
}
|
PowerShellCorpus/PoshCode/Add -__ Get-Help -Full_1.ps1
|
Add -__ Get-Help -Full_1.ps1
|
$executionContext.SessionState.InvokeCommand.PostCommandLookupAction = {
param($CommandName, $CommandLookupEventArgs)
# Only for interactive commands (and that doesn't include "prompt")
# I should exclude out-default so we don't handle it on every pipeline, but ...
if($CommandLookupEventArgs.CommandOrigin -eq "Runspace" -and $CommandName -ne "prompt" ) {
## Create a new script block that checks for the "-??" argument
## And if -?? exists, calls Get-Help -Full instead
## Otherwise calls the expected command
$CommandLookupEventArgs.CommandScriptBlock = {
if($Args.Length -eq 1 -and $Args[0] -eq "-??") {
Get-Help $CommandName -Full
} else {
& $CommandName @args
}
## Wrap it in a closure because we need $CommandName
}.GetNewClosure()
}
}
$executionContext.SessionState.InvokeCommand.PreCommandLookupAction = {
param($CommandName, $CommandLookupEventArgs)
if($CommandName.StartsWith("?")) {
$RealCommandName = $CommandName.TrimStart("?")
$CommandLookupEventArgs.CommandScriptBlock = {
Get-Help $RealCommandName -Full
## Wrap it in a closure because we need $CommandName
}.GetNewClosure()
}
}
|
PowerShellCorpus/PoshCode/.displayName to .cn.ps1
|
.displayName to .cn.ps1
|
Function ConvertUser
{
Process
{
ForEach($User In $_)
{
$strFilter = “(&(objectCategory=user)(displayName=$User))”
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = “Subtree”
$colUsers = $objSearcher.FindOne()
ForEach($objUser in $colUsers)
{
$objUser.properties.cn
}
}
}
}
Get-Content “C:\\Scripts\\Users.txt” | ConvertUser | Out-File “C:\\Scripts\\ConvertedUsers.txt”
|
PowerShellCorpus/PoshCode/Get Twitter RSS Feed_2.ps1
|
Get Twitter RSS Feed_2.ps1
|
param ([String] $ScreenName)
$client = New-Object System.Net.WebClient
$idUrl = "https://api.twitter.com/1/users/show.json?screen_name=$ScreenName"
$data = $client.DownloadString($idUrl)
$start = 0
$findStr = '"id":'
do {
$start = $data.IndexOf($findStr, $start + 1)
if ($start -gt 0) {
$start += $findStr.Length
$end = $data.IndexOf(',', $start)
$userId = $data.SubString($start, $end-$start)
}
} while ($start -le $data.Length -and $start -gt 0)
$feed = "http://twitter.com/statuses/user_timeline/$userId.rss"
$feed
|
PowerShellCorpus/PoshCode/Change Server 2012 type.ps1
|
Change Server 2012 type.ps1
|
<#
.SYNOPSIS
Use this script to change Windows Server 2012 to 1 of 4 types. The script installs or uninstalls
windows features to get to the desired type. The 4 types are:
Core - just a commandline
Minimal - commandline with added binaries to run some MMCs and Server Manager
Full GUI - standard desktop look with all GUI tools
RemoteDesktop - Add the desktop experience pack to be used in a Remote Desktop farm setting.
.DESCRIPTION
Convert-Win2012ServerType -Type (Core, Min, Gui, RemoteDesktop)
.PARAMETER Type
Choose one of the following - Core, Min, Gui, RemoteDesktop
.Notes
* Author - Nate Pope
* Date - 11/28/2012
* Version - .3
.EXAMPLE
To convert to a core install:
Convert-Win2012ServerType -Type Core
Convert to a GUI install:
Convert-Win2012ServerType -Type GUI
#>
param(
[Parameter(Mandatory=$true)]
[String[]]$Type
)
Function InstallMask {
$InstallMask = 0
if ((get-windowsfeature server-gui-mgmt-infra).installed) {
$InstallMask += 1
}
if ((get-windowsfeature server-gui-Shell).installed) {
$InstallMask += 2
}
if ((get-windowsfeature Desktop-Experience).installed) {
$InstallMask += 4
}
return $InstallMask
}
Function Covert2Core($mask) {
if ($mask -eq 0){
Write-Verbose "Already Core"
return
}
$inst = uninstall-windowsFeature -Name Desktop-Experience, server-gui-Shell, server-gui-mgmt-infra
return $inst.RestartNeeded
}
Function Covert2Min($mask) {
if ($mask -eq 1){
Write-Verbose "Already Min"
return
}else {
uninstall-windowsFeature -name server-gui-shell, desktop-Experience
}
$inst = install-windowsFeature server-gui-mgmt-infra
return $inst.RestartNeeded
}
Function Covert2Gui($mask) {
if ($mask -eq 3){
Write-Verbose "Already Full Gui"
return
}elseif ($mask -gt 4 ) {
uninstall-windowsFeature -name Desktop-Experience
}
$inst = install-windowsFeature -Name server-gui-Shell, server-gui-mgmt-infra
return $inst.RestartNeeded
}
Function Covert2RD($mask) {
if ($mask -eq 7){
Write-Verbose "Already Remote Desktop "
return
}
$inst = install-windowsFeature -Name Desktop-Experience, server-gui-Shell, server-gui-mgmt-infra
return $inst.RestartNeeded
}
###########################################################################################################
$mask = InstallMask
switch ($Type) {
Core {
$reboot = Covert2Core($mask)
break
}
Min {
$reboot = Covert2Min($mask)
break
}
Gui {
$reboot = Covert2Gui($mask)
break
}
RemoteDesktop {
$reboot = Covert2RD($mask)
break
}
default {
Write-Warning "The TYPE parameter must be specified (Core, Min, Gui, or RemoteDesktop)"
break
}
}
if ($reboot) { Restart-Computer }
|
PowerShellCorpus/PoshCode/after.ps1
|
after.ps1
|
Get-WmiObject -Class Win32_MountPoint |
where {$_.Directory -like ‘Win32_Directory.Name="D:\\\\MDBDATA*"’} |
foreach {
$vol = $_.Volume
Get-WmiObject -Class Win32_Volume | where {$_.__RELPATH -eq $vol} |
Select @{Name="Folder"; Expression={$_.Caption}},
@{Name="Server"; Expression={$_.SystemName}},
@{Name="Size (GB)"; Expression={"{0:F3}" -f $($_.Capacity / 1GB)}},
@{Name="Free (GB)"; Expression={"{0:F3}" -f $($_.FreeSpace / 1GB)}},
@{Name="%Free"; Expression={"{0:F2}" -f $(($_.FreeSpace/$_.Capacity)*100)}}
}
|
PowerShellCorpus/PoshCode/Import-CmdEnvironment_2.ps1
|
Import-CmdEnvironment_2.ps1
|
# .SYNOPSIS
# Import environment variables from cmd to PowerShell
# .DESCRIPTION
# Invoke the specified command (with parameters) in cmd.exe, and import any environment variable changes back to PowerShell
# .EXAMPLE
# Import-CmdEnvironment ${Env:VS90COMNTOOLS}\\vsvars32.bat x86
#
# Imports the x86 Visual Studio 2008 Command Tools environment
# .EXAMPLE
# Import-CmdEnvironment ${Env:VS100COMNTOOLS}\\vsvars32.bat x86_amd64
#
# Imports the x64 Cross Tools Visual Studio 2010 Command environment
# .EXAMPLE
# Import-CmdEnvironment ${Env:VS110COMNTOOLS}\\vsvars32.bat x86, x86_amd64
#
# Imports the x64 Cross Tools Visual Studio 2012 Command environment
#function Import-CmdEnvironment {
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$False,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[Alias("PSPath")]
[string]$Command = "echo"
,
[Parameter(Position=0,Mandatory=$False,ValueFromRemainingArguments=$true,ValueFromPipelineByPropertyName=$true)]
[string[]]$Parameters
)
## If it's an actual file, then we should quote it:
if(Test-Path $Command) { $Command = "`"$(Resolve-Path $Command)`"" }
$setRE = new-Object System.Text.RegularExpressions.Regex '^(?<var>.*?)=(?<val>.*)$', "Compiled,ExplicitCapture,MultiLine"
$OFS = " "
[string]$Parameters = $Parameters
$OFS = "`n"
## Execute the command, with parameters.
Write-Verbose "EXECUTING: cmd.exe /c `"$Command $Parameters > nul && set`""
## For each line of output that matches, set the local environment variable
foreach($match in $setRE.Matches((cmd.exe /c "$Command $Parameters > nul && set")) | Select Groups) {
Set-Content Env:\\$($match.Groups["var"]) $match.Groups["val"] -Verbose
}
#}
|
PowerShellCorpus/PoshCode/ConvertTo-PseudoType.ps1
|
ConvertTo-PseudoType.ps1
|
function ConvertTo-PseudoType {
<#
.Synopsis
Converts objects to custom PSObjects with robust type support
.Parameter TypeName
The name(s) of the PseudoType(s) to be inserted into the objects for the sake of formatting
.Parameter Mapping
A Hashtable of property names to types (or conversion scripts)
.Parameter InputObject
An object to convert.
.Example
Get-ChildItem | Where { !$_.PsIsContainer } | Export-CSV files.csv
## Given that a CSV file of file information exists,
## And we want to rehydrate it and be able to compare things...
## We need to create a mapping of properties to types
## Optionally, we can provide scriptblocks to convert instances
$Mapping = @{
Attributes = [System.IO.FileAttributes]
CreationTime = [System.DateTime]
CreationTimeUtc = [System.DateTime]
Directory = [System.IO.DirectoryInfo]
DirectoryName = [System.String]
Exists = [System.Boolean]
Extension = [System.String]
FullName = [System.String]
IsReadOnly = [System.Boolean]
LastAccessTime = [System.DateTime]
LastAccessTimeUtc = [System.DateTime]
LastWriteTime = [System.DateTime]
LastWriteTimeUtc = [System.DateTime]
Length = [System.Int64]
Name = [System.String]
PSChildName = [System.String]
PSDrive = [System.Management.Automation.PSDriveInfo]
PSIsContainer = [System.Boolean]
PSParentPath = [System.String]
PSPath = [System.String]
PSProvider = { Get-PSProvider $_ }
ReparsePoint = [System.Management.Automation.PSCustomObject]
VersionInfo = [System.Diagnostics.FileVersionInfo]
}
## When we import, we the Selected.System.IO.FileInfo, which is what you'd get from | Select *
Import-CSV | ConvertTo-PseudoType Selected.System.IO.FileInfo $Mapping
## That way, the output will look as though you had run:
Get-ChildItem | Where { !$_.PsIsContainer } | Select *
NOTE: Not all types are rehydrateable from CSV output -- the "VersionInfo" will be hydrated as a string...
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0)]
[Alias("Name","Tn")]
[String]$TypeName
,
[Parameter(Mandatory=$true, Position=1)]
[Hashtable]$Mapping
,
[Parameter(Mandatory=$true, Position=99, ValueFromPipeline=$true)]
[PSObject[]]$InputObject
)
begin {
$MappingFunction = @{}
foreach($key in $($Mapping.Keys)) {
$MappingFunction.$Key = {$_.$Key -as $Mapping.$Key}
}
}
process {
foreach($IO in $InputObject) {
$Properties = @{}
foreach($key in $($Mapping.Keys)) {
if($Mapping.$Key -is [ScriptBlock]) {
$Properties.$Key = $IO.$Key | ForEach-Object $Mapping.$Key
} elseif($Mapping.$Key -is [Type]) {
if($Value = $IO.$Key -as $Mapping.$Key) {
$Properties.$Key = $Value
} else {
$Properties.$Key = $IO.$Key
}
} else {
$Properties.$Key = [PSObject]$IO.$Key
}
}
New-Object PSObject -Property $Properties | %{ $_.PSTypeNames.Insert(0, $TypeName); $_ }
}
}
}
|
PowerShellCorpus/PoshCode/FTP upload_4.ps1
|
FTP upload_4.ps1
|
@charset "utf-8";
/*
Credit: http://www.templatemo.com
*/
body {
margin: 0px;
padding: 0px;
color: #c2bead;
font-family: Tahoma, Geneva, sans-serif;
font-size: 12px;
line-height: 1.5em;
background-color: #2f2e28;
background-image: url(images/templatemo_body.jpg);
background-repeat: repeat-y;
background-position: left;
}
a, a:link, a:visited { color: #34baf9; text-decoration: none; }
a:hover { color: #CCFF00; text-decoration: underline; }
p { margin: 0 0 10px 0; padding: 0; }
img { border: none; }
h1, h2, h3, h4, h5, h6 { color: #e2c934; }
h1 { font-size: 24px; font-weight: normal; margin: 0 0 30px 0; padding: 5px 0; }
h2 { font-size: 20px; font-weight: normal; margin: 0 0 30px 0; font-weight: normal; }
h3 { font-size: 16px; margin: 0 0 15px 0; padding: 0; padding: 0; font-weight: normal; }
h4 { font-size: 14px; margin: 0 0 15px 0; padding: 0; }
.cleaner { clear: both; width: 100%; height: 0px; font-size: 0px; }
.cleaner_h10 { clear: both; width:100%; height: 10px; }
.cleaner_h20 { clear: both; width:100%; height: 20px; }
.cleaner_h30 { clear: both; width:100%; height: 30px; }
.cleaner_h40 { clear: both; width:100%; height: 40px; }
.cleaner_h50 { clear: both; width:100%; height: 50px; }
.cleaner_h60 { clear: both; width:100%; height: 60px; }
.float_l { float: left; }
.float_r { float: right; }
.image_wrapper { display: inline-block; border: 1px solid #000; background: #333; padding: 4px; margin-bottom: 10px; }
.image_fl { float: left; margin: 3px 15px 0 0; }
.image_fr { float: right; margin: 3px 0 0 15px; }
blockquote { font-style: italic; margin: 0 0 0 10px;}
cite { font-weight: bold; color:#333; }
cite span { color: #666; }
em { color: #f9a834; }
.tmo_list { margin: 20px 0 20px 20px; padding: 0; list-style: none; }
.tmo_list li { background: transparent url(images/templatemo_list.png) no-repeat; margin:0 0 20px; padding: 0 0 0 20px; line-height: 1em; }
.tmo_list li a { color: #fff; }
.tmo_list li a:hover { color: #ff4301; }
.btn_more a {
display: inline-block;
font-weight: bold;
color: #dcd9cb;
}
.btn_more a span {
font-size: 16px;
}
.btn_more a:hover {
color: #CCFF00;
text-decoration: none;
}
.service_list { margin: 40px 0 0 30px; padding: 0; list-style: none; }
.service_list li { margin: 0; padding: 0; }
.service_list li a { display: block; height: 25px; margin-bottom: 20px; padding-left: 35px; }
.service_list li .service_one { background: url(images/onebit_08.png) center left no-repeat; }
.service_list li .service_two { background: url(images/onebit_11.png) center left no-repeat; }
.service_list li .service_three { background: url(images/onebit_17.png) center left no-repeat; }
.service_list li .service_four { background: url(images/onebit_21.png) center left no-repeat; }
.service_list li .service_five { background: url(images/onebit_12.png) center left no-repeat; }
#contact_form { padding: 0; }
#contact_form form { margin: 0px; padding: 0px; }
#contact_form form .input_field { width: 440px; padding: 8px; background: #333028; border: 1px solid #886; color: #FFF; }
#contact_form form label { display: block; width: 100px; margin-right: 10px; font-size: 14px; margin-bottom: 3px; }
#contact_form form textarea {
width: 440px;
height: 120px;
padding: 8px;
background: #333028;
font-family: Arial, Helvetica, sans-serif;
border: 1px solid #886;
color: #FFF;
}
#contact_form form .submit_btn {
color: #886;
background: #333028;
border: 1px solid #886;
padding: 10px 20px;
margin-right: 140px;
font-size: 15px;
}
#gallery_container {
clear: both;
margin-top: 30px;
padding-right: 40px;
width: 480px;
height: 320px;
overflow: auto;
}
#gallery_container .gallery_box {
clear: both;
display: block;
padding: 0;
margin: 0 0 40px 0;
}
.gallery_box img {
float: left;
width: 120px;
height: 100px;
padding: 4px;
background: #fff;
border: 1px solid #ccc;
margin: 3px 30px 0 0;
}
#templatemo_footer {
clear: both;
width: 600px;
padding: 20px 0;
text-align: center;
}/* CSS Document */
|
PowerShellCorpus/PoshCode/New-SQLComputerLogin_2.ps1
|
New-SQLComputerLogin_2.ps1
|
# Depends on Invoke-SQLCmd2 http://poshcode.org/2950
# Depends on Get-ADComputer http://poshcode.org/3011
function New-SqlComputerLogin {
#.Synopsis
# Creates a Login on the specified SQL server for a computer account
#.Example
# New-SqlComputerLogin -SQL DevDB2 -Computer BuildBox2 -Force
#
# Specifying the Force parameter causes us to lookup the SID and remove a duplicate entry (in case your computer had an account before under another name).
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0)]
[String]$SQLServer,
[Parameter(ValueFromPipelineByPropertyName=$true, Position=1)]
[String]$ComputerName,
[Switch]$Force
)
process {
# Import-Module QAD, SQLPS -DisableNameChecking
$Computer = Get-ADComputer $ComputerName
#$NTAccountName = $Computer.NTAccountName
#if(!$SID) { $SID = $Computer.SID.ToString() }
invoke-sqlcmd2 -ServerInstance $SQLServer -Query "CREATE LOGIN [$($Computer.NTAccountName)] FROM WINDOWS" -ErrorVariable SqlError -ErrorAction SilentlyContinue
## If this principal already exists, fail, or clean it out and recreate it:
if($SqlError[0].Exception.GetBaseException().Message.EndsWith("already exists.")) {
if(!$Force) {
Write-Error $SqlError[0].Exception.GetBaseException().Message
$ExistingAccount =
invoke-sqlcmd2 -ServerInstance $SQLServer -Query "select name, sid from sys.server_principals where type IN ('U','G')" |
add-member -membertype ScriptProperty SSDL { new-object security.principal.securityidentifier $this.SID, 0 } -passthru |
where-object {$_.SSDL -eq $Computer.SID}
Write-Warning "You need to drop [$($ExistingAccount.Name)] or run New-SqlComputerLogin again with -Force"
} else {
Write-Warning ($SqlError[0].Exception.GetBaseException().Message + " -- DROPping and reCREATEing")
$ExistingAccount =
invoke-sqlcmd2 -ServerInstance $SQLServer -Query "select name, sid from sys.server_principals where type IN ('U','G')" |
add-member -membertype ScriptProperty SSDL { new-object security.principal.securityidentifier $this.SID, 0 } -passthru |
where-object {$_.SSDL -eq $Computer.SID}
Write-Warning "Dropping [$($ExistingAccount.Name)] to create [$($Computer.NTAccountName)]"
invoke-sqlcmd2 -ServerInstance $SQLServer -Query "DROP LOGIN [$($ExistingAccount.Name)]" -ErrorAction Stop
invoke-sqlcmd2 -ServerInstance $SQLServer -Query "CREATE LOGIN [$($Computer.NTAccountName)] FROM WINDOWS"
invoke-sqlcmd2 -ServerInstance $SQLServer -Query "select name, type_desc, default_database_name, create_date from sys.server_principals where name = '$($Computer.NTAccountName)'"
}
}
}
}
|
PowerShellCorpus/PoshCode/New-PemFile.ps1
|
New-PemFile.ps1
|
function New-PemFile {
<#
.SYNOPSIS
Creates a new PEM file from one or more certificate files.
.DESCRIPTION
The New-PemFile function creates a new PEM file by using the content from certificate files.
CER, CRT, and KEY files are the most common certificate file types.
.PARAMETER Path
The path or paths to certificate files from which to create the PEM file.
.PARAMETER Target
Specifies the full path to the target PEM file.
.EXAMPLE
New-PemFile -Path C:\\temp\\domain.crt -Target C:\\temp\\domain.pem
Creates a PEM file from a single CRT file.
.EXAMPLE
New-PemFile -Path C:\\temp\\domain.crt, C:\\temp\\intermediate.crt, C:\\temp\\root.crt -Target C:\\temp\\domain.pem
Creates a PEM file from three CRT files.
.EXAMPLE
$files = dir C:\\temp\\*.crt
$files[2,0,1] | New-PemFile -Target C:\\temp\\domain.pem
Captures all the CRT files in the temp folder, orders the files for input into the function, and creates the PEM file.
.INPUTS
System.String
.OUTPUTS
None
.NOTES
Name: New-PemFile
Author: Rich Kusak
Created: 2011-11-05
LastEdit: 2011-11-30 09:46
Version: 1.0.1.0
.LINK
http://en.wikipedia.org/wiki/X.509
.LINK
http://www.digicert.com/ssl-support/pem-ssl-creation.htm
#>
[CmdletBinding()]
param (
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[ValidateScript({
foreach ($file in $_) {
if (Test-Path -LiteralPath $file) {$true} else {
throw "The argument '$_' is not a valid file."
}
}
})]
[Alias('FullName')]
[string[]]$Path,
[Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[ValidatePattern('\\.pem$')]
[string]$Target
)
begin {
New-Item $Target -ItemType File -Force | Out-Null
}
process {
[PSObject[]]$paths += $Path
}
end {
foreach ($file in $paths) {
Get-Content $file | Out-File $Target -Encoding ASCII -Append
}
}
} # function New-PemFile
|
PowerShellCorpus/PoshCode/Get-RandomNames.ps1
|
Get-RandomNames.ps1
|
function Get-RandomNames {
<#
.SYNOPSIS
Gets Full Names from a List of Names from http://names.mongabay.com
.DESCRIPTION
Downloads the Names from the Websites and randomizes the order of Names and gives back an Object with surname, lastname and gender
.PARAMETER MaxNames
Number of names returned by the function
.PARAMETER Gender
Gender of the names
.EXAMPLE
Get-RandomNames -Maxnames 20 -Gender Female
.EXAMPLE
Get-RandomNames
.NOTES
Name: Get-RandomNames
Author: baschuel
Date: 17.02.2013
Version: 1.0
Thanks to http://names.mongabay.com
#>
[CmdletBinding()]
param (
[parameter(Position=0)]
[int]$MaxNames = 10,
[parameter(Position=1)]
[string]$Gender = "Male"
)
BEGIN{
$surnameslink = "http://names.mongabay.com/most_common_surnames.htm"
$malenameslink = "http://names.mongabay.com/male_names_alpha.htm"
$femalenameslink = "http://names.mongabay.com/female_names_alpha.htm"
}#begin
PROCESS{
function get-names ($url) {
Try {
$web = Invoke-WebRequest -UseBasicParsing -Uri $url -ErrorAction Stop
$html = $web.Content
$regex = [RegEx]'((?:<td>)(.*?)(?:</td>))+'
$Matches = $regex.Matches($html)
$matches | ForEach-Object {
If ($_.Groups[2].Captures[0].Value -ge 1) {
$hash = @{Name = $_.Groups[2].Captures[0].Value;
Rank = [int]$_.Groups[2].Captures[3].Value}
New-Object -TypeName PSObject -Property $hash
}#If
}#Foreach-Object
} Catch {
Write-Warning "Can't access the data from $url."
Write-Warning "$_.Exception.Message"
Break
}
}#Function get-names
If ($Gender -eq "Male") {
$AllMaleFirstNames = (get-Names $malenameslink).name
$AllSurnames = (get-names $surnameslink).name
If ($AllMaleFirstNames.Count -le $AllSurnames.Count) {
$UpperRange = $AllMaleFirstNames.Count
} else {
$UpperRange = $AllSurnames.Count
}
If (($MaxNames -le $AllMaleFirstNames.Count) -and ($MaxNames -le $AllSurnames.Count)) {
1..$UpperRange |
Get-Random -Count $MaxNames |
ForEach-Object {
$hash = @{Givenname = $AllMaleFirstNames[$_];
Surname = $AllSurnames[$_];
Gender = "Male"}
$hash.Givenname = $($hash.Givenname[0]) + $hash.givenname.Substring(1,$hash.givenname.Length-1).ToLower()
$hash.Surname = $($hash.Surname[0]) + $hash.surname.Substring(1,$hash.surname.Length-1).ToLower()
New-Object -TypeName PSObject -Property $hash
} # Foreach-Object
} Else {
Write-Warning "Don't know so many names! Try a smaller number"
}#If
} elseIf ($Gender -eq "Female") {
$AllFeMaleFirstNames = (get-Names $femalenameslink).name
$AllSurnames = (get-names $surnameslink).name
If ($AllFeMaleFirstNames.Count -le $AllSurnames.Count) {
$UpperRange = $AllMaleFirstNames.Count
} else {
$UpperRange = $AllSurnames.Count
}
If (($MaxNames -le $AllFeMaleFirstNames.Count) -and ($MaxNames -le $AllSurnames.Count)) {
1..$UpperRange |
Get-Random -Count $MaxNames |
ForEach-Object {
$hash = @{Givenname = $AllFeMaleFirstNames[$_];
Surname = $AllSurnames[$_];
Gender = "Female"}
$hash.Givenname = $($hash.Givenname[0]) + $hash.givenname.Substring(1,$hash.givenname.Length-1).ToLower()
$hash.Surname = $($hash.Surname[0]) + $hash.surname.Substring(1,$hash.surname.Length-1).ToLower()
New-Object -TypeName PSObject -Property $hash
} # Foreach-Object
} Else {
Write-Warning "Don't know so many names! Try a smaller number"
}#If
}#If
}
}
|
PowerShellCorpus/PoshCode/3f43dbaf-2e5c-4f5c-a244-776641571a20.ps1
|
3f43dbaf-2e5c-4f5c-a244-776641571a20.ps1
|
function Get-RandomNames {
<#
.SYNOPSIS
Gets Full Names from a List of Names from http://names.mongabay.com
.DESCRIPTION
Downloads the Names from the Websites and randomizes the order of Names and gives back an Object with surname, lastname and gender
.PARAMETER MaxNames
Number of names returned by the function
.PARAMETER Gender
Gender of the names
.EXAMPLE
Get-RandomNames -Maxnames 20 -Gender Female
.EXAMPLE
Get-RandomNames
.NOTES
Name: Get-RandomNames
Author: baschuel
Date: 17.02.2013
Version: 1.0
Thanks to http://names.mongabay.com
#>
[CmdletBinding()]
param (
[parameter(Position=0)]
[int]$MaxNames = 10,
[parameter(Position=1)]
[string]$Gender = "Male"
)
BEGIN{
$surnameslink = "http://names.mongabay.com/most_common_surnames.htm"
$malenameslink = "http://names.mongabay.com/male_names_alpha.htm"
$femalenameslink = "http://names.mongabay.com/female_names_alpha.htm"
}#begin
PROCESS{
function get-names ($url) {
Try {
$web = Invoke-WebRequest -UseBasicParsing -Uri $url -ErrorAction Stop
$html = $web.Content
$regex = [RegEx]'((?:<td>)(.*?)(?:</td>))+'
$Matches = $regex.Matches($html)
$matches | ForEach-Object {
If ($_.Groups[2].Captures[0].Value -ge 1) {
$hash = @{Name = $_.Groups[2].Captures[0].Value;
Rank = [int]$_.Groups[2].Captures[3].Value}
New-Object -TypeName PSObject -Property $hash
}#If
}#Foreach-Object
} Catch {
Write-Warning "Can't access the data from $url."
Write-Warning "$_.Exception.Message"
Break
}
}#Function get-names
If ($Gender -eq "Male") {
$AllMaleFirstNames = (get-Names $malenameslink).name
$AllSurnames = (get-names $surnameslink).name
If ($AllMaleFirstNames.Count -le $AllSurnames.Count) {
$UpperRange = $AllMaleFirstNames.Count
} else {
$UpperRange = $AllSurnames.Count
}
If (($MaxNames -le $AllMaleFirstNames.Count) -and ($MaxNames -le $AllSurnames.Count)) {
1..$UpperRange |
Get-Random -Count $MaxNames |
ForEach-Object {
$hash = @{Givenname = $AllMaleFirstNames[$_];
Surname = $AllSurnames[$_];
Gender = "Male"}
$hash.Givenname = $($hash.Givenname[0]) + $hash.givenname.Substring(1,$hash.givenname.Length-1).ToLower()
$hash.Surname = $($hash.Surname[0]) + $hash.surname.Substring(1,$hash.surname.Length-1).ToLower()
New-Object -TypeName PSObject -Property $hash
} # Foreach-Object
} Else {
Write-Warning "Don't know so many names! Try a smaller number"
}#If
} elseIf ($Gender -eq "Female") {
$AllFeMaleFirstNames = (get-Names $femalenameslink).name
$AllSurnames = (get-names $surnameslink).name
If ($AllFeMaleFirstNames.Count -le $AllSurnames.Count) {
$UpperRange = $AllMaleFirstNames.Count
} else {
$UpperRange = $AllSurnames.Count
}
If (($MaxNames -le $AllFeMaleFirstNames.Count) -and ($MaxNames -le $AllSurnames.Count)) {
1..$UpperRange |
Get-Random -Count $MaxNames |
ForEach-Object {
$hash = @{Givenname = $AllFeMaleFirstNames[$_];
Surname = $AllSurnames[$_];
Gender = "Female"}
$hash.Givenname = $($hash.Givenname[0]) + $hash.givenname.Substring(1,$hash.givenname.Length-1).ToLower()
$hash.Surname = $($hash.Surname[0]) + $hash.surname.Substring(1,$hash.surname.Length-1).ToLower()
New-Object -TypeName PSObject -Property $hash
} # Foreach-Object
} Else {
Write-Warning "Don't know so many names! Try a smaller number"
}#If
}#If
}
}
|
PowerShellCorpus/PoshCode/6b9bb97b-5f9c-4504-af73-6d26a0372e0c.ps1
|
6b9bb97b-5f9c-4504-af73-6d26a0372e0c.ps1
|
Function Get-Printers
{
<#
.SYNOPSIS
Get a list of printers from the specified print server
.DESCRIPTION
This function returns the Name of each printer installed
on the specified print server.
.PARAMETER ComputerName
Name of the print server
.EXAMPLE
Get-Printers -ComputerName ps
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/PrintServerManagement#Get-Printers
#>
Param
(
[String]$ComputerName
)
Begin
{
$Host.Runspace.ThreadOptions = "ReuseThread"
if ((Get-WmiObject -Class Win32_OperatingSystem).OSArchitecture -eq '64-bit')
{
$SystemPrinting = Get-ChildItem "$($env:systemroot)\\assembly\\GAC_64\\System.Printing"
$SystemPrintingFile = Get-ChildItem -Name "*system.printing*" -Recurse -Path $SystemPrinting.FullName
$SystemPrintingFile = "$($SystemPrinting.FullName)\\$($SystemPrintingFile)"
}
else
{
$SystemPrinting = Get-ChildItem "$($env:systemroot)\\assembly\\GAC_32\\System.Printing"
$SystemPrintingFile = Get-ChildItem -Name "*system.printing*" -Recurse -Path $SystemPrinting.FullName
$SystemPrintingFile = "$($SystemPrinting.FullName)\\$($SystemPrintingFile)"
}
$ErrorActionPreference = "Stop"
Try
{
Add-Type -Path $SystemPrintingFile
$PrintServer = New-Object System.Printing.PrintServer("\\\\$($ComputerName)")
$PrintQueues = $PrintServer.GetPrintQueues()
}
Catch
{
Write-Error $Error[0].Exception
Break
}
$Printers = @()
}
Process
{
Foreach ($PrintQueue in $PrintQueues)
{
$ThisPrinter = New-Object -TypeName PSObject -Property @{
Name = $PrintQueue.Name
}
$Printers += $ThisPrinter
}
}
End
{
Return $Printers
}
}
Function Get-PrintQueue
{
<#
.SYNOPSIS
Return the print queue for a given printer
.DESCRIPTION
This function returns the print queue for a specific printer
from the print server.
.PARAMETER ComputerName
Name of the print server
.PARAMETER Name
Name of the print queue
.EXAMPLE
Get-PrintQueue -ComputerName ps -Name HPCLJ5500
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/PrintServertManagement#Get-PrintQueue
#>
Param
(
$ComputerName,
$Name
)
Begin
{
$Host.Runspace.ThreadOptions = "ReuseThread"
if ((Get-WmiObject -Class Win32_OperatingSystem).OSArchitecture -eq '64-bit')
{
$SystemPrinting = Get-ChildItem "$($env:systemroot)\\assembly\\GAC_64\\System.Printing"
$SystemPrintingFile = Get-ChildItem -Name "*system.printing*" -Recurse -Path $SystemPrinting.FullName
$SystemPrintingFile = "$($SystemPrinting.FullName)\\$($SystemPrintingFile)"
}
else
{
$SystemPrinting = Get-ChildItem "$($env:systemroot)\\assembly\\GAC_32\\System.Printing"
$SystemPrintingFile = Get-ChildItem -Name "*system.printing*" -Recurse -Path $SystemPrinting.FullName
$SystemPrintingFile = "$($SystemPrinting.FullName)\\$($SystemPrintingFile)"
}
$ErrorActionPreference = "Stop"
Try
{
Add-Type -Path $SystemPrintingFile
$PrintServer = New-Object System.Printing.PrintServer("\\\\$($ComputerName)")
$PrintQueue = $PrintServer.GetPrintQueue($Name)
}
Catch
{
Write-Error $Error[0].Exception
Break
}
}
Process
{
}
End
{
Return $PrintQueue
}
}
Function Get-PrintJobs
{
<#
.SYNOPSIS
Return the list of jobs on the current printer
.DESCRIPTION
This function returns a list of pending jobs on the specified print server for a given queue
.PARAMETER ComputerName
Name of the print sever
.PARAMETER Name
Name of the print queue
.EXAMPLE
Get-PrintJobs -ComputerName ps -Name HPLJ5000
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/PrintServerManagement#Get-PrintJobs
#>
Param
(
$ComputerName,
$Name
)
Begin
{
$Host.Runspace.ThreadOptions = "ReuseThread"
if ((Get-WmiObject -Class Win32_OperatingSystem).OSArchitecture -eq '64-bit')
{
$SystemPrinting = Get-ChildItem "$($env:systemroot)\\assembly\\GAC_64\\System.Printing"
$SystemPrintingFile = Get-ChildItem -Name "*system.printing*" -Recurse -Path $SystemPrinting.FullName
$SystemPrintingFile = "$($SystemPrinting.FullName)\\$($SystemPrintingFile)"
}
else
{
$SystemPrinting = Get-ChildItem "$($env:systemroot)\\assembly\\GAC_32\\System.Printing"
$SystemPrintingFile = Get-ChildItem -Name "*system.printing*" -Recurse -Path $SystemPrinting.FullName
$SystemPrintingFile = "$($SystemPrinting.FullName)\\$($SystemPrintingFile)"
}
$ErrorActionPreference = "Stop"
Try
{
Add-Type -Path $SystemPrintingFile
$PrintServer = New-Object System.Printing.PrintServer("\\\\$($ComputerName)")
$PrintQueue = $PrintServer.GetPrintQueue($Name)
$PrintJobs = $PrintQueue.GetPrintJobInfoCollection()
}
Catch
{
Write-Error $Error[0].Exception
Break
}
}
Process
{
}
End
{
Return $PrintJobs
}
}
|
PowerShellCorpus/PoshCode/Enable_Configure SNMP_2.ps1
|
Enable_Configure SNMP_2.ps1
|
#Powershell Script To Install SNMP Services (SNMP Service, SNMP WMI Provider)
#Variables :)
$pmanagers = "ADD YOUR MANAGER(s)"
$commstring = "ADD YOUR COMM STRING"
#Import ServerManger Module
Import-Module ServerManager
#Check If SNMP Services Are Already Installed
$check = Get-WindowsFeature | Where-Object {$_.Name -eq "SNMP-Services"}
If ($check.Installed -ne "True") {
#Install/Enable SNMP Services
Add-WindowsFeature SNMP-Services | Out-Null
}
##Verify Windows Servcies Are Enabled
If ($check.Installed -eq "True"){
#Set SNMP Permitted Manager(s) ** WARNING : This will over write current settings **
reg add "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\SNMP\\Parameters\\PermittedManagers" /v 1 /t REG_SZ /d localhost /f | Out-Null
#Used as counter for incremting permitted managers
$i = 2
Foreach ($manager in $pmanagers){
reg add "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\SNMP\\Parameters\\PermittedManagers" /v $i /t REG_SZ /d $manager /f | Out-Null
$i++
}
#Set SNMP Community String(s)- *Read Only*
Foreach ( $string in $commstring){
reg add "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\SNMP\\Parameters\\ValidCommunities" /v $string /t REG_DWORD /d 4 /f | Out-Null
}
}
Else {Write-Host "Error: SNMP Services Not Installed"}
|
PowerShellCorpus/PoshCode/Get-LogicalDiskInfo_1.ps1
|
Get-LogicalDiskInfo_1.ps1
|
# ========================================================================
#
# NAME: Get-LogicalDiskInfo.ps1
#
# AUTHOR: Alex Ocampo , Daptiv Solutions LLC
# DATE : 7/19/2011
#
# COMMENT: Using WMI, script check logical disk information of a single
# server or a group of servers. Script send email notification if any
# logical disk free space falls below minimum free disk space
# ($minFreeSpace).
#
#
# Syntax:
#
# Check logicalDisks info on a single host in this case "server1"
# PS C:\\Scripts> .\\Get-LogicalDiskInfo.ps1 -computerNames "server1"
#
# Running script without passing a parameter checks logicalDisks of all
# computers or servers listed on C:\\Scripts\\Computers.txt. Script stop
# execution if no parameter is passed and Computers.txt is not present.
#
# Sample (Computers.txt), add computers/servers to check as needed...
# SERVER1
# SERVER2
# SERVER3
#
# ========================================================================
param (
[string[]] $computerNames
)
Set-Location -Path ([System.Environment]::GetEnvironmentVariable("SystemDrive") + "\\Scripts")
# Test that parameters exists
if ($computerNames -eq $null) {
if (Test-Path -LiteralPath ".\\Computers.txt" -PathType "leaf") {
$computerNames = Get-Content -Path ".\\Computers.txt"
}
else {
Write-Host "missing parameters..."
exit
}
}
# $minFreeSpace = $_.freespace/$_.size
# higher value translate to lower maximum disk space used and reports
# more drives meeting criteria.
[double] $minFreeSpace=.25
function notify {
param (
[string] $subject,
[string] $message,
[string] $to="DL Team IT <distributionGroup@mydomain.com>",
[string] $from="IT Notification <itNotification@mydomain.com>",
[string] $smtpserver="mailServer.mydomain.com"
)
Send-MailMessage -From $from -To $to -Subject $subject -Body $message -SmtpServer $smtpserver
}
function existTest {
param ([string] $node2Chk)
$pathStr="\\\\$node2Chk\\ADMIN$"
return Test-Path -LiteralPath $pathStr
}
function chkDisk {
param (
[string] $node
)
# $messageBody string = "WARNING: Drive C: is 85% full..."
[string] $messageBody="WARNING: Immediate action required...`r`n`r`n"
Get-WmiObject Win32_LogicalDisk -ComputerName $node | `
Where-Object {$_.DriveType -eq 3} | `
ForEach-Object { If (($_.FreeSpace/$_.Size) -le $minFreeSpace) { `
$result="Drive " + $_.DeviceID + " is " + (100 - [math]::Round(($_.FreeSpace/$_.Size)*100, 2)) + "% full..."
# $result=$node + ": " + $_.DeviceID + " - Free disk space: " + [math]::Round($_.FreeSpace/1GB, 2) + "GB"
$messageBody="$messageBody" + "`t$result`r`n"
}
}
# do not call function if variable is equals to initial value
if ($messageBody -ne "WARNING: Immediate action required...`n`n") {
notify -subject "RE: \\\\$node" -message "$messageBody"
}
}
function main {
param (
[bool] $validNode
)
foreach ($computer in $computerNames) {
# Test if computer exists
$validNode = existTest $computer
if ($validNode) {
chkDisk $computer
}
}
}
# call main function
main
|
PowerShellCorpus/PoshCode/More PSDrives.ps1
|
More PSDrives.ps1
|
function Mount-UserDrives {
<#
.Synopsis
Create additional user drives.
.Description
To remove drives created with this function use Remove-UserDrives.
.Link
New-PSDrive
Remove-UserDrives
#>
[Enum]::GetNames([Environment+SpecialFolder]) | % {
New-PSDrive -n $_ -ps FileSystem -r $([Environment]::GetFolderPath($_)) -s Global | Out-Null
}
}
function Remove-UserDrives {
<#
.Synopsis
Remove additional user drives.
.Description
Dismount drives which mounted with Mount-UserDrives.
.Link
Remove-PSDrive
Mount-UserDrives
#>
[Enum]::GetNames([Environment+SpecialFolder]) | % {
Remove-PSDrive -n $_ -ps FileSystem -s Global
}
}
|
PowerShellCorpus/PoshCode/AD-PromiscDetect.ps1
|
AD-PromiscDetect.ps1
|
<#================================================================================================
NAME: AD-PromiscDetect.ps1
AUTHOR: Marty J. Piccinich
DATE CREATED: 9/15/2009
VERSION: 1.1
HISTORY: 1.0 9/15/2009 - Created
1.1 10/23/2009 - Added comment header
PARAMETERS: None
DESCRIPTION:
Queries Active Directory (currently logged into) for all computer objects,
pings the computer first, then queries WMI. The MSNdis_CurrentPackFilter class
in the root\\WMI namespace is used. Next, the NdisCurrentPacketFilter property to
see if the NDIS_PACKET_TYPE_PROMISCUOUS bit (0x00000020) is set. This determines
if the NIC is is promiscuous mode.
REQUIREMENTS:
Proper rights to query WMI\\Root on the remote computers is necessary.
NOTES:
For more details, see the blog post:
http://praetorianprefect.com/archives/2009/09/whos-being-promiscuous-in-your-active-directory/
Credit to Harlan Carvey who provided information on NdisCurrentPacketFilter in his blog.
IMPORTANT:
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.
================================================================================================#>
$ErrorActionPreference = "SilentlyContinue"
$PingTest = New-Object System.Net.NetworkInformation.Ping
$Filter = "(&(ObjectCategory=computer))"
$Searcher = New-Object System.DirectoryServices.DirectorySearcher($Filter)
ForEach ($comp in $Searcher.Findall()) {
$strComputer = $comp.properties.item("Name")
write-host "Checking: $strComputer"
if ($PingTest.Send($strComputer).Status -eq "Success") {
@@ $colComputer = get-wmiObject -class "MSNdis_CurrentPacketFilter" -namespace "root\\WMI" -comp $strComputer
if ($colComputer -eq $null) {
write-host "Couldn't connect to WMI" }
else {
foreach ($comp in $colcomputer) {
@@ $val = $comp.NdisCurrentPacketFilter
@@ if ($val -band 0x00000020) {
@@ $inst = $comp.InstanceName
@@ write-host "Interface: $inst"
write-host "The packetfilter value is above range" -foregroundcolor red -backgroundcolor yellow
}
}
}
}
else { write-host "Could not ping, machine not queried." }
}
|
PowerShellCorpus/PoshCode/Get-Parameter 2.7.ps1
|
Get-Parameter 2.7.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
# - CHANGED uses FormatData so the output is objects
# - ADDED calculation of shortest names to the aliases (idea from Shay Levy http://poshcode.org/1982,
# but with a correct implementation)
# Version 2.1 - July 22, 2010 - By Joel Bennett http://poshcode.org/2007
# - FIXED Help for SCRIPT file (script help must be separated from #Requires by an emtpy line)
# - Fleshed out and added dates to this version history after Bergle's criticism ;)
# Version 2.2 - July 29, 2010 - By Joel Bennett http://poshcode.org/2030
# - FIXED a major bug which caused Get-Parameters to delete all the parameters from the CommandInfo
# Version 2.3 - July 29, 2010 - By Joel Bennett
# - ADDED a ToString ScriptMethod which allows queries like:
# $parameters = Get-Parameter Get-Process; $parameters -match "Name"
# Version 2.4 - July 29, 2010 - By Joel Bennett http://poshcode.org/2032
# - CHANGED "Name" to CommandName
# - ADDED ParameterName parameter to allow filtering parameters
# - FIXED bug in 2.3 and 2.2 with dynamic parameters
# Version 2.5 - December 13, 2010 - By Jason Archer http://poshcode.org/2404
# - CHANGED format temp file to have static name, prevents bloat of random temporary files
# Version 2.6 - July 23, 2011 - By Jason Archer (This Version)
# - FIXED miscalculation of shortest unique name (aliases count as unique names),
# this caused some parameter names to be thrown out (like "Object")
# - CHANGED code style cleanup
# Version 2.7 - November 28, 2012 - By Joel Bennett (This Version)
# - Added * indicator on default parameter set.
#
#.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 CommandName
# The name of the command to get parameters for
#.Parameter ParameterName
# Wilcard-enabled filter for parameter names
#.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)]
[Alias("Name")]
[string[]]$CommandName
,
[Parameter(Position=2,ValueFromPipelineByPropertyName=$true,Mandatory=$false)]
[string[]]$ParameterName="*"
,
[Parameter(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 CommandName
# The name of the command to get parameters for
#.Parameter ParameterName
# Wilcard-enabled filter for parameter names
#.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, Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
[string[]]$CommandName
,
[Parameter(Position = 2, ValueFromPipelineByPropertyName=$true)]
[string[]]$ParameterName = "*"
,
[Parameter(ValueFromPipelineByPropertyName = $true)]
$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 | Get-Member -MemberType Properties | Select-Object -ExpandProperty Name
}
process {
$Output = $First | Select-Object $p1
foreach ($p in $Second | Get-Member -MemberType Properties | Where-Object {$p1 -notcontains $_.Name} | Select-Object -ExpandProperty Name) {
Add-Member -InputObject $Output -MemberType NoteProperty -Name $p -Value $Second."$p"
}
$Output
}
}
}
process {
foreach ($cmd in $CommandName) {
if ($ModuleName) {$cmd = "$ModuleName\\$cmd"}
$commands = @(Get-Command $cmd)
foreach ($command in $commands) {
# resolve aliases (an alias can point to another alias)
while ($command.CommandType -eq "Alias") {
$command = @(Get-Command ($command.definition))[0]
}
if (-not $command) {continue}
$Parameters = @{}
foreach ($provider in Get-PSProvider) {
$drive = "{0}\\{1}::\\" -f $provider.ModuleName, $provider.Name
Write-Verbose ("Get-Command $command -Args $drive | Select -Expand Parameters")
[Array]$MoreParameters = (Get-Command $command -Args $drive).Parameters.Values
[Array]$Dynamic = $MoreParameters | Where-Object {$_.IsDynamic}
foreach ($p in $MoreParameters | Where-Object{!$Parameters.ContainsKey($_.Name)}) {$Parameters.($p.Name) = $p}
# Write-Verbose "Drive: $Drive | Parameters: $($Parameters.Count)"
if ($dynamic) {
foreach ($d in $dynamic) {
if (Get-Member -InputObject $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.
$Aliases = $Parameters.Values | Select-Object -ExpandProperty Aliases ## Get defined aliases
foreach ($p in $($Parameters.Keys)) {
$shortest = "^"
foreach ($char in [char[]]$p) {
$shortest += $char
$Matches = (($Parameters.Keys + $Aliases) -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-Object -ExpandProperty "Name")) {
$paramset = $paramset | Add-Member -Name IsDefault -MemberType NoteProperty -Value ($paramset -eq $command.DefaultParameterSet) -PassThru
foreach ($parameter in $Parameters.Keys | Sort-Object) {
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-Object {
$null = $_.PSTypeNames.Insert(0,"System.Management.Automation.ParameterMetadata")
$null = $_.PSTypeNames.Insert(0,"System.Management.Automation.ParameterMetadataEx")
Write-Verbose "$(($_.PSTypeNames.GetEnumerator()) -join ", ")"
$_
} |
Add-Member ScriptMethod ToString { $this.Name } -Force -Passthru |
Where-Object {$(foreach($pn in $ParameterName) {$_ -like $Pn}) -contains $true}
}
}
}
}
}
}
}
# Since you can't update format data without a file that has a ps1xml ending, let's make one up...
$tempFile = "$([System.IO.Path]::GetTempPath())Get-Parameter.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})" + "$(if($_.ParameterSet.IsDefault){" *"})"</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/Test-Port_1.ps1
|
Test-Port_1.ps1
|
param ($ComputerName,$Port)
$sock = new-object System.Net.Sockets.Socket -ArgumentList $([System.Net.Sockets.AddressFamily]::InterNetwork),$([System.Net.Sockets.SocketType]::Stream),$([System.Net.Sockets.ProtocolType]::Tcp)
try {
$sock.Connect($ComputerName,$Port)
$sock.Connected
$sock.Close()
}
catch {
$false
}
|
PowerShellCorpus/PoshCode/Set-Prompt_2.ps1
|
Set-Prompt_2.ps1
|
#.Synopsis
# Sets my favorite prompt function
#.Notes
# I put the id in my prompt because it's very, very useful.
#
# Invoke-History and my Expand-Alias and Get-PerformanceHistory all take command history IDs
# Also, you can tab-complete with "#<id>[Tab]" so .
# For example, the following commands:
# r 4
# ## r is an alias for invoke-history, so this reruns your 4th command
#
# #6[Tab]
# ## will tab-complete whatever you typed in your 6th command (now you can edit it)
#
# Expand-Alias -History 6,8,10 > MyScript.ps1
# ## generates a script from those history items
#
# GPH -id 6, 8
# ## compares the performance of those two commands ...
#
param(
# Controls how much history we keep in the command log
[Int]$PersistentHistoryCount = 30,
# If set, we use a pasteable prompt with <# #> around the prompt info
[Alias("copy","demo")][Switch]$Pasteable,
[Int]$global:MaximumHistoryCount = 2048,
[ConsoleColor]$global:PromptForeground = "Yellow",
[ConsoleColor]$global:ErrorForeground = "Red"
)
# Some stuff goes OUTSIDE the prompt function because it doesn't need re-evaluation
# I set the title in my prompt every time, because I want the current PATH location there,
# rather than in my prompt where it takes up too much space.
# But I want other stuff too. I calculate an initial prefix for the window title
# The title will show the PowerShell version, user, current path, and whether it's elevated or not
# E.g.:"PoSh3 Jaykul@HuddledMasses (ADMIN) - C:\\Your\\Path\\Here (FileSystem)"
if(!$global:WindowTitlePrefix) {
$global:WindowTitlePrefix = "PoSh$($PSVersionTable.PSVersion.Major) ${Env:UserName}@${Env:UserDomain}"
# if you're running "elevated" we want to show that:
$ENV:PROCESS_ELEVATED = ([System.Environment]::OSVersion.Version.Major -gt 5) -and ( # Vista and ...
new-object Security.Principal.WindowsPrincipal (
[Security.Principal.WindowsIdentity]::GetCurrent()) # current user is admin
).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if($ENV:PROCESS_ELEVATED) {
$global:WindowTitlePrefix += " (ADMIN)"
}
}
## Global first-run (profile or first prompt)
if($MyInvocation.HistoryId -eq 1) {
$ProfileDir = Split-Path $Profile.CurrentUserAllHosts
## Import my history
Import-CSV $ProfileDir\\.poshhistory | Add-History
}
if($Pasteable) {
# The pasteable prompt starts with "<#PS " and ends with " #>"
# so that you can copy-paste with the prompt and it will still run
function global:prompt {
# FIRST, make a note if there was an error in the previous command
$err = !$?
Write-host "<#PS " -NoNewLine -fore gray
# Make sure Windows and .Net know where we are (they can only handle the FileSystem)
[Environment]::CurrentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath
try {
# Also, put the path in the title ... (don't restrict this to the FileSystem)
$Host.UI.RawUI.WindowTitle = "{0} - {1} ({2})" -f $global:WindowTitlePrefix,$pwd.Path,$pwd.Provider.Name
} catch {}
# Determine what nesting level we are at (if any)
$Nesting = "$([char]0xB7)" * $NestedPromptLevel
# Generate PUSHD(push-location) Stack level string
$Stack = "+" * (Get-Location -Stack).count
# I used to use Export-CliXml, but Export-CSV is a lot faster
$null = Get-History -Count 30 | Export-CSV $ProfileDir\\.poshhistory
# Output prompt string
# If there's an error, set the prompt foreground to the error color...
if($err) { $fg = $global:ErrorForeground } else { $fg = $global:PromptForeground }
# Notice: no angle brackets, makes it easy to paste my buffer to the web
Write-Host "[${Nesting}$($myinvocation.historyID)${Stack}]" -NoNewLine -Foreground $fg
Write-host " #>" -NoNewLine -fore gray
# Hack PowerShell ISE CTP2 (requires 4 characters of output)
if($Host.Name -match "ISE" -and $PSVersionTable.BuildVersion -eq "6.2.8158.0") {
return "$("$([char]8288)"*3) "
} else {
return " "
}
}
} else {
function global:prompt {
# FIRST, make a note if there was an error in the previous command
$err = !$?
# Make sure Windows and .Net know where we are (they can only handle the FileSystem)
[Environment]::CurrentDirectory = (Get-Location -PSProvider FileSystem).ProviderPath
try {
# Also, put the path in the title ... (don't restrict this to the FileSystem)
$Host.UI.RawUI.WindowTitle = "{0} - {1} ({2})" -f $global:WindowTitlePrefix,$pwd.Path,$pwd.Provider.Name
} catch {}
# Determine what nesting level we are at (if any)
$Nesting = "$([char]0xB7)" * $NestedPromptLevel
# Generate PUSHD(push-location) Stack level string
$Stack = "+" * (Get-Location -Stack).count
# I used to use Export-CliXml, but Export-CSV is a lot faster
$null = Get-History -Count 30 | Export-CSV $ProfileDir\\.poshhistory
# Output prompt string
# If there's an error, set the prompt foreground to "Red", otherwise, "Yellow"
if($err) { $fg = $global:ErrorForeground } else { $fg = $global:PromptForeground }
# Notice: no angle brackets, makes it easy to paste my buffer to the web
Write-Host "[${Nesting}$($myinvocation.historyID)${Stack}]:" -NoNewLine -Fore $fg
# Hack PowerShell ISE CTP2 (requires 4 characters of output)
if($Host.Name -match "ISE" -and $PSVersionTable.BuildVersion -eq "6.2.8158.0") {
return "$("$([char]8288)"*3) "
} else {
return " "
}
}
}
|
PowerShellCorpus/PoshCode/Get-FileEncoding_3.ps1
|
Get-FileEncoding_3.ps1
|
<#
.SYNOPSIS
Gets file encoding.
.DESCRIPTION
The Get-FileEncoding function determines encoding by looking at Byte Order Mark (BOM).
Based on port of C# code from http://www.west-wind.com/Weblog/posts/197245.aspx
.EXAMPLE
Get-ChildItem *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {$_.Encoding -ne 'ASCII'}
This command gets ps1 files in current directory where encoding is not ASCII
.EXAMPLE
Get-ChildItem *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {$_.Encoding -ne 'ASCII'} | foreach {(get-content $_.FullName) | set-content $_.FullName -Encoding ASCII}
Same as previous example but fixes encoding using set-content
#>
function Get-FileEncoding
{
[CmdletBinding()] Param (
[Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] [string]$Path
)
[byte[]]$byte = get-content -Encoding byte -ReadCount 4 -TotalCount 4 -Path $Path
if ($byte.count -ge 0)
{
if ( $byte[0] -eq 0xef -and $byte[1] -eq 0xbb -and $byte[2] -eq 0xbf )
{ Write-Output 'UTF8' }
elseif ($byte[0] -eq 0xfe -and $byte[1] -eq 0xff)
{ Write-Output 'Unicode' }
elseif ($byte[0] -eq 0 -and $byte[1] -eq 0 -and $byte[2] -eq 0xfe -and $byte[3] -eq 0xff)
{ Write-Output 'UTF32' }
elseif ($byte[0] -eq 0x2b -and $byte[1] -eq 0x2f -and $byte[2] -eq 0x76)
{ Write-Output 'UTF7'}
else
{ Write-Output 'ASCII' }
}
}
|
PowerShellCorpus/PoshCode/ADFS troubleshooting.ps1
|
ADFS troubleshooting.ps1
|
<#
This Script will check the MSOnline Office 365 setup. It will prompt the user running it to specify the
credentials. It will then check compare the onsite information with the online information and inform the
user if it is out of sync.
#>
$PSAdmin = Read-host "This script needs to be run as Administrator, have you done this? Y or N..."
If($PSAdmin -eq 'Y' -or 'y'){
Add-PSSnapin Microsoft.Adfs.Powershell
Import-Module MSOnline
$cred = Get-Credential
Connect-MsolService -credential:$cred
Write-host "Below are the URLs Office 365 uses to connect, these URLs MUST be the same (if they are not then see article http://support.microsoft.com/kb/2647020)..." -foreground "Green"
Get-MsolFederationProperty -domainname:'DomainName.com' | Select-Object 'FederationMetadataUrl'
Write-Host "Below is the certificate information for ADFS, the top section is the onsite information showing the current certificate with serial number. The bottom section shows the Office 365 online certificate details. The serial number MUST be the same. If they are not see article http://support.microsoft.com/kb/2647020..." -foreground 'Green'
Get-MsolFederationProperty -domainname:'DomainName.com' | Select-Object 'TokenSigningCertificate' | fl | Out-Default
} Else{
Write-host "Please close Powershell and re-run it as adminstrator" -foreground "Red"
Break}
|
PowerShellCorpus/PoshCode/Get-EasterWestern.ps1
|
Get-EasterWestern.ps1
|
function Get-EasterWestern {
Param(
[Parameter(Mandatory=$true)]
[int] $Year
)
$a = $Year % 19
$b = [Math]::Floor($Year / 100)
$c = $Year % 100
$d = [Math]::Floor($b / 4)
$e = $b % 4
$f = [Math]::Floor(($b + 8) / 25)
$g = [Math]::Floor((($b - $f + 1) / 3))
$h = ((19 * $a) + $b + (-$d) + (-$g) + 15) % 30
$i = [Math]::Floor($c / 4)
$k = $c % 4
$L1 = -($h + $k) #here because powershell is picking up - (subtraction operator) as incorrect toekn
$L = (32 + (2 * $e) + (2 * $i) + $L1) % 7
$m = [Math]::Floor(($a + (11 * $h) + (22 * $L)) / 451)
$v1 = -(7 * $m) #here because powershell is picking up - (subtraction operator) as incorrect toekn
$month = [Math]::Floor(($h + $L + $v1 + 114) / 31)
$day = (($h + $L + $v1 + 114) % 31) + 1
[System.DateTime]$date = "$Year/$month/$day"
$date
<#
.SYNOPSIS
Calculates the Gregorian Easter date for a given year.
.DESCRIPTION
Calculates the Gregorian Easter date for a given year greater than 1751. Algorithm sourced from http://en.wikipedia.org/wiki/Computus, Anonymous Gregorian algorithm.
.PARAMETER Year
The year to calculate easter for.
.EXAMPLE
PS C:\\> Get-EasterWestern 2017
.INPUTS
System.Int32
.OUTPUTS
System.DateTime
#>
}
|
PowerShellCorpus/PoshCode/Test-Prompt.ps1
|
Test-Prompt.ps1
|
$choices = [System.Management.Automation.Host.ChoiceDescription[]](\n(new System.Management.Automation.Host.ChoiceDescription "&Yes","Choose me!"),\n(new System.Management.Automation.Host.ChoiceDescription "&No","Pick me!"))\n\n$Answer = $host.ui.PromptForChoice('Caption',"Message",$choices,(1))\n\nWrite-Output $Answer\n\n$fields = new-object "System.Collections.ObjectModel.Collection``1[[System.Management.Automation.Host.FieldDescription]]"\n\n$f = new System.Management.Automation.Host.FieldDescription "String Field"\n$f.HelpMessage = "This is the help for the first field"\n$f.DefaultValue = "Field1"\n$f.Label = "&Any Text"\n\n$fields.Add($f)\n\n$f = new System.Management.Automation.Host.FieldDescription "Secure String"\n$f.SetparameterType( [System.Security.SecureString] )\n$f.HelpMessage = "You will get a password input with **** instead of characters"\n$f.DefaultValue = "Password"\n$f.Label = "&Password"\n\n$fields.Add($f)\n\n$f = new System.Management.Automation.Host.FieldDescription "Numeric Value"\n$f.SetparameterType( [int] )\n$f.DefaultValue = "42"\n$f.HelpMessage = "You need to type a number, or it will re-prompt"\n$f.Label = "&Number"\n\n$fields.Add($f)\n\n$results = $Host.UI.Prompt( "Caption", "Message", $fields )\n\nWrite-Output $results
|
PowerShellCorpus/PoshCode/1dee8949-c4c9-4c6b-8530-45a36de22fdd.ps1
|
1dee8949-c4c9-4c6b-8530-45a36de22fdd.ps1
|
# For TabExpansion.ps1
# this requires latest TabExpansion.ps1
function Get-PipeLineObject {
$i = -2
$property = $null
do {
$str = $line.Split("|")
# extract the command name from the string
# first split the string into statements and pipeline elements
# This doesn't handle strings however.
$_cmdlet = [regex]::Split($str[$i], '[|;=]')[-1]
# take the first space separated token of the remaining string
# as the command to look up. Trim any leading or trailing spaces
# so you don't get leading empty elements.
$_cmdlet = $_cmdlet.Trim().Split()[0]
if ( $_cmdlet -eq "?" )
{
$_cmdlet = "Where-Object"
}
$global:_exp = $_cmdlet
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0]
}
if ( "Select-Object" -eq $_cmdlet )
{
if ( $str[$i] -match '\\s+-Exp\\w*[\\s:]+(\\w+)' )
{
$property = $Matches[1] + ";" + $property
}
}
$i--
} while ( "Get-Unique", "Select-Object", "Sort-Object", "Tee-Object", "Where-Object" -contains $_cmdlet )
$host.UI.RawUI.WindowTitle = "Windows PowerShell V2 (CTP2) " + $line
if ( $global:_forgci -eq $null )
{
$a = @(ls "Alias:\\")[0]
$e = @(ls "Env:\\")[0]
$f = @(ls "Function:\\")[0]
$h = @(ls "HKCU:\\")[0]
$v = @(ls "Variable:\\")[0]
$c = @(ls "cert:\\")[0]
$global:_forgci = gi $PSHOME\\powershell.exe |
Add-Member -Name CommandType -MemberType 'NoteProperty' -Value $f.CommandType -PassThru |
Add-Member -Name Definition -MemberType 'NoteProperty' -Value $a.Definition -PassThru |
Add-Member -Name Description -MemberType 'NoteProperty' -Value $a.Description -PassThru |
Add-Member -Name Key -MemberType 'NoteProperty' -Value $e.Key -PassThru |
Add-Member -Name Location -MemberType 'NoteProperty' -Value $c.Location -PassThru |
Add-Member -Name LocationName -MemberType 'NoteProperty' -Value $c.LocationName -PassThru |
Add-Member -Name Options -MemberType 'NoteProperty' -Value $a.Options -PassThru |
Add-Member -Name ReferencedCommand -MemberType 'NoteProperty' -Value $a.ReferencedCommand -PassThru |
Add-Member -Name ResolvedCommand -MemberType 'NoteProperty' -Value $a.ResolvedCommand -PassThru |
Add-Member -Name ScriptBlock -MemberType 'NoteProperty' -Value $f.ScriptBlock -PassThru |
Add-Member -Name StoreNames -MemberType 'NoteProperty' -Value $c.StoreNames -PassThru |
Add-Member -Name SubKeyCount -MemberType 'NoteProperty' -Value $h.SubKeyCount -PassThru |
Add-Member -Name Value -MemberType 'NoteProperty' -Value $e.Value -PassThru |
Add-Member -Name ValueCount -MemberType 'NoteProperty' -Value $h.ValueCount -PassThru |
Add-Member -Name Visibility -MemberType 'NoteProperty' -Value $a.Visibility -PassThru |
Add-Member -Name Property -MemberType 'NoteProperty' -Value $h.Property -PassThru |
Add-Member -Name ResolvedCommandName -MemberType 'NoteProperty' -Value $a.ResolvedCommandName -PassThru |
Add-Member -Name Close -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name CreateSubKey -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name DeleteSubKey -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name DeleteSubKeyTree -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name DeleteValue -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Flush -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetSubKeyNames -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetValue -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetValueKind -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetValueNames -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsValidValue -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name OpenSubKey -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name SetValue -MemberType 'ScriptMethod' -Value {} -PassThru
}
if ( $global:_mix -eq $null )
{
$f = gi $PSHOME\\powershell.exe
$t = [type]
$s = ""
$global:_mix = `
Add-Member -InputObject (New-Object PSObject) -Name Mode -MemberType 'NoteProperty' -Value $f.Mode -PassThru |
Add-Member -Name Assembly -MemberType 'NoteProperty' -Value $t.Assembly -PassThru |
Add-Member -Name AssemblyQualifiedName -MemberType 'NoteProperty' -Value $t.AssemblyQualifiedName -PassThru |
Add-Member -Name Attributes -MemberType 'NoteProperty' -Value $f.Attributes -PassThru |
Add-Member -Name BaseType -MemberType 'NoteProperty' -Value $t.BaseType -PassThru |
Add-Member -Name ContainsGenericParameters -MemberType 'NoteProperty' -Value $t.ContainsGenericParameters -PassThru |
Add-Member -Name CreationTime -MemberType 'NoteProperty' -Value $f.CreationTime -PassThru |
Add-Member -Name CreationTimeUtc -MemberType 'NoteProperty' -Value $f.CreationTimeUtc -PassThru |
Add-Member -Name DeclaringMethod -MemberType 'NoteProperty' -Value $t.DeclaringMethod -PassThru |
Add-Member -Name DeclaringType -MemberType 'NoteProperty' -Value $t.DeclaringType -PassThru |
Add-Member -Name Exists -MemberType 'NoteProperty' -Value $f.Exists -PassThru |
Add-Member -Name Extension -MemberType 'NoteProperty' -Value $f.Extension -PassThru |
Add-Member -Name FullName -MemberType 'NoteProperty' -Value $f.FullName -PassThru |
Add-Member -Name GenericParameterAttributes -MemberType 'NoteProperty' -Value $t.GenericParameterAttributes -PassThru |
Add-Member -Name GenericParameterPosition -MemberType 'NoteProperty' -Value $t.GenericParameterPosition -PassThru |
Add-Member -Name GUID -MemberType 'NoteProperty' -Value $t.GUID -PassThru |
Add-Member -Name HasElementType -MemberType 'NoteProperty' -Value $t.HasElementType -PassThru |
Add-Member -Name IsAbstract -MemberType 'NoteProperty' -Value $t.IsAbstract -PassThru |
Add-Member -Name IsAnsiClass -MemberType 'NoteProperty' -Value $t.IsAnsiClass -PassThru |
Add-Member -Name IsArray -MemberType 'NoteProperty' -Value $t.IsArray -PassThru |
Add-Member -Name IsAutoClass -MemberType 'NoteProperty' -Value $t.IsAutoClass -PassThru |
Add-Member -Name IsAutoLayout -MemberType 'NoteProperty' -Value $t.IsAutoLayout -PassThru |
Add-Member -Name IsByRef -MemberType 'NoteProperty' -Value $t.IsByRef -PassThru |
Add-Member -Name IsClass -MemberType 'NoteProperty' -Value $t.IsClass -PassThru |
Add-Member -Name IsCOMObject -MemberType 'NoteProperty' -Value $t.IsCOMObject -PassThru |
Add-Member -Name IsContextful -MemberType 'NoteProperty' -Value $t.IsContextful -PassThru |
Add-Member -Name IsEnum -MemberType 'NoteProperty' -Value $t.IsEnum -PassThru |
Add-Member -Name IsExplicitLayout -MemberType 'NoteProperty' -Value $t.IsExplicitLayout -PassThru |
Add-Member -Name IsGenericParameter -MemberType 'NoteProperty' -Value $t.IsGenericParameter -PassThru |
Add-Member -Name IsGenericType -MemberType 'NoteProperty' -Value $t.IsGenericType -PassThru |
Add-Member -Name IsGenericTypeDefinition -MemberType 'NoteProperty' -Value $t.IsGenericTypeDefinition -PassThru |
Add-Member -Name IsImport -MemberType 'NoteProperty' -Value $t.IsImport -PassThru |
Add-Member -Name IsInterface -MemberType 'NoteProperty' -Value $t.IsInterface -PassThru |
Add-Member -Name IsLayoutSequential -MemberType 'NoteProperty' -Value $t.IsLayoutSequential -PassThru |
Add-Member -Name IsMarshalByRef -MemberType 'NoteProperty' -Value $t.IsMarshalByRef -PassThru |
Add-Member -Name IsNested -MemberType 'NoteProperty' -Value $t.IsNested -PassThru |
Add-Member -Name IsNestedAssembly -MemberType 'NoteProperty' -Value $t.IsNestedAssembly -PassThru |
Add-Member -Name IsNestedFamANDAssem -MemberType 'NoteProperty' -Value $t.IsNestedFamANDAssem -PassThru |
Add-Member -Name IsNestedFamily -MemberType 'NoteProperty' -Value $t.IsNestedFamily -PassThru |
Add-Member -Name IsNestedFamORAssem -MemberType 'NoteProperty' -Value $t.IsNestedFamORAssem -PassThru |
Add-Member -Name IsNestedPrivate -MemberType 'NoteProperty' -Value $t.IsNestedPrivate -PassThru |
Add-Member -Name IsNestedPublic -MemberType 'NoteProperty' -Value $t.IsNestedPublic -PassThru |
Add-Member -Name IsNotPublic -MemberType 'NoteProperty' -Value $t.IsNotPublic -PassThru |
Add-Member -Name IsPointer -MemberType 'NoteProperty' -Value $t.IsPointer -PassThru |
Add-Member -Name IsPrimitive -MemberType 'NoteProperty' -Value $t.IsPrimitive -PassThru |
Add-Member -Name IsPublic -MemberType 'NoteProperty' -Value $t.IsPublic -PassThru |
Add-Member -Name IsSealed -MemberType 'NoteProperty' -Value $t.IsSealed -PassThru |
Add-Member -Name IsSerializable -MemberType 'NoteProperty' -Value $t.IsSerializable -PassThru |
Add-Member -Name IsSpecialName -MemberType 'NoteProperty' -Value $t.IsSpecialName -PassThru |
Add-Member -Name IsUnicodeClass -MemberType 'NoteProperty' -Value $t.IsUnicodeClass -PassThru |
Add-Member -Name IsValueType -MemberType 'NoteProperty' -Value $t.IsValueType -PassThru |
Add-Member -Name IsVisible -MemberType 'NoteProperty' -Value $t.IsVisible -PassThru |
Add-Member -Name LastAccessTime -MemberType 'NoteProperty' -Value $f.LastAccessTime -PassThru |
Add-Member -Name LastAccessTimeUtc -MemberType 'NoteProperty' -Value $f.LastAccessTimeUtc -PassThru |
Add-Member -Name LastWriteTime -MemberType 'NoteProperty' -Value $f.LastWriteTime -PassThru |
Add-Member -Name LastWriteTimeUtc -MemberType 'NoteProperty' -Value $f.LastWriteTimeUtc -PassThru |
Add-Member -Name MemberType -MemberType 'NoteProperty' -Value $t.MemberType -PassThru |
Add-Member -Name MetadataToken -MemberType 'NoteProperty' -Value $t.MetadataToken -PassThru |
Add-Member -Name Module -MemberType 'NoteProperty' -Value $t.Module -PassThru |
Add-Member -Name Name -MemberType 'NoteProperty' -Value $t.Name -PassThru |
Add-Member -Name Namespace -MemberType 'NoteProperty' -Value $t.Namespace -PassThru |
Add-Member -Name Parent -MemberType 'NoteProperty' -Value $f.Parent -PassThru |
Add-Member -Name ReflectedType -MemberType 'NoteProperty' -Value $t.ReflectedType -PassThru |
Add-Member -Name Root -MemberType 'NoteProperty' -Value $f.Root -PassThru |
Add-Member -Name StructLayoutAttribute -MemberType 'NoteProperty' -Value $t.StructLayoutAttribute -PassThru |
Add-Member -Name TypeHandle -MemberType 'NoteProperty' -Value $t.TypeHandle -PassThru |
Add-Member -Name TypeInitializer -MemberType 'NoteProperty' -Value $t.TypeInitializer -PassThru |
Add-Member -Name UnderlyingSystemType -MemberType 'NoteProperty' -Value $t.UnderlyingSystemType -PassThru |
Add-Member -Name PSChildName -MemberType 'NoteProperty' -Value $f.PSChildName -PassThru |
Add-Member -Name PSDrive -MemberType 'NoteProperty' -Value $f.PSDrive -PassThru |
Add-Member -Name PSIsContainer -MemberType 'NoteProperty' -Value $f.PSIsContainer -PassThru |
Add-Member -Name PSParentPath -MemberType 'NoteProperty' -Value $f.PSParentPath -PassThru |
Add-Member -Name PSPath -MemberType 'NoteProperty' -Value $f.PSPath -PassThru |
Add-Member -Name PSProvider -MemberType 'NoteProperty' -Value $f.PSProvider -PassThru |
Add-Member -Name BaseName -MemberType 'NoteProperty' -Value $f.BaseName -PassThru |
Add-Member -Name Clone -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name CompareTo -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Contains -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name CopyTo -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Create -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name CreateObjRef -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name CreateSubdirectory -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Delete -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name EndsWith -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name FindInterfaces -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name FindMembers -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetAccessControl -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetArrayRank -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetConstructor -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetConstructors -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetCustomAttributes -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetDefaultMembers -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetDirectories -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetElementType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetEnumerator -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetEvent -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetEvents -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetField -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetFields -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetFiles -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetFileSystemInfos -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetGenericArguments -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetGenericParameterConstraints -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetGenericTypeDefinition -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetInterface -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetInterfaceMap -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetInterfaces -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetLifetimeService -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetMember -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetMembers -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetMethod -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetMethods -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetNestedType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetNestedTypes -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetObjectData -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetProperties -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetProperty -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetTypeCode -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IndexOf -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IndexOfAny -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name InitializeLifetimeService -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Insert -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name InvokeMember -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsAssignableFrom -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsDefined -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsInstanceOfType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsNormalized -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsSubclassOf -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name LastIndexOf -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name LastIndexOfAny -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name MakeArrayType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name MakeByRefType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name MakeGenericType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name MakePointerType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name MoveTo -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Normalize -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name PadLeft -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name PadRight -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Refresh -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Remove -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Replace -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name SetAccessControl -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Split -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name StartsWith -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Substring -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name ToCharArray -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name ToLower -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name ToLowerInvariant -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name ToUpper -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name ToUpperInvariant -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Trim -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name TrimEnd -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name TrimStart -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Chars -MemberType 'NoteProperty' -Value $s.Chars -PassThru
}
if ( "Add-Member" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Compare-Object" -eq $_cmdlet )
{
$global:_dummy = (Compare-Object 1 2)[0]
}
if ( "ConvertFrom-SecureString" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "ConvertTo-SecureString" -eq $_cmdlet )
{
$global:_dummy = convertto-securestring "P@ssW0rD!" -asplaintext -force
}
if ( "ForEach-Object" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Get-Acl" -eq $_cmdlet )
{
$global:_dummy = Get-Acl
}
if ( "Get-Alias" -eq $_cmdlet )
{
$global:_dummy = (Get-Alias)[0]
}
if ( "Get-AuthenticodeSignature" -eq $_cmdlet )
{
$global:_dummy = Get-AuthenticodeSignature $PSHOME\\powershell.exe
}
if ( "Get-ChildItem" -eq $_cmdlet )
{
$global:_dummy = $global:_forgci
}
if ( "Get-Command" -eq $_cmdlet )
{
$global:_dummy = gcm Add-Content
}
if ( "Get-Content" -eq $_cmdlet )
{
$global:_dummy = (type $PSHOME\\profile.ps1)[0]
}
if ( "Get-Credential" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Get-Culture" -eq $_cmdlet )
{
$global:_dummy = Get-Culture
}
if ( "Get-Date" -eq $_cmdlet )
{
$global:_dummy = Get-Date
}
if ( "Get-Event" -eq $_cmdlet )
{
$global:_dummy = (Get-Event)[0]
}
if ( "Get-EventLog" -eq $_cmdlet )
{
$global:_dummy = Get-EventLog Windows` PowerShell -Newest 1
}
if ( "Get-ExecutionPolicy" -eq $_cmdlet )
{
$global:_dummy = Get-ExecutionPolicy
}
if ( "Get-Help" -eq $_cmdlet )
{
$global:_dummy = Get-Help Add-Content
}
if ( "Get-History" -eq $_cmdlet )
{
$global:_dummy = Get-History -Count 1
}
if ( "Get-Host" -eq $_cmdlet )
{
$global:_dummy = Get-Host
}
if ( "Get-Item" -eq $_cmdlet )
{
$global:_dummy = Get-Item .
}
if ( "Get-ItemProperty" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Get-Location" -eq $_cmdlet )
{
$global:_dummy = Get-Location
}
if ( "Get-Member" -eq $_cmdlet )
{
$global:_dummy = (1|Get-Member)[0]
}
if ( "Get-Module" -eq $_cmdlet )
{
$global:_dummy = (Get-Module)[0]
}
if ( "Get-PfxCertificate" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Get-Process" -eq $_cmdlet )
{
$global:_dummy = ps powershell
}
if ( "Get-PSBreakpoint" -eq $_cmdlet )
{
$global:_dummy =
Add-Member -InputObject (New-Object PSObject) -Name Action -MemberType 'NoteProperty' -Value '' -PassThru |
Add-Member -Name Command -MemberType 'NoteProperty' -Value '' -PassThru |
Add-Member -Name Enabled -MemberType 'NoteProperty' -Value '' -PassThru |
Add-Member -Name HitCount -MemberType 'NoteProperty' -Value '' -PassThru |
Add-Member -Name Id -MemberType 'NoteProperty' -Value '' -PassThru |
Add-Member -Name Script -MemberType 'NoteProperty' -Value '' -PassThru
}
if ( "Get-PSCallStack" -eq $_cmdlet )
{
$global:_dummy = Get-PSCallStack
}
if ( "Get-PSDrive" -eq $_cmdlet )
{
$global:_dummy = Get-PSDrive Function
}
if ( "Get-PSProvider" -eq $_cmdlet )
{
$global:_dummy = Get-PSProvider FileSystem
}
if ( "Get-PSSnapin" -eq $_cmdlet )
{
$global:_dummy = Get-PSSnapin Microsoft.PowerShell.Core
}
if ( "Get-Service" -eq $_cmdlet )
{
$global:_dummy = (Get-Service)[0]
}
if ( "Get-TraceSource" -eq $_cmdlet )
{
$global:_dummy = Get-TraceSource AddMember
}
if ( "Get-UICulture" -eq $_cmdlet )
{
$global:_dummy = Get-UICulture
}
if ( "Get-Variable" -eq $_cmdlet )
{
$global:_dummy = Get-Variable _
}
if ( "Get-WmiObject" -eq $_cmdlet )
{
$global:_dummy = @(iex $str[$i+1])[0]
}
if ( "Group-Object" -eq $_cmdlet )
{
$global:_dummy = 1 | group
}
if ( "Measure-Command" -eq $_cmdlet )
{
$global:_dummy = Measure-Command {}
}
if ( "Measure-Object" -eq $_cmdlet )
{
$global:_dummy = Measure-Object
}
if ( "New-PSDrive" -eq $_cmdlet )
{
$global:_dummy = Get-PSDrive Alias
}
if ( "New-TimeSpan" -eq $_cmdlet )
{
$global:_dummy = New-TimeSpan
}
if ( "Resolve-Path" -eq $_cmdlet )
{
$global:_dummy = $PWD
}
if ( "Select-String" -eq $_cmdlet )
{
$global:_dummy = " " | Select-String " "
}
if ( "Set-Date" -eq $_cmdlet )
{
$global:_dummy = Get-Date
}
if ( $property -ne $null)
{
foreach ( $name in $property.Split(";", "RemoveEmptyEntries" -as [System.StringSplitOptions]) )
{
$global:_dummy = @($global:_dummy.$name)[0]
}
}
}
|
PowerShellCorpus/PoshCode/LibraryInvocation.ps1
|
LibraryInvocation.ps1
|
## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n\nSet-StrictMode -Version Latest\n\n## Return the name of the currently executing script\n## By placing this in a function, we drastically simplify\n## the logic it takes to determine the currently running\n## script\n\nfunction Get-ScriptName\n{\n $myInvocation.ScriptName\n}\n\nfunction Get-ScriptPath\n{\n Split-Path $myInvocation.ScriptName\n}
|
PowerShellCorpus/PoshCode/Beginner event 10 _1.ps1
|
Beginner event 10 _1.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-Hostname.ps1
|
Get-Hostname.ps1
|
# .SYNOPSIS
# Print the hostname of the system.
# .DESCRIPTION
# This function prints the hostname of the system. You can additionally output the DNS
# domain or the FQDN by using the parameters as described below.
# .PARAMETER Short
# (Default) Print only the computername, i.e. the same value as returned by $env:computername
# .PARAMETER Domain
# If set, print only the DNS domain to which the system belongs. Overrides the Short parameter.
# .PARAMETER FQDN
# If set, print the fully-qualified domain name (FQDN) of the system. Overrides the Domain parameter.
param (
[switch]$Short = $true,
[switch]$Domain = $false,
[switch]$FQDN = $false
)
$ipProperties = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()
if ( $FQDN ) {
return "{0}.{1}" -f $ipProperties.HostName, $ipProperties.DomainName
}
if ( $Domain ) {
return $ipProperties.DomainName
}
if ( $Short ) {
return $ipProperties.HostName
}
|
PowerShellCorpus/PoshCode/Export-WLANSettings_1.ps1
|
Export-WLANSettings_1.ps1
|
# ==============================================================================================
#
#
# NAME: Export-WLANSettings.ps1
#
# AUTHOR: Jan Egil Ring
#
# DATE : 14.03.2010
#
# COMMENT: Using netsh.exe to loop through each WLAN on the system and export the settings to the user-provided output-file.
# Must be run with Administrator-privileges for the Key Content (security key) to be exported.
#
#
# ==============================================================================================
Write-Warning "Must be run with Administrator-privileges for Key Content to be exported"
$filepath = Read-Host "Provide path to output-file. E.g. C:\\temp\\wlan.txt"
$wlans = netsh wlan show profiles | Select-String -Pattern "All User Profile" | Foreach-Object {$_.ToString()}
$exportdata = $wlans | Foreach-Object {$_.Replace(" All User Profile : ",$null)}
$exportdata | ForEach-Object {netsh wlan show profiles name="$_" key=clear} | Out-File $filepath
|
PowerShellCorpus/PoshCode/POC $psnull.ps1
|
POC $psnull.ps1
|
$a = @"
using System;
namespace ClassLibrary1
{
#proof of concept
public static class Class1
{
public static string Foo(string value)
{
if (value == null)
return "Special processing of null.";
else
return "'" + value + "' has been processed.";
}
}
}
"@
$b = @"
using System;
namespace testnullD
{
public class nulltest
{
public nulltest(){}
public override string ToString() {return null;}
}
}
"@
add-type $a
add-type $b
$psnull = new-object testnullD.nulltest
add-type $a
[ClassLibrary1.Class1]::Foo($null)
[ClassLibrary1.Class1]::Foo($psnull)
|
PowerShellCorpus/PoshCode/New-Zip_5.ps1
|
New-Zip_5.ps1
|
Function New-Zip
{
<#
.SYNOPSIS
Create a Zip File from any files piped in.
.DESCRIPTION
Requires that you have the SharpZipLib installed, which is available from
http://www.icsharpcode.net/OpenSource/SharpZipLib/
.NOTES
File Name : PowerZip.psm1
Author : Christophe CREMON (uxone) - http://powershell.codeplex.com
Requires : PowerShell V2
.PARAMETER Source
Set the name of the source to zip (file or directory)
.PARAMETER ZipFile
Set the name of the zip file to create
.PARAMETER Recurse
Browse the source recursively
.PARAMETER Include
Include only items you specify
.PARAMETER Exclude
Exclude items you specify
.PARAMETER AbsolutePaths
Preserve the absolute path name of each item in the zip container
.PARAMETER DeleteAfterZip
Delete source items after successful zip
.EXAMPLE
New-Zip -Source C:\\Temp -ZipFile C:\\Archive\\Scripts.zip -Include *.ps1 -DeleteAfterZip
Copies all PS1 files from the C:\\Temp directory to C:\\Archive\\Scripts.zip and delete them after successful ZIP
#>
Param (
[ValidateNotNullOrEmpty()]
[Parameter(
Mandatory = $true)
]
[string] $Source,
[Parameter(
Mandatory = $true)
]
[string] $ZipFile,
[switch] $Recurse,
[array] $Include,
[array] $Exclude,
[switch] $AbsolutePaths,
[switch] $DeleteAfterZip )
$LoadAssembly = [System.Reflection.Assembly]::LoadWithPartialName("ICSharpCode.SharpZipLib")
if ( -not $LoadAssembly ) { throw "! Assembly not found {ICSharpCode.SharpZipLib}" }
$IncludeArgument,$ExcludeArgument,$RecurseArgument = $null
$ErrorsArray,$ItemsNotZipped = @()
$Source = $Source -replace "\\\\$|\\/$",""
$CheckSource = Get-Item -Path $Source -Force -ErrorAction SilentlyContinue
if ( -not $CheckSource ) { Write-Output "! Source not found {$Source}" }
else
{
if ( $CheckSource.psIsContainer )
{
$RootPath = ( Resolve-Path -Path $Source -ErrorAction SilentlyContinue ).ProviderPath
}
else
{
$RootPath = ( Resolve-Path -Path $Source -ErrorAction SilentlyContinue ).ProviderPath
if ( $RootPath )
{
$RootPath = Split-Path -Path $RootPath -ErrorAction SilentlyContinue
}
}
}
if ( $ZipFile -notmatch "\\.zip$" ) { $ZipFile = $ZipFile -replace "$",".zip" }
if ( $Recurse -eq $true ) { $RecurseArgument = "-Recurse" }
if ( $Include )
{
$Include = $Include -join ","
$IncludeArgument = "-Include $Include"
$Source = $Source+"\\*"
}
if ( $Exclude )
{
$Exclude = $Exclude -join ","
$ExcludeArgument = "-Exclude $Exclude"
}
$GetCommand = "Get-ChildItem -Path '$Source' $RecurseArgument $IncludeArgument $ExcludeArgument -Force -ErrorAction SilentlyContinue"
$ItemsToZip = Invoke-Expression -Command $GetCommand
$SizeBeforeZip = ( $ItemsToZip | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue ).Sum
$SizeBeforeZipInMB = $SizeBeforeZip | ForEach-Object { "{0:N2}" -f ($_ / 1MB) }
if ( -not $SizeBeforeZip )
{
Write-Output "NOTHING TO ZIP"
return $true
break
}
$CreateZIPContainer = New-Item -ItemType File -Path $ZipFile -Force -ErrorAction SilentlyContinue
if ( -not $CreateZIPContainer ) { Write-Output "! Unable to create ZIP container {$ZipFile}" }
else { $ZipFile = ( Resolve-Path -Path $ZipFile -ErrorAction SilentlyContinue ).ProviderPath }
$oZipOutputStream = New-Object -TypeName ICSharpCode.SharpZipLib.Zip.ZipOutputStream([System.IO.File]::Create($ZipFile))
if ( $? -ne $true )
{
$ErrorsArray += @("! Unable to create ZIP stream {$ZipFile}")
}
[byte[]] $Buffer = New-Object Byte[] 4096
$StartTime = Get-Date
Write-Output "`n===================================`n=> Start Time : $($StartTime.ToString(""dd/MM/yyyy-HH:mm:ss""))`n"
Write-Output "TOTAL SIZE BEFORE ZIP : {$SizeBeforeZipInMB MB}`n"
foreach ( $Item in $ItemsToZip )
{
if ( $Item.FullName -ne $ZipFile )
{
if ( Test-Path ( $Item.FullName ) -ErrorAction SilentlyContinue )
{
$ZipEntry = $Item.FullName
if ( -not $AbsolutePaths )
{
$ReplacePath = [Regex]::Escape( $RootPath+"\\" )
$ZipEntry = $Item.FullName -replace $ReplacePath,""
}
if ( $Item.psIsContainer -eq $true )
{
if ( $Recurse -eq $true )
{
Write-Output "Processing ZIP of Directory {$($Item.FullName)} ..."
$OldErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
$oZipEntry = New-Object -TypeName ICSharpCode.SharpZipLib.Zip.ZipEntry("$ZipEntry/")
$oZipEntry.DateTime = ([System.IO.FileInfo] $Item.FullName).LastWriteTime
$oZipEntry.Size = ([System.IO.FileInfo] $Item.FullName).Length
$oZipOutputStream.PutNextEntry($oZipEntry)
if ( $? -ne $true )
{
$ItemsNotZipped += @($Item.FullName)
$ErrorsArray += @("! Unable to ZIP Directory {$($Item.FullName)}")
}
$ErrorActionPreference = $OldErrorActionPreference
}
}
else
{
Write-Output "Processing ZIP of File {$($Item.FullName)} ..."
$OldErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
$FileStream = [IO.File]::OpenRead($Item.FullName)
$oZipEntry = New-Object -TypeName ICSharpCode.SharpZipLib.Zip.ZipEntry("$ZipEntry")
$oZipEntry.DateTime = ([System.IO.FileInfo] $Item.FullName).LastWriteTime
$oZipEntry.Size = ([System.IO.FileInfo] $Item.FullName).Length
$oZipOutputStream.PutNextEntry($oZipEntry)
[ICSharpCode.SharpZipLib.Core.StreamUtils]::Copy($FileStream,$oZipOutputStream,$Buffer)
if ( $? -ne $true )
{
$ItemsNotZipped += @($Item.FullName)
$ErrorsArray += @("! Unable to ZIP File {$($Item.FullName)}")
}
$FileStream.Close()
$ErrorActionPreference = $OldErrorActionPreference
}
}
}
}
$oZipOutputStream.Finish()
$oZipOutputStream.Close()
if ( $? -eq $true )
{
if ( $DeleteAfterZip -eq $true )
{
$ItemsToZip | Where-Object { $ItemsNotZipped -notcontains $_.FullName } | ForEach-Object {
if ( $_.psIsContainer -ne $true )
{
if ( Test-Path ( $_.FullName ) -ErrorAction SilentlyContinue )
{
Write-Output "Processing Delete of File {$($_.FullName)} ..."
$RemoveItem = Remove-Item -Path $_.FullName -Force -ErrorAction SilentlyContinue
if ( $? -ne $true )
{
$ErrorsArray += @("! Unable to Delete File {$($_.FullName)}")
}
}
}
}
if ( $Recurse )
{
$ItemsToZip | Where-Object { $ItemsNotZipped -notcontains ( Split-Path -Parent $_.FullName ) } | ForEach-Object {
if ( $_.psIsContainer -eq $true )
{
if ( Test-Path ( $_.FullName ) -ErrorAction SilentlyContinue )
{
Write-Output "Processing Delete of Directory {$($_.FullName)} ..."
$RemoveItem = Remove-Item -Path $_.FullName -Force -Recurse -ErrorAction SilentlyContinue
if ( $? -ne $true )
{
$ErrorsArray += @("! Unable to Delete Directory {$($_.FullName)}")
}
}
}
}
}
}
Write-Output "`nZIP File Created {$ZipFile} ...`n"
}
else
{
$ErrorsArray += @("! ZIP Archive {$ZipFile} Creation Failed`n")
}
$EndTime = Get-Date
$ExecutionTime = ($EndTime-$StartTime)
Write-Output "`nExecution Time : $ExecutionTime`n"
Write-Output "=> End Time : $($EndTime.ToString(""dd/MM/yyyy-HH:mm:ss""))`n=================================`n"
if ( $ErrorsArray )
{
Write-Output "`n[ ERRORS OCCURED ]"
$ErrorsArray
return $false
}
else
{
$SizeAfterZip = ( Get-Item -Path $ZipFile -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue ).Sum
$SizeAfterZipInMB = $SizeAfterZip | ForEach-Object { "{0:N2}" -f ($_ / 1MB) }
Write-Output "`nTOTAL SIZE AFTER ZIP : {$SizeAfterZipInMB MB}`n"
$Gain = ( $SizeBeforeZip - $SizeAfterZip )
$GainInMB = $Gain | ForEach-Object { "{0:N2}" -f ($_ / 1MB) }
if ( $Gain -gt 0 )
{
$GainInPercent = (($SizeBeforeZip - $SizeAfterZip) / $SizeBeforeZip) * 100 | ForEach-Object { "{0:N2}" -f $_ }
Write-Output "GAIN : {$GainInMB MB} ($GainInPercent %)`n"
}
return $true
}
}
|
PowerShellCorpus/PoshCode/Add-Namespace_1.ps1
|
Add-Namespace_1.ps1
|
trap [System.Management.Automation.RuntimeException]
{
$entryException = $_
if ($_.CategoryInfo.Category -eq [System.Management.Automation.ErrorCategory]::InvalidOperation)
{
if ($_.FullyQualifiedErrorId -eq "TypeNotFound")
{
$targetName = $_.CategoryInfo.TargetName
try
{
$isUnresolvable = $global:__ambiguousTypeNames.Contains($targetName)
}
catch
{
throw $entryException
}
if ($isUnresolvable)
{
$message = New-Object System.Text.StringBuilder
$message.AppendFormat("The type [{0}] is ambiguous. Specify one of the following: ", $targetName).AppendLine() | Out-Null
[System.Type]::GetType("System.Management.Automation.TypeAccelerators")::Get.GetEnumerator() | ForEach-Object {
if (($_.Key.Split('.'))[-1] -eq $targetName)
{
$message.Append($_.Key).AppendLine() | Out-Null
}
}
$exception = New-Object System.Management.Automation.RuntimeException -ArgumentList $message.ToString()
$errorId = "TypeNotFound"
$errorCategory = [System.Management.Automation.ErrorCategory]::InvalidOperation
$targetObject = $_.TargetObject
throw New-Object System.Management.Automation.ErrorRecord -ArgumentList $exception, $errorId, $errorCategory, $targetObject
}
}
}
}
<#
.SYNOPSIS
Imports the types in the specified namespaces in the specified assemblies.
.DESCRIPTION
The Add-Namespace function adds a type accelerator for each type found in the specified namespaces in the specified assemblies that satisfy a set of conditions. For more information see the NOTES section.
.PARAMETER Assembly
The namespace to import.
.PARAMETER Namespace
Specifies one or more namespaces to import.
.INPUTS
System.Reflection.Assembly
You can pipe an assembly to Add-Namespace.
.OUTPUTS
None
This function does not return any output.
.NOTES
The type accelerator for the type is added if the type:
- Has a base type which is not System.Attribute, System.Delegate or System.MulticastDelegate
- Is not abstract
- Is not an interface
- Is not nested
- Is public
- Is visible
- Is qualified by the namespace specified in the Namespace parameter
This function also comes with an exception handler in the form of a trap block. Type name collisions occur when a type has the same name of another type which is in a different namespace. When this happens, the function adds or replaces the type accelerator for that type using its fully-qualified type name. If a type resolution occurs during runtime, the trap block will determine if the type was unresolved during any of the calls made to Add-Namespace and throw an exception listing valid replacements.
The type accelerators added by this function exist only in the current session. To use the type accelerators in all sessions, add them to your Windows PowerShell profile. For more information about the profile, see about_profiles.
Be aware that namspaces can span multiple assemblies, in which case you would have to import the namespace for each assembly that it exists in.
This function will not attempt to add or replace types which already exist under the same name.
.EXAMPLE
C:\\PS> [System.Reflection.Assembly]::LoadWithPartialName("mscorlib") | Add-Namespace System.Reflection
C:\\PS> [Assembly]::LoadWithPartialName("System.Windows.Forms")
This example shows how to import namespaces from an assembly. The assembly must be loaded non-reflectively into the current application domain.
.EXAMPLE
C:\\PS> $assemblies = @([System.Reflection.Assembly]::LoadWithPartialName("mscorlib"), [System.Reflection.Assembly]::LoadWithPartialName("System"), [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms"), [System.Reflection.Assembly]::LoadWithPartialName("System.Xml"), [System.Reflection.Assembly]::LoadWithPartialName("System.Xml.Linq"))
C:\\PS> $assemblies | Add-Namespace System, System.Collections, System.Collections.Generic, System.Net, System.Net.NetworkInformation, System.Reflection, System.Windows.Forms, System.Xml.Linq
This example shows how to import multiple namespaces from multiple assemblies.
.LINK
about_trap
#>
function Add-Namespace
{
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[Parameter(ValueFromPipeline = $true)]
[System.Reflection.Assembly]$Assembly,
[Parameter(Mandatory = $true, Position = 0)]
[ValidateNotNullOrEmpty()]
[String[]]$Namespace
)
BEGIN
{
if ($global:__ambiguousTypeNames -eq $null)
{
$global:__ambiguousTypeNames = New-Object 'System.Collections.Generic.List[System.String]'
}
$genericRegex = [Regex]'(?<Name>.*)`\\d+'
$typeAccelerators = [System.Type]::GetType("System.Management.Automation.TypeAccelerators")
$typeDictionary = $typeAccelerators::Get
}
PROCESS
{
$_.GetTypes() | Where-Object {
($_.BaseType -ne [System.Attribute]) -and
($_.BaseType -ne [System.Delegate]) -and
($_.BaseType -ne [System.MulticastDelegate]) -and
!$_.IsAbstract -and
!$_.IsInterface -and
!$_.IsNested -and
$_.IsPublic -and
$_.IsVisible -and
($Namespace -contains $_.Namespace)
} | ForEach-Object {
$name = $_.Name
$fullName = $_.FullName
if ($_.IsGenericType)
{
if ($_.Name -match $genericRegex)
{
$name = $Matches["Name"]
}
if ($_.FullName -match $genericRegex)
{
$fullName = $Matches["Name"]
}
}
if ($typeDictionary.ContainsKey($name))
{
if ($typeDictionary[$name] -eq $_)
{
return
}
}
if ($typeDictionary.ContainsKey($fullName))
{
if ($typeDictionary[$fullName] -eq $_)
{
return
}
}
if ($global:__ambiguousTypeNames.Contains($name))
{
$typeAccelerators::Add($fullName, $_)
return
}
if ($typeDictionary.ContainsKey($name))
{
$type = $typeDictionary[$name]
if ($_ -ne $type)
{
$global:__ambiguousTypeNames.Add($name)
$newName = $typeDictionary[$name].FullName
if ($newName -match $genericRegex)
{
$newName = $Matches["Name"]
}
$typeAccelerators::Remove($name)
$typeAccelerators::Add($newName, $type)
$typeAccelerators::Add($fullName, $_)
}
return
}
$typeAccelerators::Add($name, $_)
} | Out-Null
}
END
{
}
}
# Sample usage
# You can do this as an initialization task for your script
@(
[System.Reflection.Assembly]::LoadWithPartialName("mscorlib"),
[System.Reflection.Assembly]::LoadWithPartialName("System"),
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms"),
[System.Reflection.Assembly]::LoadWithPartialName("System.Xml"),
[System.Reflection.Assembly]::LoadWithPartialName("System.Xml.Linq")
) | Add-Namespace -Namespace `
System,
System.Collections,
System.Collections.Generic,
System.Net,
System.Net.NetworkInformation,
System.Reflection,
System.Windows.Forms,
System.Xml.Linq
|
PowerShellCorpus/PoshCode/Enable-BreakOnError.ps1
|
Enable-BreakOnError.ps1
|
#############################################################################\n##\n## Enable-BreakOnError\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\nCreates a breakpoint that only fires when PowerShell encounters an error\n\n.EXAMPLE\n\nPS >Enable-BreakOnError\n\nID Script Line Command Variable Action\n-- ------ ---- ------- -------- ------\n 0 Out-Default ...\n\nPS >1/0\nEntering debug mode. Use h or ? for help.\n\nHit Command breakpoint on 'Out-Default'\n\n\nPS >$error\nAttempted to divide by zero.\n\n#>\n\nSet-StrictMode -Version Latest\n\n## Store the current number of errors seen in the session so far\n$GLOBAL:EnableBreakOnErrorLastErrorCount = $error.Count\n\nSet-PSBreakpoint -Command Out-Default -Action {\n\n ## If we're generating output, and the error count has increased,\n ## break into the debugger.\n if($error.Count -ne $EnableBreakOnErrorLastErrorCount)\n {\n $GLOBAL:EnableBreakOnErrorLastErrorCount = $error.Count\n break\n }\n}
|
PowerShellCorpus/PoshCode/Deleted-ObjectsAD.ps1
|
Deleted-ObjectsAD.ps1
|
param(
$Domen
)
function Ping ($Name){
$ping = new-object System.Net.NetworkInformation.Ping
if ($ping.send($Name).Status -eq "Success") {$True}
else {$False}
trap {Write-Verbose "Error Ping"; $False; continue}
}
[string[]]$ObjectPath
[string[]]$Disks
[string[]]$Info
[string[]]$Computers
$Computers = Get-QADComputer -Service $Domen -OSName '*XP*','*Vista*','*7*' -SizeLimit 0 -ErrorAction SilentlyContinue |
Select-Object name -ExpandProperty name
foreach ($Computer in $Computers){
$Alive = Ping $Computer
if ($Alive -eq "True"){
Write-Host "Seach $Computer" -BackgroundColor Blue
trap {Write-Host "Error WmiObject $Computer";Continue}
$Disks += Get-WmiObject win32_logicaldisk -ComputerName $Computer -ErrorAction SilentlyContinue |
Where-Object {$_.Size -ne $null}
if ($Disks){
foreach ($Disk in $Disks){
if ($Disk.Name -like "*:*") {
$Disk = $Disk.Name.Replace(":","$")
}
trap {Write-Host "Error ChildItem $Computer";Continue}
$ObjectPath += Get-ChildItem "\\\\$Computer\\$Disk\\*" -Recurse -ErrorAction SilentlyContinue
if ($ObjectPath){
foreach ($Object in $ObjectsDeleted){
$ObjectPath |
Where-Object {$_.Name -like $Object} |
% { $Path = $_.FullName;
Remove-Item $_.FullName -Recurse -Force -ErrorAction SilentlyContinue;
$Info += "" | Select-Object @{e={$Path};n='Path'},`
@{e={"Delete"};n='Action'}
}
}
}
}
}
}
}
$Info | Format-Table -AutoSize -ErrorAction SilentlyContinue
|
PowerShellCorpus/PoshCode/Get-Netstat 1,2.ps1
|
Get-Netstat 1,2.ps1
|
$null, $null, $null, $null, $netstat = netstat -a -n -o
$ps = Get-Process
[regex]$regexTCP = '(?<Protocol>\\S+)\\s+((?<LAddress>(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?))|(?<LAddress>\\[?[0-9a-fA-f]{0,4}(\\:([0-9a-fA-f]{0,4})){1,7}\\%?\\d?\\]))\\:(?<Lport>\\d+)\\s+((?<Raddress>(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?))|(?<RAddress>\\[?[0-9a-fA-f]{0,4}(\\:([0-9a-fA-f]{0,4})){1,7}\\%?\\d?\\]))\\:(?<RPort>\\d+)\\s+(?<State>\\w+)\\s+(?<PID>\\d+$)'
[regex]$regexUDP = '(?<Protocol>\\S+)\\s+((?<LAddress>(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?))|(?<LAddress>\\[?[0-9a-fA-f]{0,4}(\\:([0-9a-fA-f]{0,4})){1,7}\\%?\\d?\\]))\\:(?<Lport>\\d+)\\s+(?<RAddress>\\*)\\:(?<RPort>\\*)\\s+(?<PID>\\d+)'
[psobject]$process = "" | Select-Object Protocol, LocalAddress, Localport, RemoteAddress, Remoteport, State, PID, ProcessName
foreach ($net in $netstat)
{
switch -regex ($net.Trim())
{
$regexTCP
{
$process.Protocol = $matches.Protocol
$process.LocalAddress = $matches.LAddress
$process.Localport = $matches.LPort
$process.RemoteAddress = $matches.RAddress
$process.Remoteport = $matches.RPort
$process.State = $matches.State
$process.PID = $matches.PID
$process.ProcessName = ( $ps | Where-Object {$_.Id -eq $matches.PID} ).ProcessName
}
$regexUDP
{
$process.Protocol = $matches.Protocol
$process.LocalAddress = $matches.LAddress
$process.Localport = $matches.LPort
$process.RemoteAddress = $matches.RAddress
$process.Remoteport = $matches.RPort
$process.State = $matches.State
$process.PID = $matches.PID
$process.ProcessName = ( $ps | ? {$_.Id -eq $matches.PID} ).ProcessName
}
}
$process
}
|
PowerShellCorpus/PoshCode/Findup_1.ps1
|
Findup_1.ps1
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
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;
// Checked = false; // Set if the file has already been checked.
// string SHA512_1st1K; // SHA512 hash of first 1K bytes.
// string SHA512_All; // SHA512 hash of complete file.
}
public FileInfo FI { get; private set; }
public bool Checked { get; set; }
public string SHA512_1st1K { get; set; }
public string SHA512_All { get; set; }
}
class Recurse // Return FileInfoExt list of files matching filenames, file specifications (IE: *.*), and in directories in pathRec
{
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);
returnList.AddRange(Dir.GetFiles(searchPattern).Select(s => new FileInfoExt(s)));
}
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
{
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);
}
}
return;
}
}
class Program
{
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;
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(" ");
Console.WriteLine("Examples: findup.exe c:\\\\finances -recurse");
Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data -recurse -delete -noprompt");
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;
}
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;
}
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 (fs[i].FI.FullName == fs[c].FI.FullName) // don't count the same file as a match.
continue;
if (fs[i].SHA512_1st1K == null) // check/hash first 1K first.
fs[i].SHA512_1st1K = ComputeInitialHash(fs[i].FI.FullName);
if (fs[c].SHA512_1st1K == null)
fs[c].SHA512_1st1K = ComputeInitialHash(fs[c].FI.FullName);
if (fs[i].SHA512_1st1K != fs[c].SHA512_1st1K) // if the 1st 1K has the same hash..
continue;
if (fs[i].SHA512_1st1K == null) // if hash error, then skip to next file.
continue;
if (fs[i].FI.Length > 1024) // skip hashing the file again if < 1024 bytes.
{
if (fs[i].SHA512_All == null) // check/hash the rest of the files.
fs[i].SHA512_All = ComputeFullHash(fs[i].FI.FullName);
if (fs[c].SHA512_All == null)
fs[c].SHA512_All = ComputeFullHash(fs[c].FI.FullName);
if (fs[i].SHA512_All != fs[c].SHA512_All)
continue;
if (fs[i].SHA512_All == null) // check for hash fail before declairing a duplicate.
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: " + fs.Count);
Console.WriteLine("Duplicate files: " + numOfDupes);
Console.WriteLine("Bytes in duplicate files: " + bytesInDupes);
Console.WriteLine("Duplicates deleted: " + delFiles);
Console.WriteLine("Bytes recovered: " + bytesRec);
return;
}
private static readonly byte[] readBuf = new byte[1024];
private static string ComputeInitialHash(string path)
{
try
{
using (var stream = File.OpenRead(path))
{
var length = stream.Read(readBuf, 0, readBuf.Length);
var hash = SHA512.Create().ComputeHash(readBuf, 0, length);
return BitConverter.ToString(hash);
}
}
catch (Exception e)
{
Console.WriteLine("Hash Error: " + e.Message);
return (null);
}
}
private static string ComputeFullHash(string path)
{
try
{
using (var stream = File.OpenRead(path))
{
return BitConverter.ToString(SHA512.Create().ComputeHash(stream));
}
}
catch (Exception e)
{
Console.WriteLine("Hash error: " + e.Message);
return (null);
}
}
}
}
|
PowerShellCorpus/PoshCode/chkhash_25.ps1
|
chkhash_25.ps1
|
# calculate SHA512 of file.
function Get-SHA512([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]'))
{
$stream = $null;
$cryptoServiceProvider = [System.Security.Cryptography.SHA512CryptoServiceProvider];
$hashAlgorithm = new-object $cryptoServiceProvider
$stream = $file.OpenRead();
$hashByteArray = $hashAlgorithm.ComputeHash($stream);
$stream.Close();
## We have to be sure that we close the file stream if any exceptions are thrown.
trap
{
if ($stream -ne $null)
{
$stream.Close();
}
break;
}
foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }}
return [string]$result;
}
function noequal ( $first, $second)
{
if (!($second) -or $second -eq "") {return $true}
$first=join-path $first "\\"
foreach($s in $second)
{
if ($first.tolower().startswith($s.tolower())) {return $false}
}
return $true
}
function WriteFileName ( [string]$writestr ) # this function prints multiline messages on top of each other, good for iterating through filenames without filling
{ # the console with a huge wall of text. Call this function to print each of the filename messages, then call WriteFileNameEnd when done
# before printing anything else, so that you are not printing into a long file name with extra characters from it visible.
if ($global:lastlen -eq $null) {$global:lastlen=0}
$ctop=[console]::cursortop
[console]::cursorleft=0
$oldwritestrlen=$writestr.length
$spaces = ""
if ($global:lastlen -gt $writestr.length)
{
$spaces = " " * ($global:lastlen-$writestr.length)
}
$writelines = [math]::divrem($writestr.length, [console]::bufferwidth, [ref]$null)
$cwe = ($writelines-([console]::bufferheight-$ctop))+1 # calculate where text has scroll back to.
if ($cwe -gt 0) {$ctop-=($cwe)}
write-host "$writestr" -nonewline
$global:oldctop=[console]::cursortop
if ([console]::cursorleft -ne 0) {$global:oldctop+=1}
write-host "$spaces" -nonewline
$global:lastlen = $oldwritestrlen
[console]::cursortop=$ctop
[console]::cursorleft=0
}
function WriteFileNameEnd ( ) # call this function when you are done overwriting messages on top of each other
{ # and before printing something else
if ($global:oldctop -ne $null)
{
[console]::cursortop=$global:oldctop
[console]::cursorleft=0
}
$global:oldctop=$null
$global:lastlen=$null
}
# chkhash.ps1 [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #3] [-u] [-h [path of .xml database]]
# -u updates the XML file database and exits
# otherwise, all files are checked against the XML file database.
# -h specifies location of xml hash database
$hashespath=".\\hashes.xml"
del variable:\\args3 -ea 0
del variable:\\args2 -ea 0
del variable:\\xfiles -ea 0
del variable:\\files -ea 0
del variable:\\exclude -ea 0
$args3=@()
$args2=@($args)
$nu = 0
$errs = 0
$fc = 0
$fm = 0
$upd = $false
$create = $false
"ChkHash.ps1 - ChkHash.ps1 can create a .XML database of files and their SHA-512 hashes and check files against the database, "
"in order to detect corrupt or hacked files."
""
".\\chkhash.ps1 -h for usage."
""
for($i=0;$i -lt $args2.count; $i++)
{
if ($args2[$i] -like "-h*") # -help specified?
{
"Usage: .\\chkhash.ps1 [-h] [-u] [-c] [-x <file path of hashes .xml database>] [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #n] [-e <Dirs>]"
"Options: -h - Help display."
" -c - Create hash database. If .xml hash database does not exist, -c will be assumed."
" -u - Update changed files and add new files to existing database."
" -x - specifies .xml database file path to use. Default is .\\hashes.xml"
" -e - exclude dirs. Put this after the files/dirs you want to check with SHA512 and needs to be fullpath (e.g. c:\\users\\bob not ..\\bob)."
""
"Examples: PS>.\\chkhash.ps1 c:\\ d:\\ -c -x c:\\users\\bob\\hashes\\hashes.xml"
" [hash all files on c:\\ and d:\\ and subdirs, create and store hashes in c:\\users\\bob\\hashes\\hashes.xml]"
" PS>.\\chkhash.ps1 c:\\users\\alice\\pictures\\sunset.jpg -u -x c:\\users\\alice\\hashes\\pictureshashes.xml]"
" [hash c:\\users\\alice\\pictures\\sunset.jpg and add or update the hash to c:\\users\\alice\\hashes\\picturehashes.xml"
" PS>.\\chkhash.ps1 c:\\users\\eve\\documents d:\\media\\movies -x c:\\users\\eve\\hashes\\private.xml"
" [hash all files in c:\\users\\eve\\documents and d:\\media\\movies, check against hashes stored in c:\\users\\eve\\hashes\\private.xml"
" or create it and store hashes there if not present]"
" PS>.\\chkhash.ps1 c:\\users\\eve -x c:\\users\\eve\\hashes\\private.xml -e c:\\users\\eve\\hashes"
" [hash all files in c:\\users\\eve and subdirs, check hashes against c:\\users\\eve\\hashes\\private.xml or store if not present, exclude "
" c:\\users\\eve\\hashes directory and subdirs]"
" PS>.\\chkhash.p1s c:\\users\\ted\\documents\\f* d:\\data -x d:\\hashes.xml -e d:\\data\\test d:\\data\\favorites -u"
" [hash all files starting with 'f' in c:\\users\\ted\\documents, and all files in d:\\data, add or update hashes to"
" existing d:\\hashes.xml, exclude d:\\data\\test and d:\\data\\favorites and subdirs]"
" PS>.\\chkhash -x c:\\users\\alice\\hashes\\hashes.xml"
" [Load hashes.xml and check hashes of all files contained within.]"
""
"Note: files in subdirectories of any specified directory are automatically processed."
" if you specify only an -x option, or no option and .\\hash.xml exists, only files in the database will be checked."
exit
}
if ($args2[$i] -like "-u*") {$upd=$true;continue} # Update and Add new files to database?
if ($args2[$i] -like "-c*") {$create=$true;continue} # Create database specified?
if ($args2[$i] -like "-x*")
{
$i++ # Get hashes xml database path
if ($i -ge $args2.count)
{
write-host "-X specified but no file path of .xml database specified. Exiting."
exit
}
$hashespath=$args2[$i]
continue
}
if ($args2[$i] -like "-e*") # Exclude files, dirs
{
while (($i+1) -lt $args2.count)
{
$i++
if ($args2[$i] -like "-*") {break}
$exclude+=@(join-path $args2[$i] "\\") # collect array of excluded directories.
}
continue
}
$args3+=@($args2[$i]) # Add files/dirs
}
if ($args3.count -ne 0)
{
# Get list of files and SHA512 hash them.
"Enumerating files from specified locations..."
$files=@(dir $args3 -recurse -ea 0 | ?{$_.mode -notmatch "d"} | ?{noequal $_.directoryname $exclude}) # Get list of files, minus directories and minus files in excluded paths
if ($files.count -eq 0) {"No files found. Exiting."; exit}
if ($create -eq $true -or !(test-path $hashespath)) # Create database?
{
# Create SHA512 hashes of files and write to new database
$files = $files | %{WriteFileName "SHA-512 Hashing: `"$($_.fullname)`" ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
WriteFileNameEnd
$files |export-clixml $hashespath
"Created $hashespath"
"$($files.count) file hash(es) saved. Exiting."
exit
}
write-host "Loading file hashes from $hashespath..." -nonewline
$xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database
if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit}
}
else
{
if (!(test-path $hashespath)) {"No database found or specified, exiting."; exit}
write-host "Loading file hashes from $hashespath..." -nonewline
$xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database and check it
if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit}
$files=$xfiles
}
"Loaded $($xfiles.count) file hash(es)."
$hash=@{}
for($x=0;$x -lt $xfiles.count; $x++) # Build dictionary (hash) of filenames and indexes into file array
{
if ($hash.contains($xfiles[$x].fullname)) {continue}
$hash.Add($xfiles[$x].fullname,$x)
}
foreach($f in $files)
{
if ((get-item -ea 0 -literalpath $f.fullname) -eq $null) {continue} # skip if file no longer exists.
$n=($hash.($f.fullname))
if ($n -eq $null)
{
$nu++ # increment needs/needed updating count
if ($upd -eq $false) {WriteFileNameEnd; "Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue
WriteFileName "SHA-512 Hashing `"$($f.fullname)`" ..."
# Create SHA512 hash of file
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force}
$xfiles+=@($f) # then add file + hash to list
continue
}
WriteFileName "SHA-512 Hashing and checking: `"$($f.fullname)`" ..."
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force}
$fc++ # File checked increment.
if ($xfiles[$n].SHA512 -eq $f.SHA512) # Check SHA512 for mixmatch.
{$fm++;continue} # if matched, increment file matches and continue loop
$errs++ # increment mixmatches
WriteFileNameEnd
if ($upd -eq $true) { $xfiles[$n]=$f; "Updated `"$($f.fullname)`"";continue}
"Bad SHA-512 found: `"$($f.fullname)`""
}
WriteFileNameEnd # restore cursor position after last write string
if ($upd -eq $true) # if database updated
{
$xfiles|export-clixml $hashespath # write xml database
"Updated $hashespath"
"$nu file hash(es) added to database."
"$errs file hash(es) updated in database."
exit
}
"$errs SHA-512 mixmatch(es) found."
"$fm file(s) SHA512 matched."
"$fc file(s) checked total."
if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
|
PowerShellCorpus/PoshCode/ISE-CopyOutPutToEditor.ps1
|
ISE-CopyOutPutToEditor.ps1
|
function ISE-CopyOutPutToEditor () {
$count = $psise.CurrentOpenedRunspace.OpenedFiles.count
$psIse.CurrentOpenedRunspace.OpenedFiles.Add()
$Newfile = $psIse.CurrentOpenedRunspace.OpenedFiles[$count]
$Newfile.Editor.Text = $psIse.CurrentOpenedRunspace.output.Text
$Newfile.Editor.Focus()
# $psise.CurrentOpenedFile.editor.Text = $psIse.CurrentOpenedRunspace.output.Text
}
$null = $psIse.CustomMenu.Submenus.Add("Copy Output to Editor", {ISE-CopyOutPutToEditor}, 'Ctrl+O')
|
PowerShellCorpus/PoshCode/Invoke-SqlCmd_8.ps1
|
Invoke-SqlCmd_8.ps1
|
#######################
<#
.SYNOPSIS
Runs a T-SQL script.
.DESCRIPTION
Runs a T-SQL script. Invoke-Sqlcmd2 only returns message output, such as the output of PRINT statements when -verbose parameter is specified.
Paramaterized queries are supported.
.INPUTS
None
You cannot pipe objects to Invoke-Sqlcmd2
.OUTPUTS
System.Data.DataTable
.EXAMPLE
Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -Query "SELECT login_time AS 'StartTime' FROM sysprocesses WHERE spid = 1"
This example connects to a named instance of the Database Engine on a computer and runs a basic T-SQL query.
StartTime
-----------
2010-08-12 21:21:03.593
.EXAMPLE
Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -InputFile "C:\\MyFolder\\tsqlscript.sql" | Out-File -filePath "C:\\MyFolder\\tsqlscript.rpt"
This example reads a file containing T-SQL statements, runs the file, and writes the output to another file.
.EXAMPLE
Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -Query "PRINT 'hello world'" -Verbose
This example uses the PowerShell -Verbose parameter to return the message output of the PRINT command.
VERBOSE: hello world
.NOTES
Version History
v1.0 - Chad Miller - Initial release
v1.1 - Chad Miller - Fixed Issue with connection closing
v1.2 - Chad Miller - Added inputfile, SQL auth support, connectiontimeout and output message handling. Updated help documentation
v1.3 - Chad Miller - Added As parameter to control DataSet, DataTable or array of DataRow Output type
v1.4 - Justin Dearing <zippy1981 _at_ gmail.com> - Added the ability to pass parameters to the query.
v1.4.1 - Paul Bryson <atamido _at_ gmail.com> - Added fix to check for null values in parameterized queries and replace with [DBNull]
#>
function Invoke-Sqlcmd2
{
[CmdletBinding()]
param(
[Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance,
[Parameter(Position=1, Mandatory=$false)] [string]$Database,
[Parameter(Position=2, Mandatory=$false)] [string]$Query,
[Parameter(Position=3, Mandatory=$false)] [string]$Username,
[Parameter(Position=4, Mandatory=$false)] [string]$Password,
[Parameter(Position=5, Mandatory=$false)] [Int32]$QueryTimeout=600,
[Parameter(Position=6, Mandatory=$false)] [Int32]$ConnectionTimeout=15,
[Parameter(Position=7, Mandatory=$false)] [ValidateScript({test-path $_})] [string]$InputFile,
[Parameter(Position=8, Mandatory=$false)] [ValidateSet("DataSet", "DataTable", "DataRow")] [string]$As="DataRow" ,
[Parameter(Position=9, Mandatory=$false)] [System.Collections.IDictionary]$SqlParameters
)
if ($InputFile)
{
$filePath = $(resolve-path $InputFile).path
$Query = [System.IO.File]::ReadAllText("$filePath")
}
$conn=new-object System.Data.SqlClient.SQLConnection
if ($Username)
{ $ConnectionString = "Server={0};Database={1};User ID={2};Password={3};Trusted_Connection=False;Connect Timeout={4}" -f $ServerInstance,$Database,$Username,$Password,$ConnectionTimeout }
else
{ $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerInstance,$Database,$ConnectionTimeout }
$conn.ConnectionString=$ConnectionString
#Following EventHandler is used for PRINT and RAISERROR T-SQL statements. Executed when -Verbose parameter specified by caller
if ($PSBoundParameters.Verbose)
{
$conn.FireInfoMessageEventOnUserErrors=$true
$handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] {Write-Verbose "$($_)"}
$conn.add_InfoMessage($handler)
}
$conn.Open()
$cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn)
$cmd.CommandTimeout=$QueryTimeout
if ($SqlParameters -ne $null)
{
$SqlParameters.GetEnumerator() |
ForEach-Object {
If ($_.Value -ne $null)
{ $cmd.Parameters.AddWithValue($_.Key, $_.Value) }
Else
{ $cmd.Parameters.AddWithValue($_.Key, [DBNull]::Value) }
} > $null
}
$ds=New-Object system.Data.DataSet
$da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd)
[void]$da.fill($ds)
$conn.Close()
switch ($As)
{
'DataSet' { Write-Output ($ds) }
'DataTable' { Write-Output ($ds.Tables) }
'DataRow' { Write-Output ($ds.Tables[0]) }
}
} #Invoke-Sqlcmd2
|
PowerShellCorpus/PoshCode/SVMotion-VM.ps1
|
SVMotion-VM.ps1
|
# author: Hal Rottenberg
# Website/OpenID: http://halr9000.com
# purpose: does "real" SVMotion of a VM
# usage: get-vm | SVMotion-VM -destination (get-datastore foo)
function SVMotion-VM {
param(
[VMware.VimAutomation.Client20.DatastoreImpl]
$destination
)
Begin {
$datastoreView = get-view $destination
$relocationSpec = new-object VMware.Vim.VirtualMachineRelocateSpec
$relocationSpec.Datastore = $datastoreView.MoRef
}
Process {
if ( $_ -isnot VMware.VimAutomation.Client20.VirtualMachineImpl ) {
Write-Error "Expected VMware object on pipeline. skipping $_"
continue
}
$vmView = Get-View $_
$vmView.RelocateVM_Task($relocationSpec)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.