full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/GithubGist/NickJosevski_175313_raw_accfad80ded2a017ecbc6f028c4af72d947046ce_ExtractCopyCompressDeploy.ps1
|
NickJosevski_175313_raw_accfad80ded2a017ecbc6f028c4af72d947046ce_ExtractCopyCompressDeploy.ps1
|
function Select-Folder($message='Select a folder', $path = 0) {
$object = New-Object -comObject Shell.Application
$folder = $object.BrowseForFolder(0, $message, 0, $path)
if ($folder -ne $null) {
$folder.self.Path
}
}
function Add-Zip
{
param([string]$zipfilename)
if(-not (test-path($zipfilename)))
{
set-content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipfilename).IsReadOnly = $false
}
$shellApplication = new-object -com shell.application
$zipPackage = $shellApplication.NameSpace($zipfilename)
foreach($file in $input)
{
$zipPackage.CopyHere($file.FullName)
Start-sleep -milliseconds 500
}
}
$folder = Select-Folder 'Select the SketchFlow Package Folder...'
#could prompt user for deployment location also, for the final compressed file
$deploymentFolder = "$folder\..\Deployment"
$types = ".xap", ".html"
#PSisContainer - fetches only files not directories
#Group-Object - assists in the ForEach loop that performs the copy
$files= Get-ChildItem $folder | Where-Object {-not$_.PSisContainer} | Group-Object Extension
$files = $files | Where-Object {$types-contains$_.Name}
New-Item -itemType Directory -path $deploymentFolder -ea SilentlyContinue
$files | ForEach-Object { $_.Group | Copy-Item -destination $deploymentFolder }
#rename testpage to something even more obvious
Move-Item "$deploymentFolder\TestPage.html" "$deploymentFolder\LaunchMe.html"
Get-ChildItem $deploymentFolder -Recurse | Add-Zip "$folder\deploy.zip"
#moving the file because Add-Zip cannot take an adjusted path ($folder\..\file.zip) as input.
Move-Item "$folder\deploy.zip" "$folder\..\deploy.zip"
|
PowerShellCorpus/GithubGist/breezhang_1868969_raw_6ee351590937e93d947fd0fec1d9bb73c8a26bdd_Get-HexDump.ps1
|
breezhang_1868969_raw_6ee351590937e93d947fd0fec1d9bb73c8a26bdd_Get-HexDump.ps1
|
function Get-HexDump($path,$width=10, $bytes=-1)
{
$OFS=""
Get-Content -Encoding byte $path -ReadCount $width `
-totalcount $bytes | Foreach-Object {
$byte = $_
$hex = $byte | Foreach-Object {
" " + ("{0:x}" -f $_).PadLeft(2,"0")}
$char = $byte | Foreach-Object {
if ([char]::IsLetterOrDigit($_))
{ [char] $_ } else { "." }}
"$hex $char"
}
}
#function Get-xxx {
# Write-Host "Get-xxxx:"
#}
|
PowerShellCorpus/GithubGist/writeameer_1044248_raw_7fa3fde3774cb329786383e7e22aacf89c2ef1bb_InstallRightLink57.ps1
|
writeameer_1044248_raw_7fa3fde3774cb329786383e7e22aacf89c2ef1bb_InstallRightLink57.ps1
|
###
# This script installs RightLink on a Windows Server 2008 R2 Server Core machine
function Download-File
{
param (
[parameter(Mandatory=$true)] $url
)
$fileName = $url.Split("/")[-1]
$webClient = New-Object System.Net.WebClient
Write-Host "Downloading: $url"
$webClient.DownloadFile($url,$fileName)
}
function Install-RightLink()
{
# Download Installer from RightScale Mirror
$baseUrl = "http://mirror.rightscale.com/rightscale_rightlink/latest_windows/"
$x86FileName = "Rightscale_Windows_i386_5.7.1.msi"
$x64FileName = "Rightscale_Windows_x64_5.7.1.msi"
$osArchitecture = (gwmi win32_OperatingSystem).OsArchitecture
if ($osArchitecture -eq "32-bit")
{
$url = $baseUrl + $x86FileName
}
else
{
$url = $baseUrl + $x64FileName
}
Download-File -url $url
$fileName = $url.Split("/")[-1]
if (Test-Path(".\$fileName"))
{
Write-Host "RightLink Installer downloaded successfully...."
gci ".\$fileName"
}
else
{
Write-Host "Error! Could not download installer"
}
# Run installer
$cmd = ".\$fileName /quiet"
Invoke-Expression $cmd
# Verify Installation was successful
$rightScaleService = gwmi win32_service -filter "Name='RightScale'"
$rightLinkService = gwmi win32_service -filter "Name='RightLink'"
if ($rightScaleService -eq $null)
{
Write-Error "RightScale service not installed!"
Exit 1
}
elseif ($rightLinkService -eq $null)
{
Write-Error "RightLink service not installed!"
Exit 1
}
else
{
Write-Host "RightLink Installed Successfully !"
}
}
function Install-PrintSpooler()
{
$cmd = "dism /Online /Enable-Feature /FeatureName:Printing-ServerCore-Role"
Invoke-Expression $cmd
}
Install-PrintSpooler
Install-RightLink
|
PowerShellCorpus/GithubGist/bill-long_230830312b70742321e0_raw_ad3650de9681cb25e5c5df8c6a1befcc9850ea73_Refresh-Path.ps1
|
bill-long_230830312b70742321e0_raw_ad3650de9681cb25e5c5df8c6a1befcc9850ea73_Refresh-Path.ps1
|
foreach($level in "Machine","User") {
[Environment]::GetEnvironmentVariables($level).GetEnumerator() | % {
# For Path variables, append the new values, if they're not already in there
if($_.Name -match 'Path$') {
$_.Value = ($((Get-Content "Env:$($_.Name)") + ";$($_.Value)") -split ';' | Select -unique) -join ';'
}
$_
} | Set-Content -Path { "Env:$($_.Name)" }
}
|
PowerShellCorpus/GithubGist/to-taka_3e7a4a9bf6f8b6ffd52f_raw_84cb8bc3e20dbd01cd84e0f13c3ace9f0da9eb99_Get-ADComputer.ps1
|
to-taka_3e7a4a9bf6f8b6ffd52f_raw_84cb8bc3e20dbd01cd84e0f13c3ace9f0da9eb99_Get-ADComputer.ps1
|
Get-ADComputer -Filter {CN -like "hoge*"} -Properties IPv4Address # change CN condition to target pc name.
|
PowerShellCorpus/GithubGist/belotn_7038878_raw_16ade3a7aa101fe52f6a7b69872ac642697a1f77_get-tsemapconfig.ps1
|
belotn_7038878_raw_16ade3a7aa101fe52f6a7b69872ac642697a1f77_get-tsemapconfig.ps1
|
$TSEKey="SYSTEM\ControlSet001\Control\Terminal Server\WinStations\RDP-Tcp"
get-XAserver | %{
$reg=[microsoft.win32.registrykey]::OpenRemoteBaseKey('LocalMachine',$_.ServerName)
$copy = $_
$reg.OpenSubKey($TSEKey).getValueNames() |? { $_ -like 'fDisable*'} |% {
$copy | Add-member -Type NoteProperty -Name $_ -Value $reg.OpenSubKey($TSEKey).getValue($_)
}
$copy
} | select ServerName, fDisable*
|
PowerShellCorpus/GithubGist/janikvonrotz_8004176_raw_237a280981c603cf20aea0c069eed2f0f7b04d82_Open-TrueCryptwithKeePass.ps1
|
janikvonrotz_8004176_raw_237a280981c603cf20aea0c069eed2f0f7b04d82_Open-TrueCryptwithKeePass.ps1
|
& KeePass (Get-Path "$($PSconfigs.Path)..\..\..\..\..\Data\keepass\KeepassData.kdbx") -preselect:((Mount-TrueCyptContainer -Name pc1).Drive + ":\KeePass\keepass_data.key")
Read-Host "`nPress any key to dismount the TrueCrypt drive"
Dismount-TrueCyptContainer -Name pc1
|
PowerShellCorpus/GithubGist/kouphax_1065644_raw_16c5881c94fde58604d4538bb403181a434108d7_default.ps1
|
kouphax_1065644_raw_16c5881c94fde58604d4538bb403181a434108d7_default.ps1
|
Properties {
}
$framework = '4.0'
Task Default -depends Build
Task Build {
Exec { msbuild .\MySolution.sln /v:quiet }
}
|
PowerShellCorpus/GithubGist/PureKrome_90a1587ea2b6c4f51269_raw_dd9aa4699977586086f08d1e1f34961faf865c62_NuGetPackageAndPublish.ps1
|
PureKrome_90a1587ea2b6c4f51269_raw_dd9aa4699977586086f08d1e1f34961faf865c62_NuGetPackageAndPublish.ps1
|
############################################################################
### ###
### NUGET PACKAGE and PUBLISH ###
### ###
############################################################################
param (
[string]$version = "",
[string]$apiKey = "",
[string]$source = $PSScriptRoot,
[string]$destination = $PSScriptRoot,
[string]$pushSource = "https://nuget.org",
[string]$nuget = "",
[bool]$clean = $false
)
function DisplayCommandLineArgs()
{
"Options provided:"
" => version: $version"
" => source: $source"
" => destination: $destination"
" => nuget: $nuget"
" => api key: $apiKey"
" => clean: $clean"
""
"eg. NuGetPackageAndPublish.ps1 -version 0.1-alpha"
"eg. NuGetPackageAndPublish.ps1 -version 0.1-alpha -destination C:\temp\TempNuGetPackages"
"eg. NuGetPackageAndPublish.ps1 -version 0.1-alpha -source ../nugetspecs/ -destination C:\temp\TempNuGetPackages"
"eg. NuGetPackageAndPublish.ps1 -version 0.1-alpha -nuget c:\temp\nuget.exe"
"eg. NuGetPackageAndPublish.ps1 -version 0.1-alpha -nuget c:\temp\nuget.exe -apiKey ABCD-EFG..."
""
if (-Not $version)
{
""
"**** The version of this NuGet package is required."
"**** Eg. ./NuGetPackageAndPublish.ps1 -version 0.1-alpha"
""
""
throw;
}
if ($source -eq "")
{
""
"**** A source parameter provided cannot be an empty string."
""
""
throw;
}
if ($destination -eq "")
{
""
"**** A destination parameter provided cannot be an empty string."
""
""
throw;
}
if ($pushSource -eq "")
{
""
"**** The NuGet push source parameter provided cannot be an empty string."
""
""
throw;
}
# Setup the nuget path.
if (-Not $nuget -eq "")
{
$global:nugetExe = $nuget
}
else
{
# Assumption, nuget.exe is the current folder where this file is.
$global:nugetExe = Join-Path $source "nuget"
}
$global:nugetExe
if (!(Test-Path $global:nugetExe -PathType leaf))
{
""
"**** Nuget file was not found. Please provide the -nuget parameter with the nuget.exe path -or- copy the nuget.exe to the current folder, side-by-side to this powershell file."
""
""
throw;
}
}
function CleanUp()
{
if ($clean -eq $false)
{
return;
}
$nupkgFiles = @(Get-ChildItem $destination -Filter *.nupkg)
if ($nupkgFiles.Count -gt 0)
{
"Found " + $nupkgFiles.Count + " *.nupkg files. Lets delete these first..."
foreach($nupkgFile in $nupkgFiles)
{
$combined = Join-Path $destination $nupkgFile
"... Removing $combined."
Remove-Item $combined
}
"... Done!"
}
}
function PackageTheSpecifications()
{
""
"Getting all *.nuspec files to package in directory: $source"
$files = Get-ChildItem $source -Filter *.nuspec
if ($files.Count -eq 0)
{
""
"**** No nuspec files found in the directory: $source"
"Terminating process."
throw;
}
"Found: " + $files.Count + " files :)"
foreach($file in $files)
{
&$nugetExe pack $file -Version $version -OutputDirectory $destination
""
}
}
function PushThePackagesToNuGet()
{
if ($apiKey -eq "")
{
"@@ No NuGet server api key provided - so not pushing anything up."
return;
}
""
"Getting all *.nupkg's files to push to : $pushSource"
$files = Get-ChildItem $destination -Filter *.nupkg
if ($files.Count -eq 0)
{
""
"**** No nupkg files found in the directory: $destination"
"Terminating process."
throw;
}
"Found: " + $files.Count + " files :)"
foreach($file in $files)
{
&$nugetExe push ($file.FullName) -Source $pushSource -apiKey $apiKey
""
}
}
##############################################################################
##############################################################################
$ErrorActionPreference = "Stop"
$global:nugetExe = ""
cls
""
" ---------------------- start script ----------------------"
""
""
" Starting NuGet packing/publishing script - (╯°□°)╯︵ ┻━┻"
""
" This script will look for -all- *.nuspec files in a source directory,"
" then paackage them up to *.nupack files. Finally, it can publish"
" them to a NuGet server, if an api key was provided."
""
DisplayCommandLineArgs
CleanUp
PackageTheSpecifications
PushThePackagesToNuGet
""
""
" ---------------------- end of script ----------------------"
""
""
|
PowerShellCorpus/GithubGist/crancker_5319697_raw_41eeab1f8a123858d9cb6106b28f5263e326a69b_installed.ps1
|
crancker_5319697_raw_41eeab1f8a123858d9cb6106b28f5263e326a69b_installed.ps1
|
remove-item ./output.txt; $output = get-wmiobject -class Win32_Product | format-table Name, Vendor, Version, caption -auto | Out-String -Width 4096; $output >> ./output.txt; notepad ./output.txt
|
PowerShellCorpus/PoshCode/GetSet-Users.ps1
|
GetSet-Users.ps1
|
param(
[Parameter(Position=0,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
[alias("Name","ComputerName")][string[]] $Computers = @($env:computername),
#works automagically for domain members or local computer,
#must be set manual for workgroups or forests
[string] $NTDomain = ($env:UserDomain),
# multiple groups usually makes sense when reporting only
[string[]] $LocalGroups = @("Administrators"),
[string[]] $Add = @(), # can be user or group
[string[]] $Remove = @() # can be user or group
)
begin{
$script:objReport = @()
# list current members in defined group
Function ListMembers ($Group){
$members = $Group.psbase.invoke("Members") | %{$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}
return $members
}
#
Function LocalNTGroup ($ComputerName,$Group){
$NTgroup = ([ADSI]("WinNT://" + $Computer + ",computer")).psbase.children.find($Group)
return $NTgroup
}
# provides central output code in case of future revisions
Function Output($ComputerName,$GroupName,$UserName,$Action,$Result){
$script:objReport += New-Object PSObject -Property @{
Computername = $ComputerName
GroupName = $GroupName
UserName = $UserName
Action = $Action
Result = $Result
}
write-host "on $ComputerName -- $GroupName for $UserName the result for $Action is: $Result"
}
}#begin
process{
#foreach loops will not iterate when empty thus no try-catch
foreach ($Computer in $Computers){
if (Test-Connection -ComputerName $Computer -Count 1 -Quiet -EA "Stop"){
write-verbose "getting local group members on $Computer"
foreach ($Group in $LocalGroups){
$LocalGroup = LocalNTGroup $Computer $Group
foreach ($member in $(ListMembers $LocalGroup)){
Output $Computer $Group $member "ENUM" "Existing"
}
foreach ($AddID in $Add){
try{
$LocalGroup.Add("WinNT://" + $NTDomain + "/" + $AddID)
$Action = "Added"
}
catch{
write-debug "$AddID is not added"
$Action = $Error[0].Exception.InnerException.Message.ToString().Trim()
}
Output $Computer $Group $AddID "ADDING" $Action
}
foreach ($RemID in $Remove){
try{
$LocalGroup.Remove("WinNT://" + $NTDomain + "/" + $RemID)
$Action = "Removed"
}
catch{
write-debug "$RemID is not added"
$Action = $Error[0].Exception.InnerException.Message.ToString().Trim()
}
Output $Computer $Group $RemID "REMOVING" $Action
}
}
}
}
}#process
end{
$script:objReport | select computername, groupname, username, action, result | sort username
}
|
PowerShellCorpus/PoshCode/UIAutomation 1.7.ps1
|
UIAutomation 1.7.ps1
|
## UI Automation v 1.7 -- REQUIRES the Reflection module (current version: http://poshcode.org/2480 )
##
# WASP 2.0 is getting closer, but this is still just a preview:
# -- a lot of the commands have weird names still because they're being generated ignorantly
# -- eg: Invoke-Toggle.Toggle and Invoke-Invoke.Invoke
# v 1.7 - Fixes using multiple checks like: Select-UIElement Red: Edit
Add-Type -AssemblyName "UIAutomationClient, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Add-Type -AssemblyName "UIAutomationTypes, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
$SWA = "System.Windows.Automation"
# Add-Accelerator InvokePattern "$SWA.InvokePattern" -EA SilentlyContinue
# Add-Accelerator ExpandPattern "$SWA.ExpandCollapsePattern" -EA SilentlyContinue
# Add-Accelerator WindowPattern "$SWA.WindowPattern" -EA SilentlyContinue
# Add-Accelerator TransformPattern "$SWA.TransformPattern" -EA SilentlyContinue
# Add-Accelerator ValuePattern "$SWA.ValuePattern" -EA SilentlyContinue
# Add-Accelerator TextPattern "$SWA.TextPattern" -EA SilentlyContinue
# This is what requires the Reflection module:
Add-Accelerator Automation "$SWA.Automation" -EA SilentlyContinue
Add-Accelerator AutomationElement "$SWA.AutomationElement" -EA SilentlyContinue
Add-Accelerator TextRange "$SWA.Text.TextPatternRange" -EA SilentlyContinue
##### Conditions
Add-Accelerator Condition "$SWA.Condition" -EA SilentlyContinue
Add-Accelerator AndCondition "$SWA.AndCondition" -EA SilentlyContinue
Add-Accelerator OrCondition "$SWA.OrCondition" -EA SilentlyContinue
Add-Accelerator NotCondition "$SWA.NotCondition" -EA SilentlyContinue
Add-Accelerator PropertyCondition "$SWA.PropertyCondition" -EA SilentlyContinue
##### IDentifiers
Add-Accelerator AutoElementIds "$SWA.AutomationElementIdentifiers" -EA SilentlyContinue
Add-Accelerator TransformIds "$SWA.TransformPatternIdentifiers" -EA SilentlyContinue
##### Patterns:
$patterns = Get-Type -Assembly UIAutomationClient -Base System.Windows.Automation.BasePattern
#| Where { $_ -ne [System.Windows.Automation.InvokePattern] }
Add-Type -TypeDefinition @"
using System;
using System.ComponentModel;
using System.Management.Automation;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Windows.Automation;
using System.Runtime.InteropServices;
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class StaticFieldAttribute : ArgumentTransformationAttribute {
private Type _class;
public override string ToString() {
return string.Format("[StaticField(OfClass='{0}')]", OfClass.FullName);
}
public override Object Transform( EngineIntrinsics engineIntrinsics, Object inputData) {
if(inputData is string && !string.IsNullOrEmpty(inputData as string)) {
System.Reflection.FieldInfo field = _class.GetField(inputData as string, BindingFlags.Static | BindingFlags.Public);
if(field != null) {
return field.GetValue(null);
}
}
return inputData;
}
public StaticFieldAttribute( Type ofClass ) {
OfClass = ofClass;
}
public Type OfClass {
get { return _class; }
set { _class = value; }
}
}
public static class UIAutomationHelper {
[DllImport ("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr FindWindow (string lpClassName, string lpWindowName);
[DllImport ("user32.dll", CharSet = CharSet.Auto)]
static extern bool AttachThreadInput (int idAttach, int idAttachTo, bool fAttach);
[DllImport ("user32.dll", CharSet = CharSet.Auto)]
static extern int GetWindowThreadProcessId (IntPtr hWnd, IntPtr lpdwProcessId);
[DllImport ("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SetForegroundWindow (IntPtr hWnd);
public static AutomationElement RootElement {
get { return AutomationElement.RootElement; }
}
///<synopsis>Using Win32 to set foreground window because AutomationElement.SetFocus() is unreliable</synopsis>
public static bool SetForeground(this AutomationElement element)
{
if(element == null) {
throw new ArgumentNullException("element");
}
// Get handle to the element
IntPtr other = FindWindow (null, element.Current.Name);
// // Get the Process ID for the element we are trying to
// // set as the foreground element
// int other_id = GetWindowThreadProcessId (other, IntPtr.Zero);
//
// // Get the Process ID for the current process
// int this_id = GetWindowThreadProcessId (Process.GetCurrentProcess().Handle, IntPtr.Zero);
//
// // Attach the current process's input to that of the
// // given element. We have to do this otherwise the
// // WM_SETFOCUS message will be ignored by the element.
// bool success = AttachThreadInput(this_id, other_id, true);
// Make the Win32 call
IntPtr previous = SetForegroundWindow(other);
return !IntPtr.Zero.Equals(previous);
}
}
"@ -ReferencedAssemblies UIAutomationClient, UIAutomationTypes
## TODO: Write Get-SupportedPatterns or rather ...
## Get-SupportedFunctions (to return the names of the functions for the supported patterns)
## TODO: Support all the "Properties" too
## TODO: Figure out why Notepad doesn't support SetValue
## TODO: Figure out where the menus support went
ForEach($pattern in $patterns){
$pattern | Add-Accelerator
$PatternFullName = $pattern.FullName
$PatternName = $Pattern.Name -Replace "Pattern","."
$newline = "`n`t`t"
New-Item "Function:ConvertTo-$($Pattern.Name)" -Value "
param(
[Parameter(ValueFromPipeline=`$true)][Alias('Element','AutomationElement')][AutomationElement]`$InputObject
)
process {
trap {
if(`$_.Exception.Message -like '*Unsupported Pattern.*') {
Write-Error `"Cannot get ```"$($Pattern.Name)```" from that AutomationElement, `$(`$_)` You should try one of: `$(`$InputObject.GetSupportedPatterns()|%{```"'```" + (`$_.ProgrammaticName.Replace(```"PatternIdentifiers.Pattern```",```"```")) + ```"Pattern'```"})`"; continue;
}
}
Write-Output `$InputObject.GetCurrentPattern([$PatternFullName]::Pattern).Current
}"
$pattern.GetMethods() |
Where { $_.DeclaringType -eq $_.ReflectedType -and !$_.IsSpecialName } |
ForEach {
$FunctionName = "Function:Invoke-$PatternName$($_.Name)"
$Position = 1
if (test-path $FunctionName) { remove-item $FunctionName }
$Parameters = @("$newline[Parameter(ValueFromPipeline=`$true)]"+
"$newline[Alias('Parent','Element','Root','AutomationElement')]"+
"$newline[AutomationElement]`$InputObject"
) +
@(
"[Parameter()]$newline[Switch]`$Passthru"
) +
@($_.GetParameters() | % { "[Parameter(Position=$($Position; $Position++))]$newline[$($_.ParameterType.FullName)]`$$($_.Name)" })
$Parameters = $Parameters -Join "$newline,$newline"
$ParameterValues = '$' + (@($_.GetParameters() | Select-Object -Expand Name ) -Join ', $')
$definition = @"
param(
$Parameters
)
process {
## trap { Write-Warning "`$(`$_)"; break }
`$pattern = `$InputObject.GetCurrentPattern([$PatternFullName]::Pattern)
if(`$pattern) {
`$Pattern.$($_.Name)($(if($ParameterValues.Length -gt 1){ $ParameterValues }))
}
if(`$passthru) {
`$InputObject
}
}
"@
trap {
Write-Warning $_
Write-Host $definition -fore cyan
}
New-Item $FunctionName -value $definition
}
$pattern.GetProperties() |
Where { $_.DeclaringType -eq $_.ReflectedType -and $_.Name -notmatch "Cached|Current"} |
ForEach {
$FunctionName = "Function:Get-$PatternName$($_.Name)".Trim('.')
if (test-path $FunctionName) { remove-item $FunctionName }
New-Item $FunctionName -value "
param(
[Parameter(ValueFromPipeline=`$true)]
[AutomationElement]`$AutomationElement
)
process {
trap { Write-Warning `"$PatternFullName `$_`"; continue }
`$pattern = `$AutomationElement.GetCurrentPattern([$PatternFullName]::Pattern)
if(`$pattern) {
`$pattern.'$($_.Name)'
}
}"
}
## So far this seems to be restricted to Text (DocumentRange) elements
$pattern.GetFields() |
Where { $_.FieldType.Name -like "*TextAttribute"} |
ForEach {
$FunctionName = "Function:Get-Text$($_.Name -replace 'Attribute')"
if (test-path $FunctionName) { remove-item $FunctionName }
New-Item $FunctionName -value "
param(
[Parameter(ValueFromPipeline=`$true)]
[AutomationElement]`$AutomationElement
)
process {
trap { Write-Warning `"$PatternFullName `$_`"; continue }
`$AutomationElement.GetAttributeValue([$PatternFullName]::$($_.Name))
}"
}
$pattern.GetFields() | Where { $_.FieldType -eq [System.Windows.Automation.AutomationEvent] } |
ForEach {
$Name = $_.Name -replace 'Event$'
$FunctionName = "Function:Register-$($PatternName.Trim('.'))$Name"
if (test-path $FunctionName) { remove-item $FunctionName }
New-Item $FunctionName -value "
param(
[Parameter(ValueFromPipeline=`$true)]
[AutomationElement]`$AutomationElement
,
[System.Windows.Automation.TreeScope]`$TreeScope = 'Element'
,
[ScriptBlock]`$EventHandler
)
process {
trap { Write-Warning `"$PatternFullName `$_`"; continue }
[Automation]::AddAutomationEventHandler( [$PatternFullName]::$Name, `$AutomationElement, `$TreeScope, `$EventHandler )
}"
}
}
$FalseCondition = [Condition]::FalseCondition
$TrueCondition = [Condition]::TrueCondition
Add-Type -AssemblyName System.Windows.Forms
Add-Accelerator SendKeys System.Windows.Forms.SendKeys -EA SilentlyContinue
$AutomationProperties = [system.windows.automation.automationelement+automationelementinformation].GetProperties()
Set-Alias Invoke-UIElement Invoke-Invoke.Invoke
function formatter { END {
$input | Format-Table @{l="Text";e={$_.Text.SubString(0,25)}}, ClassName, FrameworkId -Auto
}}
function Get-ClickablePoint {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
)
process {
$InputObject.GetClickablePoint()
}
}
function Show-Window {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
,
[Parameter()]
[Switch]$Passthru
)
process {
Set-UIFocus $InputObject
if($passthru) {
$InputObject
}
}
}
function Set-UIFocus {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
,
[Parameter()]
[Switch]$Passthru
)
process {
try {
[UIAutomationHelper]::SetForeground( $InputObject )
$InputObject.SetFocus()
} catch {
Write-Verbose "SetFocus fail, trying SetForeground"
}
if($passthru) {
$InputObject
}
}
}
function Send-UIKeys {
[CmdletBinding()]
param(
[Parameter(Position=0)]
[string]$Keys
,
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
,
[Parameter()]
[Switch]$Passthru
,
[Parameter()]
[Switch]$Async
)
process {
if(!$InputObject.Current.IsEnabled)
{
Write-Warning "The Control is not enabled!"
}
if(!$InputObject.Current.IsKeyboardFocusable)
{
Write-Warning "The Control is not focusable!"
}
Set-UIFocus $InputObject
if($Async) {
[SendKeys]::Send( $Keys )
} else {
[SendKeys]::SendWait( $Keys )
}
if($passthru) {
$InputObject
}
}
}
function Set-UIText {
[CmdletBinding()]
param(
[Parameter(Position=0)]
[string]$Text
,
[Parameter(ValueFromPipeline=$true)]
[Alias("Parent","Element","Root")]
[AutomationElement]$InputObject
,
[Parameter()]
[Switch]$Passthru
)
process {
if(!$InputObject.Current.IsEnabled)
{
Write-Warning "The Control is not enabled!"
}
if(!$InputObject.Current.IsKeyboardFocusable)
{
Write-Warning "The Control is not focusable!"
}
$valuePattern = $null
if($InputObject.TryGetCurrentPattern([ValuePattern]::Pattern,[ref]$valuePattern)) {
Write-Verbose "Set via ValuePattern!"
$valuePattern.SetValue( $Text )
}
elseif($InputObject.Current.IsKeyboardFocusable)
{
Set-UIFocus $InputObject
[SendKeys]::SendWait("^{HOME}");
[SendKeys]::SendWait("^+{END}");
[SendKeys]::SendWait("{DEL}");
[SendKeys]::SendWait( $Text )
}
if($passthru) {
$InputObject
}
}
}
function Select-UIElement {
[CmdletBinding(DefaultParameterSetName="FromParent")]
PARAM (
[Parameter(ParameterSetName="FromWindowHandle", Position="0", Mandatory=$true)]
[Alias("MainWindowHandle","hWnd","Handle","Wh")]
[IntPtr[]]$WindowHandle=[IntPtr]::Zero
,
[Parameter(ParameterSetName="FromPoint", Position="0", Mandatory=$true)]
[System.Windows.Point[]]$Point
,
[Parameter(ParameterSetName="FromParent", ValueFromPipeline=$true, Position=100)]
[System.Windows.Automation.AutomationElement]$Parent = [UIAutomationHelper]::RootElement
,
[Parameter(ParameterSetName="FromParent", Position="0")]
[Alias("WindowName")]
[String[]]$Name
,
[Parameter(ParameterSetName="FromParent", Position="1")]
[Alias("Type","Ct")]
[System.Windows.Automation.ControlType]
[StaticField(([System.Windows.Automation.ControlType]))]$ControlType
,
[Parameter(ParameterSetName="FromParent")]
[Alias("UId")]
[String[]]$AutomationId
,
## Removed "Id" alias to allow get-process | Select-Window pipeline to find just MainWindowHandle
[Parameter(ParameterSetName="FromParent", ValueFromPipelineByPropertyName=$true )]
[Alias("Id")]
[Int[]]$PID
,
[Parameter(ParameterSetName="FromParent")]
[Alias("Pn")]
[String[]]$ProcessName
,
[Parameter(ParameterSetName="FromParent")]
[Alias("Cn")]
[String[]]$ClassName
,
[switch]$Recurse
,
[switch]$Bare
)
process {
Write-Debug "Parameters Found"
Write-Debug ($PSBoundParameters | Format-Table | Out-String)
$search = "Children"
if($Recurse) { $search = "Descendants" }
$condition = [System.Windows.Automation.Condition]::TrueCondition
Write-Verbose $PSCmdlet.ParameterSetName
switch -regex ($PSCmdlet.ParameterSetName) {
"FromWindowHandle" {
Write-Verbose "Finding from Window Handle $HWnd"
$Element = $(
foreach($hWnd in $WindowHandle) {
[System.Windows.Automation.AutomationElement]::FromHandle( $hWnd )
}
)
continue
}
"FromPoint" {
Write-Verbose "Finding from Point $Point"
$Element = $(
foreach($pt in $Point) {
[System.Windows.Automation.AutomationElement]::FromPoint( $pt )
}
)
continue
}
"FromParent" {
Write-Verbose "Finding from Parent!"
## [System.Windows.Automation.Condition[]]$conditions = [System.Windows.Automation.Condition]::TrueCondition
[ScriptBlock[]]$filters = @()
if($AutomationId) {
[System.Windows.Automation.Condition[]]$current = $(
foreach($aid in $AutomationId) {
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::AutomationIdProperty), $aid
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
if($PID) {
[System.Windows.Automation.Condition[]]$current = $(
foreach($p in $PID) {
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ProcessIdProperty), $p
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
if($ProcessName) {
if($ProcessName -match "\\?|\\*|\\[") {
[ScriptBlock[]]$filters += { $(foreach($p in $ProcessName){ (Get-Process -id $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ProcessIdProperty)).ProcessName -like $p }) -contains $true }
} else {
[System.Windows.Automation.Condition[]]$current = $(
foreach($p in Get-Process -Name $ProcessName) {
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ProcessIdProperty), $p.id, "IgnoreCase"
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
}
if($Name) {
Write-Verbose "Name: $Name"
if($Name -match "\\?|\\*|\\[") {
[ScriptBlock[]]$filters += { $(foreach($n in $Name){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::NameProperty) -like $n }) -contains $true }
} else {
[System.Windows.Automation.Condition[]]$current = $(
foreach($n in $Name){
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::NameProperty), $n, "IgnoreCase"
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
}
if($ClassName) {
if($ClassName -match "\\?|\\*|\\[") {
[ScriptBlock[]]$filters += { $(foreach($c in $ClassName){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ClassNameProperty) -like $c }) -contains $true }
} else {
[System.Windows.Automation.Condition[]]$current = $(
foreach($c in $ClassName){
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ClassNameProperty), $c, "IgnoreCase"
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
}
if($ControlType) {
if($ControlType -match "\\?|\\*|\\[") {
[ScriptBlock[]]$filters += { $(foreach($c in $ControlType){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ControlTypeProperty) -like $c }) -contains $true }
} else {
[System.Windows.Automation.Condition[]]$current = $(
foreach($c in $ControlType){
new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ControlTypeProperty), $c
}
)
if($current.Length -gt 1) {
[System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current
} elseif($current.Length -eq 1) {
[System.Windows.Automation.Condition[]]$conditions += $current[0]
}
}
}
if($conditions.Length -gt 1) {
[System.Windows.Automation.Condition]$condition = New-Object System.Windows.Automation.AndCondition $conditions
} elseif($conditions) {
[System.Windows.Automation.Condition]$condition = $conditions[0]
} else {
[System.Windows.Automation.Condition]$condition = [System.Windows.Automation.Condition]::TrueCondition
}
If($VerbosePreference -gt "SilentlyContinue") {
function Write-Condition {
param([Parameter(ValueFromPipeline=$true)]$condition, $indent = 0)
process {
Write-Debug ($Condition | fl * | Out-String)
if($condition -is [System.Windows.Automation.AndCondition] -or $condition -is [System.Windows.Automation.OrCondition]) {
Write-Verbose ((" "*$indent) + $Condition.GetType().Name )
$condition.GetConditions().GetEnumerator() | Write-Condition -Indent ($Indent+4)
} elseif($condition -is [System.Windows.Automation.PropertyCondition]) {
Write-Verbose ((" "*$indent) + $Condition.Property.ProgrammaticName + " = '" + $Condition.Value + "' (" + $Condition.Flags + ")")
} else {
Write-Verbose ((" "*$indent) + $Condition.GetType().Name + " where '" + $Condition.Value + "' (" + $Condition.Flags + ")")
}
}
}
Write-Verbose "CONDITIONS ============="
$global:LastCondition = $condition
foreach($c in $condition) {
Write-Condition $c
}
Write-Verbose "============= CONDITIONS"
}
if($filters.Count -gt 0) {
$Element = $Parent.FindAll( $search, $condition ) | Where-Object { $item = $_; foreach($f in $filters) { $item = $item | Where $f }; $item }
} else {
$Element = $Parent.FindAll( $search, $condition )
}
}
}
Write-Verbose "Element Count: $(@($Element).Count)"
if($Element) {
foreach($el in $Element) {
if($Bare) {
Write-Output $el
} else {
$e = New-Object PSObject $el
foreach($prop in $e.GetSupportedProperties() | Sort ProgrammaticName)
{
## TODO: make sure all these show up: [System.Windows.Automation.AutomationElement] | gm -sta -type Property
$propName = [System.Windows.Automation.Automation]::PropertyName($prop)
Add-Member -InputObject $e -Type ScriptProperty -Name $propName -Value ([ScriptBlock]::Create( "`$this.GetCurrentPropertyValue( [System.Windows.Automation.AutomationProperty]::LookupById( $($prop.Id) ))" )) -EA 0
}
foreach($patt in $e.GetSupportedPatterns()| Sort ProgrammaticName)
{
Add-Member -InputObject $e -Type ScriptProperty -Name ($patt.ProgrammaticName.Replace("PatternIdentifiers.Pattern","") + "Pattern") -Value ([ScriptBlock]::Create( "`$this.GetCurrentPattern( [System.Windows.Automation.AutomationPattern]::LookupById( '$($patt.Id)' ) )" )) -EA 0
}
Write-Output $e
}
}
}
}
}
# [Cmdlet(VerbsCommon.Add, "UIAHandler")]
# public class AddUIAHandlerCommand : PSCmdlet
# {
# private AutomationElement _parent = AutomationElement.RootElement;
# private AutomationEvent _event = WindowPattern.WindowOpenedEvent;
# private TreeScope _scope = TreeScope.Children;
#
# [Parameter(ValueFromPipeline = true)]
# [Alias("Parent", "Element", "Root")]
# public AutomationElement InputObject { set { _parent = value; } get { return _parent; } }
#
# [Parameter()]
# public AutomationEvent Event { set { _event = value; } get { return _event; } }
#
# [Parameter()]
# public AutomationEventHandler ScriptBlock { set; get; }
#
# [Parameter()]
# public SwitchParameter Passthru { set; get; }
#
# [Parameter()]
# public TreeScope Scope { set { _scope = value; } get { return _scope; } }
#
# protected override void ProcessRecord()
# {
# Automation.AddAutomationEventHandler(Event, InputObject, Scope, ScriptBlock);
#
# if (Passthru.ToBool())
# {
# WriteObject(InputObject);
# }
#
# base.ProcessRecord();
# }
# }
Export-ModuleMember -cmdlet * -Function * -Alias *
|
PowerShellCorpus/PoshCode/Enable PS Remoting.ps1
|
Enable PS Remoting.ps1
|
#Run winrm quickconfig defaults
echo Y | winrm quickconfig
#Run enable psremoting command with defaults
enable-psremoting -force
#Enabled Trusted Hosts for Universial Access
cd wsman:
cd localhost\\client
Set-Item TrustedHosts * -force
restart-Service winrm
echo "Complete"
|
PowerShellCorpus/PoshCode/Get-User_6.ps1
|
Get-User_6.ps1
|
function Get-User($user)
{
# this function should be passed the CN of the user to be returned
$dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$root = [ADSI] "LDAP://$($dom.Name)"
$searcher = New-Object System.DirectoryServices.DirectorySearcher $root
$searcher.filter = "(&(objectCategory=person)(objectClass=user)(cn=$user))"
$user = $searcher.FindOne()
[System.Collections.Arraylist]$names = $user.Properties.PropertyNames
[System.Collections.Arraylist]$props = $user.Properties.Values
$userobj = New-Object System.Object
for ($i = 0; $i -lt $names.Count)
{
$userobj | Add-Member -type NoteProperty -Name $($names[$i]) -Value $($props[$i])
$i++
}
$userobj.pwdlastset = [System.DateTime]::FromFileTime($userobj.pwdlastset)
$userobj.lastlogontimestamp = [System.DateTime]::FromFileTime($userobj.lastlogontimestamp)
return $userobj
}
|
PowerShellCorpus/PoshCode/Send-TcpRequest.ps1
|
Send-TcpRequest.ps1
|
##############################################################################\n##\n## Send-TcpRequest\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\nSend a TCP request to a remote computer, and return the response.\nIf you do not supply input to this script (via either the pipeline, or the\n-InputObject parameter,) the script operates in interactive mode.\n\n.EXAMPLE\n\nPS >$http = @"\n GET / HTTP/1.1\n Host:bing.com\n `n`n\n"@\n\n$http | Send-TcpRequest bing.com 80\n\n#>\n\nparam(\n ## The computer to connect to\n [string] $ComputerName = "localhost",\n\n ## A switch to determine if you just want to test the connection\n [switch] $Test,\n\n ## The port to use\n [int] $Port = 80,\n\n ## A switch to determine if the connection should be made using SSL\n [switch] $UseSSL,\n\n ## The input string to send to the remote host\n [string] $InputObject,\n\n ## The delay, in milliseconds, to wait between commands\n [int] $Delay = 100\n)\n\nSet-StrictMode -Version Latest\n\n[string] $SCRIPT:output = ""\n\n## Store the input into an array that we can scan over. If there was no input,\n## then we will be in interactive mode.\n$currentInput = $inputObject\nif(-not $currentInput)\n{\n $currentInput = @($input)\n}\n$scriptedMode = ([bool] $currentInput) -or $test\n\nfunction Main\n{\n ## Open the socket, and connect to the computer on the specified port\n if(-not $scriptedMode)\n {\n write-host "Connecting to $computerName on port $port"\n }\n\n try\n {\n $socket = New-Object Net.Sockets.TcpClient($computerName, $port)\n }\n catch\n {\n if($test) { $false }\n else { Write-Error "Could not connect to remote computer: $_" }\n\n return\n }\n\n ## If we're just testing the connection, we've made the connection\n ## successfully, so just return $true\n if($test) { $true; return }\n\n ## If this is interactive mode, supply the prompt\n if(-not $scriptedMode)\n {\n write-host "Connected. Press ^D followed by [ENTER] to exit.`n"\n }\n\n $stream = $socket.GetStream()\n\n ## If we wanted to use SSL, set up that portion of the connection\n if($UseSSL)\n {\n $sslStream = New-Object System.Net.Security.SslStream $stream,$false\n $sslStream.AuthenticateAsClient($computerName)\n $stream = $sslStream\n }\n\n $writer = new-object System.IO.StreamWriter $stream\n\n while($true)\n {\n ## Receive the output that has buffered so far\n $SCRIPT:output += GetOutput\n\n ## If we're in scripted mode, send the commands,\n ## receive the output, and exit.\n if($scriptedMode)\n {\n foreach($line in $currentInput)\n {\n $writer.WriteLine($line)\n $writer.Flush()\n Start-Sleep -m $Delay\n $SCRIPT:output += GetOutput\n }\n\n break\n }\n ## If we're in interactive mode, write the buffered\n ## output, and respond to input.\n else\n {\n if($output)\n {\n foreach($line in $output.Split("`n"))\n {\n write-host $line\n }\n $SCRIPT:output = ""\n }\n\n ## Read the user's command, quitting if they hit ^D\n $command = read-host\n if($command -eq ([char] 4)) { break; }\n\n ## Otherwise, Write their command to the remote host\n $writer.WriteLine($command)\n $writer.Flush()\n }\n }\n\n ## Close the streams\n $writer.Close()\n $stream.Close()\n\n ## If we're in scripted mode, return the output\n if($scriptedMode)\n {\n $output\n }\n}\n\n## Read output from a remote host\nfunction GetOutput\n{\n ## Create a buffer to receive the response\n $buffer = new-object System.Byte[] 1024\n $encoding = new-object System.Text.AsciiEncoding\n\n $outputBuffer = ""\n $foundMore = $false\n\n ## Read all the data available from the stream, writing it to the\n ## output buffer when done.\n do\n {\n ## Allow data to buffer for a bit\n start-sleep -m 1000\n\n ## Read what data is available\n $foundmore = $false\n $stream.ReadTimeout = 1000\n\n do\n {\n try\n {\n $read = $stream.Read($buffer, 0, 1024)\n\n if($read -gt 0)\n {\n $foundmore = $true\n $outputBuffer += ($encoding.GetString($buffer, 0, $read))\n }\n } catch { $foundMore = $false; $read = 0 }\n } while($read -gt 0)\n } while($foundmore)\n\n $outputBuffer\n}\n\n. Main
|
PowerShellCorpus/PoshCode/Add-Namespace.ps1
|
Add-Namespace.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:__unresolvableTypeNames.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:__unresolvableTypeNames -eq $null)
{
$global:__unresolvableTypeNames = 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:__unresolvableTypeNames.Contains($name))
{
$typeAccelerators::Add($fullName, $_)
return
}
if ($typeDictionary.ContainsKey($name))
{
$type = $typeDictionary[$name]
if ($_ -ne $type)
{
$global:__unresolvableTypeNames.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/New-FullDataSet.ps1
|
New-FullDataSet.ps1
|
## Generate two dummy datatables in a dataset for testing
$global:dt1 = New-Object system.data.datatable "Times"
$global:dt2 = New-Object system.data.datatable "Properties"
$global:ds = New-Object system.data.dataset "dataset"
$null = $ds.Tables.Add( $dt1 )
$null = $ds.Tables.Add( $dt2 )
$global:cols1 = ls|?{!$_.PsIsContainer}| gm -type Properties "Name", "CreationTime", "LastAccessTime", "LastWriteTime"
$global:cols2 = ls|?{!$_.PsIsContainer}| gm -type Properties "Name", "Length", "Extension", "Mode", "FullName"
foreach($c in $cols1){
$null = $dt1.Columns.Add( $c.Name, $($c.Definition -split " ")[0] )
}
foreach($c in $cols2){
$null = $dt2.Columns.Add( $c.Name, $($c.Definition -split " ")[0] )
}
foreach($f in ls|?{!$_.PsIsContainer}){
$null = $dt1.LoadDataRow( @($cols1 | % { $f.$($_.Name) }), $null )
$null = $dt2.LoadDataRow( @($cols2 | % { $f.$($_.Name) }), $null )
}
return $ds
# boots { datagrid -itemssource $dt.DefaultView }
|
PowerShellCorpus/PoshCode/Get Virtual ESXi IP Addr.ps1
|
Get Virtual ESXi IP Addr.ps1
|
function Get-VirtualEsxiIp {
param($vm)
$tmpFileTemplate = ($env:TEMP + "\\ipdetect-")
$tmpFile = $tmpFileTemplate + (Get-Random) + ".png"
# Take the screenshot.
$view = $vm | Get-View -Property Name
$path = $view.CreateScreenShot()
$path -match "([^/]+/[^/]+$)" | Out-Null
$relativePath = $matches[1]
# Determine the VM's datastore.
$datastore = $vm | Get-Datastore
$remotePath = ($datastore.DatastoreBrowserPath + "\\" + $relativePath)
Write-Verbose ("Use remote path " + $remotePath)
# Copy it locally. Requires PowerCLI 4.0 U1.
Write-Verbose ($remotePath + ", " + $tmpFile)
Copy-DatastoreItem $remotePath $tmpFile
# OCR the screenshot.
$output = Apply-Ocr -pngFile $tmpFile
# Pull out the IP address.
$output -match "http://([^/]+)" | Out-Null
$ip = $matches[1]
# Clean up.
Write-Verbose "Cleaning up"
# Remove-Item -Force $remotePath
Remove-Item -Force $tmpFile
# Output the IP.
Write-Output $ip
}
# Apply OCR to a PNG file and return the text results.
function Apply-Ocr {
param($pngFile)
$tmpFileTemplate = ($env:TEMP + "\\ipdetectocr-")
$tmpFile = $tmpFileTemplate + (Get-Random) + ".tif"
# Convert the PNG to TIFF.
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
$image = [System.Drawing.Image]::FromFile($pngFile)
$image.Save($tmpFile, [System.Drawing.Imaging.ImageFormat]::TIFF)
# OCR it! (Requires Microsoft Office Document Imaging)
$modi = new-object -com MODI.Document
$modi.Create($tmpFile)
$modi.OCR()
$OCRText = ($modi.Images | select -expand Layout).Text
$modi.Close()
$image.Dispose()
# Clean out old left over files.
foreach ($file in (
Get-Childitem $tmpFileTemplate* |
Where { $_.LastWriteTime -lt ((Get-Date).addMinutes(-1)) } )) {
Remove-Item -Force $file
}
Write-Output $OCRText
}
# Example use:
# Get-VirtualEsxiIp -vm (Get-VM "ESXi 4.0 Instance 3")
|
PowerShellCorpus/PoshCode/finddupe.ps1
|
finddupe.ps1
|
param($dir = '.')
$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/Join.ps1
|
Join.ps1
|
## Join
## Joins array elements together using a specific string separator
############################################
## Usage:
## $Env:Path = ls | ? {$_.PSIsContainer} | Select -expand FullName | Join ";" -Append $Env:Path
## get-process | select -expand name | join ","
##
function join {
param ( [string]$sep, [string]$append, [string]$prepend )
begin { $ofs = $sep; [string[]]$items = @($prepend.split($sep)) }
process { $items += $_ }
end { $items += $append.split($sep); return "$($items -ne '')" }
}
|
PowerShellCorpus/PoshCode/Get-MonthAccountCreated .ps1
|
Get-MonthAccountCreated .ps1
|
function Get-MonthAccountCreated {
<#
.SYNOPSIS
Gets Account created in given month.
.DESCRIPTION
Gets Account created in given month.
.EXAMPLE
Get-MonthAccountCreated -Month 2 -Year 2012
.EXAMPLE
Get-MonthAccountCreated -Month 10 -Year 2012
.PARAMETER Month
Month as number.
.PARAMETER YEAR
Year
#>
[cmdletBinding()]
param(
[Parameter(mandatory=$True)]
[ValidateRange(1,12)]
[int]$Month,
[Parameter(mandatory=$True)]
[ValidateRange(1990,2020)]
[int]$Year
)
BEGIN {}
PROCESS {
$mbx = Get-Mailbox -ResultSize Unlimited
$result = $mbx | Where-Object { ($_.WhenCreated).Month -eq $month -and ($_.WhenCreated).year -eq $year } | Select-Object Name, WhenCreated
$result
}
END{}
}
|
PowerShellCorpus/PoshCode/get windows product key.ps1
|
get windows product key.ps1
|
$Reg = [WMIClass]"root\\default:StdRegProv"
$values = [byte[]]($reg.getbinaryvalue(2147483650,"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion","DigitalProductId").uvalue)
$lookup = [char[]]("B","C","D","F","G","H","J","K","M","P","Q","R","T","V","W","X","Y","2","3","4","6","7","8","9")
$keyStartIndex = [int]52;
$keyEndIndex = [int]($keyStartIndex + 15);
$decodeLength = [int]29
$decodeStringLength = [int]15
$decodedChars = new-object char[] $decodeLength
$hexPid = new-object System.Collections.ArrayList
for ($i = $keyStartIndex; $i -le $keyEndIndex; $i++){ [void]$hexPid.Add($values[$i]) }
for ( $i = $decodeLength - 1; $i -ge 0; $i--)
{
if (($i + 1) % 6 -eq 0){$decodedChars[$i] = '-'}
else
{
$digitMapIndex = [int]0
for ($j = $decodeStringLength - 1; $j -ge 0; $j--)
{
$byteValue = [int](($digitMapIndex * [int]256) -bor [byte]$hexPid[$j]);
$hexPid[$j] = [byte]($byteValue / [int]24);
$digitMapIndex = $byteValue % 24;
$decodedChars[$i] = $lookup[$digitMapIndex];
}
}
}
$str = "";
$decodedChars | % { $str+=$_}
$str
|
PowerShellCorpus/PoshCode/Autoload Module.ps1
|
Autoload Module.ps1
|
#Requires -Version 2.0
## Automatically load functions from scripts on-demand, instead of having to dot-source them ahead of time, or reparse them from the script every time.
## Provides significant memory benefits over pre-loading all your functions, and significant performance benefits over using plain scripts. Can also *inject* functions into Modules so they inherit the module scope instead of the current local scope.
## Please see the use example in the script below
## Version History
## v 1.0 - 2010.10.20
## Officially out of beta -- this is working for me without problems on a daily basis.
## Renamed functions to respect the Verb-Noun expectations, and added Export-ModuleMember
## beta 8 - 2010.09.20
## Finally fixed the problem with aliases that point at Invoke-Autoloaded functions!
## beta 7 - 2010.06.03
## Added some help, and a function to force loading "now"
## Added a function to load AND show the help...
## beta 6 - 2010.05.18
## Fixed a bug in output when multiple outputs happen in the END block
## beta 5 - 2010.05.10
## Fixed non-pipeline use using $MyInvocation.ExpectingInput
## beta 4 - 2010.05.10
## I made a few tweaks and bug fixes while testing it's use with PowerBoots.
## beta 3 - 2010.05.10
## fix for signed scripts (strip signature)
## beta 2 - 2010.05.09
## implement module support
## beta 1 - 2010.04.14
## Initial Release
## To use:
## 1) Create a function. To be 100% compatible, it should specify pipeline arguments
## For example:
<#
function Skip-Object {
param(
[int]$First = 0, [int]$Last = 0, [int]$Every = 0, [int]$UpTo = 0,
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
$InputObject
)
begin {
if($Last) {
$Queue = new-object System.Collections.Queue $Last
}
$e = $every; $UpTo++; $u = 0
}
process {
$InputObject | where { --$First -lt 0 } |
foreach {
if($Last) {
$Queue.EnQueue($_)
if($Queue.Count -gt $Last) { $Queue.DeQueue() }
} else { $_ }
} |
foreach {
if(!$UpTo) { $_ } elseif( --$u -le 0) { $_; $U = $UpTo }
} |
foreach {
if($every -and (--$e -le 0)) { $e = $every } else { $_ }
}
}
}
#>
## 2) Put the function into a script (for our example: C:\\Users\\${Env:UserName}\\Documents\\WindowsPowerShell\\Scripts\\SkipObject.ps1 )
## 3) Import the Autoload Module
## 5) Run this command (or add it to your profile):
<#
New-Autoload C:\\Users\\${Env:UserName}\\Documents\\WindowsPowerShell\\Scripts\\SkipObject.ps1 Skip-Object
#>
## This tells us that you want to have that function loaded for you out of the script file if you ever try to use it.
## Now, you can just use the function:
## 1..10 | Skip-Object -first 2 -upto 2
function Invoke-Autoloaded {
#.Synopsis
# This function was autoloaded, but it has not been parsed yet.
# Use Get-AutoloadHelp to force parsing and get the correct help (or just invoke the function once).
#.Description
# You are seeing this help because the command you typed was imported via the New-Autoload command from the Autoload module. The script file containing the function has not been loaded nor parsed yet. In order to see the correct help for your function we will need to parse the full script file, to force that at this time you may use the Get-AutoloadHelp function.
#
# For example, if your command was Get-PerformanceHistory, you can force loading the help for it by running the command: Get-AutoloadHelp Get-PerformanceHistory
[CmdletBinding()]Param()
DYNAMICPARAM {
$CommandName = $MyInvocation.InvocationName
return LoadNow $CommandName
}#DynamicParam
begin {
Write-Verbose "Command: $CommandName"
if(!$Script:AutoloadHash[$CommandName]) {
do {
$Alias = $CommandName
$CommandName = Get-Alias $CommandName -ErrorAction SilentlyContinue | Select -Expand Definition
Write-Verbose "Invoke-Autoloaded Begin: $Alias -> $CommandName"
} while(!$Script:AutoloadHash[$CommandName] -and (Get-Alias $CommandName -ErrorAction SilentlyContinue))
} else {
Write-Verbose "CommandHash: $($Script:AutoloadHash[$CommandName])"
}
if(!$Script:AutoloadHash[$CommandName]) { throw "Unable to determine command!" }
$ScriptName, $ModuleName, $FunctionName = $Script:AutoloadHash[$CommandName]
Write-Verbose "Invoke-Autoloaded Begin: $Alias -> $CommandName -> $FunctionName"
#Write-Host "Parameters: $($PSBoundParameters | ft | out-string)" -Fore Magenta
$global:command = $ExecutionContext.InvokeCommand.GetCommand( $FunctionName, [System.Management.Automation.CommandTypes]::Function )
Write-Verbose "Autoloaded Command: $($Command|Out-String)"
$scriptCmd = {& $command @PSBoundParameters | Write-Output }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($myInvocation.ExpectingInput)
}
process
{
Write-Verbose "Invoke-Autoloaded Process: $CommandName ($_)"
try {
if($_) {
$steppablePipeline.Process($_)
} else {
$steppablePipeline.Process()
}
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
Write-Verbose "Invoke-Autoloaded End: $CommandName"
}
}#Invoke-Autoloaded
function Get-AutoloadHelp {
[CmdletBinding()]
Param([Parameter(Mandatory=$true)][String]$CommandName)
$null = LoadNow $CommandName
Get-Help $CommandName
}
function LoadNow {
[CmdletBinding()]
Param([Parameter(Mandatory=$true)][String]$CommandName)
Write-Verbose "Command: $CommandName"
if(!$Script:AutoloadHash[$CommandName]) {
do {
$Alias = $CommandName
$CommandName = Get-Alias $CommandName -ErrorAction SilentlyContinue | Select -Expand Definition
Write-Verbose "LoadNow Begin: $Alias -> $CommandName"
} while(!$Script:AutoloadHash[$CommandName] -and (Get-Alias $CommandName -ErrorAction SilentlyContinue))
} else {
Write-Verbose "CommandHash: $($Script:AutoloadHash[$CommandName])"
}
if(!$Script:AutoloadHash[$CommandName]) { throw "Unable to determine command!" }
Write-Verbose "LoadNow DynamicParam: $CommandName from $($Script:AutoloadHash[$CommandName])"
$ScriptName, $ModuleName, $FunctionName = $Script:AutoloadHash[$CommandName]
Write-Verbose "Autoloading:`nScriptName: $ScriptName `nModuleName: $ModuleName `nFunctionName: $FunctionName"
if(!$ScriptName){ $ScriptName = $CommandName }
if(!$FunctionName){ $FunctionName = $CommandName }
if($ModuleName) {
$Module = Get-Module $ModuleName
} else { $Module = $null }
## Determine the command name based on the alias used to invoke us
## Store the parameter set for use in the function later...
$paramDictionary = new-object System.Management.Automation.RuntimeDefinedParameterDictionary
#$externalScript = $ExecutionContext.InvokeCommand.GetCommand( $CommandName, [System.Management.Automation.CommandTypes]::ExternalScript )
$externalScript = Get-Command $ScriptName -Type ExternalScript | Select -First 1
Write-Verbose "Processing Script: $($externalScript |Out-String)"
$parserrors = $null
$prev = $null
$script = $externalScript.ScriptContents
[System.Management.Automation.PSToken[]]$tokens = [PSParser]::Tokenize( $script, [ref]$parserrors )
[Array]::Reverse($tokens)
ForEach($token in $tokens) {
if($prev -and $token.Content -eq "# SIG # Begin signature block") {
$script = $script.SubString(0, $token.Start )
}
if($prev -and $token.Type -eq "Keyword" -and $token.Content -ieq "function" -and $prev.Content -ieq $FunctionName ) {
$script = $script.Insert( $prev.Start, "global:" )
Write-Verbose "Globalized: $($script[(($prev.Start+7)..($prev.Start + 7 +$prev.Content.Length))] -join '')"
}
$prev = $token
}
if($Module) {
$script = Invoke-Expression "{ $Script }"
Write-Verbose "Importing Function into $($Module) module."
&$Module $Script | Out-Null
$command = Get-Command $FunctionName -Type Function
Write-Verbose "Loaded Module Function: $($command | ft CommandType, Name, ModuleName, Visibility|Out-String)"
} else {
Write-Verbose "Importing Function without module."
Invoke-Expression $script | out-null
$command = Get-Command $FunctionName -Type Function
Write-Verbose "Loaded Local Function: $($command | ft CommandType, Name, ModuleName, Visibility|Out-String)"
}
if(!$command) {
throw "Something went wrong autoloading the $($FunctionName) function. Function definition doesn't exist in script: $($externalScript.Path)"
}
if($CommandName -eq $FunctionName) {
Remove-Item Alias::$($CommandName)
Write-Verbose "Defined the function $($FunctionName) and removed the alias $($CommandName)"
} else {
Set-Alias $CommandName $FunctionName -Scope Global
Write-Verbose "Defined the function $($FunctionName) and redefined the alias $($CommandName)"
}
foreach( $pkv in $command.Parameters.GetEnumerator() ){
$parameter = $pkv.Value
if( $parameter.Aliases -match "vb|db|ea|wa|ev|wv|ov|ob" ) { continue }
$param = new-object System.Management.Automation.RuntimeDefinedParameter( $parameter.Name, $parameter.ParameterType, $parameter.Attributes)
$paramdictionary.Add($pkv.Key, $param)
}
return $paramdictionary
}
function New-Autoload {
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$True,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string[]]$Name
,
[Parameter(Position=1,Mandatory=$False,ValueFromPipelineByPropertyName=$true)]
[Alias("BaseName")]
$Alias = $Name
,
[Parameter(Position=2,Mandatory=$False,ValueFromPipelineByPropertyName=$true)]
$Function = $Alias
,
[Parameter(Position=3,Mandatory=$false)]
[String]$Module
,
[Parameter(Mandatory=$false)]
[String]$Scope = '2'
)
begin {
$xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators")
if(!$xlr8r::Get["PSParser"]) {
$xlr8r::Add( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" )
}
}
process {
for($i=0;$i -lt $Name.Count;$i++){
if($Alias -is [Scriptblock]) {
$a = $Name[$i] | &$Alias
} elseif($Alias -is [Array]) {
$a = $Alias[$i]
} else {
$a = $Alias
}
if($Function -is [Scriptblock]) {
$f = $Name[$i] | &$Function
} elseif($Function -is [Array]) {
$f = $Function[$i]
} else {
$f = $Function
}
Write-Verbose "Set-Alias $Module\\$a Invoke-Autoloaded -Scope $Scope"
Set-Alias $a Invoke-Autoloaded -Scope $Scope
$Script:AutoloadHash[$a] = $Name[$i],$Module,$f
Write-Verbose "`$AutoloadHash[$a] = $($Script:AutoloadHash[$a])"
}
}
}
Set-Alias Autoload New-Autoload
$Script:AutoloadHash = @{}
Export-ModuleMember -Function New-Autoload, Invoke-Autoloaded, Get-AutoloadHelp -Alias *
# SIG # Begin signature block
# MIIIDQYJKoZIhvcNAQcCoIIH/jCCB/oCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUb3/clQw2bZEEQ0SGW6DCheFL
# mMegggUrMIIFJzCCBA+gAwIBAgIQKQm90jYWUDdv7EgFkuELajANBgkqhkiG9w0B
# AQUFADCBlTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0
# IExha2UgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYD
# VQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHTAbBgNVBAMTFFVUTi1VU0VS
# Rmlyc3QtT2JqZWN0MB4XDTEwMDUxNDAwMDAwMFoXDTExMDUxNDIzNTk1OVowgZUx
# CzAJBgNVBAYTAlVTMQ4wDAYDVQQRDAUwNjg1MDEUMBIGA1UECAwLQ29ubmVjdGlj
# dXQxEDAOBgNVBAcMB05vcndhbGsxFjAUBgNVBAkMDTQ1IEdsb3ZlciBBdmUxGjAY
# BgNVBAoMEVhlcm94IENvcnBvcmF0aW9uMRowGAYDVQQDDBFYZXJveCBDb3Jwb3Jh
# dGlvbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMfUdxwiuWDb8zId
# KuMg/jw0HndEcIsP5Mebw56t3+Rb5g4QGMBoa8a/N8EKbj3BnBQDJiY5Z2DGjf1P
# n27g2shrDaNT1MygjYfLDntYzNKMJk4EjbBOlR5QBXPM0ODJDROg53yHcvVaXSMl
# 498SBhXVSzPmgprBJ8FDL00o1IIAAhYUN3vNCKPBXsPETsKtnezfzBg7lOjzmljC
# mEOoBGT1g2NrYTq3XqNo8UbbDR8KYq5G101Vl0jZEnLGdQFyh8EWpeEeksv7V+YD
# /i/iXMSG8HiHY7vl+x8mtBCf0MYxd8u1IWif0kGgkaJeTCVwh1isMrjiUnpWX2NX
# +3PeTmsCAwEAAaOCAW8wggFrMB8GA1UdIwQYMBaAFNrtZHQUnBQ8q92Zqb1bKE2L
# PMnYMB0GA1UdDgQWBBTK0OAaUIi5wvnE8JonXlTXKWENvTAOBgNVHQ8BAf8EBAMC
# B4AwDAYDVR0TAQH/BAIwADATBgNVHSUEDDAKBggrBgEFBQcDAzARBglghkgBhvhC
# AQEEBAMCBBAwRgYDVR0gBD8wPTA7BgwrBgEEAbIxAQIBAwIwKzApBggrBgEFBQcC
# ARYdaHR0cHM6Ly9zZWN1cmUuY29tb2RvLm5ldC9DUFMwQgYDVR0fBDswOTA3oDWg
# M4YxaHR0cDovL2NybC51c2VydHJ1c3QuY29tL1VUTi1VU0VSRmlyc3QtT2JqZWN0
# LmNybDA0BggrBgEFBQcBAQQoMCYwJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmNv
# bW9kb2NhLmNvbTAhBgNVHREEGjAYgRZKb2VsLkJlbm5ldHRAWGVyb3guY29tMA0G
# CSqGSIb3DQEBBQUAA4IBAQAEss8yuj+rZvx2UFAgkz/DueB8gwqUTzFbw2prxqee
# zdCEbnrsGQMNdPMJ6v9g36MRdvAOXqAYnf1RdjNp5L4NlUvEZkcvQUTF90Gh7OA4
# rC4+BjH8BA++qTfg8fgNx0T+MnQuWrMcoLR5ttJaWOGpcppcptdWwMNJ0X6R2WY7
# bBPwa/CdV0CIGRRjtASbGQEadlWoc1wOfR+d3rENDg5FPTAIdeRVIeA6a1ZYDCYb
# 32UxoNGArb70TCpV/mTWeJhZmrPFoJvT+Lx8ttp1bH2/nq6BDAIvu0VGgKGxN4bA
# T3WE6MuMS2fTc1F8PCGO3DAeA9Onks3Ufuy16RhHqeNcMYICTDCCAkgCAQEwgaow
# gZUxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJVVDEXMBUGA1UEBxMOU2FsdCBMYWtl
# IENpdHkxHjAcBgNVBAoTFVRoZSBVU0VSVFJVU1QgTmV0d29yazEhMB8GA1UECxMY
# aHR0cDovL3d3dy51c2VydHJ1c3QuY29tMR0wGwYDVQQDExRVVE4tVVNFUkZpcnN0
# LU9iamVjdAIQKQm90jYWUDdv7EgFkuELajAJBgUrDgMCGgUAoHgwGAYKKwYBBAGC
# NwIBDDEKMAigAoAAoQKAADAZBgkqhkiG9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgor
# BgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQUJpn1AoNt
# fkCBtyXmwWmxrRhYWdEwDQYJKoZIhvcNAQEBBQAEggEAWOPeCojDVAZDOQvT+QCH
# satm5ghVu6MCt71WYsb67G6UI1dfQ8vJkI2GddFrEyjECEVoySaVHieBGLpknvMI
# Ek/CdPFUya6pN1IkK7C6TOJRK98ohaiao3EJIf4qmy5uQwwp60dUzcJkfkndJv5t
# 37mUU9JXJWiWk5r/kTUlkYawPd4gheJFi4QOo69t4TCzsbk8pTZTdLm91ByGBr0i
# WrjegJAvfqOT126AwRRVUDbNW04TNNxTx0+ISdoVsjhFR/4F0GpiMYZMZa7BBwpa
# j+VitSQci9I9p1D19eES5wAk1UHbzEFTOz1TXcAz6GTbwgtgTcV1klmSlLghsr6k
# EQ==
# SIG # End signature block
|
PowerShellCorpus/PoshCode/ScriptMethod Example_1.ps1
|
ScriptMethod Example_1.ps1
|
$x = New-Object PSObject | Add-Member -MemberType ScriptMethod -Name Test -Value {
.{
param (
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$Message
)
"This is the message: $Message"
} @args
} -PassThru
# You should now call $x.Test("Hello World")
# But if you call $x.Test() it will prompt you for the $message value
|
PowerShellCorpus/PoshCode/Set-Computername_12.ps1
|
Set-Computername_12.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/VMware Host Network Info.ps1
|
VMware Host Network Info.ps1
|
Connect-VIServer MYVISERVER
$filename = "c:\\DetailedNetworkInfo.csv"
Write "Gathering VMHost objects"
$vmhosts = Get-VMHost | Sort Name | Where-Object {$_.State -eq "Connected"} | Get-View
$MyCol = @()
foreach ($vmhost in $vmhosts){
$ESXHost = $vmhost.Name
Write "Collating information for $ESXHost"
$networkSystem = Get-view $vmhost.ConfigManager.NetworkSystem
foreach($pnic in $networkSystem.NetworkConfig.Pnic){
$pnicInfo = $networkSystem.QueryNetworkHint($pnic.Device)
foreach($Hint in $pnicInfo){
$NetworkInfo = "" | select-Object Host, PNic, Speed, MAC, DeviceID, PortID, Observed, VLAN
$NetworkInfo.Host = $vmhost.Name
$NetworkInfo.PNic = $Hint.Device
$NetworkInfo.DeviceID = $Hint.connectedSwitchPort.DevId
$NetworkInfo.PortID = $Hint.connectedSwitchPort.PortId
$record = 0
Do{
If ($Hint.Device -eq $vmhost.Config.Network.Pnic[$record].Device){
$NetworkInfo.Speed = $vmhost.Config.Network.Pnic[$record].LinkSpeed.SpeedMb
$NetworkInfo.MAC = $vmhost.Config.Network.Pnic[$record].Mac
}
$record ++
}
Until ($record -eq ($vmhost.Config.Network.Pnic.Length))
foreach ($obs in $Hint.Subnet){
$NetworkInfo.Observed += $obs.IpSubnet + " "
Foreach ($VLAN in $obs.VlanId){
If ($VLAN -eq $null){
}
Else{
$strVLAN = $VLAN.ToString()
$NetworkInfo.VLAN += $strVLAN + " "
}
}
}
$MyCol += $NetworkInfo
}
}
}
$Mycol | Sort Host, PNic | Export-Csv $filename -NoTypeInformation
|
PowerShellCorpus/PoshCode/VMtoolsUpgrade_2.ps1
|
VMtoolsUpgrade_2.ps1
|
#####################################################################
#
# Purpose: "Check and upgrade Tools during power cycling"
# Author: David Chung
# Support: IT Infrastructure
# Docs: N/A
#
# Instruction: 1. Create CSV file with list of servers
# 2. Execute script from PowerCLI
# 3. Enter virtual server name
#
#####################################################################
$viserver = read-host "Please enter vCenter Server:"
connect-viserver $viserver
$vms = Import-Csv c:\\server.csv
foreach ($vm.name in $vms)
{
Write-Host $vm.name " - Enabling VMTools Update at Power Cycle"
$vmConfig = New-Object VMware.Vim.VirtualMachineConfigSpec
$vmConfig.Tools = New-Object VMware.Vim.ToolsConfigInfo
$vmConfig.Tools.ToolsUpgradePolicy = "UpgradeAtPowerCycle"
Get-VM $vm.name | where {$_.Extensiondata.ReconfigVM($vmconfig)}
}
|
PowerShellCorpus/PoshCode/ELIM (Event Log IM) 1.1.ps1
|
ELIM (Event Log IM) 1.1.ps1
|
$ELIMServer = $Env:ComputerName
$ELIMChannel = "ELIM"
$ELIMUser = $Env:UserName
function New-ELIMUser {
#.Synopsis
# Send a message to the ELIM (Event Log Instant Messaging) Log
[CmdletBinding()]
param (
# The Computer whose event logs will be used for instant messaging
[String]$Server = $ELIMServer,
# The Log Name to use for instant messaging
[Alias("To")]
[String]$Channel = $ELIMChannel,
# The "Source" for messages that you will send
[Alias("As")]
[String]$UserName = $ELIMUser
)
New-EventLog -LogName $Channel -Source $UserName -ComputerName $Server -EA 0 -EV Failed
if($Failed -and $Failed[0].Exception.Message.StartsWith( "The `"$UserName`" source is already registered" )) {
}
sleep -milli 500
if(!(Get-EventLog -ComputerName $Server -list |where {$_.Log -eq $Channel })) {
throw "Failed to register on server, please check server and username and try again:`n`n$Failed"
}
Set-ELIMDefaults @PSBoundParameters
}
function Set-ELIMDefaults {
#.Synopsis
# Set your default username for the ELIM (Event Log Instant Messaging) Log
#.Description
# Normally your current computer ($Env:ComputerName), UserName ($Env:UserName), and the "ELIM" log are used unless you overwrite it on the console.
# This allows you to override those defaults
param (
# The Computer whose event logs will be used for instant messaging
[String]$Server = $ELIMServer,
# The Log Name to use for instant messaging
[Alias("To")]
[String]$Channel = $ELIMChannel,
# The "Source" for messages that you will send
[Alias("As")]
[String]$UserName = $ELIMUser
)
$script:ELIMServer = $Server
$script:ELIMChannel = $Channel
$script:ELIMUser = $UserName
}
function Send-ELIMMessage {
#.Synopsis
# Send a message to the ELIM (Event Log Instant Messaging) Log
[CmdletBinding()]
param(
# The message to send
[Parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0, ValueFromRemainingArguments=$true, Mandatory=$true)]
[String]$Message,
# The Computer whose event logs will be used for instant messaging
[String]$Server = $ELIMServer,
# The Log Name to use for instant messaging
[Alias("To")]
[String]$Channel = $ELIMChannel,
# The "Source" for messages that you will send
[Alias("As")]
[String]$UserName = $ELIMUser
)
process {
Write-Verbose "Write-EventLog -ComputerName $Server -LogName $Channel -Source $UserName -EventID 1 -Message '$Message'"
Write-EventLog -ComputerName $Server -LogName $Channel -Source $UserName -EventID 1 -Message $Message
}
}
Set-Alias Msg Send-ELIMMessage
function Start-ELIM {
[CmdletBinding()]
param(
# The Computer whose event logs will be used for instant messaging
[String]$Server = $ELIMServer,
# The Log Name to use for instant messaging
[Alias("To")]
[String]$Channel = $ELIMChannel,
# The "Source" for messages that you will send
[Alias("As")]
[String]$UserName = $ELIMUser,
# Time stamp format for output
$TimeStampFormat = "dd-MM hh:mm:ss",
# The default background color for instant messages
$Background = "Black",
# The highlight color for instant messages
$HighlightBackground = "White",
# The regular expression for highlighting (defaults to your username)
$HighlightRegex = ".*${UserName}.*",
# Available colors for user names. You can use any of "Black", "DarkBlue", "DarkGreen", "DarkCyan", "DarkRed", "DarkMagenta", "DarkYellow", "Gray", "DarkGray", "Blue", "Green", "Cyan", "Red", "Magenta", "Yellow", "White" -- but you want to exclude any of them which aren't readable.
[ConsoleColor[]]$Colors = $("DarkGreen", "DarkCyan", "DarkRed", "DarkYellow", "Gray", "DarkGray", "Blue", "Green", "Cyan", "Red", "Magenta", "Yellow", "White"),
[Switch]$Force
)
end {
Set-ELIMDefaults -Server $Server -Channel $Channel -UserName $UserName
try {
$exists = [System.Diagnostics.EventLog]::SourceExists($UserName, $Server)
} catch {}
if(!$exists) {
Write-Warning "Your user name ($UserName) doesn't exist on '$Server', you won't be able to send messages until you run New-ELIMUser in an elevated console"
} else {
$RealChannel = [System.Diagnostics.EventLog]::LogNameFromSourceName($UserName,$Server)
if($Channel -ne $RealChannel -and !$Force) {
throw "Your username is registered to SEND to '$RealChannel' not '$Channel', if you want to LISTEN to '$Channel' anyway, use -Force"
}
}
$elim = Get-EventLog -ComputerName $Server -list | where { $_.Log -eq $Channel }
if(!$elim) {
throw "Failed to connect to the '$Channel' channel on the server ($Server)."
} else {
Register-ObjectEvent $elim EntryWritten -Action {
$Message = "[{0:$($Event.MessageData.TimeStampFormat)}] {1}: {2}" -f $EventArgs.Entry.TimeGenerated, $EventArgs.Entry.Source, $EventArgs.Entry.Message
$Color = $Event.MessageData.Colors[(([int[]][char[]]"$($EventArgs.Entry.Source)" | measure -sum ).Sum % $Event.MessageData.Colors.Count)]
if( $EventArgs.Entry.Source -ne $Event.MessageData.UserName -and $Message -match $Event.MessageData.HighlightRegex ) {
Write-Host $Message -ForegroundColor $Color -BackgroundColor $Event.MessageData.HighlightBackground
} else {
Write-Host $Message -ForegroundColor $Color -BackgroundColor $Event.MessageData.Background
}
} -MessageData @{
Server = $Server
Channel = $Channel
UserName = $UserName
TimeStampFormat = $TimeStampFormat
Background = $Background
HighlightBackground = $HighlightBackground
HighlightRegex = $HighlightRegex
Colors = $Colors
}
}
}
}
Export-ModuleMember -Function * -Alias *
|
PowerShellCorpus/PoshCode/LocalStorage module.ps1
|
LocalStorage module.ps1
|
if($Args) {
[string]$script:LocalStorageModuleName = $Args[0]
} elseif($LocalStorageModuleName) {
[string]$script:LocalStorageModuleName = $LocalStorageModuleName
} else {
[string]$script:LocalStorageModuleName = "LocalStorage"
}
function Get-LocalStoragePath {
#.Synopsis
# Gets the LocalApplicationData path for the specified company\\module
#.Description
# Appends Company\\Module to the LocalApplicationData, and ensures that the folder exists.
param(
# The name of the module you want to access storage for
[Parameter(Position=0)]
[ValidateScript({
$invalid = $_.IndexOfAny([IO.Path]::GetInvalidFileNameChars())
if($invalid -eq -1){
return $true
} else {
throw "Invalid character in Module Name '$_' at $invalid"
}
})]
[string]$Module = $LocalStorageModuleName,
# The name of a "company" to use in the storage path (defaults to "Huddled")
[Parameter(Position=1)]
[ValidateScript({
$invalid = $_.IndexOfAny([IO.Path]::GetInvalidFileNameChars())
if($invalid -eq -1){
return $true
} else {
throw "Invalid character in Company Name '$_' at $invalid"
}
})]
[string]$Company = "Huddled"
)
end {
$path = Join-Path ([Environment]::GetFolderPath("LocalApplicationData")) $Company
$path = Join-Path $path $Module
if(!(Test-Path $path -PathType Container)) {
$null = New-Item $path -Type Directory -Force
}
$script:LocalStorageModuleName = $Module
Write-Output $path
}
}
function Export-LocalStorage {
#.Synopsis
# Saves the object to local storage with the specified name
#.Description
# Persists objects to disk using Get-LocalStoragePath and Export-CliXml
param(
# A unique valid file name to use when persisting the object to disk
[Parameter(Mandatory=$true, Position=0)]
[ValidateScript({
$invalid = $_.IndexOfAny([IO.Path]::GetInvalidFileNameChars())
if($invalid -eq -1){
return $true
} else {
throw "Invalid character in Object Name '$_' at $invalid"
}
})]
[string]$name,
# The object to persist to disk
[Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true)]
$InputObject,
# A unique valid module name to use when persisting the object to disk
[Parameter(Position=2)]
[ValidateScript({
$invalid = $_.IndexOfAny([IO.Path]::GetInvalidFileNameChars())
if($invalid -eq -1){
return $true
} else {
throw "Invalid character in Module Name '$_' at $invalid"
}
})]
[string]$Module = $LocalStorageModuleName
)
begin {
$path = Join-Path (Get-LocalStoragePath $Module) $Name
if($PSBoundParameters.ContainsKey("InputObject")) {
Write-Verbose "Clean Export"
Export-CliXml -Path $Path -InputObject $InputObject
} else {
$Output = @()
}
}
process {
$Output += $InputObject
}
end {
if($PSBoundParameters.ContainsKey("InputObject")) {
Write-Verbose "Tail Export"
# Avoid arrays when they're not needed:
if($Output.Count -eq 1) { $Output = $Output[0] }
Export-CliXml -Path $Path -InputObject $Output
}
}
}
function Import-LocalStorage {
#.Synopsis
# Loads an object with the specified name from local storage
#.Description
# Retrieves objects from disk using Get-LocalStoragePath and Import-CliXml
param(
# A unique valid file name to use when persisting the object to disk
[Parameter(Mandatory=$true, Position=0)]
[ValidateScript({
$invalid = $_.IndexOfAny([IO.Path]::GetInvalidFileNameChars())
if($invalid -eq -1){
return $true
} else {
throw "Invalid character in Object Name '$_' at $invalid"
}
})]
[string]$name,
# A unique valid module name to use when persisting the object to disk
[Parameter(Position=1)]
[ValidateScript({
$invalid = $_.IndexOfAny([IO.Path]::GetInvalidFileNameChars())
if($invalid -eq -1){
return $true
} else {
throw "Invalid character in Module name '$_' at $invalid"
}
})]
[string]$Module = $LocalStorageModuleName,
# A default value (used in case there's an error importing):
[Parameter(Position=2)]
[Object]$DefaultValue
)
begin {
if($PSBoundParameters.ContainsKey("Module")) {
$script:LocalStorageModuleName = $Module
}
}
end {
try {
$path = Join-Path (Get-LocalStoragePath $Module) $Name
Import-CliXml -Path $Path
} catch {
if($PSBoundParameters.ContainsKey("DefaultValue")) {
Write-Output $DefaultValue
} else {
throw
}
}
}
}
Export-ModuleMember -Function Import-LocalStorage, Export-LocalStorage, Get-LocalStoragePath -Variable LocalStorageModuleName
|
PowerShellCorpus/PoshCode/Stop-Pipeline.ps1
|
Stop-Pipeline.ps1
|
$Wasp = Add-Type -MemberDefinition @'
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
'@ -Passthru
$null = Add-Type -Assembly System.Windows.Forms
filter Stop-Pipeline( [scriptblock]$condition = {$true} ) {
if (& $condition) {
## You need to make sure PowerShell is the foreground Window before you send Ctrl+C
if($Wasp::SetForegroundWindow( (Get-Process -id $PID).MainWindowHandle )) {
[System.Windows.Forms.SendKeys]::SendWait("^C")
} else {
Throw (New-Object System.Management.Automation.PipelineStoppedException)
}
$condition = { $true } ## Make sure that once it's true, it's always true
} else { ## Sometimes, the commands upstream manage to send out extras
$_
}
}
|
PowerShellCorpus/PoshCode/Select-Grid.ps1
|
Select-Grid.ps1
|
#requires -version 2.0
### Import the WPF assemblies
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName PresentationCore
Set-PSDebug -Strict
## Select-Grid
## Displays objects in a grid view and returns (only) the selected ones when closed.
########################################################################################################################
## Usage:
## ls | Select-Grid Name, Length, Mode, LastWriteTime
## ps | Select-Grid ProcessName, Id, VM, WS, PM, Product, Path
## Select-Grid Name, Length, Mode, LastWriteTime -Input (ls)
##
## Take advantage of the graphing:
## ls | Select-Grid Name,Length,LastModifiedTime,Mode -Title $pwd -Sort Length -Graph Length
## Kill the selected processes:
## ps | Select-Grid ProcessName, Id, VM, WS, PM, Product, Path -Title "Processes" -Sort WS -Graph VM,WS,PM | kill
########################################################################################################################
## History:
## v3.1 - Fixed a bug with not passing the graph parameter
## v3.0 - Added CellTemplate for graphing (first release to PowerShellCentral.com/scripts)
## v2.5 - Added Multi-select and made it output the selected items
## v2.3 - Added Title and made columns dragable
## v2.2 - Fixed pipeline problems
## v2.1 - Added "Get-Default" to populate blank rows
## v2.0 - Added clickable headers and sorting
## -- broken on columns with blanks?
## v1.0 - Basic grid with data-binding
## -- broken on pipeline
########################################################################################################################
Cmdlet Select-Grid -ConfirmImpact low -snapin Huddled.WPF
{
Param (
[Parameter(Position=0)][string[]]$Properties,
[Parameter(Position=1)][string[]]$Title,
[Parameter(Position=2)][string[]]$Sort,
[Parameter(Position=3)][string[]]$Graph,
[Parameter(Mandatory=$true, ValueFromPipeline=$true)] $InputObjects
)
BEGIN {
if ($CommandLineParameters.ContainsKey("InputObjects")) {
$outputObjects = @(,$InputObjects)
} else {
$outputObjects = @()
}
}
PROCESS {
### Collect together all input objects
$outputObjects += $InputObjects
}
END {
### Create our window and listview
$window = New-Object System.Windows.Window
$window.SizeToContent = "WidthAndHeight"
$window.SnapsToDevicePixels = $true
$window.Content = New-Object System.Windows.Controls.ListView
if($Title) {
$window.Title = $Title
} else {
$window.Title = $outputObjects[-1].GetType().Name
}
### The ListView takes ViewBase object which controls the layout and appearance
### We'll use a GridView
$window.Content.View = New-Object System.Windows.Controls.GridView
$window.Content.View.AllowsColumnReorder = $true
$columns = Get-PropertyTypes $outputObjects ([ref]$Properties)
### Make columns (use Properties instead of Columns.Keys to preserve order)
foreach($Name in $Properties) {
### Try to ensure that every object has _some_ value for each column (so sorting works)
$outputObjects | add-member -Type NoteProperty -Name $Name -value (Get-DefaultValue($columns[$name])) -ea SilentlyContinue
## For each property, make a column
$gvc = New-Object System.Windows.Controls.GridViewColumn
## And bind the data ...
$gvc.DisplayMemberBinding = New-Object System.Windows.Data.Binding $Name
## In order to add sorting, we need to create the header ourselves
$gvc.Header = New-Object System.Windows.Controls.GridViewColumnHeader
$gvc.Header.Content = $Name
## Add a click handler to enable sorting ...
$gvc.Header.add_click({
$view = [System.Windows.Data.CollectionViewSource]::GetDefaultView( $outputObjects )
$sd = new-object System.ComponentModel.SortDescription $this.Content, $(
if($view.SortDescriptions[0].PropertyName -eq $this.Content) {
switch($view.SortDescriptions[0].Direction) {
"Ascending" { "Descending" } "Descending" { "Ascending" }
}} else { "Ascending" } )
$view.SortDescriptions.Clear()
$view.SortDescriptions.Add($sd)
# if($view.SortDescriptions.Count -gt 2) { $view.SortDescriptions.RemoveAt(2) }
$view.Refresh()
})
# Format-Column-Conditionally $obj, $Name, $gvc
## Use that column in the view
$window.Content.View.Columns.Insert($window.Content.View.Columns.Count,$gvc)
}
$Graph = @($Graph | Where-Object { $Properties -contains $_ })
if( $Graph.Count -gt 0 ) {
FormatColumn-Percent $outputObjects $window.Content.View $Graph
}
## Databind the argument
$window.Content.ItemsSource = $outputObjects
## Add an initial sort ...
$sd = new-object System.ComponentModel.SortDescription
$sd.PropertyName = &{ if($Sort) { $Sort }else{ $Properties[0] } }
$sd.Direction = "Descending"
[System.Windows.Data.CollectionViewSource]::GetDefaultView( $outputObjects ).SortDescriptions.Add($sd)
## Show the window
$Null = $window.ShowDialog()
$window.Content.SelectedItems
}
}
## return a hash of property names and maximum values for each
function Get-Max($collection,$properties) {
$max = @{}
$collection | Measure-Object $properties -Max | ForEach-Object { $max[$($_.Property)] = $($_.Maximum)}
return $max
}
## a quick and easy function to create default-value instances of any type
function Get-DefaultValue([type]$type) {
if( $type.IsValueType) {
[Activator]::CreateInstance($type)
} else {
$null
}
}
function Get-PropertyTypes($outputObjects, [ref]$Properties) {
### Collect the columns we're going to use
$columns = @{}
### if we have a list, use all the items on the list that are defined
if($Properties.Value) {
$Properties.Value = $outputObjects | Get-Member $Properties.Value -type Properties | ForEach-Object { $_.Name }
} else {
### if we don't have a list, make one, from all the items...
$Properties.Value = $outputObjects | Get-Member -type Properties | ForEach-Object { $_.Name }
}
### Figure out the types
ForEach($Name in $Properties.Value) {
$columns[$name] = $Null
ForEach($obj in $outputObjects) {
if( $obj.($Name) ) {
$columns[$name] = $obj.($Name).GetType()
break;
}
}
}
return $columns
}
#############################################################
## Conditionally format the columns ...
function FormatColumn-Percent( $outputObjects, $gridview, $properties)
{
# Calculate the max values
$max = Get-Max $outputObjects $properties
# And finally, set the CellTemplace on those columns...
foreach($property in $properties) {
# And then calculate the percentages, based on that...
# $outputObjects.Value | Add-Member ScriptProperty "$($property)Percent" {(`$this.${property} -as [int]) / $($max.($property))}
# $outputObjects | Add-Member ScriptProperty "$($property)Percent" $executioncontext.InvokeCommand.NewScriptBlock(
# "(`$this.$($property) -as [double]) / $($max.($property))")
foreach($obj in $outputObjects) {
Add-Member NoteProperty "$($property)Percent" (($($obj.$($property)) -as [double]) / $($max.($property))) -input $obj
}
$column = @($gridview.Columns | ? { $_.Header.Content -eq $property })[0];
## dump the binding and use a template instead... (this shouldn't be necessary)...
$column.DisplayMemberBinding = $null
$column.CellTemplate = `
[Windows.Markup.XamlReader]::Load(
(New-Object System.Xml.XmlNodeReader (
[Xml]"<DataTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>
<Grid>
<Rectangle Margin='-6,0' VerticalAlignment='Stretch' RenderTransformOrigin='0,1' >
<Rectangle.Fill>
<LinearGradientBrush StartPoint='0,0' EndPoint='1,0'>
<GradientStop Color='#FFFF4500' Offset='0' />
<GradientStop Color='#FFFF8585' Offset='1' />
</LinearGradientBrush>
</Rectangle.Fill>
<Rectangle.RenderTransform>
<ScaleTransform ScaleX='{Binding $($property)Percent}' ScaleY='1' />
</Rectangle.RenderTransform>
</Rectangle>
<TextBlock Width='100' Margin='-6,0' TextAlignment='Right' Text='{Binding $property}' />
</Grid>
</DataTemplate>")))
}
}
|
PowerShellCorpus/PoshCode/Edit-Variable.ps1
|
Edit-Variable.ps1
|
function Edit-Variable {
#.Parameter name
# The name (or path) to the variable to edit.
#.Parameter Environment
# Optional switch to force evaluating the name as an environment variable. You don't need this if you specify the path as env:Path instead of just "Path"
#.Example
# Edit-Variable -env path
#.Example
# Edit-Variable profile
#.Example
# Edit-Variable env:\\path
#.Example
# Edit-Variable variable:profile
param(
[Parameter(Position=0,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
[string]$name
,
[switch]$Environment
)
process {
$path = Resolve-Path $name -ErrorAction SilentlyContinue
if($Environment) {
## Force Env: if they said -Env
if(!$path -or $Path.Provider.Name -ne "Environment") {
$path = Resolve-Path "Env:$name"
}
} else {
if($Path -and $Path.Provider.Name -eq "Environment") {
$Environment = $true
} elseif(!$path -or $Path.Provider.Name -ne "Variable") {
$path = Resolve-Path "Variable:$name" -ErrorAction SilentlyContinue
}
}
$temp = [IO.Path]::GetTempFileName()
if($path) {
if(!$Environment) {
$value = (Get-Variable $path.ProviderPath).Value
$string = $value -is [String]
if(!$string) {
Write-Warning "Variable $name is not a string variable, editing as CliXml"
Export-Clixml $temp -InputObject $Value
} else {
Set-Content $temp $Value
}
} else {
Get-Content $path | Set-Content $temp
}
} else {
$Environment = $false
New-Variable $Name
$path = Resolve-Path Variable:$name -ErrorAction SilentlyContinue
}
if(!$path) {
Write-Error "Cannot find variable '$name' because it does not exist."
} else {
# Let the user edit it in notepad, and see if they save it
$pre = Get-ChildItem $temp
(Start-Process notepad $temp -passthru).WaitForExit()
$post = Get-ChildItem $temp
if($post.LastWriteTime -gt $pre.LastWriteTime) {
if(!$Environment) {
if(!$string) {
Import-CliXml $temp | Set-Variable $path.ProviderPath
} else {
Get-Content $temp | Set-Variable $path.ProviderPath
}
} else {
Get-Content $temp | Set-Content $path
}
}
}
Remove-Item $temp -ErrorAction SilentlyContinue
}
}
Set-Alias vared Edit-Variable
|
PowerShellCorpus/PoshCode/Get-Snapinfo_1.ps1
|
Get-Snapinfo_1.ps1
|
Function Get-Snapinfo {
<#
.Synopsis
Get the snapshot info out of a Virtual Machine Managed Entity. Most useful for
reporting!
.PARAMETER VM
VirtualMachine object to scan to extract snapshots from
.PARAMETER VirtualMachineSnapshotTree
used to recursively crawl a VM for snapshots... just use -VM
.PARAMETER Filter
Specify the name of the snapshots you want to retrieve, will perform a regex match.
.Example
Get-View -ViewType virtualmachine | Get-Snapinfo
.Example
Get-View -ViewType virtualmachine | Get-Snapinfo -Filter "^SMVI"
.notes
#Requires -verson 2
Author: Glenn Sizemore
get-admin.com/blog/?p=879
#>
[cmdletBinding(SupportsShouldProcess=$false,DefaultParameterSetName="VM")]
Param(
[parameter(Mandatory=$true,ValueFromPipeline=$true, ParameterSetName="VM")]
[VMware.Vim.VirtualMachine[]]
$VM,
[parameter(Mandatory=$true,ValueFromPipeline=$true, ParameterSetName="Snaptree")]
[VMware.Vim.VirtualMachineSnapshotTree[]]
$VirtualMachineSnapshotTree,
[parameter(ParameterSetName="VM")]
[parameter(ParameterSetName="Snaptree")]
[string]
$Filter
)
Process {
switch ($PScmdlet.ParameterSetName)
{
"Snaptree"
{
Foreach ($Snapshot in $VirtualMachineSnapshotTree) {
Foreach ($ChildSnap in $Snapshot.ChildSnapshotList) {
if ($ChildSnap) {
Get-Snapinfo -VirtualMachineSnapshotTree $ChildSnap -Filter $Filter
}
}
If ($Snapshot.Name -match $Filter ) {
write-output $Snapshot | Select Name, CreateTime, Vm, Snapshot
}
}
}
"VM"
{
Foreach ($v in $VM) {
Get-Snapinfo -VirtualMachineSnapshotTree $v.Snapshot.RootSnapshotList -Filter $Filter
}
}
}
}
}
|
PowerShellCorpus/PoshCode/a706909d-64de-4e36-abce-4f3cc5441fde.ps1
|
a706909d-64de-4e36-abce-4f3cc5441fde.ps1
|
$vm = get-vm testvm
$ds = $vm | get-datastore
move-vm -VM $vm -Destination (get-vmhost MyDestination) -Datastore $ds
|
PowerShellCorpus/PoshCode/Google Chromium Download_1.ps1
|
Google Chromium Download_1.ps1
|
<#
.Synopsis
Download Google Chromium if there is a later build.
.Description
Download Google Chromium if there is a later build.
http://poshcode.org/2422
#>
Set-StrictMode -Version Latest
Import-Module bitstransfer
# comment out when not debugging
$VerbosePreference = "Continue"
#$VerbosePreference = "SilentlyContinue"
$versionFile = "$Env:temp\\latestChromiumVersion.txt"
$installedChromiumVersion = 0
trap [Exception] {
write-host
write-error $("TRAPPED: " + $_.Exception.GetType().FullName);
write-error $("TRAPPED: " + $_.Exception.Message);
[string]($installedChromiumVersion) > $versionFile
exit;
}
if (Test-Path $versionFile)
{ $installedChromiumVersion = [int32] (cat $versionFile) }
#$latestChromiumBuildURL ="http://build.chromium.org/f/chromium/snapshots/chromium-rel-xp"
$latestChromiumBuildURL ="http://build.chromium.org/f/chromium/snapshots/Win"
Start-BitsTransfer "$latestChromiumBuildURL/LATEST" $versionFile
$latestChromiumVersion = [int32] (cat $versionFile)
if ($installedChromiumVersion -eq $latestChromiumVersion)
{
Write-Verbose "Exiting... Version $installedChromiumVersion is the latest."
return
}
$installerAppName = "mini_installer"
$installer = "$Env:temp\\$installerAppName.exe"
Write-Verbose "Initiating download of new version $latestChromiumVersion"
Start-BitsTransfer "$latestChromiumBuildURL/$latestChromiumVersion/mini_installer.exe" $installer
Write-Verbose "Installing new version of Chromium"
Invoke-Item $installer
$installerRunning = 1
while (!($installerRunning -eq $null))
{
sleep 5
$installerRunning = ( Get-Process | ? {$_.ProcessName -match "$installerAppName"} )
}
Write-Verbose "New Chromium Installed! Please restart the Chromium browser"
|
PowerShellCorpus/PoshCode/Sync-Time.ps1
|
Sync-Time.ps1
|
function sync-time(
[string] $server = "clock.psu.edu",
[int] $port = 37)
{
$servertime = get-time -server $server -port $port -set
#leave off -set to just check the remote time
write-host "Server time:" $servertime
write-host "Local time :" $(date)
}
|
PowerShellCorpus/PoshCode/Select-ToString_1.ps1
|
Select-ToString_1.ps1
|
[CmdletBinding(DefaultParameterSetName='DefaultParameter')]
param(
[Parameter(ValueFromPipeline=$true)]
[System.Management.Automation.PSObject]
${InputObject},
[Parameter(ParameterSetName='DefaultParameter', Position=0)]
[System.String[]]
${Property},
[Parameter(ParameterSetName='DefaultParameter')]
[System.String[]]
${ExcludeProperty},
[Parameter(ParameterSetName='DefaultParameter')]
[System.String]
${ExpandProperty},
[Switch]
${Unique},
[Parameter(ParameterSetName='DefaultParameter')]
[ValidateRange(0, 2147483647)]
[System.Int32]
${Last},
[Parameter(ParameterSetName='DefaultParameter')]
[ValidateRange(0, 2147483647)]
[System.Int32]
${First},
[Parameter(ParameterSetName='DefaultParameter')]
[ValidateRange(0, 2147483647)]
[System.Int32]
${Skip},
[Parameter(ParameterSetName='IndexParameter')]
[ValidateRange(0, 2147483647)]
[System.Int32[]]
${Index}
)
begin
{
try {
$propHash = @()
foreach($Prop in $Property) {
$propHash += @(@{Name=$Prop; Expression=$(iex "{if(`$_.'$Prop' -is [Array]){ ""{`$(`$_.'$Prop' -join "", "")}"" }else{ `$_.'$Prop' } }")})
}
$PSBoundParameters['Property'] = $propHash
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Select-Object', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Select-Object
.ForwardHelpCategory Cmdlet
#>
|
PowerShellCorpus/PoshCode/Autoload (beta 6).ps1
|
Autoload (beta 6).ps1
|
#Requires -Version 2.0
## Version History
## beta 6 - 2010.05.18
## Fixed a bug in output when multiple outputs happen in the END block
## beta 5 - 2010.05.10
## Fixed non-pipeline use using $MyInvocation.ExpectingInput
## beta 4 - 2010.05.10
## I made a few tweaks and bug fixes while testing it's use with PowerBoots.
## beta 3 - 2010.05.10
## fix for signed scripts (strip signature)
## beta 2 - 2010.05.09
## implement module support
## beta 1 - 2010.04.14
## Initial Release
## Automatically load functions from scripts on-demand, instead of having to dot-source them ahead of time, or reparse them from the script every time.
## To use:
## 1) Create a function. To be 100% compatible, it should specify pipeline arguments
## For example:
<#
function Skip-Object {
param(
[int]$First = 0, [int]$Last = 0, [int]$Every = 0, [int]$UpTo = 0,
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
$InputObject
)
begin {
if($Last) {
$Queue = new-object System.Collections.Queue $Last
}
$e = $every; $UpTo++; $u = 0
}
process {
$InputObject | where { --$First -lt 0 } |
foreach {
if($Last) {
$Queue.EnQueue($_)
if($Queue.Count -gt $Last) { $Queue.DeQueue() }
} else { $_ }
} |
foreach {
if(!$UpTo) { $_ } elseif( --$u -le 0) { $_; $U = $UpTo }
} |
foreach {
if($every -and (--$e -le 0)) { $e = $every } else { $_ }
}
}
}
#>
## 2) Put the function into a script with the same name (in our case: Skip-Object.ps1)
## 3) Put the script in your PATH ($env:Path) somewhere (i have a "scripts" folder I add to my path as part of my profile)
## 4) Dot-source this file, or include it as part of your profile
## 5) Add one line to your profile (or on the commandline):
<#
autoload Skip-Object
#>
## This tells us that you want to have that function loaded for you out of the script file if you ever try to use it.
## Now, you can just use the function:
## 1..10 | Skip-Object -first 2 -upto 2
function Autoloaded {
[CmdletBinding()]Param()
DYNAMICPARAM {
$CommandName = $MyInvocation.InvocationName
if(!$Script:AutoloadHash[$CommandName]) {
do {
$Alias = $CommandName
$CommandName = Get-Alias $CommandName -ErrorAction SilentlyContinue | Select -Expand Definition
} while(!$Script:AutoloadHash[$Alias] -and (Get-Alias $CommandName -ErrorAction SilentlyContinue))
$CommandName = $Alias
}
if(!$Script:AutoloadHash[$CommandName]) { throw "Unable to determine command!" }
Write-Verbose "Autoloaded DynamicParam: $CommandName from $($Script:AutoloadHash[$CommandName])"
$ScriptName, $ModuleName = $Script:AutoloadHash[$CommandName]
if(!$ScriptName){ $ScriptName = $CommandName }
if($ModuleName) {
$Module = Get-Module $ModuleName
} else { $Module = $null }
## Determine the command name based on the alias used to invoke us
## Store the parameter set for use in the function later...
$paramDictionary = new-object System.Management.Automation.RuntimeDefinedParameterDictionary
# $command = Get-Command $MyInvocation.InvocationName -Type ExternalScript
#$externalScript = $ExecutionContext.InvokeCommand.GetCommand( $CommandName, [System.Management.Automation.CommandTypes]::ExternalScript )
$externalScript = Get-Command $ScriptName -Type ExternalScript | Select -First 1
Write-Verbose "Processing Script: $($externalScript |Out-String)"
$parserrors = $null
$prev = $null
$script = $externalScript.ScriptContents
[System.Management.Automation.PSToken[]]$tokens = [PSParser]::Tokenize( $script, [ref]$parserrors )
[Array]::Reverse($tokens)
ForEach($token in $tokens) {
if($prev -and $token.Content -eq "# SIG # Begin signature block") {
$script = $script.SubString(0, $token.Start )
}
if($prev -and $token.Type -eq "Keyword" -and $token.Content -ieq "function" -and $prev.Content -eq $CommandName ) {
$script = $script.Insert( $prev.Start, "global:" )
}
$prev = $token
}
if($Module) {
$script = Invoke-Expression "{ $Script }"
Write-Verbose "What the $($Module)"
&$Module $Script | Out-Null
$command = Get-Command $CommandName -Type Function
Write-Verbose "Loaded Module Function: $($command |Out-String)"
} else {
Invoke-Expression $script | out-null
$command = Get-Command $CommandName -Type Function
Write-Verbose "Loaded Local Function: $($command |Out-String)"
}
if(!$command) {
throw "Something went wrong autoloading the $($CommandName) function. Function definition doesn't exist in script: $($externalScript.Path)"
}
Remove-Item Alias::$($CommandName)
Write-Verbose "Defined the function and removed the alias... $($command | Out-string)"
foreach( $pkv in $command.Parameters.GetEnumerator() ){
$parameter = $pkv.Value
if( $parameter.Aliases -match "vb|db|ea|wa|ev|wv|ov|ob" ) { continue }
$param = new-object System.Management.Automation.RuntimeDefinedParameter( $parameter.Name, $parameter.ParameterType, $parameter.Attributes)
$paramdictionary.Add($pkv.Key, $param)
}
return $paramdictionary
}#DynamicParam
begin {
Write-Verbose "Autoloaded Begin: $CommandName"
#Write-Host "Parameters: $($PSBoundParameters | ft | out-string)" -Fore Magenta
$global:command = $ExecutionContext.InvokeCommand.GetCommand( $CommandName, [System.Management.Automation.CommandTypes]::Function )
$scriptCmd = {& $command @PSBoundParameters | Write-Output }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($myInvocation.ExpectingInput)
}
process
{
Write-Verbose "Autoloaded Process: $CommandName ($_)"
try {
if($_) {
$steppablePipeline.Process($_)
} else {
$steppablePipeline.Process()
}
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
Write-Verbose "Autoloaded End: $CommandName"
}
}#AutoLoaded
function autoload {
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$True,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string[]]$Name
,
[Parameter(Position=1,Mandatory=$False,ValueFromPipelineByPropertyName=$true)]
[Alias("BaseName")]
$Alias = $Name
,
[Parameter(Position=2,Mandatory=$false)]
[String]$Module
,
[Parameter(Mandatory=$false)]
[String]$Scope = '2'
)
begin {
$xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators")
if(!$xlr8r::Get["PSParser"]) {
$xlr8r::Add( "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" )
}
}
process {
for($i=0;$i -lt $Name.Count;$i++){
if($Alias -is [Scriptblock]) {
$a = $Name[$i] | &$Alias
} elseif($Alias -is [Array]) {
$a = $Alias[$i]
} else {
$a = $Alias
}
Write-Verbose "Set-Alias $Module\\$a Autoloaded -Scope $Scope"
Set-Alias $a Autoloaded -Scope $Scope
$Script:AutoloadHash[$a] = $Name[$i],$Module
Write-Verbose "`$AutoloadHash[$a] = $($Script:AutoloadHash[$a])"
}
}
}
$Script:AutoloadHash = @{}
|
PowerShellCorpus/PoshCode/Asp_2.net-Using httpConext.ps1
|
Asp_2.net-Using httpConext.ps1
|
Default.aspx
----------------
Partial Class _Default
Inherits System.Web.UI.Page
Dim var1 As String
Dim var2 As String
Protected Sub lnk_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnk.Click
Context.Items("Nome") = var1
Context.Items("Email") = var2
Server.Transfer("pagina3.aspx")
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
var1 = "20091005"
var2 = "20091106"
End Sub
End Class
pagina3.aspx
--------------------------
Partial Class pagina3
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim context As HttpContext = HttpContext.Current
Label1.Text = CStr(context.Items("Nome"))
Label2.Text = CStr(context.Items("Email"))
End Sub
End Class
|
PowerShellCorpus/PoshCode/Spin-Busy_2.ps1
|
Spin-Busy_2.ps1
|
## Spin-Busy displays a "spinning" character with each step reflecting a single pipeline object being passed.
## The current cursor position, fg/bg colors, screen width, etc. can be specified or automatically detected.
##
## This is *very* loosly adapted from Out-Working by Joel Bennett (http://powershellcentral.com/scripts/105).
##
## Parameters:
## -msWait Can be specified in order to insert a delay (in ms) after each character is written
## -spinStr Can be specified in order to use an alternate set of "spin" characters (see below)
## -spinChars Can be specified in order to use an alternate set of "spin" characters (see below)
## -rawUI Can be specified if an alternate console window is to be used
## -bgColor Can be specified to use a background color different than the current configuration
## -fgColor Can be specified to use a foreground color different than the current configuration
## -curPos Can be specified to spin in a different location than the current cursor position
## -startX Can be specified to start spinning at a different "X" coordinate than the current cursor position
## -maxX Can be specified to limit spinning to less than the current window width
## -trails Can be used to leave a "trail" of characters to help with longer term waits
##
## If specified, -spinStr is passed as a string of characters with the
## last 2 characters being the trailing and blank character, respectively.
## Default: '-\\|/. ', spinning '-\\|/', trailing with '.' and blanking empty cells with ' ' when complete.
##
## If specified, -spinChars is passed as an array of characters with the
## last 2 elements being the trailing and blank character, respectively.
## Default: [Char[]]$spinStr.ToCharArray()
##
## Examples:
## $t = (0..1000 | Spin-Busy)
## $t = (0..1000 | Spin-Busy -trails)
## $t = (0..1000 | Spin-Busy -mswait 1 -trails)
## $t = (0..1000 | Spin-Busy -mswait 1 -spinStr "123456789. " -trails)
## $t = (0..1000 | Spin-Busy 1 -fgColor "Red" -trails)
## $t = (0..1000 | Spin-Busy 1 -fgColor "Red" -bgColor "Black" -trails)
function Spin-Busy {
param(
[Int] $msWait = 0,
[String] $spinStr = '-\\|/. ',
[Char[]] $spinChars = [Char[]] ($spinStr.ToCharArray()),
[System.Management.Automation.Host.PSHostRawUserInterface] $rawUI = (Get-Host).UI.RawUI,
[ConsoleColor] $bgColor = $rawUI.BackgroundColor,
[ConsoleColor] $fgColor = $rawUI.ForegroundColor,
[System.Management.Automation.Host.Coordinates] $curPos = $rawUI.Get_CursorPosition(),
[Int32] $startX = $curPos.X,
[Int32] $maxX = $rawUI.WindowSize.Width,
[Switch] $trails
)
begin {
$trailCell = $rawUI.NewBufferCellArray(@($spinChars[-2]), $fgColor, $bgColor);
$blankCell = $rawUI.NewBufferCellArray(@($spinChars[-1]), $fgColor, $bgColor);
$spinCells = $spinChars[0..($spinChars.Count - 3)];
for ($i=0; $i -lt ($spinCells.Count); ++$i) {
$spinCells[$i] = $rawUI.NewBufferCellArray(@($spinCells[$i]), $fgColor, $bgColor)
}
$charNdx = 0;
}
process {
if ($charNdx -lt $spinCells.Count) {
$rawUI.SetBufferContents($curPos, $spinCells[$charNdx++]);
}
else {
$charNdx = 0;
$rawUI.SetBufferContents($curPos, $trailCell);
if ($trails) {
if (++$curPos.X -gt $maxX) {
do {
--$curPos.X;
$rawUI.SetBufferContents($curPos, $blankCell);
} until ($curPos.X -le $startX);
}
}
}
Start-Sleep -milliseconds $msWait;
$_
}
end {
do {
$rawUI.SetBufferContents($curPos, $blankCell);
}
until (--$curPos.X -le $startX);
}
}
|
PowerShellCorpus/PoshCode/Set-PowerGUIWelcomePage_1.ps1
|
Set-PowerGUIWelcomePage_1.ps1
|
########################################################
# Modifies the default PowerGUI admin console
# welcome screen to the mht file you supply
# Details available at:
# http://dmitrysotnikov.wordpress.com/2009/02/11/rebranding-powergui-consolerebranding-powergui-console/
########################################################
# Usage:
# & .\\Set-PowerGUIWelcomePage.ps1 \\\\server\\share\\my.mht
########################################################
# (c) Dmitry Sotnikov, Oleg Shevnin
# 1.1 - Mar 17: added exception if PowerGUI Admin Console is running
# v1, Feb 11, 2009
#
########################################################
param ($mhtpath)
# this should be path (local or UNC) to the new welcome page
# make sure that the admin console is closed
if (( get-process Quest.PowerGUI -ErrorAction SilentlyContinue ) -ne $null) {
throw "Please close the PowerGUI administrative console before running this script "
}
# verify that the new file exists and is mht
if ( $mhtpath -eq $null ) {
$mhtpath = Read-Host "Please provide path to the MHT file."
}
$mhtfile = Get-ChildItem $mhtpath
if ( $mhtfile -eq $null) {
throw "MHT file $mhtpath not found. Please verify the script parameter."
}
if ( $mhtfile.Extension -ne ".mht" ) {
throw "File $mhtpath is not an MHT file. Only MHT files are supported."
}
# Locate PowerGUI configuration for current user on this computer
$cfgpath = "$($env:APPDATA)\\Quest Software\\PowerGUI\\quest.powergui.xml"
# Create backup
Copy-Item $cfgpath "$cfgpath.backupconfig"
# Read the file
$xml = [xml]$(Get-Content $cfgpath)
# If the section for custom welcome page does not exist - create it
$node = $xml.SelectSingleNode("//container[@id='4b510268-a4eb-42e0-9276-06223660291d']")
if ($node -eq $null) {
$node = $xml.CreateElement("container")
$node.SetAttribute("id", "4b510268-a4eb-42e0-9276-06223660291d")
$node.SetAttribute("name", "Home Page")
$node.AppendChild($xml.CreateElement("value"))
$xml.SelectSingleNode("/configuration/items").AppendChild($node)
}
# Set the new value and save the file
$node.Value = $mhtpath
$xml.Save($cfgpath)
|
PowerShellCorpus/PoshCode/Hex2Dec_6.ps1
|
Hex2Dec_6.ps1
|
<!DOCTYPE html>
<html>
<head>
<title>He2Dec</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript" type="text/javascript">
var num = {
hex2dec : function(n) {
return Number(n) ? Number(n) : 'Wrong data type';
},
dec2hex : function(n) {
return Number(n) ? '0x' + Number(n).toString(16).toUpperCase() : 'Wrong data type';
},
parseData : function(n) {
if (n.slice(0, 2) == '0x') return this.hex2dec(n);
else if (n.slice(0, 1) == 'x') return this.hex2dec('0' + n);
else return this.dec2hex(n);
}
};
function onClick() {
document.getElementById('out').value =
num.parseData(document.getElementById('in').value);
}
</script>
<style type="text/css">
body { font-family: tahoma, sans-serif; }
h1, h5 { color: #000080; margin-bottom: 0; }
h3 { color: #9933cc; margin-top: 0; padding-top: 0; }
h1 { font-size: 370%; }
h5 { font-size: 65%; }
p { font-size: 80%; }
</style>
</head>
<body>
<center>
<h1>Hex2Dec</h1>
<h3>Converts hex to decimal and vice versa</h3>
<p>Note that you should strongly input hex numbers with '0x' or 'x' prefixes.</p>
<p>Input: <input type="textbox" id="in" /></p>
<p>Output: <input type="textbox" id="out" /></p>
<input type="button" value="Convert" onclick="onClick();" />
<br />
<h5>Copyright (C) 2010-2013 greg zakharov gregzakh@gmail.com</h5>
</center>
</body>
</html>
|
PowerShellCorpus/PoshCode/Write-Sitemap.ps1
|
Write-Sitemap.ps1
|
####################################################################################################
## Write-Sitemap.ps1
##
## Generates a basic Sitemap for your website, based on a list of locations / products or whatever,
## (depending on your requirements). Can easily be extended to create more complex Sitemaps.
##
## This uses XMLTextWriter and is based on the RSS creator script at
## http`://pshscripts.blogspot.com/2008/12/write-rssstreamps1.html
##
## Note the URLs in this script have been escaped. You may have to remove the backticks.
####################################################################################################
## Sitemap format, as output by this script (see http`://www.sitemaps.org/protocol.php for more)
##
## <?xml version="1.0" encoding="utf-8"?>
## <urlset xmlns="http`://www.google.com/schemas/sitemap/0.9">
## <url>
## <loc>http`://your.url/here/product1</loc>
## </url>
## <url>
## <loc>http`://your.url/here/product2</loc>
## </url>
## </urlset>
####################################################################################################
# Let's Set up some variables
$workingdir = "c:\\scripts"
$Domain = "http`://www.somesite.url" # Base URL - CHANGE THIS!
$path = "$workingdir\\sitemap.xml" # Where the output file will go
$Statics = @("help", "contact", "terms", "privacy") # Any static links go here
$Locations = Get-Content "$workingdir\\products.txt" # A list of product IDs
$Counter = 0 # Keep track of how many URLs we include. Must be less than 50k per file.
# This function does the bulk of the work, creating a new <url> and <loc> element for each URL
function CreateElement([string]$url)
{
$w = $global:writer
$w.WriteStartElement("url")
$w.WriteStartElement("loc")
$w.WriteString($url)
$w.WriteEndElement() #end loc
$w.WriteEndElement() #end url
$global:counter++ # Increment URL counter
}
#### MAIN #####
# Set up encoding, and create new instance of XMLTextWriter
$encoding = [System.Text.Encoding]::UTF8
$writer = New-Object System.Xml.XmlTextWriter( $Path, $encoding )
$writer.Formatting = [system.xml.formatting]::indented
Write-Host "`r`n`r`nGenerating $Domain Sitemap... $path"
# Write start of XML document
$writer.WriteStartDocument()
# Write Start of sitemap doc
$writer.WriteStartElement( "urlset" )
$writer.WriteAttributeString( "xmlns", "http`://www.sitemaps.org/schemas/sitemap/0.9" )
# Write our static URLs
foreach ($static in $statics)
{
CreateElement "$Domain/$Static"
}
# Write all location URLs
foreach ($Location in $Locations)
{
$r = "$domain/product/$location"
CreateElement $r
}
# You could add more URL definitions here as needed...
# Write end of document information
$writer.WriteEndElement() # End urlset
# Make sure we close the file
$writer.close()
# Let's see what it has done
# cat $path
# See how many elements were output
Write-Host "`n`rTotal number of URLs : $Counter"
# If this is more than 50,000 we should split into multiple sitemap files...
|
PowerShellCorpus/PoshCode/New-Password.ps1
|
New-Password.ps1
|
#.Synopsis
# Generate pseudo-random passwords based on templates
#
#.Parameter Template
# The template for the password you want to generate. This defines which types of characters are generated for each character in the password. The valid template characters are:
# * * - any character: a-z, A-Z, 0-9 + punctuation
# * A - any alphanumeric character: a-z, A-Z, 0-9
# * a - any alphabetic character: a-z, A-Z
# * L - any uppercase letter
# * l - any lowercase letter
# * C - uppercase consonant
# * c - lowercase consonant
# * V - uppercase vowel
# * v - lowercase vowel
# * . - punctuation
# * # - numeric character
# * An actual number modifies the presceding character to allow UP TO that many of that character class
# * An escaped character: \\L will be inserted literally...
# * Anything else will be inserted literally...
#
#.Example
# New-Password "Cvcvc##"
# Jemad46
#
# Description
# -----------
# Generates a "pronounceable" 7 character password consisting of alternating consonants and vowels followed by a 2-digit number
#
#.Example
# ("Cvcvc##," * 8).Split(",") | New-Password
#
# Description
# -----------
# Demonstrates that the function can take pipeline input. Passing multiple templates via the pipeline will generate multiple passwords.
# In this case, we generate EIGHT "pronounceable" 7 character password consisting of alternating consonants and vowels followed by a 2-digit number
#
#.Example
# New-Password "Cvvc.Cvvc##"
# Ziir-Diud55
#
# Description
# -----------
# Generates a password which starts with an upper-case consonant, followed by two lower-case vowels, followed by a punctuation mark, followed by an upper-case consonant, followed by two lower-case vowels, followed by two numbers.
#
#.Example
# New-Password "********"
# !u($OA:*
#
# Description
# -----------
# Generates a totally random 8 character password
#
#.Example
# New-Password "Get-Cvcvvc"
# Get-Wodeaj
#
# Description
# -----------
# Generates a password which looks like a strange PowerShell command, starting with "Get-" and ending with an uppercase consonant, a vowel, a consonant, two vowels, and a final consonant.
#
#.Notes
# On PowerShell 2.0 if you define an alias "rand" to point to Microsoft.PowerShell.Utility\\Get-Random, this script will use the Get-Random cmdlet instead of it's built-in rand function.
# Set-Alias rand Microsoft.PowerShell.Utility\\Get-Random -Option AllScope
#.Inputs
# [String]
# A string template for a password
#.Outputs
# [String]
# A password string
# function New-Password {
#[CmdletBinding()]
Param (
# [Parameter(ValueFromPipeline=$true,Position=0)]
[string]$Template = "************"
)
BEGIN {
#if($Template.Length -lt 8) { THROW "Passwords less than 8 characters are not allowed." }
## You might consider avoiding the O which is easily confused with 0 except in the Consolas font ;)
[char[]]$UpperAlpha = 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
[char[]]$LowerAlpha = 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'
[char[]]$UpperConsonants = 'B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','T','V','W','X','Y','Z'
[char[]]$LowerConsonants = 'b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'
[char[]]$LowerVowels = 'a','e','i','o','u'
[char[]]$UpperVowels = 'A','E','I','O','U'
[char[]]$Numeric = '1','2','3','4','5','6','7','8','9','0'
# In case this is used in a DCPromo answer files, theres a few chars to avoid: Ampersand, Less than, double quote and back slash
# And because they're easily confused for ' , let's also avoid the backtick `
## '&','<','"','\\','``',
[char[]]$Punctuation = '!','#','$','%','''','(',')','*','+',',','-','.','/',':',';','=','>','?','@','[',']','^','_'
$script:RANDOM = new-object Random
function rand {
begin { $list = @() }
process { $list += $_ }
end {
$list[$RANDOM.Next(0,$list.Count-1)]
}
}
}
PROCESS {
if($_) { $Template = $_ }
Write-Verbose "Template: $Template"
$password = ""
$randoms = @()
for($c = 0; $c -lt $Template.Length; $c++) {
switch -CaseSensitive ($Template[$c])
{
'l' { # Make this character a Lowercase Alpha
$password += $LowerAlpha | rand
break
}
'L' { # Make this character a Uppercase Alpha
$password += $UpperAlpha | rand
break
}
'l' { # Make this character a Lowercase Alpha
$password += $LowerAlpha | rand
break
}
'C' { # Make this character a Uppercase consonant
$password += $UpperConsonants | rand
break
}
'c' { # Make this character a Lowercase consonant
$password += $LowerConsonants | rand
break
}
'V' { # Make this character a Uppercase vowel
$password += $UpperVowels | rand
break
}
'v' { # Make this character a Lowercase vowel
$password += $LowerVowels | rand
break
}
'.' { # Make this character punctuation
$password += $Punctuation | rand
break
}
'#' { # Make this character numeric
$password += $Numeric | rand
break
}
'a' { # Make this character any alphabetic
$password += $UpperAlpha + $LowerAlpha | rand
break
}
'A' { # Make this character any alphanumeric
$password += $UpperAlpha + $LowerAlpha + $Numeric | rand
break
}
'*' { # Make this character any character
$password += $UpperAlpha + $LowerAlpha + $Numeric + $Punctuation | rand
break
}
# For a number, decrement the number, and then go back one...
{ [bool](([string]$_) -as [int]) } {
if($randoms -notcontains $c) {
$randoms += $c
[int]$count = $(0..([int][string]$_) | rand)
} else {
[int]$count = $(([int][string]$_) - 1)
}
if($c -gt 0 -and $count -gt 0) {
$Template = $Template.Remove($c,1).Insert($c,$count)
$c -= 2
Write-Verbose "ALTER Template: $Template Active: $($Template[$c]) ($c), Generating $count ($_) Password: $password"
}
break
}
'\\' {
$password += $Template[($c++)]
break
}
default {
$password += $Template[$c]
break
}
}
}
return $Password
}
#}
|
PowerShellCorpus/PoshCode/Networker - Delete ssids.ps1
|
Networker - Delete ssids.ps1
|
Write-Host ""
Write-Host "This is dangerous - beware!"
Write-Host "Type: delssids client.domain.com to DELETE ALL it's SAVESETS!!"
function delssids {
## warning - no checks on first arg, security hole! ;)
$client = $args[0]
$ssids = (mminfo -av -q "client=$client" -r ssid)
$ssids | ForEach-Object { nsrmm -d -S $_ -y }
Write-Host "Done!"
}
|
PowerShellCorpus/PoshCode/New-PrintJob.ps1
|
New-PrintJob.ps1
|
<#
.SYNOPSIS
Log a print job to a file.
.DESCRIPTION
This script works in conjunction with an Event Trigger on the PrintService
event on our print servers. This script queries the Microsoft-Windows-PrintService/Operational
log for EventID 307, and returns the drive letter from the most recent event.
This should be the same event that triggered this script to
run in the first place.
It appends to a CSV log file if it exists, or creates a new file if it doesn't.
.PARAMETER FileName
The fully qualified path and filename for the report.
.EXAMPLE
.\\New-PrintJob.ps1
Description
-----------
This is the only syntax for this script.
.NOTES
ScriptName: New-PrintJob.ps1
Created By: Jeff Patton
Date Coded: August 17, 2011
ScriptName is used to register events for this script
LogName is used to determine which classic log to write to
Microsoft .NET Framework 3.5 or greater is required.
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/Production/New-PrintJob
#>
Param
(
$FileName = "PrintLog-$((get-date -format "yyyMMdd")).csv"
)
Begin
{
$ScriptName = $MyInvocation.MyCommand.ToString()
$LogName = "Microsoft-Windows-PrintService/Operational"
$ScriptPath = $MyInvocation.MyCommand.Path
$Username = $env:USERDOMAIN + "\\" + $env:USERNAME
$ErrorActionPreference = "Stop"
New-EventLog -Source $ScriptName -LogName $LogName -ErrorAction SilentlyContinue
$Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nStarted: " + (Get-Date).toString()
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message
# Dotsource in the functions you need.
}
Process
{
Try
{
$Event307 = Get-WinEvent -LogName $LogName |Where-Object {$_.id -eq 307}
}
Catch
{
Write-Warning "This script requires Microsoft .NET Framework version 3.5 or greater"
Break
}
if ($Event307.Count -eq $null)
{
$PrintJob = $Event307
}
else
{
$PrintJob = $Event307[0]
}
$Client = $PrintJob.Properties[3].Value
if($Client.IndexOf("\\\\") -gt -1)
{
$Lookup = "nslookup $($Client.Substring(2,($Client.Length)-2)) |Select-String 'Name:'"
}
else
{
$Lookup = "nslookup $($Client) |Select-String 'Name:'"
}
Try
{
[string]$Return = Invoke-Expression $Lookup
$Client = $Return.Substring($Return.IndexOf(" "),(($Return.Length) - $Return.IndexOf(" "))).Trim()
}
Catch
{
$Client = $PrintJob.Properties[3].Value
}
$PrintLog = New-Object -TypeName PSObject -Property @{
Time = $PrintJob.TimeCreated
Job = $PrintJob.Properties[0].Value
Document = $PrintJob.Properties[1].Value
User = $PrintJob.Properties[2].Value
Client = $Client
Printer = $PrintJob.Properties[4].Value
Port = $PrintJob.Properties[5].Value
Size = $PrintJob.Properties[6].Value
Pages = $PrintJob.Properties[7].Value
}
$PrintLog = ConvertTo-Csv -InputObject $PrintLog -NoTypeInformation
}
End
{
$Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nFinished: " + (Get-Date).toString()
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message
if ((Test-Path -Path "P:\\PrintLogs\\$($FileName)") -eq $true)
{
$PrintLog |Select-Object -Skip 1 |Out-File -FilePath $FileName -Append
}
else
{
$PrintLog |Out-File -FilePath $FileName
}
}
|
PowerShellCorpus/PoshCode/Sort-Random.ps1
|
Sort-Random.ps1
|
## Sort-Random.ps1
## Shuffle pipeline input into a random order...
## Note that, as with any Sort- function, this is a natural holdup in your pipeline
begin {
$list = @()
}
process {
$list += $_
}
end {
$r = new-object Random
1..$list.Count | % { $list[$r.Next(0,$list.Count-1)] }
}
## There's another way this could be done, which would result in being able to
## reshuffle the output by just sorting. If you needed to reshuffle a lot,
## you could use this, and then to shuffle, just sort by RandomOrder
# begin{
# $global:Random = new-object Random
# }
# process{
# add-member -in $_ -p -n RandomOrder -t ScriptProperty -val {$Random.NextDouble()}
# }
##
## TO give you an idea of the difference, I liste files and shuffled them:
## While using the TOP method 1000 times takes about 36 seconds on my PC:
#### $files = gci
#### 1..1000 | %{$null = $files | sort-random }
## Using the bottom method, and then just resorting takes about 7 seconds:
#### $files = gci | Add-RandomOrder
#### 1..1000 | %{$null = $files | sort RandomOrder }
## However, if you're not reshuffling THE SAME list many times, the top method
## is much better, so I left that as the default....
|
PowerShellCorpus/PoshCode/Get-StringRange.ps1
|
Get-StringRange.ps1
|
function Get-StringRange ( $Start, $End ) {
[char[]]( [int][char]$Start..[int][char]$End )
}
|
PowerShellCorpus/PoshCode/ConvertTo-DN.ps1
|
ConvertTo-DN.ps1
|
#Author: Glenn Sizemore glnsize@get-admin.com
#
#Purpose: Convert a DN to a conicalname, and back again.
#
#Example: PS > ConvertFrom-Canonical 'get-admin.local/test/test1/Sizemore, Glenn E'
# CN=Sizemore\\, Glenn E,OU=test1,OU=test,DC=getadmin,DC=local
# PS > ConvertFrom-DN 'CN=Sizemore\\, Glenn E,OU=test1,OU=test,DC=getadmin,DC=local'
# get-admin.local/test/test1/Sizemore, Glenn E
function ConvertFrom-DN
{
param([string]$DN=(Throw '$DN is required!'))
foreach ( $item in ($DN.replace('\\,','~').split(",")))
{
switch -regex ($item.TrimStart().Substring(0,3))
{
"CN=" {$CN = '/' + $item.replace("CN=","");continue}
"OU=" {$ou += ,$item.replace("OU=","");$ou += '/';continue}
"DC=" {$DC += $item.replace("DC=","");$DC += '.';continue}
}
}
$canoincal = $dc.Substring(0,$dc.length - 1)
for ($i = $ou.count;$i -ge 0;$i -- ){$canoincal += $ou[$i]}
$canoincal += $cn.ToString().replace('~',',')
return $canoincal
}
function ConvertFrom-Canonical
{
param([string]$canoincal=(trow '$Canonical is required!'))
$obj = $canoincal.Replace(',','\\,').Split('/')
[string]$DN = "CN=" + $obj[$obj.count - 1]
for ($i = $obj.count - 2;$i -ge 1;$i--){$DN += ",OU=" + $obj[$i]}
$obj[0].split(".") | ForEach-Object { $DN += ",DC=" + $_}
return $dn
}
|
PowerShellCorpus/PoshCode/NTFS ACLs Folder Tree_5.ps1
|
NTFS ACLs Folder Tree_5.ps1
|
#######################################
# TITLE: listACL.ps1 #
# AUTHOR: Santiago Fernandez Muñoz #
# #
# DESC: This script generate a HTML #
# report show all ACLs asociated with #
# a Folder tree structure starting in #
# root specified by the user #
#######################################
param ([string] $computer = 'localhost',
[string] $path = $(if ($help -eq $false) {Throw "A path is needed."}),
[int] $level = 0,
[string] $scope = 'administrator',
[switch] $help = $false,
[switch] $debug = $false
)
#region Initializations and previous checkings
#region Initialization
$allowedLevels = 10
$Stamp = get-date -uformat "%Y%m%d"
$report = "$PWD\\$computer.html"
$comparison = ""
$UNCPath = "\\\\" + $computer + "\\" + $path + "\\"
#endregion
#region Previous chekings
#require -version 2.0
if ($level -gt $allowedLevels -or $level -lt 0) {Throw "Level out of range."}
if ($computer -eq 'localhost' -or $computer -ieq $env:COMPUTERNAME) { $UNCPath = $path }
switch ($scope) {
micro {
$comparison = '($acl -notlike "*administrator*" -and $acl -notlike "*BUILTIN*" -and $acl -notlike "*NT AUTHORITY*")'
}
user {
$comparison = '($acl -notlike "*administrator*" -and $acl -notlike "*BUILTIN*" -and $acl -notlike "*IT*" -and $acl -notlike "*NT AUTHORITY*" -and $acl -notlike "*All*")'
}
}
#endregion
#endregion
#region Function definitions
function drawDirectory([ref] $directory) {
$dirHTML = '
<div class="'
if ($directory.value.level -eq 0) { $dirHTML += 'he0_expanded' } else { $dirHTML += 'he' + $directory.value.level }
$dirHTML += '"><span class="sectionTitle" tabindex="0">Folder ' + $directory.value.Folder.FullName + '</span></div>
<div class="container"><div class="he' + ($directory.value.level + 1) + '"><span class="sectionTitle" tabindex="0">Access Control List</span></div>
<div class="container">
<div class="heACL">
<table class="info3" cellpadding="0" cellspacing="0">
<thead>
<th scope="col"><b>Owner</b></th>
<th scope="col"><b>Privileges</b></th>
</thead>
<tbody>'
foreach ($itemACL in $directory.value.ACL) {
$acls = $null
if ($itemACL.AccessToString -ne $null) {
$acls = $itemACL.AccessToString.split("`n")
}
$dirHTML += '<tr><td>' + $itemACL.Owner + '</td>
<td>
<table>
<thead>
<th>User</th>
<th>Control</th>
<th>Privilege</th>
</thead>
<tbody>'
foreach ($acl in $acls) {
$temp = [regex]::split($acl, "(?<!(,|NT))\\s{1,}")
if ($debug) {
write-host "ACL(" $temp.gettype().name ")[" $temp.length "]: " $temp
}
if ($temp.count -eq 1) {
continue
}
if ($scope -ne 'administrator') {
if ( Invoke-Expression $comparison ) {
$dirHTML += "<tr><td>" + $temp[0] + "</td><td>" + $temp[1] + "</td><td>" + $temp[2] + "</td></tr>"
}
} else {
$dirHTML += "<tr><td>" + $temp[0] + "</td><td>" + $temp[1] + "</td><td>" + $temp[2] + "</td></tr>"
}
}
$dirHTML += '</tbody>
</table>
</td>
</tr>'
}
$dirHTML += '
</tbody>
</table>
</div>
</div>
</div>'
return $dirHTML
}
#endregion
#region Printing help message
if ($help) {
Write-Host @"
/··················································\\
· Script gather access control lists per directory ·
\\··················································/
USAGE: ./listACL -computer <machine or IP>
-path <path>
-level <0-10>
-help:[$false]
PARAMETERS:
computer [OPTIONAL] - Computer name or IP addres where folder is hosted (Default: localhost)
path [REQUIRED] - Folder's path to query.
level [OPTIONAL] - Level of folders to go down in the query. Allowd values are between 0 and $allowedLevels.
0 show that there's no limit in the going down (Default: 0)
scope [OPTIONAL] - Sets the amount of information showd in the report. Allowd values are:
· user, show important information to the user.
· micro, show user scope information plus important information for the IT Department.
· administrator, show all information.
help [OPTIONAL] - This help.
"@
exit 0
}
#endregion
if (Test-Path $report)
{
Remove-item $report
}
#To normalize I check if last character in the path is the folder separator character
if ($path.Substring($path.Length - 1,1) -eq "\\") { $path = $path.Substring(0,$path.Length - 1) }
#region Header, style and javascript functions needed by the html report
@"
<html dir="ltr" xmlns:v="urn:schemas-microsoft-com:vml" gpmc_reportInitialized="false">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-16" />
<title>Access Control List for $path in $computer</title>
<!-- Styles -->
<style type="text/css">
body{ background-color:#FFFFFF; border:1px solid #666666; color:#000000; font-size:68%; font-family:MS Shell Dlg; margin:0px 0px 10px 0px; }
table{ font-size:100%; table-layout:fixed; width:100%; }
td,th{ overflow:visible; text-align:left; vertical-align:top; white-space:normal; }
.title{ background:#FFFFFF; border:none; color:#333333; display:block; height:24px; margin:0px 0px -1px 0px; padding-top:4px; position:relative; table-layout:fixed; width:100%; z-index:5; }
.he0_expanded{ background-color:#FEF7D6; border:1px solid #BBBBBB; color:#3333CC; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:0px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he1_expanded{ background-color:#A0BACB; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:10px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he1{ background-color:#A0BACB; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:10px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he2{ background-color:#C0D2DE; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:20px; margin-right:0px; padding-left:8px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he3{ background-color:#D9E3EA; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:30px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he4{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:40px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he4h{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:45px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he4i{ background-color:#F9F9F9; border:1px solid #BBBBBB; color:#000000; display:block; font-family:MS Shell Dlg; font-size:100%; margin-bottom:-1px; margin-left:45px; margin-right:0px; padding-bottom:5px; padding-left:21px; padding-top:4px; position:relative; width:100%; }
.he5{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:50px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he5h{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; padding-left:11px; padding-right:5em; padding-top:4px; margin-bottom:-1px; margin-left:55px; margin-right:0px; position:relative; width:100%; }
.he5i{ background-color:#F9F9F9; border:1px solid #BBBBBB; color:#000000; display:block; font-family:MS Shell Dlg; font-size:100%; margin-bottom:-1px; margin-left:55px; margin-right:0px; padding-left:21px; padding-bottom:5px; padding-top: 4px; position:relative; width:100%; }
.he6{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:55px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he7{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:60px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he8{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:65px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he9{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:70px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he10{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:75px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.he11{ background-color:#E8E8E8; border:1px solid #BBBBBB; color:#000000; cursor:pointer; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:80px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
.heACL { background-color:#ECFFD7; border:1px solid #BBBBBB; color:#000000; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; height:2.25em; margin-bottom:-1px; margin-left:90px; margin-right:0px; padding-left:11px; padding-right:5em; padding-top:4px; position:relative; width:100%; }
DIV .expando{ color:#000000; text-decoration:none; display:block; font-family:MS Shell Dlg; font-size:100%; font-weight:normal; position:absolute; right:10px; text-decoration:underline; z-index: 0; }
.he0 .expando{ font-size:100%; }
.info, .info3, .info4, .disalign{ line-height:1.6em; padding:0px 0px 0px 0px; margin:0px 0px 0px 0px; }
.disalign TD{ padding-bottom:5px; padding-right:10px; }
.info TD{ padding-right:10px; width:50%; }
.info3 TD{ padding-right:10px; width:33%; }
.info4 TD, .info4 TH{ padding-right:10px; width:25%; }
.info5 TD, .info5 TH{ padding-right:0px; width:20%; }
.info TH, .info3 TH, .info4 TH, .disalign TH{ border-bottom:1px solid #CCCCCC; padding-right:10px; }
.subtable, .subtable3{ border:1px solid #CCCCCC; margin-left:0px; background:#FFFFFF; margin-bottom:10px; }
.subtable TD, .subtable3 TD{ padding-left:10px; padding-right:5px; padding-top:3px; padding-bottom:3px; line-height:1.1em; width:10%; }
.subtable TH, .subtable3 TH{ border-bottom:1px solid #CCCCCC; font-weight:normal; padding-left:10px; line-height:1.6em; }
.subtable .footnote{ border-top:1px solid #CCCCCC; }
.subtable3 .footnote, .subtable .footnote{ border-top:1px solid #CCCCCC; }
.subtable_frame{ background:#D9E3EA; border:1px solid #CCCCCC; margin-bottom:10px; margin-left:15px; }
.subtable_frame TD{ line-height:1.1em; padding-bottom:3px; padding-left:10px; padding-right:15px; padding-top:3px; }
.subtable_frame TH{ border-bottom:1px solid #CCCCCC; font-weight:normal; padding-left:10px; line-height:1.6em; }
.subtableInnerHead{ border-bottom:1px solid #CCCCCC; border-top:1px solid #CCCCCC; }
.explainlink{ color:#000000; text-decoration:none; cursor:pointer; }
.explainlink:hover{ color:#0000FF; text-decoration:underline; }
.spacer{ background:transparent; border:1px solid #BBBBBB; color:#FFFFFF; display:block; font-family:MS Shell Dlg; font-size:100%; height:10px; margin-bottom:-1px; margin-left:43px; margin-right:0px; padding-top: 4px; position:relative; }
.filler{ background:transparent; border:none; color:#FFFFFF; display:block; font:100% MS Shell Dlg; line-height:8px; margin-bottom:-1px; margin-left:43px; margin-right:0px; padding-top:4px; position:relative; }
.container{ display:block; position:relative; }
.rsopheader{ background-color:#A0BACB; border-bottom:1px solid black; color:#333333; font-family:MS Shell Dlg; font-size:130%; font-weight:bold; padding-bottom:5px; text-align:center; }
.rsopname{ color:#333333; font-family:MS Shell Dlg; font-size:130%; font-weight:bold; padding-left:11px; }
.gponame{ color:#333333; font-family:MS Shell Dlg; font-size:130%; font-weight:bold; padding-left:11px; }
.gpotype{ color:#333333; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; padding-left:11px; }
#uri { color:#333333; font-family:MS Shell Dlg; font-size:100%; padding-left:11px; }
#dtstamp{ color:#333333; font-family:MS Shell Dlg; font-size:100%; padding-left:11px; text-align:left; width:30%; }
#objshowhide { color:#000000; cursor:pointer; font-family:MS Shell Dlg; font-size:100%; font-weight:bold; margin-right:0px; padding-right:10px; text-align:right; text-decoration:underline; z-index:2; }
#gposummary { display:block; }
#gpoinformation { display:block; }
</style>
</head>
<body>
<table class="title" cellpadding="0" cellspacing="0">
<tr><td colspan="2" class="gponame">Access Control List for $path on machine $computer</td></tr>
<tr>
<td id="dtstamp">Data obtained on: $(Get-Date)</td>
<td><div id="objshowhide" tabindex="0"></div></td>
</tr>
</table>
<div class="filler"></div>
"@ | Set-Content $report
#endregion
#region Information gathering
$colFiles = Get-ChildItem -path $UNCPath -Filter *. -Recurse -force -Verbose | Sort-Object FullName
$colACLs = @()
#We start going through the path pointed out by the user
foreach($file in $colFiles)
{
#To control the current level in the tree we are in it's needed to count the number of separator characters
#contained in the path. However in order to make the count correctly it's needed to delete the path
#provided by the user (the parent). Once the parent has been deleted, the rest of the full name will be
#string used to do the level count.
#It's needed to use a REGEX object to get ALL separator character matches.
$matches = (([regex]"\\\\").matches($file.FullName.substring($path.length, $file.FullName.length - $path.length))).count
if ($level -ne 0 -and ($matches - 1) -gt $level) {
continue
}
if ($debug) {
Write-Host $file.FullName "->" $file.Mode
}
if ($file.Mode -notlike "d*") {
continue
}
$myobj = "" | Select-Object Folder,ACL,level
$myobj.Folder = $file
$myobj.ACL = Get-Acl $file.FullName
$myobj.level = $matches - 1
$colACLs += $myobj
}
#endregion
#region Setting up the report
'<div class="gposummary">' | Add-Content $report
for ($i = 0; $i -lt $colACLs.count; $i++) {
drawDirectory ([ref] $colACLs[$i]) | Add-Content $report
}
'</div></body></html>' | Add-Content $report
#endregion
|
PowerShellCorpus/PoshCode/Set-Computername_9.ps1
|
Set-Computername_9.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/Send SNMP trap.ps1
|
Send SNMP trap.ps1
|
Param ( $DestinationHost )
Add-Type -Path "C:\\Program Files\\LeXtudio Software\\sharpsnmplib.dll"
Add-Type -Path "C:\\Program Files\\LeXtudio Software\\SharpSnmpLib.Controls.dll"
$manager = [system.Net.Dns]::Resolve( $DestinationHost ).AddressList[0]
$TrapDest = New-Object Net.IPEndPoint( $manager, 162 )
[Lextm.SharpSnmpLib.Messaging.Messenger]::SendTrapV1( $TrapDest,
[IPAddress]::Loopback,
[Lextm.SharpSnmpLib.OctetString]"public",
[Lextm.SharpSnmpLib.ObjectIdentifier]"1.3.6",
[Lextm.SharpSnmpLib.GenericCode]::ColdStart,
0,
0,
( New-GenericObject.ps1 system.collections.generic.list lextm.sharpsnmplib.variable )
)
|
PowerShellCorpus/PoshCode/Audit iPhone Users.ps1
|
Audit iPhone Users.ps1
|
#Created by P. Sukus
#Name: iPhone users syncing through OWA audit
#set the timeframe to audit in days
$Daysold = 1
$Date = (get-date).adddays(-$daysold)
$servers = "server1", "server2", "server3"
foreach ($s in $servers)
{
Write-host -ForegroundColor Blue "Checking server $s for files from the last $daysold day(s)"
$logfiles += gci -path \\\\$s\\c$\\windows\\system32\\logfiles\\W3SVC1 | where {$_.LastWriteTime -gt $date}
}
Foreach ($l in $logfiles)
{
Write-host "Processing "$l.fullname
Copy-item $l.fullname -Destination $pwd.path
$listousers += gc $l.name | where {$_ -match "DeviceType="}
Remove-Item $l.name
}
$user = @()
foreach ($l in $listousers | where {$_ -ne $null})
{
$u = $l.split(" ")[8]
if ($user -notcontains $u)
{
$user += "$u"
}
$u = $null
}
$body = "<!DOCTYPE html PUBLIC `"-//W3C//DTD XHTML 1.0 Strict//EN`" `"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd`">"
$body += "<html xmlns=`"http://www.w3.org/1999/xhtml`">"
$body += "<head>"
$body += "<title>iPhone Users</title>"
$body += "</head><body>"
$body += "<table border=1>"
$body += "<colgroup>"
$body += "<col/>"
$body += "</colgroup>"
$body += "<tr><td><b>iPhone Users</b></td></tr>"
foreach ($y in $user)
{
$body += "<tr><td>$y</td></tr>"
}
$body += "</table>"
$body += "</body></html>"
$smtpServer = "your.SMTPserver.here"
$mailer = new-object Net.Mail.SMTPclient($smtpserver)
$From = "iphoneusersync@company.internal"
$To = "admin@company.internal"
$subject = "iPhone users syncing through OWA in the last $daysold day(s)"
$msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body)
$msg.IsBodyHTML = $true
$mailer.send($msg)
|
PowerShellCorpus/PoshCode/b8e330a7-320a-4ae1-8797-9fb1195bfce3.ps1
|
b8e330a7-320a-4ae1-8797-9fb1195bfce3.ps1
|
param($sqlserver, $filepath)
#Note: Uses Changeset 59378 or higher of SQLPSX SQLServer module http://sqlpsx.codeplex.com/SourceControl/changeset/view/58378#564810
#Added FileListOnly option to Invoke-SqlRestore. The option will be included in releases after 2.3.1
import-module sqlserver -force
$server = get-sqlserver $sqlserver
$filepath = Resolve-Path $filepath | select -ExpandProperty Path
$dbname = Get-ChildItem $filePath | select -ExpandProperty basename
$dataPath = Get-SqlDefaultDir -sqlserver $server -dirtype Data
$logPath = Get-SqlDefaultDir -sqlserver $server -dirtype Log
$relocateFiles = @{}
Invoke-SqlRestore -sqlserver $server -filepath $filepath -fileListOnly | foreach { `
if ($_.Type -eq 'L')
{ $physicalName = "$logPath\\{0}" -f [system.io.path]::GetFileName("$($_.PhysicalName)") }
else
{ $physicalName = "$dataPath\\{0}" -f [system.io.path]::GetFileName("$($_.PhysicalName)") }
$relocateFiles.Add("$($_.LogicalName)", "$physicalName")
}
$server.KillAllProcesses($dbname)
Invoke-SqlRestore -sqlserver $server -dbname $dbname -filepath $filepath -relocatefiles $relocateFiles -Verbose -force
|
PowerShellCorpus/PoshCode/Create-SCCMCollection_1.ps1
|
Create-SCCMCollection_1.ps1
|
function Create-SCCMCollection
{
param($Server = $Env:ComputerName, $Name, $Site, $ParentCollectionID = "COLLROOT")
$ColClass = [WMIClass]"\\\\$Server\\Root\\SMS\\Site_$($Site):SMS_Collection"
$Col = $ColClass.PSBase.CreateInstance()
$Col.Name = $Name
$Col.OwnedByThisSite = $True
$Col.Comment = "Collection $Name"
$Col.psbase
$Col.psbase.Put()
$NewCollectionID = (Get-WmiObject -computerName $Server -namespace Root\\SMS\\Site_$Site -class SMS_Collection | where {$_.Name -eq $Name}).CollectionID
$RelClass = [WMIClass]"\\\\$Server\\Root\\SMS\\Site_$($Site):SMS_CollectToSubCollect"
$Rel = $RelClass.PSBase.CreateInstance()
$Rel.ParentCollectionID = $ParentCollectionID
$Rel.SubCollectionID = $NewCollectionID
$Rel.psbase
$Rel.psbase.Put()
}
|
PowerShellCorpus/PoshCode/Export-PSCredential_2.ps1
|
Export-PSCredential_2.ps1
|
# Author: Hal Rottenberg <hal@halr9000.com>
# Url: http://halr9000.com/article/tag/lib-authentication.ps1
# Purpose: These functions allow one to easily save network credentials to disk in a relatively
# secure manner. The resulting on-disk credential file can only [1] be decrypted
# by the same user account which performed the encryption. For more details, see
# the help files for ConvertFrom-SecureString and ConvertTo-SecureString as well as
# MSDN pages about Windows Data Protection API.
# [1]: So far as I know today. Next week I'm sure a script kiddie will break it.
#
# Usage: Export-PSCredential [-Credential <PSCredential object>] [-Path <file to export>]
#
# If Credential is not specififed, user is prompted by Get-Credential cmdlet.
# If not specififed, Path is "./credentials.enc.xml".
# Output: FileInfo object referring to saved credentials
#
# Import-PSCredential [-Path <file to import>]
#
# If not specififed, Path is "./credentials.enc.xml".
# Output: PSCredential object
function Export-PSCredential {
param ( $Credential = (Get-Credential), $Path = "credentials.enc.xml" )
# Test for valid credential object
if ( !$Credential -or ( $Credential -isnot [system.Management.Automation.PSCredential] ) ) {
Throw "You must specify a credential object to export to disk."
}
# Create temporary object to be serialized to disk
$export = "" | Select-Object Username, EncryptedPassword
$export.Username = $Credential.Username
# Encrypt SecureString password using Data Protection API
# Only the current user account can decrypt this cipher
$export.EncryptedPassword = $Credential.Password | ConvertFrom-SecureString
# Export using the Export-Clixml cmdlet
$export | Export-Clixml $Path
Write-Host -foregroundcolor Green "Credentials saved to: " -noNewLine
# Return FileInfo object referring to saved credentials
Get-Item $Path
}
function Import-PSCredential {
param ( $Path = "credentials.enc.xml" )
# Import credential file
$import = Import-Clixml $Path
# Test for valid import
if ( !$import.UserName -or !$import.EncryptedPassword ) {
Throw "Input is not a valid ExportedPSCredential object, exiting."
}
$Username = $import.Username
# Decrypt the password and store as a SecureString object for safekeeping
$SecurePass = $import.EncryptedPassword | ConvertTo-SecureString
# Build the new credential object
$Credential = New-Object System.Management.Automation.PSCredential $Username, $SecurePass
Write-Output $Credential
}
|
PowerShellCorpus/PoshCode/f5a3c50b-0ede-4fca-ae08-d97b3e9694f1.ps1
|
f5a3c50b-0ede-4fca-ae08-d97b3e9694f1.ps1
|
function Start-ISE ()
{
<#
.synopsis
Load some file into ISE
.Description
Load some file into ISE
.Parameter fileObjOrFileName
file to be loaded
.ReturnValue
$null
.Notes
Author: bernd kriszio
e-mail: bkriszio@googlemail.com
Created: 2008-12-28
Requires: V2 CTP 3
Todo: I do not see the solution using advanced functions for a variable number of arguments
Start-ISE .\\foo.ps1 .\\bar.ps1
fails.
.Example
Start-ISE $profile
get-childitem *.ps1 | Start-ise
'foo.ps1', 'bar.ps1' | Start-ise
#>
param(
[Parameter(Position = 0, Mandatory=$false, ValueFromPipeline=$True)]
$fileObjOrFileName
)
PROCESS {
if ($fileObjOrFileName -ne $null){
if ($fileObjOrFileName.gettype().Name -eq 'FileInfo'){
& "$PSHome/powershell_ise.exe" $fileObjOrFileName.Fullname
}
elseif ($fileObjOrFileName.gettype().Name -eq 'String') {
& "$PSHome/powershell_ise.exe" "$(pwd)\\$fileObjOrFileName"
}
}
}
<# End{
foreach ($file in $args)
{
if ($file.gettype().Name -eq 'FileInfo'){
& "$PSHome/powershell_ise.exe" $file.Fullname
}
elseif ($file.gettype().Name -eq 'String') {
& "$PSHome/powershell_ise.exe" "$(pwd)\\$file"
}
}
}
#>
}
|
PowerShellCorpus/PoshCode/Clear-XCAttributes_1.ps1
|
Clear-XCAttributes_1.ps1
|
param(
[Parameter(Position=0,ValueFromPipeline=$True)]
[ValidateNotNullorEmpty()] $User,
[switch]$ClearXCAttributes
)
begin{
$Global:LegacyXCUsers = @()
# attributes to be nulled according to:
# http://blogs.technet.com/b/exchange/archive/2006/10/13/3395089.aspx
$XCattributes=@(
"adminDisplayName","altRecipient","authOrig","autoReplyMessage","deletedItemFlags","delivContLength","deliverAndRedirect","displayNamePrintable",
"dLMemDefault","dLMemRejectPerms","dLMemSubmitPerms","extensionAttribute1","extensionAttribute10","extensionAttribute11","extensionAttribute12",
"extensionAttribute13","extensionAttribute14","extensionAttribute15","extensionAttribute2","extensionAttribute3","extensionAttribute4","extensionAttribute5",
"extensionAttribute6","extensionAttribute7","extensionAttribute8","extensionAttribute9","folderPathname","garbageCollPeriod","homeMDB","homeMTA",
"internetEncoding","legacyExchangeDN","mail","mailNickname","mAPIRecipient","mDBOverHardQuotaLimit","mDBOverQuotaLimit","mDBStorageQuota","mDBUseDefaults",
"msExchADCGlobalNames","msExchControllingZone","msExchExpansionServerName","msExchFBURL","msExchHideFromAddressLists","msExchHomeServerName",
"msExchMailboxGuid","msExchMailboxSecurityDescriptor","msExchPoliciesExcluded","msExchPoliciesIncluded","msExchRecipLimit","msExchResourceGUID",
"protocolSettings","proxyAddresses","publicDelegates","securityProtocol","showInAddressBook","submissionContLength","targetAddress","textEncodedORAddress",
"unauthOrig"
)
}
process{
$Global:LegacyXCUsers += (get-aduser -Identity $User -Properties *)
if ($ClearXCAttributes){
write-verbose "all XC attributes will be cleared for $user"
set-aduser -Identity $User -Clear $XCattributes
}
}
end{
$Global:LegacyXCUsers
}
|
PowerShellCorpus/PoshCode/Get-SiSReport_3.ps1
|
Get-SiSReport_3.ps1
|
Function Get-SiSReport
{
<#
.SYNOPSIS
Get the overall SIS usage information.
.DESCRIPTION
This function uses the sisadmin command to get the usage
information for a SIS enabled drive.
.PARAMETER SisDisk
The drive letter of a disk that has SiS enabled
.EXAMPLE
Get-SiSReport -SisDisk o
LinkFiles : 20004
Used : 442378481664
Disk : o
InaccessibleLinkFiles : 0
CommonStoreFiles : 6678
SpaceSaved : 7708860 KB
Free : 0
Description
-----------
This example shows the basic usage of the command
.NOTES
This function will return nothing if the drive being analyzed does not have SiS enabled
This function will return a message if the sisadmin command returns any error
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/ComputerManagemenet#Get-SiSReport
#>
Param
(
$SisDisk = "c"
)
Begin
{
$SisAdmin = "& sisadmin /v $($SisDisk):"
Try
{
$SisResult = Invoke-Expression $SisAdmin
}
Catch
{
Return "Single Instance Storage is not available on this computer"
}
}
Process
{
If ($SisResult.Count)
{
$ThisDisk = Get-PSDrive $SisDisk
$SisReport = New-Object -TypeName PSObject -Property @{
Disk = $SisDisk
Used = [math]::round(($ThisDisk.Used /1024 /1024 /1024),2)
Free = [math]::round(($ThisDisk.Used /1024 /1024 /1024),2)
CommonStoreFiles = ($SisResult[($SisResult.Count)-4]).TrimStart("Common store files:")
LinkFiles = ($SisResult[($SisResult.Count)-3]).TrimStart("Link files:")
InaccessibleLinkFiles = ($SisResult[($SisResult.Count)-2]).TrimStart("Inaccessible link files:")
SpaceSaved = [math]::round(((($SisResult[($SisResult.Count)-1]).TrimStart("Space saved:")).TrimEnd(" KB")/1024 /1024),2)
}
}
}
End
{
Return $SisReport
}
}
|
PowerShellCorpus/PoshCode/Get-UserLogonLogoffScrip_1.ps1
|
Get-UserLogonLogoffScrip_1.ps1
|
##############################################################################
##
## Get-UserLogonLogoffScript
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################
<#
.SYNOPSIS
Get the logon or logoff scripts assigned to a specific user
.EXAMPLE
Get-UserLogonLogoffScript LEE-DESK\\LEE Logon
Gets all logon scripts for the user 'LEE-DESK\\Lee'
#>
param(
## The username to examine
[Parameter(Mandatory = $true)]
$Username,
[Parameter(Mandatory = $true)]
[ValidateSet("Logon","Logoff")]
$ScriptType
)
Set-StrictMode -Version Latest
## Find the SID for the username
$account = New-Object System.Security.Principal.NTAccount $username
$sid =
$account.Translate([System.Security.Principal.SecurityIdentifier]).Value
## Map that to their group policy scripts
$registryKey = "HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\" +
"Group Policy\\State\\$sid\\Scripts"
if(-not (Test-Path $registryKey))
{
return
}
## Go through each of the policies in the specified key
foreach($policy in Get-ChildItem $registryKey\\$scriptType)
{
## For each of the scripts in that policy, get its script name
## and parameters
foreach($script in Get-ChildItem $policy.PsPath)
{
Get-ItemProperty $script.PsPath | Select Script,Parameters
}
}
|
PowerShellCorpus/PoshCode/File encoding no BOM.ps1
|
File encoding no BOM.ps1
|
#region Function: Get-DTWFileEncoding
<#
.SYNOPSIS
Returns the encoding type of the file
.DESCRIPTION
Returns the encoding type of the file. It first attempts to determine the
encoding by detecting the Byte Order Marker using Lee Holmes' algorithm
(http://poshcode.org/2153). However, if the file does not have a BOM
it makes an attempt to determine the encoding by analyzing the file content
(does it 'appear' to be UNICODE, does it have characters outside the ASCII
range, etc.). If it can't tell based on the content analyzed, then
it assumes it's ASCII. I haven't checked all editors but PowerShell ISE and
PowerGUI both create their default files as non-ASCII with a BOM (they use
Unicode Big Endian and UTF-8, respectively). If your file doesn't have a
BOM and 'doesn't appear to be Unicode' (based on my algorithm*) but contains
non-ASCII characters after index ByteCountToCheck, the file will be incorrectly
identified as ASCII. So put a BOM in there, would ya!
For more information and sample encoding files see:
http://danspowershellstuff.blogspot.com/2012/02/get-file-encoding-even-if-no-byte-order.html
And please give me any tips you have about improving the detection algorithm.
*For a full description of the algorithm used to analyze non-BOM files,
see "Determine if Unicode/UTF8 with no BOM algorithm description".
.PARAMETER Path
Path to file
.PARAMETER ByteCountToCheck
Number of bytes to check, by default check first 10000 character.
Depending on the size of your file, this might be the entire content of your file.
.PARAMETER PercentageMatchUnicode
If pecentage of null 0 value characters found is greater than or equal to
PercentageMatchUnicode then this file is identified as Unicode. Default value .5 (50%)
.EXAMPLE
Get-IHIFileEncoding -Path .\\SomeFile.ps1 1000
Attempts to determine encoding using only first 1000 characters
BodyName : unicodeFFFE
EncodingName : Unicode (Big-Endian)
HeaderName : unicodeFFFE
WebName : unicodeFFFE
WindowsCodePage : 1200
IsBrowserDisplay : False
IsBrowserSave : False
IsMailNewsDisplay : False
IsMailNewsSave : False
IsSingleByte : False
EncoderFallback : System.Text.EncoderReplacementFallback
DecoderFallback : System.Text.DecoderReplacementFallback
IsReadOnly : True
CodePage : 1201
#>
function Get-DTWFileEncoding {
#region Function parameters
[CmdletBinding()]
param(
[Parameter(Mandatory = $true,ValueFromPipeline = $true,ValueFromPipelineByPropertyName = $true)]
[ValidateNotNullOrEmpty()]
[Alias("FullName")]
[string]$Path,
[Parameter(Mandatory = $false)]
[int]$ByteCountToCheck = 10000,
[Parameter(Mandatory = $false)]
[decimal]$PercentageMatchUnicode = .5
)
#endregion
process {
# minimum number of characters to check if no BOM
[int]$MinCharactersToCheck = 400
#region Parameter validation
#region SourcePath must exist; if not, exit
if ($false -eq (Test-Path -Path $Path)) {
Write-Error -Message "$($MyInvocation.MyCommand.Name) :: Path does not exist: $Path"
return
}
#endregion
#region ByteCountToCheck should be at least MinCharactersToCheck
if ($ByteCountToCheck -lt $MinCharactersToCheck) {
Write-Error -Message "$($MyInvocation.MyCommand.Name) :: ByteCountToCheck should be at least $MinCharactersToCheck : $ByteCountToCheck"
return
}
#endregion
#endregion
#region Determine file encoding based on BOM - if exists
# the code in this section is mostly Lee Holmes' algorithm: http://poshcode.org/2153
# until we determine the file encoding, assume it is unknown
$Unknown = "UNKNOWN"
$result = $Unknown
# The hashtable used to store our mapping of encoding bytes to their
# name. For example, "255-254 = Unicode"
$encodings = @{}
# Find all of the encodings understood by the .NET Framework. For each,
# determine the bytes at the start of the file (the preamble) that the .NET
# Framework uses to identify that encoding.
$encodingMembers = [System.Text.Encoding] | Get-Member -Static -MemberType Property
$encodingMembers | ForEach-Object {
$encodingBytes = [System.Text.Encoding]::($_.Name).GetPreamble() -join '-'
$encodings[$encodingBytes] = $_.Name
}
# Find out the lengths of all of the preambles.
$encodingLengths = $encodings.Keys | Where-Object { $_ } | ForEach-Object { ($_ -split "-").Count }
# Go through each of the possible preamble lengths, read that many
# bytes from the file, and then see if it matches one of the encodings
# we know about.
foreach ($encodingLength in $encodingLengths | Sort-Object -Descending) {
$bytes = (Get-Content -Path $Path -Encoding byte -ReadCount $encodingLength)[0]
$encoding = $encodings[$bytes -join '-']
# If we found an encoding that had the same preamble bytes,
# save that output and break.
if ($encoding) {
$result = $encoding
break
}
}
# if encoding determined from BOM, then return it
if ($result -ne $Unknown) {
[System.Text.Encoding]::$result
return
}
#endregion
#region No BOM on file, attempt to determine based on file content
#region Determine if Unicode/UTF8 with no BOM algorithm description
<#
Looking at the content of many code files, most of it is code or
spaces. Sure, there are comments/descriptions and there are variable
names (which could be double-byte characters) or strings but most of
the content is code - represented as single-byte characters. If the
file is Unicode but the content is mostly code, the single byte
characters will have a null/value 0 byte as either as the first or
second byte in each group, depending on Endian type.
My algorithm uses the existence of these 0s:
- look at the first ByteCountToCheck bytes of the file
- if any character is greater than 127, note it (if any are found, the
file is at least UTF8)
- count the number of 0s found (in every other character)
- if a certain percentage (compared to total # of characters) are
null/value 0, then assume it is Unicode
- if the percentage of 0s is less than we identify as a Unicode
file (less than PercentageMatchUnicode) BUT a character greater
than 127 was found, assume it is UTF8.
- Else assume it's ASCII.
Yes, technically speaking, the BOM is really only for identifying the
byte order of the file but c'mon already... if your file isn't ASCII
and you don't want it's encoding to be confused just put the BOM in
there for pete's sake.
Note: if you have a huge amount of text at the beginning of your file which
is not code and is not single-byte, this algorithm may fail. Again, put a
BOM in.
#>
#endregion
$Content = (Get-Content -Path $Path -Encoding byte -ReadCount $ByteCountToCheck -TotalCount $ByteCountToCheck)
# get actual count of bytes (in case less than $ByteCountToCheck)
$ByteCount = $Content.Count
[bool]$NonAsciiFound = $false
# yes, the big/little endian sections could be combined in one loop
# sorry, crazy busy right now...
#region Check if Big Endian
# check if big endian Unicode first - even-numbered index bytes will be 0)
$ZeroCount = 0
for ($i = 0; $i -lt $ByteCount; $i += 2) {
if ($Content[$i] -eq 0) { $ZeroCount++ }
if ($Content[$i] -gt 127) { $NonAsciiFound = $true }
}
if (($ZeroCount / ($ByteCount / 2)) -ge $PercentageMatchUnicode) {
# create big-endian Unicode with no BOM
New-Object System.Text.UnicodeEncoding $true,$false
return
}
#endregion
#region Check if Little Endian
# check if little endian Unicode next - odd-numbered index bytes will be 0)
$ZeroCount = 0
for ($i = 1; $i -lt $ByteCount; $i += 2) {
if ($Content[$i] -eq 0) { $ZeroCount++ }
if ($Content[$i] -gt 127) { $NonAsciiFound = $true }
}
if (($ZeroCount / ($ByteCount / 2)) -ge $PercentageMatchUnicode) {
# create little-endian Unicode with no BOM
New-Object System.Text.UnicodeEncoding $false,$false
return
}
#endregion
#region Doesn't appear to be Unicode; either UTF8 or ASCII
# Ok, at this point, it's not a Unicode based on our percentage rules
# if not Unicode but non-ASCII character found, call it UTF8 (no BOM, alas)
if ($NonAsciiFound -eq $true) {
New-Object System.Text.UTF8Encoding $false
return
} else {
# if made it this far, I'm calling it ASCII; done deal pal
[System.Text.Encoding]::"ASCII"
return
}
#endregion
#endregion
}
}
Export-ModuleMember -Function Get-DTWFileEncoding
#endregion
|
PowerShellCorpus/PoshCode/qwinsta.ps1
|
qwinsta.ps1
|
param (
$ComputerName #(Read-Host -Prompt "Enter a computer name")
)
if($ComputerName -eq $null) {
$c = qwinsta 2>&1 | where {$_.gettype().equals([string]) }
} else {
$c = psexec "\\\\$ComputerName" -s qwinsta 2>&1 | where {$_.gettype().equals([string]) }
}
$starters = New-Object psobject -Property @{"SessionName" = 0; "Username" = 0; "ID" = 0; "State" = 0; "Type" = 0; "Device" = 0;};
foreach($line in $c) {
try {
if($line.trim().substring(0, $line.trim().indexof(" ")) -eq "SESSIONNAME") {
$starters.Username = $line.indexof("USERNAME");
$starters.ID = $line.indexof("ID");
$starters.State = $line.indexof("STATE");
$starters.Type = $line.indexof("TYPE");
$starters.Device = $line.indexof("DEVICE");
continue;
}
New-Object psobject -Property @{
"SessionNAme" = $line.trim().substring(0, $line.trim().indexof(" ")).trim(">")
;"Username" = $line.Substring($starters.Username, $line.IndexOf(" ", $starters.Username) - $starters.Username)
;"ID" = $line.Substring($line.IndexOf(" ", $starters.Username), $starters.ID - $line.IndexOf(" ", $starters.Username) + 2).trim()
;"State" = $line.Substring($starters.State, $line.IndexOf(" ", $starters.State)-$starters.State).trim()
;"Type" = $line.Substring($starters.Type, $starters.Device - $starters.Type).trim()
;"Device" = $line.Substring($starters.Device).trim()
}
} catch {
throw $_;
#$e = $_;
#Write-Error -Exception $e.Exception -Message $e.PSMessageDetails;
}
}
|
PowerShellCorpus/PoshCode/LetterDiamondOneliner v_4.ps1
|
LetterDiamondOneliner v_4.ps1
|
&{param([char]$c)[int]$s=65;$p=$c-$s;$r=,(' '*$p+[char]$s);$r+=@(do{"{0,$p} {1}{0}"-f([char]++$s),(' '*$f++)}until(!--$p));$r;$r[-2..-99]}Z
# trimmed 130 chars w/o arg
&{param([char]$c)$p=$c-($s=65);$r=,(' '*$p+[char]$s);do{$r+="{0,$p} {1}{0}"-f([char]++$s),(' '*$f++)}until(!--$p);$r;$r[-2..-99]}J
# trimmed to 124 chars w/o arg
&{$r=,(' '*($p=[char]$args[0]-($s=65))+[char]$s);do{$r+="{0,$p} {1}{0}"-f[char]++$s,(' '*$f++)}until(!--$p);$r;$r[-2..-99]}J
|
PowerShellCorpus/PoshCode/AJAX Scrape.ps1
|
AJAX Scrape.ps1
|
## scraping method for ajax driven websites. in this example, google marketplace is the target.
## requires: watin, htmlagilitypack
## http://watin.org/
## http://htmlagilitypack.codeplex.com/
## this scripts directs watin to gunbros and angry birds product pages and htmlagility is used to scrape user reviews
$rootDir = "C:\\Users\\khtruong\\Desktop\\android review scrape"
$WatiNPath = "$rootDir\\WatiN.Core.dll"
$HtmlAgilityPath = "$rootDir\\HtmlAgilityPack.dll"
[reflection.assembly]::loadfrom( $WatiNPath )
[reflection.assembly]::loadfrom( $HtmlAgilityPath )
$ie = New-Object Watin.Core.IE
## application identifiers on android market.
$packages = @("com.glu.android.gunbros_free", "com.rovio.angrybirds")
$global:reviews = @()
foreach($package in $packages){
$ie.Goto("https://market.android.com/details?id=$package")
$ie.WaitForComplete(300)
## clicks Read All User Reviews link
$($ie.Links | ?{$_.ClassName -eq "tabBarLink"}).Click()
## clicks the Sort By menu
$($($ie.Divs | ?{$_.ClassName -eq "reviews-sort-menu-container goog-inline-block"}).Divs | ?{$_.ClassName -eq "goog-inline-block selected-option"}).ClickNoWait()
## selects Newest option from the Sort By menu
$($($($ie.Divs | ?{$_.ClassName -eq "reviews-menu"}).Divs | ?{$_.ClassName -eq "goog-menuitem-content"})[0]).ClickNoWait()
$lastPage = $false
## selects the page forward button
$nextButton = $($ie.Divs | ?{$_.ClassName -eq "num-pagination-page-button num-pagination-next goog-inline-block"})
## clicks through all 48 pages of review. review data isn't visibile in page source until a page is loaded.
$count = 1
while($count -lt 49){
write-host $count
$nextButton.Click()
## make sure data is properly loaded before continuing to the next page
Sleep 1
$count++
}
## get html page source
$result = $ie.Html
$doc = New-Object HtmlAgilityPack.HtmlDocument
$doc.LoadHtml($result)
$reviewSize = $($doc.DocumentNode.SelectNodes("//div[@class='doc-review']")).length
$reviews += @(for($counter = 0; $counter -lt $reviewSize; $counter++){
if($($($($doc.DocumentNode.SelectNodes("//div[@class='doc-review']"))[-1]).ChildNodes[3].ChildNodes | %{$_.Attributes | ?{$_.Name -eq "href"}}).Value -ne $null){
Write-Host "($counter / $reviewSize)" -fore Yellow
$PackageName = $($($($doc.DocumentNode.SelectNodes("//div[@class='doc-review']"))[$counter]).ChildNodes[3].ChildNodes | %{$_.Attributes | ?{$_.Name -eq "href"}}).Value.Split("=&")[1]
$ReviewID = $($($($doc.DocumentNode.SelectNodes("//div[@class='doc-review']"))[$counter]).ChildNodes[3].ChildNodes | %{$_.Attributes | ?{$_.Name -eq "href"}}).Value.Split("=&")[-1]
Write-Host "$ReviewID"
}
## Author
if($($($doc.DocumentNode.SelectNodes("//div[@class='doc-review']"))[$counter]).ChildNodes[0].InnerText -ne $null){
$Author = $($($doc.DocumentNode.SelectNodes("//div[@class='doc-review']"))[$counter]).ChildNodes[0].InnerText
}
else{
$Author = "Unknown"
}
## Review Date
if($($($($doc.DocumentNode.SelectNodes("//div[@class='doc-review']"))[$counter]).ChildNodes[1].InnerText).Replace(" on ","").Trim() -ne $null){
$Date = $($($($doc.DocumentNode.SelectNodes("//div[@class='doc-review']"))[$counter]).ChildNodes[1].InnerText).Replace(" on ","").Trim()
}
else{
$Date = "Unknown"
}
## Handset
if($($($doc.DocumentNode.SelectNodes("//div[@class='doc-review']"))[$counter]).ChildNodes[2].InnerText -like "*with*"){
$Handset = $($($($($doc.DocumentNode.SelectNodes("//div[@class='doc-review']"))[$counter]).ChildNodes[2].InnerText).Trim().replace("with","|").Split("|")[0]).Replace("(","").trim()
}
else{
$Handset = "Unknown"
}
## Version
if($($($($doc.DocumentNode.SelectNodes("//div[@class='doc-review']"))[$counter]).ChildNodes[2].InnerText).Trim().Split(" ")[-1].replace(")","").Trim() -ne $null){
$Version = $($($($doc.DocumentNode.SelectNodes("//div[@class='doc-review']"))[$counter]).ChildNodes[2].InnerText).Trim().Split(" ")[-1].replace(")","").Trim()
}
else{
$Version = "Unknown"
}
## Rating
if($($($($($($($doc.DocumentNode.SelectNodes("//div[@class='doc-review']"))[$counter]).ChildNodes[4]).ChildNodes) | %{$_.Attributes | ?{$_.Name -eq "Title"}}).Value) -ne $null){
$Rating = [Int]$($($($($($($doc.DocumentNode.SelectNodes("//div[@class='doc-review']"))[$counter]).ChildNodes[4]).ChildNodes) | %{$_.Attributes | ?{$_.Name -eq "Title"}}).Value).Split(" ")[1]
if($Rating -lt 3){
$Flag = "Critical"
}
else{
$Flag = ""
}
}
else{
$Rating = "Unknown"
}
## Title
if($($($($doc.DocumentNode.SelectNodes("//div[@class='doc-review']"))[$counter]).ChildNodes[4].InnerText) -ne $null){
$Title = $($($($doc.DocumentNode.SelectNodes("//div[@class='doc-review']"))[$counter]).ChildNodes[4].InnerText)
}
else{
$Title = "Review title not given."
}
## Review
if($($($($doc.DocumentNode.SelectNodes("//div[@class='doc-review']"))[$counter]).ChildNodes[5].InnerText) -ne " "){
$Review = $($($($doc.DocumentNode.SelectNodes("//div[@class='doc-review']"))[$counter]).ChildNodes[5].InnerText)
}
else{
$Review = "User did not write a review."
}
New-Object psobject -Property @{
PackageName = $PackageName
ReviewID = $ReviewID
Author = $Author
Date = $Date
Handset = $Handset
Version = $Version
Rating = $Rating
Title = $Title
Review = $Review
Flag = $Flag
}
})
}
|
PowerShellCorpus/PoshCode/Get-Snapinfo.ps1
|
Get-Snapinfo.ps1
|
Function Get-Snapinfo {
<#
.Synopsis
Get the snapshot info out of a Virtual Machine Managed Entity. Most useful for
reporting!
.PARAMETER VM
VirtualMachine object to scan to abstract snapshots from
.PARAMETER VirtualMachineSnapshotTree
used to recursivley crawl a VM for snapshots... just use -VM
.PARAMETER Filter
Specify the name of the snapshots you want to retrieve, will perform a regex match.
.Example
Get-View -ViewType virtualmachine | Get-Snapinfo
.Example
Get-View -ViewType virtualmachine | Get-Snapinfo -Filter "^SMVI"
.notes
#Requires -verson 2
Author: Glenn Sizemore
get-admin.com/blog/?p=879
#>
[cmdletBinding(SupportsShouldProcess=$false,DefaultParameterSetName="VM")]
Param(
[parameter(Mandatory=$true,ValueFromPipeline=$true, ParameterSetName="VM")]
[VMware.Vim.VirtualMachine[]]
$VM,
[parameter(Mandatory=$true,ValueFromPipeline=$true, ParameterSetName="Snaptree")]
[VMware.Vim.VirtualMachineSnapshotTree[]]
$VirtualMachineSnapshotTree,
[parameter(ParameterSetName="VM")]
[parameter(ParameterSetName="Snaptree")]
[string]
$Filter
)
Process {
switch ($PScmdlet.ParameterSetName)
{
"Snaptree"
{
Foreach ($Snapshot in $VirtualMachineSnapshotTree) {
Foreach ($ChildSnap in $Snapshot.ChildSnapshotList) {
if ($ChildSnap) {
Get-Snapinfo -VirtualMachineSnapshotTree $ChildSnap -Filter $Filter
}
}
If ($Snapshot.Name -match $Filter ) {
write-output $Snapshot | Select Name, CreateTime, Vm, Snapshot
}
}
}
"VM"
{
Foreach ($v in $VM) {
Get-Snapinfo -VirtualMachineSnapshotTree $v.Snapshot.RootSnapshotList -Filter $Filter
}
}
}
}
}
|
PowerShellCorpus/PoshCode/dc5f3df6-1aa2-4d34-abf2-d113722bce02.ps1
|
dc5f3df6-1aa2-4d34-abf2-d113722bce02.ps1
|
################################################################################
# Get-GprsTime.ps1(V 1006A)
# Check the total connect time of any GPRS devices from a specified date.
# Use the -Detail switch for some extra information if desired. A default value
# can be set with the -Monthly switch but can be temporarily overridden with any
# -Start value and deleted by entering an invalid date. Now uses .NET Parse to
# use any culture date input. Switches -M and -S cannot be used together.
# A Balloon prompt will be issued in the Notification area for the 5 days
# before the nominal month end, and a suitable Icon (exclamation.ico) file needs
# to be available in the $PWD directory for this to work.
# NOTE: this can effectively be suppressed by using a value higher than the SIM
# card term, ie something like -Expire 100 for a 30 day card which will override
# the default setting. Use -Today to check only today's usage.
# Examples:
# .\\Get-GprsTime.ps1 -Monthly 4/8/2009
# .\\Get-GprsTime.ps1 -Start 12/07/2009 -Expires 100 -Detail
# .\\Get-GprsTime.ps1 -m 5/9/2009
# .\\Get-GprsTime.ps1 10/4/2009 -d
# .\\Get-GprsTime.ps1 -d
# .\\Get-GprsTime.ps1 -Today
# .\\Get-GprsTime.ps1
#
# The author can be contacted at www.SeaStarDevelopment.Bravehost.com and the
# 'exclamation.ico' file is included in the Gprs100x.zip download there.
################################################################################
Param ([String] $start,
[String] $monthly,
[Int] $expires = 30, #Start warning prompt 5 days before month end.
[Switch] $today,
[Switch] $detail)
Trap [System.Management.Automation.MethodInvocationException] {
Write-Warning "[$name] Date is missing or invalid $SCRIPT:form"
[System.Media.SystemSounds]::Hand.Play()
[Int]$line = $error[0].InvocationInfo.ScriptLineNumber
If ($line -eq 114) {
Write-Warning "Current GPRS variable has been deleted."
$monthly = ""
[Environment]::SetEnvironmentVariable("GPRS",$monthly,"User")
}
Exit 1
}
$name = $myInvocation.MyCommand
$newLine = "[$name] The switches -Start and -Monthly `n $(' '*($name.ToString().Length +10)) can only be used separately."
If ($start -and $monthly) {
[System.Media.SystemSounds]::Hand.Play()
Write-Warning "$newLine"
Exit 1
}
$SCRIPT:form = ""
#In certain cases Culture & UICulture can be different and have been known to
# return conflicting results regarding '-is [DateTime]' queries, etc.
If ($Host.CurrentCulture -eq $Host.CurrentUICulture) {
$SCRIPT:form = '-Use format mm/dd/year'
[Int]$culture = "{0:%d}" -f [DateTime] "6/5/2009" #Returns local day.
If ($culture -eq 6) {
$SCRIPT:form = '-Use format dd/mm/year'
}
}
$VerbosePreference = 'SilentlyContinue'
$WarningPreference = 'Continue'
$conn = $disc = $null
$timeNow = [DateTime]::Now
$total = $timeNow - $timeNow #Set initial value to 00:00:00
$insert = "since"
If ($detail) {
$VerbosePreference = 'Continue'
}
Function CreditMsg ($value) {
$value = [Math]::Abs($value)
$prefix = "CURRENT"
$creditDate = [Environment]::GetEnvironmentVariable("GPRS","User")
If ($creditDate) { #Do nothing if no monthly date set.
[DateTime] $creditDT = $creditDate
$creditDT = $creditDT.AddDays($value) #Add the -Expires days.
$thisDay = "{0:M/d/yyyy}" -f [DateTime]::Now #Force US format.
#If we use '$number = $creditDT - (Get-Date)' instead of the line below
#we can sometimes get a value of 1 returned instead 2, hence the above.
$number = $creditDT - [DateTime] $thisDay
[String] $credit = $creditDT
$credit = $credit.Replace('00:00:00','') #Remove any trailing time.
$credit = "{0:d}" -f [DateTime]$credit
Switch($number.Days) {
1 {$prefix = "($value days) will expire tomorrow"; break}
0 {$prefix = "($value days) will expire today"; break}
-1 {$prefix = "($value days) expired yesterday"; break}
{($_ -lt 0)} {$prefix = "($value days) expired on $credit"; break}
{($_ -le 5)} {$prefix = "($value days) will expire on $credit"}
Default {$prefix = "CURRENT"} #Only come here if over 5 days.
}
}
Return $prefix
}
Function Interval ([String] $value) {
Switch($value) {
{ $_ -match '^00:00:\\d+(.*)$' } {$suffix = "seconds"; break}
{ $_ -match '^00:\\d+:\\d+(.*)$'} {$suffix = "minutes"; break}
Default {$suffix = " hours"}
}
Return $suffix
}
#The Script effectively starts here.............................................
If ($start) {
[DateTime] $limit = [DateTime]::Parse($start) #Trigger TRAP if invalid!
$convert = "{0:D}" -f $limit
}
If ($monthly) {
$start = [DateTime]::Parse($monthly) #Trigger TRAP if invalid!
Write-Output "Setting GPRS (monthly) environment variable to: $monthly"
$gprs = [String]$start.Replace('00:00:00','')
[Environment]::SetEnvironmentVariable("GPRS",$gprs,"User")
[DateTime] $limit = $start #Change to required US date format.
$convert = "{0:D}" -f $limit
}
If ($today) {
$verBosePreference = 'Continue' #Show VERBOSE by default.
[DateTime] $limit = (Get-Date)
$convert = "{0:D}" -f $limit
$limit = $limit.Date #Override any start date if using -Today input.
$insert = "for today"
}
#Now we can only continue if we have a valid GPRS environment variable.
If ((!$today) -and (!$monthly) -and (!$start)) { #Come here if -Expires.
$monthly = [Environment]::GetEnvironmentVariable("GPRS","User")
#If no GPRS we have to generate an error for TRAP to catch.
If (!$monthly) {
$monthly = [DateTime]::Parse($monthly)
}
[DateTime] $limit = $monthly
$convert = "{0:D}" -f $limit
}
Write-Verbose "All records $($insert.Replace('for ','')) - $convert"
Write-Verbose "Script activation - User [$($env:UserName)] Computer [$($env:ComputerName)]"
$text = CreditMsg $expires #Check if we are within 5 days of expiry date.
If (($text -ne "CURRENT") -and (Test-Path "$pwd\\exclamation.ico")) {
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon
$objNotifyIcon.Icon = "$pwd\\exclamation.ico"
$objNotifyIcon.BalloonTipIcon = "Info"
$objNotifyIcon.BalloonTipTitle = "GPRS online account"
$objNotifyIcon.BalloonTipText = "Credit $text"
$objNotifyIcon.Visible = $True
$objNotifyIcon.ShowBalloonTip(10000)
}
Write-Output ""
Write-Output "Calculating total connect time of all GPRS modem devices..."
#We cannot proceed beyond here without a valid $limit value.
$lines = Get-EventLog system | Where-Object {($_.TimeGenerated -ge $limit) -and `
($_.EventID -eq 20159 -or $_.EventID -eq 20158)}
If ($lines) {
Write-Verbose "A total of $([Math]::Truncate($lines.Count/2)) online sessions extracted from the System Event Log."
}
Else {
Write-Output "(There are no events indicated in the System Event Log)"
}
$lines | ForEach-Object {
$source = $_.Source
If ($_.EventID -eq 20159) { #Event 20159 is Disconnect.
$disc = $_.TimeGenerated
}
Else { #Event 20158 is Connect.
$conn = $_.TimeGenerated
} #We are only interested in matching pairs of DISC/CONN...
If ($disc -ne $null -and $conn -ne $null -and $disc -gt $conn) {
$diff = $disc - $conn
$total += $diff
$convDisc = "{0:G}" -f $disc
$convConn = "{0:G}" -f $conn
$period = Interval $diff
Write-Verbose "Disconnect at $convDisc. Online - $diff $period"
Write-Verbose " Connect at $convConn."
}
} #End ForEach
If (!$source) {
$source = '(Undetermined)'
}
Write-Verbose "Using local event source - System Event Log [$source]"
$period = Interval $total
Write-Output "Total online usage $insert $convert is $total $($period.Trim())."
Write-Output ""
|
PowerShellCorpus/PoshCode/Remove-LocalProfile.ps1
|
Remove-LocalProfile.ps1
|
<#
.SYNOPSIS
Interactive menu that allows a user to connect to a local or remote computer and remove a local profile.
.DESCRIPTION
Presents an interactive menu for user to first make a connection to a remote or local machine. After making connection to the machine,
the user is presented with all of the local profiles and then is asked to make a selection of which profile to delete. This is only valid
on Windows Vista OS and above for clients and Windows 2008 and above for server OS.
.NOTES
Name: Remove-LocalProfile
Author: Boe Prox
DateCreated: 26JAN2011
.LINK
http://boeprox.wordpress.com
http://msdn.microsoft.com/en-us/library/ee886409%28v=vs.85%29.aspx
.EXAMPLE
Remove-LocalProfile
Description
-----------
Presents a text based menu for the user to interactively remove a local profile on local or remote machine.
#>
#Prompt for a computer to connect to
$computer = Read-Host "Please enter a computer name"
#Test network connection before making connection
If ($computer -ne $Env:Computername) {
If (!(Test-Connection -comp $computer -count 1 -quiet)) {
Write-Warning "$computer is not accessible, please try a different computer or verify it is powered on."
Break
}
}
Try {
#Verify that the OS Version is 6.0 and above, otherwise the script will fail
If ((Get-WmiObject -ComputerName $computer Win32_OperatingSystem -ea stop).Version -lt 6.0) {
Write-Warning "The Operating System of the computer is not supported.`nClient: Vista and above`nServer: Windows 2008 and above."
Break
}
}
Catch {
Write-Warning "$($error[0])"
Break
}
Do {
#Gather all of the user profiles on computer
Try {
$users = Get-WmiObject -ComputerName $computer Win32_UserProfile -filter "LocalPath Like 'C:\\\\Users\\\\%'" -ea stop
}
Catch {
Write-Warning "$($error[0]) "
Break
}
#Cache the number of users
$num_users = $users.count
Write-Host -ForegroundColor Green "User profiles on $($computer):"
#Begin iterating through all of the accounts to display
For ($i=0;$i -lt $num_users; $i++) {
Write-Host -ForegroundColor Green "$($i): $(($users[$i].localpath).replace('C:\\Users\\',''))"
}
Write-Host -ForegroundColor Green "q: Quit"
#Prompt for user to select a profile to remove from computer
Do {
$account = Read-Host "Select a number to delete local profile or 'q' to quit"
#Find out if user selected to quit, otherwise answer is an integer
If ($account -NotLike "q*") {
$account = $account -as [int]
}
}
#Ensure that the selection is a number and within the valid range
Until (($account -lt $num_users -AND $account -match "\\d") -OR $account -Like "q*")
If ($account -Like "q*") {
Break
}
Write-Host -ForegroundColor Yellow "Deleting profile: $(($users[$account].localpath).replace('C:\\Users\\',''))"
#Remove the local profile
($users[$account]).Delete()
Write-Host -ForegroundColor Green "Profile: $(($users[$account].localpath).replace('C:\\Users\\','')) has been deleted"
#Configure yes choice
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes","Remove another profile."
#Configure no choice
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No","Quit profile removal"
#Determine Values for Choice
$choice = [System.Management.Automation.Host.ChoiceDescription[]] @($yes,$no)
#Determine Default Selection
[int]$default = 0
#Present choice option to user
$userchoice = $host.ui.PromptforChoice("Information","Remove Another Profile?",$choice,$default)
}
#If user selects No, then quit the script
Until ($userchoice -eq 1)
|
PowerShellCorpus/PoshCode/Get-ActiveRules (SCOM).ps1
|
Get-ActiveRules (SCOM).ps1
|
## Get-ActiveRules grabs the workflows running on the specified server
## Author: Jeremy D. Pavleck - Jeremy@Pavleck.NET
## Requires: The Microsoft.SystemCenter.Internal.Tasks.mp on the SP1 CD
## Notes: You can find this task inside the console by going to monitoring, computers and under "Windows Computer Tasks" run
## "Show Running Rules and Monitors" for this object.
function Get-ActiveRules ([string]$server, [string]$location) {
If (!$location) { $location = "C:\\$server-Rules.xml" }
# Create the Task object
$taskobj = Get-Task | Where-Object {$_.Name -eq "Microsoft.SystemCenter.GetAllRunningWorkflows"}
# Make sure we have it, if not, the MP isn't installed.
If (!$taskobj) {
Write-Host "Unable to find required monitoring tasks - MS System Center Internal Tasks MP needs to be installed." -ForeGroundColor Magenta;
break;
}
# Grab HealthService class object
$hsobj = Get-MonitoringClass -name "Microsoft.SystemCenter.HealthService"
# Find HealthService object defined for named server
$monobj = Get-MonitoringObject -MonitoringClass $hsobj | Where-Object {$_.DisplayName -match $server}
# Now actually proceed with the task. I have mine formatted like this version, but I've added some light
# error checking for the 'public' version.
#(Start-Task -task $taskobj -TargetMonitoringObject $monobj).Output | Out-File C:\\$server-Rules.xml
$taskOut = Start-Task -Task $taskobj -TargetMonitoringObject $monobj
# See if it worked, if it did, export out the OutPut part and save as an XML file, then display some items.
If ($taskOut.ErrorCode -eq 0) {
[xml]$taskXML = $taskOut.OutPut
$ruleCount = $taskXML.DataItem.Count
Write-Host "Succeeded in gathering rules for $server" -ForeGroundColor Green
Write-Host "Currently $ruleCount rules active." -ForeGroundColor Green
Write-Host "Exporting to $location" -ForeGroundColor Green
$taskOut.OutPut | Out-File $location
} else {
Write-Host "Error gathering rules for $server" -ForeGroundColor Magenta
Write-Host "Error Code: " + $taskOut.ErrorCode -ForeGroundColor Magenta
Write-Host "Error Message: " + $taskOut.ErrorMessage -ForeGroundColor Magenta
}
} # End Get-ActiveRules
#######################
|
PowerShellCorpus/PoshCode/Move-VMTemplate.ps1
|
Move-VMTemplate.ps1
|
#requires -pssnapin VMware.VimAutomation.Core -version 1.0
# Author: Glenn Sizemore
# URL: http`://get-admin.com/blog/?p=47
# Purpose: Move VMware templates
#
# Usage: move-VMTemplate -targetpool "pool1" -targethost "ESX1.localdomain.local"
# Will move Every Template in VIVC to ESX1.
#
# move-VMTemplate -template win2k3_x86_ENT -targetpool pool1 -targethost ESX1.localdomain.local -targetfolder win_templates
# Will move win2k3_x86_ENT template onto ESX1, and into win_templates
param(
$template,
[string]$targetpool = "pool1",
[string]$targetHost = "ESX1.localdomain.local",
[string]$targetFolder = "Templates"
)
# This is not bulletproof because $DefaultVIServer is not nulled
# when the connection is either manually disconnected or times out.
#
# That being said, this will prompt for connection if your current
# Session has never connected to VIVC.
if (-not $DefaultVIServer) {Connect-VIServer}
# get the moref for the Target Resource pool
# NOTE: MoRef is VMware's equivalent of a GUID
$targetPoolMoRef = (get-cluster $targetpool | Get-ResourcePool | get-view).MoRef
# gets the moref for the Target ESX Host
$targethostMoRef = (get-VMHost $targetHost | get-view).MoRef
# gets the moref for the Target Folder
$TargetFolderMoRef = (Get-Folder Templates | Get-View).MoRef
# gets the moref for every template registered in Virtual center.
foreach ($template in (Get-Template $template | get-view))
{
#when we convert the template into a VM we will move it into
#the target resource pool / host
$template.MarkAsVirtualMachine($targetPoolMoRef,$targethostMoRef)
# Convert the VM back into a template
$template.MarkAsTemplate()
# Move that template into the target folder
$TargetFolder.MoveIntofolder($TargetFolderMoRef)
}
|
PowerShellCorpus/PoshCode/chkhash_28.ps1
|
chkhash_28.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 ($Host.Name -match 'ise')
{ write-host $writestr; return }
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 ($Host.Name -match 'ise')
{ return }
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
$n = $null
"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 ($create -eq $true -or !(test-path $hashespath)) # Create database?
{
# Create SHA512 hashes of files and write to new database
if ($files.count -eq 0) {"No files found. Exiting."; exit}
$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) -or ($files.count -eq 0)) {"No files in Database or no files specified. 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 | %{get-item -ea 0 -literalpath $_}
}
"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) {WriteFileName "Needs to be added: `"$($f.fullname)`"";WriteFileNameEnd;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)`" ..."
$fc++ # File checked increment.
if (($upd -eq $false) -and ($f.length -ne $xfiles[$n].length))
{
$errs++
WriteFileName "Size mixmatch: `"$($f.fullname)`""; WriteFileNameEnd
continue
}
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force}
# Check SHA512 and size for mixmatch.
if ($xfiles[$n].length -eq $f.length)
{
if ($xfiles[$n].SHA512 -eq $f.SHA512)
{
$fm++;continue # if matched, increment file matches and continue loop
}
}
$errs++ # increment mixmatches
if ($upd -eq $true) { $xfiles[$n]=$f; WriteFileName "Updated `"$($f.fullname)`""; WriteFileNameEnd;continue}
WriteFileName "SHA-512 and/or size mixmatch found: `"$($f.fullname)`""; WriteFileNameEnd
}
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 or size mixmatch(es) found."
"$fm file(s) SHA512 and size 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/Speech Recognition 2.ps1
|
Speech Recognition 2.ps1
|
$null = [Reflection.Assembly]::LoadWithPartialName("System.Speech")
## Create the two main objects we need for speech recognition and synthesis
if(!$Global:SpeechModuleListener){ ## For XP's sake, don't create them twice...
$Global:SpeechModuleSpeaker = new-object System.Speech.Synthesis.SpeechSynthesizer
$Global:SpeechModuleListener = new-object System.Speech.Recognition.SpeechRecognizer
}
$Script:SpeechModuleMacros = @{}
## Add a way to turn it off
$Script:SpeechModuleMacros.Add("Stop Listening", { $script:listen = $false; Suspend-Listening })
$Script:SpeechModuleComputerName = ${Env:ComputerName}
function Update-SpeechCommands {
#.Synopsis
# Recreate the speech recognition grammar
#.Description
# This parses out the speech module macros,
# and recreates the speech recognition grammar and semantic results,
# and then updates the SpeechRecognizer with the new grammar,
# and makes sure that the ObjectEvent is registered.
$choices = new-object System.Speech.Recognition.Choices
foreach($choice in $Script:SpeechModuleMacros.GetEnumerator()) {
$g = New-Object System.Speech.Recognition.GrammarBuilder
$phrases = @($choice.Key -split "\\s*\\*\\s*")
for($i=0;$i -lt $phrases.Count;$i++) {
if($phrases[$i].Length -gt 0) {
$g.Append( $phrases[$i] )
if($i+1 -lt $phrases.Count) {
$g.AppendDictation()
}
} elseif($i -eq 0) {
$g.AppendDictation()
}
}
$choices.Add( (New-Object System.Speech.Recognition.SemanticResultValue $g, $choice.Value.ToString()).ToGrammarBuilder() )
}
if($VerbosePreference -ne "SilentlyContinue") { $Script:SpeechModuleMacros.Keys |
ForEach-Object { Write-Host "$Computer, $_" -Fore Cyan } }
$builder = New-Object System.Speech.Recognition.GrammarBuilder "$Computer, "
$builder.Append((New-Object System.Speech.Recognition.SemanticResultKey "Commands", $choices.ToGrammarBuilder()))
$grammar = new-object System.Speech.Recognition.Grammar $builder
$grammar.Name = "Power VoiceMacros"
## Take note of the events, but only once (make sure to remove the old one)
Unregister-Event "SpeechModuleCommandRecognized" -ErrorAction SilentlyContinue
$null = Register-ObjectEvent $grammar SpeechRecognized `
-SourceIdentifier "SpeechModuleCommandRecognized" `
-Action { $_ = $event.SourceEventArgs.Result.Text; iex $event.SourceEventArgs.Result.Semantics.Item("Commands").Value }
$Global:SpeechModuleListener.UnloadAllGrammars()
$Global:SpeechModuleListener.LoadGrammarAsync( $grammar )
}
function Add-SpeechCommands {
#.Synopsis
# Add one or more commands to the speech-recognition macros, and update the recognition
#.Parameter CommandText
# The string key for the command to remove
[CmdletBinding()]
Param([hashtable]$VoiceMacros,[string]$Computer=$Script:SpeechModuleComputerName)
## Add the new macros
$Script:SpeechModuleMacros += $VoiceMacros
## Update the default if they change it, so they only have to do that once.
$Script:SpeechModuleComputerName = $Computer
Update-SpeechCommands
}
function Remove-SpeechCommands {
#.Synopsis
# Remove one or more command from the speech-recognition macros, and update the recognition
#.Parameter CommandText
# The string key for the command to remove
Param([string[]]$CommandText)
foreach($command in $CommandText) { $Script:SpeechModuleMacros.Remove($Command) }
Update-SpeechCommands
}
function Clear-SpeechCommands {
#.Synopsis
# Removes all commands from the speech-recognition macros, and update the recognition
#.Parameter CommandText
# The string key for the command to remove
$Script:SpeechModuleMacros = @{}
## Default value: A way to turn it off
$Script:SpeechModuleMacros.Add("Stop Listening", { Suspend-Listening })
Update-SpeechCommands
}
function Start-Listening {
#.Synopsis
# Sets the SpeechRecognizer to Enabled
$Global:SpeechModuleListener.Enabled = $true
Say "Speech Macros are $($Global:SpeechModuleListener.State)"
Write-Host "Speech Macros are $($Global:SpeechModuleListener.State)"
}
function Suspend-Listening {
#.Synopsis
# Sets the SpeechRecognizer to Disabled
$Global:SpeechModuleListener.Enabled = $false
Say "Speech Macros are disabled"
Write-Host "Speech Macros are disabled"
}
function Out-Speech {
#.Synopsis
# Speaks the input object
#.Description
# Uses the default SpeechSynthesizer settings to speak the string representation of the InputObject
#.Parameter InputObject
# The object to speak
# NOTE: this should almost always be a pre-formatted string,
# most objects don't render to very speakable text.
Param( [Parameter(ValueFromPipeline=$true)][Alias("IO")]$InputObject )
$null = $Global:SpeechModuleSpeaker.SpeakAsync(($InputObject|Out-String))
}
function Remove-SpeechXP {
#.Synopis
# Dispose of the SpeechModuleListener and SpeechModuleSpeaker
$Global:SpeechModuleListener.Dispose(); $Global:SpeechModuleListener = $null
$Global:SpeechModuleSpeaker.Dispose(); $Global:SpeechModuleSpeaker = $null
}
set-alias asc Add-SpeechCommands
set-alias rsc Remove-SpeechCommands
set-alias csc Clear-SpeechCommands
set-alias say Out-Speech
set-alias listen Start-Listener
Export-ModuleMember -Function * -Alias * -Variable SpeechModuleListener, SpeechModuleSpeaker
|
PowerShellCorpus/PoshCode/Backup exchange 2007.ps1
|
Backup exchange 2007.ps1
|
#######################################################################################
#Backup Exchange 2007
#Fecha: 14/01/2012
#Pedro Genil
#Realizamos un backup de los SG del mailbox
#Se realizara de todos un incremental, y un full del que lleve X dias sin hacerse
######################################################################################
# Ańadimos el moduklo de exchange
If ((Get-PSSnapin | where {$_.Name -match "Exchange.Management"}) -eq $null)
{
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin
}
# Inicializar variables
$lista_incremental = ""
$lista_full = ""
$oldest_full = $(Get-Date).AddDays(4)
# Obtener los datos del servidor
$server = "MAILBOX"
# Procesar todas sus bases de datos excepto las que tienen "TSMRSG" como parte del nombre
foreach ($database in Get-MailboxDatabase -Server $server -Status | where { $_.storagegroupname -notlike "TSMRSG" })
{
# Continuar solo si la bbdd no es de recovery
if (-not $database.Recovery)
{
# Continuar solo si la bbdd esta montada
if ($database.Mounted)
{
# Continuar solo si la bbdd no esta en modo backup
if (-not $database.BackupInProgress)
{
# A partir de aqui, la bbdd es candidato a backup
# Creamos el listado con los fulls
# Para el backup full, solo nos quedamos con la que hace mas tiempo que no tiene backup full
if ($database.LastFullBackup -lt $oldest_full)
{
$lista_full = "`"" + $($database.StorageGroupname) + "`""
$oldest_full = $database.LastFullBackup
}
}
}
}
}
# Procesar todas sus bases de datos excepto las que tienen "TSMRSG" como parte del nombre
foreach ($database in Get-MailboxDatabase -Server $server -Status | where { $_.storagegroupname -notlike "TSMRSG" })
{
# Continuar solo si la bbdd no es de recovery
if (-not $database.Recovery)
{
# Continuar solo si la bbdd esta montada
if ($database.Mounted)
{
# Continuar solo si la bbdd no esta en modo backup
if (-not $database.BackupInProgress)
{
# A partir de aqui, la bbdd es candidato a backup
# Quitamos el full de los incremental
if (-not $database.CircularLoggingEnabled)
{
if ($lista_full -ne "`"" + $($database.StorageGroupname) + "`"")
{
if ($lista_incremental.Length -gt 0)
{
$lista_incremental += ","
}
$lista_incremental += "`"" + $($database.StorageGroupname) + "`""
}
}
}
}
}
}
#Ańadimos las public Folder
foreach ($pf in Get-PublicFolderDatabase -Server $server -Status)
{
if ($pf.Mounted -and -not $pf.BackupInProgress)
{
if ($lista_full.Length -gt 0)
{
$lista_full += ","
}
$lista_full += "`"" + $($pf.storagegroupname) + "`""
}
}
# Ejecutar los jobs de backup, primero el incremental y luego el full
$hoy = Get-Date
$fecha = $hoy.ToString("yyyyMMdd")
$log_incr = "Incr_" + $fecha + ".log"
$log_full = "Full_" + $fecha + ".log"
Write-Output (Get-Date) | out-file -File $log_incr -Append
cd "Ruta donde este el tdpexcc"
. ".\\tdpexcc.exe" "backup" $lista_incremental >> $log_incr
Write-Output (Get-Date) | out-file -File $log_full -Append
. ".\\tdpexcc.exe" "backup" $lista_full "full" >> $log_full
#Guardamos la lista de backups por dia
$fechac = Get-date
if ((Test-Path "F:\\Logs_BCKP\\sg.txt") -ne $true)
{
New-Item -path "F:\\Logs_BCKP" -name "sg.txt" -type File
}
Write "------------------------------------------" >> "F:\\Logs_BCKP\\sg.txt"
Write $fechac >> "F:\\Logs_BCKP\\sg.txt"
Write "FULL" $lista_full >> "F:\\Logs_BCKP\\sg.txt"
Write "INCREMENTAL" $lista_incremental >> "F:\\Logs_BCKP\\sg.txt"
Write "------------------------------------------" >> "F:\\Logs_BCKP\\sg.txt"
# Limpiar logs, conservar 60 dias
foreach ($oldfile in (Get-ChildItem Incr_*.log,Full_*.log))
{
if ($oldfile.LastWriteTime -le $hoy.AddDays(-60))
{
Remove-Item $oldfile
}
}
#END
|
PowerShellCorpus/PoshCode/Set-IPConfig.ps1
|
Set-IPConfig.ps1
|
# script parameters
param(
[string[]] $Computers = $env:computername,
[switch] $ChangeSettings,
[switch] $EnableDHCP
)
# check for Admin rights
if ($ChangeSettings -or $EnableDHCP){
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")){
Write-Warning "You need Administrator rights to run this script!"
Break
}
}
else{
""
Write-Warning "For changing settings add -ChangeSettings as parameter, if not this script is output only"
}
# script variables
$nl = [Environment]::NewLine
$Domain = "domain.local"
$DNSSuffix = @("domain.local", "domain.com")
$DNSServers = @("10.10.0.1", "10.20.0.1", "10.10.0.2", "10.20.0.2")
$WINSServers = @("10.10.0.125", "10.10.0.126")
$Gateway = @("10.10.255.254")
# script functions
Function NewNICDetails($NIC, $Computer){
# retrieve updated values for changed NIC
$UpdatedNIC = Get-WMIObject Win32_NetworkAdapterConfiguration -Computername $Computer | where{$_.Index -eq $NIC.Index}
ShowDetails $UpdatedNIC
}
Function ChangeIPConfig($NIC){
if ($EnableDHCP){$NIC.EnableDHCP()}
#$NIC.SetGateways($Gateway)
#$NIC.SetWINSServer($WINSServers)
$DNSServers = Get-random $DNSservers -Count 4
$NIC.SetDNSServerSearchOrder($DNSServers)
$NIC.SetDynamicDNSRegistration("TRUE")
$NIC.SetDNSDomain($Domain)
# remote WMI registry method for updating DNS Suffix SearchOrder
$registry = [WMIClass]"\\\\$computer\\root\\default:StdRegProv"
$HKLM = [UInt32] "0x80000002"
$registry.SetStringValue($HKLM, "SYSTEM\\CurrentControlSet\\Services\\TCPIP\\Parameters", "SearchList", $DNSSuffix)
}
Function ShowDetails($NIC){
Write-Host "Hostname = " $NIC.DNSHostName
Write-Host "DNSDomain= " $NIC.DNSDomain
Write-Host "Domain DNS Registration Enabled = " $NIC.DomainDNSRegistrationEnabled
Write-Host "Full DNS Registration Enabled = " $NIC.FullDNSRegistrationEnabled
Write-Host "DNS Domain Suffix Search Order = " $NIC.DNSDomainSuffixSearchOrder
Write-Host "MAC address = " $NIC.MACAddress
Write-Host "DHCP enabled = " $NIC.DHCPEnabled
# show all IP adresses on this NIC
$x = 0
foreach ($IP in $NIC.IPAddress){
Write-Host "IP address $x =" $NIC.IPAddress[$x] "/" $NIC.IPSubnet[$x]
$x++
}
Write-Host "Default IP Gateway = " $NIC.DefaultIPGateway
Write-Host "DNS Server Search Order = " $NIC.DNSServerSearchOrder
}
# actual script execution
foreach ($Computer in $Computers){
if (Test-connection $Computer -quiet -count 1){
Try {
[array]$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration -Computername $Computer | where{$_.IPEnabled -eq "TRUE"}
}
Catch {
Write-Warning "$($error[0]) "
Break
}
# Generate selection menu only if there is indeed more than 1 NIC
$NICindex = $NICs.count
$SelectIndex = 0
if ($NICindex -gt 1){
Write-Host "$nl Selection for " $Computer.ToUpper() ": $nl"
For ($i=0;$i -lt $NICindex; $i++) {
Write-Host -ForegroundColor Green $i --> $($NICs[$i].Description)
}
Write-Host -ForegroundColor Green q --> Quit
Write-host $nl
# Wait for user selection input
Do {
$SelectIndex = Read-Host "Select connection (default = $SelectIndex) or 'q' to quit"
If ($SelectIndex -NotLike "q*"){$SelectIndex = $SelectIndex -as [int]}
}
Until (($SelectIndex -lt $NICindex -AND $SelectIndex -match "\\d") -OR $SelectIndex -Like "q*")
If ($SelectIndex -Like "q*"){continue}
}
# Show selected network card name + current values
Write-Host "$nl IP settings on:"$Computer.ToUpper() "$nl $nl for " $NICs[$SelectIndex].Description ":"
Write-host "$nl ====BEFORE====$nl $nl"
Write-Host $(ShowDetails $NICs[$SelectIndex]) $nl
# Change settings for selected network card if option is true and show updated values
If ($ChangeSettings){
ChangeIPConfig $NICs[$SelectIndex]
Write-Host "$nl IP settings on:"$Computer.ToUpper() "$nl $nl for " $NICs[$SelectIndex].Description ":"
Write-host "$nl ====AFTER====$nl $nl"
Write-Host $(NewNICDetails $NICs[$SelectIndex] $Computer) $nl
}
}
}
|
PowerShellCorpus/PoshCode/Get-HelpInfo - PS V3.ps1
|
Get-HelpInfo - PS V3.ps1
|
#requires -version 3
function Get-HelpInfo {
write-progress -id 1 -Activity "Get-HelpInfo" -Status "Getting remote version table..."
# could cache this
$remote = & {
$html = invoke-webrequest http://technet.microsoft.com/en-us/windowsserver/jj662920
$html.ParsedHtml.getElementsByTagName("TABLE").item(2).rows| % -begin {
$total = $html.ParsedHtml.getElementsByTagName("TABLE").item(2).rows.length
$index = 0
} -process {
write-progress -id 1 -Activity "Get-HelpInfo" -Status "Getting remote version table..." `
-PercentComplete (([float]$index / $total) * 100)
($_.cells | % innertext) -join ","
$index++
} | convertfrom-csv
}
write-progress -id 1 -Activity "Get-HelpInfo" -Status "Enumerating local modules..." `
-CurrentOperation "Please wait..."
# could cache "gmo -list" output too - it's dog slow, and no way to get progress either.
gmo -list | ? {
write-progress -id 1 -Activity "Get-HelpInfo" -Status "Examining $($_.name) ..."
test-path ($info = join-path (split-path $_.path) `
("{0}_{1}_HelpInfo.xml" -f $_.name, $_.guid))
} | % {
$name = $_.Name
([xml](gc $info)).HelpInfo.SupportedUICultures.UICulture
} | % {
[pscustomobject]@{
ModuleName = $name
UICulture = $_.UICultureName
Installed = $_.UICultureVersion
Available = ($remote|? { ($_.modulename -eq $name) -and $_.uiculture `
-contains $_.uiculturename } ).version
}
}
}
get-helpinfo | ft -AutoSize
|
PowerShellCorpus/PoshCode/Get-ProcessProfile.ps1
|
Get-ProcessProfile.ps1
|
##############################################################################
##
## Get-ProcessProfile
##
##############################################################################
<#
.SYNOPSIS
Uses cdb.exe from the Debugging Tools for Windows to create a sample-based
profile of .NET or native applications.
.EXAMPLE
$frames = C:\\temp\\Get-ProcessProfile.ps1 -ProcessId 11844
$frames | % { $_[0] } | group | sort Count | Select Count,Name | ft -auto
Runs a sampling profile on process ID 1184. Then, it extracts out the top
(current) stack entry from each call frame and groups it by the resulting
text.
This gives a report like the following, which was taken while PowerShell
version 2 was slowly enumerating a network share. The output below
demonstrates that PowerShell was spending the majority of its time invoking a
pipeline, and calling the .NET System.IO.FillAttributeInfo API:
Count Name
----- ----
1 System.Collections.Specialized.HybridDictionary.set_Item(System.Object...
1 System.Text.StringBuilder..ctor(System.String, Int32, Int32, Int32)
1 System.Management.Automation.Provider.CmdletProvider.WrapOutputInPSObj...
1 System.Management.Automation.Provider.NavigationCmdletProvider.GetPare...
1 System.Management.Automation.Provider.CmdletProvider.get_Force()
1 System.Management.Automation.Cmdlet.WriteObject(System.Object)
1 System.String.AppendInPlace(Char[], Int32, Int32, Int32)
1 Microsoft.PowerShell.ConsoleHostRawUserInterface.LengthInBufferCells(C...
1 System.Security.Util.StringExpressionSet.CanonicalizePath(System.Strin...
1 Microsoft.PowerShell.ConsoleControl.GetConsoleScreenBufferInfo(Microso...
1 System.IO.DirectoryInfo..ctor(System.String, Boolean)
1 System.Security.Permissions.FileIOPermission.AddPathList(System.Securi...
2 System.IO.Path.InternalCombine(System.String, System.String)
2 System.Runtime.InteropServices.SafeHandle.Dispose(Boolean)
18 System.IO.Directory.InternalGetFileDirectoryNames(System.String, Syste...
66 System.IO.File.FillAttributeInfo(System.String, WIN32_FILE_ATTRIBUTE_D...
100 System.Management.Automation.Runspaces.PipelineBase.Invoke(System.Coll...
#>
param(
## The process ID to attach to
[Parameter(Mandatory = $true)]
$ProcessId,
## How many samples to retrieve
$SampleCount = 100,
## Switch parameter to debug a native process
[Switch] $UseNativeDebugging,
## Path to CDB. Will be detected if not supplied.
$CdbPath
)
## If the user didn't specify a path to CDB, see if we can find it in the
## standard locations.
if(-not $CdbPath)
{
$cdbPaths = "C:\\Program Files (x86)\\Windows Kits\\8.0\\Debuggers\\x64\\cdb.exe",
"C:\\Program Files (x86)\\Windows Kits\\8.0\\Debuggers\\x86\\cdb.exe",
"C:\\Program Files\\Debugging Tools for Windows (x64)\\cdb.exe",
"C:\\Program Files\\Debugging Tools for Windows (x86)\\cdb.exe"
foreach($path in $CdbPaths)
{
if(Test-Path $path)
{
## If we found it, remember it and break.
$CdbPath = $path
break
}
}
if(-not $CdbPath)
{
throw "Could not find cdb.exe from the Debugging Tools for Windows package"
}
}
if(-not (Get-Process -Id $ProcessId))
{
throw "Could not find process ID $ProcessId"
}
## Prepare the command we will send to cdb.exe. We use one command for
## managed applications, and another for native.
$debuggingCommand = ""
$managedDebuggingCommand = ".loadby sos mscorwks; .loadby sos clr; ~*e !CLRStack"
$nativeDebuggingCommand = "~*k"
if($UseNativeDebugging)
{
$debuggingCommand = $nativeDebuggingCommand
}
else
{
$debuggingCommand = $managedDebuggingCommand
}
## Create the info to start cdb.exe, redirecting its standard input and output
## so that we can automate it.
$startInfo = [System.Diagnostics.ProcessStartInfo] @{
FileName = $CdbPath;
Arguments = "-p $processId -noinh -c `"$debuggingCommand`"";
UseShellExecute = $false;
RedirectStandardInput = $true
RedirectStandardOutput = $true
}
$frames = @()
## Start sampling the process by launching cdb.exe, taking the stack trace,
## and detaching.
1..$SampleCount | % {
$process = [System.Diagnostics.Process]::Start($startInfo)
$process.StandardInput.WriteLine("qd")
$process.StandardInput.Close()
$r = $process.StandardOutput.ReadToEnd() -split "`n"
## Go through the output data, extracting the actual stack trace text
## data.
$frame = @()
$capture = $false
switch -regex ($r)
{
'Child SP|Child-SP' { $capture = $true; continue; }
'OS Thread Id|^\\s*$' { $capture = $false; if($frame) { $frames += ,$frame; $frame = @() } }
{ $capture -and ($_ -match '\\)$|!') } { $frame += $_ -replace ".*? .*? ([^+]*).*",'$1' }
}
if($frame) { $frames += ,$frame }
## Sleep a little bit (with randomness) so that we get accurate
## samples
Start-Sleep -m (100 + (Get-Random 100))
}
## Output the frames we retrieved.
,$frames
|
PowerShellCorpus/PoshCode/Set-dvSwitch.ps1
|
Set-dvSwitch.ps1
|
Function Set-dvSwitch {
param($vmName,$dvPG) # the two parameters.
$nic = "Network adapter 1" # change this line if you want to change network adapter 2
# Find the NIC
$vm = Get-VM $vmName | Get-View
foreach($tempdev in $vm.Config.Hardware.Device){
if($tempdev.DeviceInfo.Label -eq $nic){
$tgtdev = $tempdev
}
}
# Find the dvSwitch & dvPortGroup
$esx = Get-View -Id $vm.Runtime.Host
foreach($netMoRef in $esx.Network){
if($netMoRef.Type -eq "DistributedVirtualPortGroup"){
$net = Get-View -Id $netMoRef
if($net.Name -eq $dvPg){
$dvPGKey = $net.MoRef.Value
$dvSwitchUuid = (Get-View -Id $net.Config.DistributedVirtualSwitch).Summary.Uuid
}
}
}
# Prepare Spec
$spec = New-Object VMware.Vim.VirtualMachineConfigSpec
$devChange = New-Object VMware.Vim.VirtualDeviceConfigSpec
$devChange.operation = "edit"
$dev = New-Object ("VMware.Vim." + $tgtdev.GetType().Name)
$dev.deviceInfo = New-Object VMware.Vim.Description
$dev.deviceInfo.label = $tgtdev.DeviceInfo.Label
$dev.deviceInfo.summary = $tgtdev.DeviceInfo.Summary
$dev.Backing = New-Object VMware.Vim.VirtualEthernetCardDistributedVirtualPortBackingInfo
$dev.Backing.Port = New-Object VMware.Vim.DistributedVirtualSwitchPortConnection
$dev.Backing.Port.PortgroupKey = $dvPGKey
$dev.Backing.Port.SwitchUuid = $dvSwitchUuid
$dev.Key = $tgtdev.Key
$devChange.Device = $dev
$spec.deviceChange = $devChange
$taskMoRef = $vm.ReconfigVM_Task($spec)
}
|
PowerShellCorpus/PoshCode/Create-Printers.ps1
|
Create-Printers.ps1
|
###########################################################################"
#
# NAME: Create-Printers.ps1
#
# AUTHOR: Jan Egil Ring
# EMAIL: jan.egil.ring@powershell.no
# BLOG: http://blog.powershell.no
#
# COMMENT: Simple script to bulk-create printers on a print-server. Printers are imported from a csv-file.
# Running the script from Windows Server 2003 returns an access denied error, possibly due to the impersonation-model in Windows Server 2003.
# Created and tested from Windows Server 2008 against a remote Windows Server 2003 print-server.
# Should work from Windows Vista, Windows 7, Windows Server 2008 and Windows Server 2008 R2 against remote print-servers (2000/2003/2008/2008 R2)
#
# You have a royalty-free right to use, modify, reproduce, and
# distribute this script file in any way you find useful, provided that
# you agree that the creator, owner above has no warranty, obligations,
# or liability for such use.
#
# VERSION HISTORY:
# 1.0 07.11.2009 - Initial release
#
###########################################################################"
function CreatePrinter {
$server = $args[0]
$print = ([WMICLASS]"\\\\$server\\ROOT\\cimv2:Win32_Printer").createInstance()
$print.drivername = $args[1]
$print.PortName = $args[2]
$print.Shared = $true
$print.Sharename = $args[3]
$print.Location = $args[4]
$print.Comment = $args[5]
$print.DeviceID = $args[6]
$print.Put()
}
function CreatePrinterPort {
$server = $args[0]
$port = ([WMICLASS]"\\\\$server\\ROOT\\cimv2:Win32_TCPIPPrinterPort").createInstance()
$port.Name= $args[1]
$port.SNMPEnabled=$false
$port.Protocol=1
$port.HostAddress= $args[2]
$port.Put()
}
$printers = Import-Csv c:\\printers.csv
foreach ($printer in $printers) {
CreatePrinterPort $printer.Printserver $printer.Portname $printer.IPAddress
CreatePrinter $printer.Printserver $printer.Driver $printer.Portname $printer.Sharename $printer.Location $printer.Comment $printer.Printername
}
|
PowerShellCorpus/PoshCode/Get-HtmlHelp_1.ps1
|
Get-HtmlHelp_1.ps1
|
Hello
I contact you a few weeks ago to inquire as to the possibility of sponsoring guest posts on your website: http://huddledmasses.org. I wanted to follow up again to see if there was any interest.
We will research and write quality unique content and pay to have it published to your readers. No spam, and no spun content.
Send me an emal when you get a chance,
-Brandon Murphy
brandon@submitdigital.com
www.SubmitDigital.com
|
PowerShellCorpus/PoshCode/CertMgmt pack_1.ps1
|
CertMgmt pack_1.ps1
|
#####################################################################
# CertMgmtPack.ps1
# Version 0.51
#
# Digital certificate management pack
#
# Vadims Podans (c) 2009
# http://www.sysadmins.lv/
#####################################################################
#requires -Version 2.0
function Import-Certificate {
<#
.Synopsis
Imports digital certificates to Certificate Store from files
.Description
Improrts digital certificates to Certificate Store from various types of
certificates files, such .CER, .DER, .PFX (password required), .P7B.
.Parameter Path
Specifies the path to certificate file
.Parameter Password
Specifies password to PFX/PKCS#12 file only. For other certificate types
is not required.
Note: this parameter must be passed as SecureString.
.Parameter Storage
Specifies place in Sertificate Store for certificate. For user certificates
(default) you MAY specify 'User' and importing certificate will be stored
in CurrentUser Certificate Store. For computer certificates you MUST specify
'Computer' and importing certificates will be stored in LocalMachine Certificate
Store.
.Parameter Container
Specifies container within particular Certificate Store location. Container may
be one of AuthRoot/CA/Disallowed/My/REQUEST/Root/SmartCardRoot/Trust/TrustedPeople/
TrustedPublisher/UserDS. These containers represent MMC console containers
as follows:
AddressBook - AddressBook
AuthRoot - Third-Party Root CAs
CA - Intermediate CAs
Disallowed - Untrused Certificates
My - Personal
REQUEST - Certificate Enrollment Requests
Root - Trusted Root CAs
SmartCardRoot - Smart Card Trusted Roots
Trust - Enterprise Trust
TrustedPeople - Trusted People
TrustedPublishers - Trusted Publishers
UserDS - Active Directory User Object
.Parameter Exportable
Marks imported certificates private key as exportable. May be used only for PFX
files only. If this switch is not presented for PFX files, after importing you
will not be able to export this certificate with private key again.
.Parameter StrongProtection
Enables private key strong protection that requires user password each time
when certificate private key is used. Not available for computer certificates,
because computers certificates are used under LocalSystem account and here is
no UI for user to type password.
.Outputs
This command provide a simple message if the export is successful.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
[string]$Path,
[Parameter(Position = 1)]
[System.Security.SecureString]$Password,
[Parameter(Position = 2)]
[string][ValidateSet("CurrentUser", "LocalMachine")]$Storage = "CurrentUser",
[string][ValidateSet("AddressBook", "AuthRoot", "CA", "Disallowed", "My", "REQUEST",
"Root", "SmartCardRoot", "Trust", "TrustedPeople", "TrustedPublisher", "UserDS")]$Container = "My",
[switch]$Exportable,
[switch]$StrongProtection
)
if (!(Resolve-Path $Path)) {throw "Looks like your specified certificate file doesn't exist"}
$file = gi $Path -Force -ErrorAction Stop
$certs = New-Object system.security.cryptography.x509certificates.x509certificate2
switch ($Storage) {
"CurrentUser" {$flags = "UserKeySet"}
"LocalMachine" {$flags = "MachineKeySet"}
}
switch -regex ($file.Extension) {
".CER|.DER" {$certs.Import($file.FullName, $null, $flags)}
".PFX" {
if (!$password) {throw "For PFX files password is required."}
if ($StrongProtection -and $Storage -eq "Computer") {
throw "You cannot use Private Key Strong Protection for computer certificates!"
}
if ($Exportable) {$flags = $flags + ", Exportable"}
if ($StrongProtection) {$flags = $flags + ", UserProtected"}
$certs.Import($file.FullName, $password, $flags)
}
".P7B|.SST" {
$certs = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
$certs.Import([System.IO.File]::ReadAllBytes($file.FullName))
}
default {throw "Looks like your specified file is not a certificate file"}
}
$store = New-Object system.security.cryptography.X509Certificates.X509Store $Container, $Storage
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$certs | %{$store.Add($_)}
if ($?) {Write-Host -ForegroundColor Green Certificate file`: $file.fullname was successfully added to $Container container}
$store.Close()
}
function Export-Certificate {
<#
.Synopsis
Exports digital certificates to file Certificate Store.
.Description
Exports digital certificates from Certificate Store to various types of certificate
file such .CER, .DER, .PFX (password required), .P7B or .SST (serializd store).
.Parameter Path
Specifies the path to certificate storing folder
.Parameter Type
Specifies type of imported certificate. May be one of CERT/PFX/PKCS#12/P7B/PKCS#7.
.Parameter Password
Specifies a password for PFX files and used only if type is specified as PFX/PKCS#12.
Note: password must be supplied as SecureString.
.Parameter Storage
Specifies place in Sertificate Store for certificate. For user certificates
(default) you MAY specify 'User' to export certificates from CurrentUser Certificate Store.
For computer certificates you MUST specify 'Computer' to export certificates from
LocalMachine Certificate Store.
.Parameter Container
Specifies container within particular Certificate Store location. Container may
be one of AuthRoot/CA/Disallowed/My/REQUEST/Root/SmartCardRoot/Trust/TrustedPeople/
TrustedPublisher/UserDS. These containers represent MMC console containers
as follows:
AddressBook - AddressBook
AuthRoot - Third-Party Root CAs
CA - Intermediate CAs
Disallowed - Untrused Certificates
My - Personal
REQUEST - Certificate Enrollment Requests
Root - Trusted Root CAs
SmartCardRoot - Smart Card Trusted Roots
Trust - Enterprise Trust
TrustedPeople - Trusted People
TrustedPublishers - Trusted Publishers
UserDS - Active Directory User Object
.EXAMPLE
.Outputs
This command doesn't provide any output, except errors.
.Link
#>
[CmdletBinding()]
param (
[Parameter(Position = 0)]
[string]$Path,
[Parameter(Mandatory = $true, Position = 1)]
[string][ValidatePattern("Cert|Pfx|pkcs12|pkcs7|SST")]$Type,
[Parameter(Position = 2)]
[System.Security.SecureString]$Password,
[Parameter(Position = 3)]
[string][ValidateSet("CurrentUser", "LocalMachine")]$Storage = "CurrentUser",
[Parameter(ValueFromPipeline = $true, Position = 4)]
[string][ValidateSet("AddressBook", "AuthRoot", "CA", "Disallowed", "My", "REQUEST",
"Root", "SmartCardRoot", "Trust", "TrustedPeople", "TrustedPublisher", "UserDS")]$Container = "My",
[string]$Thumbprint,
[string]$Subject,
[string]$Issuer,
[string]$SerialNumber,
[string]$NotAfter,
[string]$NotBefore,
[switch]$DeleteKey,
[switch]$Recurse
)
if (!(Test-Path $Path)) {
New-Item -ItemType directory -Path $Path -Force -ErrorAction Stop
}
if ((Resolve-Path $Path).Provider.Name -ne "FileSystem") {
throw "Spicifed path is not recognized as filesystem path. Try again"
}
if ($Recurse) {
function dirx ($Storage) {
dir cert:\\$Storage -Recurse | ?{!$_.PsIsContainer}
}
} else {
function dirx ($Storage, $Container) {
dir cert:\\$Storage\\$Container
}
}
# îďđĺäĺëĺíčĺ, ÷ňî äë˙ PFX ńĺđňčôčęŕňîâ óęŕçŕí ďŕđîëü
if ($Type -eq 'pkcs12') {$Type = "PFX"}
if ($Type -eq 'SST') {$Type = "SerializedStore"}
if ($Type -eq "PFX" -and !$Password) {throw "For PFX files password is required."}
# ęîíâĺđňŕöč˙ ďđĺäâŕđčňĺëüíűő çíŕ÷ĺíčé ŕđăóěĺíňîâ â ęîíĺ÷íűĺ çíŕ÷ĺíč˙ č ňčďű
# .NET ęëŕńńîâ
$Type = [System.Security.Cryptography.X509Certificates.X509ContentType]::$Type
if ($NotAfter) {$NotAfter = [datetime]::ParseExact($NotAfter, "dd.MM.yyy", $null)}
if ($NotBefore) {$NotBefore = [datetime]::ParseExact($NotBefore, "dd.MM.yyy", $null)}
# ďđîâĺđęŕ îńíîâíűő ęđčňĺđčĺâ)
if ($Thumbprint) {$certs = @(dirx | ?{$_.Thumbprint -like "*$Thumbprint*"})}
elseif ($Subject) {$certs = @(dirx | ?{$_.Subject -like "*$Subject*"})}
elseif ($Issuer) {$certs = @(dirx | ?{$_.Issuer -like "*$Issuer*"})}
elseif ($SerialNumber) {$certs = @(dirx | ?{$_.SerialNumber -like "*$SerialNumber*"})}
elseif ($NotAfter -and !$NotBefore) {$certs = @(dirx | ?{$_.NotAfter -lt $NotAfter})}
elseif (!$NotAfter -and $NotBefore) {$certs = @(dirx | ?{$_.NotBefore -gt $NotBefore})}
elseif ($NotAfter -and $NotBefore) {$certs = @(dirx | ?{$_.NotAfter -lt $NotAfter `
-and $_.NotBefore -gt $NotBefore})}
else {$certs = @(dirx)}
if ($certs.Count -eq 0) {Write-Warning "Sorry, we unable to find certificates that correspond your filter :("; return}
switch -regex ($Type) {
"Cert" {
foreach ($cert in $certs) {
[void]($cert.Subject -match 'CN=([^,]+)')
$CN = $matches[1] -replace '[\\\\/:\\*?`"<>|]', ''
$bytes = $cert.Export($type)
$base64Data = [System.Convert]::ToBase64String($bytes)
Set-Content -LiteralPath $(Join-Path $Path ($CN + "_" + $cert.Thumbprint + ".cer")) -Value $base64Data
}
}
"PFX" {
foreach ($cert in $certs) {
[void]($cert.Subject -match 'CN=([^,]+)')
$CN = $matches[1] -replace '[\\\\/:\\*?`"<>|]', ''
$bytes = $cert.Export($Type, $Password)
[System.IO.File]::WriteAllBytes($(Join-Path $Path ($CN + "_" + $cert.Thumbprint + ".pfx")), $bytes)
if ($DeleteKey) {
$tempcert = $cert.Export("Cert")
$store = New-Object system.security.cryptography.X509Certificates.X509Store $container, $Storage
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$store.Remove($cert)
$store.Add($tempcert)
$store.Close()
}
}
}
"Pkcs7|SerializedStore" {
# ńîçäŕ¸ě îáúĺęň ěŕńńčâŕ x509Certificate2 îáúĺęňîâ
$certcol = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
# äîáŕâë˙ĺě âńĺ ńĺđňčôčęŕňű čç $certs â ýňîň ěŕńńčâ
$certs | %{[void]$certcol.Add($_)}
# ýęńďîđňčđóĺě ýňîň ěŕńńčâ â áŕéňîâűé ěŕńńčâ
$bytes = $certcol.Export($Type)
# çŕďčńűâŕĺě ěŕńńčâ áŕéňîâ â p7b ôŕéë
if ($Type -eq "Pkcs7") {$ext = ".p7b"} else {$ext = ".sst"}
[System.IO.File]::WriteAllBytes($("ExportedCertificates" + $ext, $bytes))
}
}
}
|
PowerShellCorpus/PoshCode/Rename NICs.ps1
|
Rename NICs.ps1
|
$Shell = New-Object -com shell.application
$NetCons = $Shell.Namespace(0x31)
$NetCons.Items() |
where {$_.Name -like 'Local Area Connection*'} |
foreach{$AdapName=$_.Name; get-WmiObject -class Win32_NetworkAdapter |
where-Object {$_.NetConnectionID -eq $AdapName} |
foreach {$MAC=$_.MacAddress}
$_.Name=$MAC.replace(':','.')
}
|
PowerShellCorpus/PoshCode/Compare Table & DataRow_2.ps1
|
Compare Table & DataRow_2.ps1
|
function Compare-DataRow
{
param( $a, $b)
# @bernd_k http://pauerschell.blogspot.com/
$diff = ''
$a_columncount = $a.Table.columns.count
$b_columncount = $b.Table.columns.count
if ( $a_columncount -ne $b_columncount)
{
Write-host "Tables have different number of columns"
}
foreach ( $i in 0..($a_columncount - 1))
{
if ($a.item($i) -ne $b.item($i))
{
$diff += ' ' + $a.item($i) + ' <> ' + $b.item($i) +';'
}
}
$diff
}
function Compare-Table
{
param( $a, $b)
# @bernd_k http://pauerschell.blogspot.com/
$diff = ''
$a_rowcount = $a.Rows.count
$b_rowcount = $b.Rows.count
if ( $a_rowcount -ne $b_rowcount)
{
Write-host "Tables have different number of columns"
}
foreach ( $i in 0..($a_rowcount - 1))
{
Compare-DataRow $a.rows[$i] $b.rows[$i]
}
$diff
}
Compare-DataRow $a.tables[0].rows[0] $b.tables[0].rows[0]
Compare-Table ($a.tables[0]) ($b.tables[0])
|
PowerShellCorpus/PoshCode/XC_SMTPFunctions.ps1
|
XC_SMTPFunctions.ps1
|
param(
[Parameter(Position=0,ValueFromPipeline=$True)]
[ValidateNotNullorEmpty()][string[]]$Mailboxes = @(),
[string] $Regex = "domain\\.local$|^CCMAIL|^MS:COMPREGION",
$SMTPdomains = @("domain.com","sub.domain.com"),
$Delimiter = "|",
$OutputLog = "C:\\Projects\\XC\\smtpadresses.csv",
[switch] $Output,
[switch]$Remove,
[switch]$Update
)
Function NewSMTPAddress{
param(
$Mailbox,
$Prefix,
$Domain
)
$Address = "$Prefix@$Domain"
$Mailbox | Set-Mailbox -EmailAddresses @{add = $Address}
OutputMB -Mailbox $Mailbox -Address $Address -Match $False -Action "Added"
}
Function RemoveSMTPAddress{
param(
$Mailbox,
$Address,
$Match
)
$Mailbox | Set-Mailbox -EmailAddresses @{remove = $Address}
OutputMB -Mailbox $Mailbox -Address $Address -Match $Match -Action "Removed"
}
Function OutputMB{
param(
$Mailbox,
$Address,
$Match,
$Action
)
$global:objOut += New-Object -Typename PSObject -Property @{
Mailbox = $Mailbox
Address = $Address
Match = $Match
Action = $Action
}
}
$global:objOut = @()
ForEach ($Mailbox in $Mailboxes){
try{
$sMailbox = get-mailbox -identity $Mailbox -EA Stop
foreach ($Address in $sMailbox.EmailAddresses){
if([regex]::IsMatch($Address,$Regex)){
if ($Remove){RemoveSMTPAddress -Mailbox $sMailbox -Address $Address -Match $True}
else{OutputMB -Mailbox $sMailbox -Address $Address -Match $True -Action "Matched"}
}
else{OutputMB -Mailbox $sMailbox -Address $Address -Match $False -Action "None"}
}
if ($Update){
foreach ($sDomain in $SMTPdomains){
NewSMTPAddress -Mailbox $sMailbox -Prefix $sMailbox.SamAccountName -Domain $sDomain
}
}
}
catch{write-warning "no such mailbox: $Mailbox";continue}
}
if($Output){
$objOut | Select Mailbox, Address, Match, Action | ConvertTo-Csv -Delimiter $Delimiter -NoTypeInformation | out-file $OutputLog -append
}
else {$objOut | Select Mailbox, Address, Match, Action}
|
PowerShellCorpus/PoshCode/SqlProxy_7.psm1.ps1
|
SqlProxy_7.psm1.ps1
|
# ---------------------------------------------------------------------------
### <Author>
### Chad Miller
### </Author>
### <Description>
### Based on functions in SQLPSX. SqlProxy.psm1 module is used for administering
### SQL Server logins, users, and roles. Designed to be used with PS Remoting.
### All actions audited to a custom Eventlog.
### See Write-SqlProxyLog for log setup details
### </Description>
# ---------------------------------------------------------------------------
try {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop}
catch {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo"}
try {add-type -AssemblyName "Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop; $smoVersion = 10}
catch {add-type -AssemblyName "Microsoft.SqlServer.Smo"; $smoVersion = 9}
try {add-type -AssemblyName "Microsoft.SqlServer.SqlEnum, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop; $smoVersion = 10}
catch {add-type -AssemblyName "Microsoft.SqlServer.SqlEnum"; $smoVersion = 9}
try
{
try {add-type -AssemblyName "Microsoft.SqlServer.SMOExtended, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop}
catch {add-type -AssemblyName "Microsoft.SqlServer.SMOExtended" -EA Stop}
}
catch {Write-Warning "SMOExtended not available"}
$EventID = @{
"Add-SqlDatabaseRoleMember"=0
"Add-SqlLogin"=1
"Add-SqlServerRoleMember"=2
"Add-SqlUser"=3
"Remove-SqlDatabaseRoleMember"=4
"Remove-SqlLogin"=5
"Remove-SqlServerRoleMember"=6
"Remove-SqlUser"=7
"Rename-SqlLogin"=8
"Set-SqlLogin"=9
"Set-SqlLoginDefaultDatabase"=10
}
#######################
<#
.SYNOPSIS
Gets a ServerConnection.
.DESCRIPTION
The Get-SqlConnection function gets a ServerConnection to the specified SQL Server.
.INPUTS
None
You cannot pipe objects to Get-SqlConnection
.OUTPUTS
Microsoft.SqlServer.Management.Common.ServerConnection
Get-SqlConnection returns a Microsoft.SqlServer.Management.Common.ServerConnection object.
.EXAMPLE
Get-SqlConnection "Z002\\sql2K8"
This command gets a ServerConnection to SQL Server Z002\\SQL2K8.
.EXAMPLE
Get-SqlConnection "Z002\\sql2K8" "sa" "Passw0rd"
This command gets a ServerConnection to SQL Server Z002\\SQL2K8 using SQL authentication.
.LINK
Get-SqlConnection
#>
function Get-SqlConnection
{
param(
[Parameter(Position=0, Mandatory=$true)] [string]$sqlserver,
[Parameter(Position=1, Mandatory=$false)] [string]$username,
[Parameter(Position=2, Mandatory=$false)] [string]$password
)
Write-Verbose "Get-SqlConnection $sqlserver"
try {
if($Username -and $Password)
{ $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $sqlserver,$username,$password }
else
{ $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $sqlserver }
$con.Connect()
Write-Output $con
}
catch { $message = $_.Exception.GetBaseException().Message
write-error $message
}
} #Get-ServerConnection
#######################
<#
.SYNOPSIS
Gets an SMO Server object.
.DESCRIPTION
The Get-SqlServer function gets a SMO Server object for the specified SQL Server.
.INPUTS
None
You cannot pipe objects to Get-SqlServer
.OUTPUTS
Microsoft.SqlServer.Management.Smo.Server
Get-SqlServer returns a Microsoft.SqlServer.Management.Smo.Server object.
.EXAMPLE
Get-SqlServer "Z002\\sql2K8"
This command gets an SMO Server object for SQL Server Z002\\SQL2K8.
.EXAMPLE
Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd"
This command gets a SMO Server object for SQL Server Z002\\SQL2K8 using SQL authentication.
.LINK
Get-SqlServer
#>
function Get-SqlServer
{
param(
[Parameter(Position=0, Mandatory=$true)] [string]$sqlserver,
[Parameter(Position=1, Mandatory=$false)] [string]$username,
[Parameter(Position=2, Mandatory=$false)] [string]$password,
[Parameter(Position=3, Mandatory=$false)] [string]$StatementTimeout=0
)
#When $sqlserver passed in from the SMO Name property, brackets
#are automatically inserted which then need to be removed
$sqlserver = $sqlserver -replace "\\[|\\]"
Write-Verbose "Get-SqlServer $sqlserver"
$con = Get-SqlConnection $sqlserver $Username $Password
$server = new-object ("Microsoft.SqlServer.Management.Smo.Server") $con
#Some operations might take longer than the default timeout of 600 seconnds (10 minutes). Set new default to unlimited
$server.ConnectionContext.StatementTimeout = $StatementTimeout
$server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.StoredProcedure], "IsSystemObject")
$server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.Table], "IsSystemObject")
$server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.View], "IsSystemObject")
$server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.UserDefinedFunction], "IsSystemObject")
#trap { "Check $SqlServer Name"; continue} $server.ConnectionContext.Connect()
Write-Output $server
} #Get-SqlServer
#######################
<#
.SYNOPSIS
Gets an SMO Database object.
.DESCRIPTION
The Get-SqlDatabase function gets an SMO Database object for the specified SQL Database or collection of Database objects.
.INPUTS
None
You cannot pipe objects to Get-SqlDatabase
.OUTPUTS
Microsoft.SqlServer.Management.Smo.Database
Get-SqlDatabase returns a Microsoft.SqlServer.Management.Smo.Database object.
.EXAMPLE
Get-SqlDatabase "Z002\\sql2K8"
This command gets a collection of SMO Database objects for SQL Server Z002\\SQL2K8.
.EXAMPLE
Get-SqlDatabase $(Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd") "pubs"
This command gets a SMO Database object for SQL database pubs on the SQL Server Z002\\SQL2K8 using SQL authentication.
.LINK
Get-SqlDatabase
#>
function Get-SqlDatabase
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$false)] [string]$dbname
)
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Get-SqlDatabase:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Get-SqlDatabase $($server.Name) $dbname"
if ($dbname)
{ if ($server.Databases.Contains("$dbname") -and $server.Databases[$dbname].IsAccessible)
{$server.Databases[$dbname]}
else
{throw "Database $dname does not exist or is not accessible."}
}
else
{ $server.Databases | where {$_.IsAccessible -eq $true} }
} # Get-SqlDatabase
#######################
<#
.SYNOPSIS
Executes a query and returns an array of System.Data.DataRow.
.DESCRIPTION
The Get-SqlData function executes a query and returns an array of System.Data.DataRow.
.INPUTS
None
You cannot pipe objects to Get-SqlData
.OUTPUTS
System.Data.DataRow
Get-SqlData returns an array of System.Data.DataRow.
.EXAMPLE
Get-SqlData "Z002\\sql2K8" "pubs" "select * from authors"
This command executes the specified SQL query using Windows authentication.
.EXAMPLE
$server = Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd"
Get-SqlData $server "pubs" "select * from authors"
This command executes the specified SQL query using SQL authentication.
.LINK
Get-SqlData
#>
function Get-SqlData
{
param(
[Parameter(Position=0, Mandatory=$false)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] $dbname,
[Parameter(Position=2, Mandatory=$true)] [string]$qry
)
switch ($dbname.GetType().Name)
{
'String' { $database = Get-SqlDatabase $sqlserver $dbname }
'Database' { $database = $dbname }
default { throw "Get-SqlData:Param '`$dbname' must be a String or Database object." }
}
#Write-Verbose "Get-SqlData $($database.Parent.Name) $($database.Name) $qry"
Write-Verbose "Get-SqlData $($database.Parent.Name) $($database.Name)"
$ds = $database.ExecuteWithResults("$qry")
$ds.Tables | foreach { $_.Rows}
}# Get-SqlData
#######################
<#
.SYNOPSIS
Executes a query that does not return a result set.
.DESCRIPTION
The Set-SqlData function executes a query that does not return a result set.
.INPUTS
None
You cannot pipe objects to Set-SqlData
.OUTPUTS
None
Set-SqlData does not produce any output.
.EXAMPLE
Set-SqlData "Z002\\sql2K8" "pubs" "Update authors set au_lname = 'Brown' WHERE au_lname = 'White'"
This command executes the specified SQL query using Windows authentication.
.EXAMPLE
$server = Set-SqlServer "Z002\\sql2K8" "sa" "Passw0rd"
Set-SqlData $server "pubs" "Update authors set au_lname = 'Brown' WHERE au_lname = 'White'"
This command executes the specified SQL query using SQL authentication.
.LINK
Set-SqlData
#>
function Set-SqlData
{
param(
[Parameter(Position=0, Mandatory=$false)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$dbname,
[Parameter(Position=2, Mandatory=$true)] [string]$qry
)
switch ($dbname.GetType().Name)
{
'String' { $database = Get-SqlDatabase $sqlserver $dbname }
'Database' { $database = $dbname }
default { throw "Set-SqlData:Param '`$dbname' must be a String or Database object." }
}
#Write-Verbose "Set-SqlData $($database.Parent.Name) $($database.Name) $qry"
Write-Verbose "Set-SqlData $($database.Parent.Name) $($database.Name)"
$database.ExecuteNonQuery("$qry")
}# Set-SqlData
#######################
<#
.SYNOPSIS
Adds a login to a SQL Server.
.DESCRIPTION
The Add-SqlLogin function adds a new login to the specified SQL server.
.INPUTS
None
You cannot pipe objects to Add-SqlLogin
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Add-SqlLogin "Z002\\sql2k8" "TestPSUnit" "SQLPSXTesting" 'SqlLogin'
This command adds the TestPSUnit login to the Z002\\sql2k8 server.
.EXAMPLE
$server = Get-SqlServer "Z002\\sql2k8"
Add-SqlLogin $server "TestPSUnit" "SQLPSXTesting" 'SqlLogin'
This command adds the TestPSUnit login to the Z002\\sql2k8 server.
.LINK
Add-SqlLogin
#>
function Add-SqlLogin
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$name,
[Parameter(Position=2, Mandatory=$false)] [System.Security.SecureString]$password,
[Parameter(Position=3, Mandatory=$false)] [Microsoft.SqlServer.Management.Smo.LoginType]$logintype='WindowsUser',
[Parameter(Position=4, Mandatory=$false)] [string]$DefaultDatabase='master',
[Parameter(Position=5, Mandatory=$false)] [switch]$PasswordExpirationEnabled,
[Parameter(Position=6, Mandatory=$false)] [switch]$PasswordPolicyEnforced,
[Parameter(Position=7, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=8, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Add-SqlLogin:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Add-SqlLogin $($server.Name) $name"
try {
$login = new-object ('Microsoft.SqlServer.Management.Smo.Login') $server, $name
$login.DefaultDatabase = $defaultDatabase
$login.LoginType = $logintype
if ($logintype -eq 'SqlLogin')
{
if ($server.Information.Version.Major -ne '8')
{
$login.PasswordExpirationEnabled = $($PasswordExpirationEnabled.IsPresent)
$login.PasswordPolicyEnforced = $($PasswordPolicyEnforced.IsPresent)
}
$login.Create($password)
}
else {
$login.Create()
}
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
} #Add-SqlLogin
#######################
<#
.SYNOPSIS
Removes a login from a SQL Server.
.DESCRIPTION
The Remove-SqlLogin function removes a login from the specified SQL server.
.INPUTS
None
You cannot pipe objects to Remove-SqlLogin
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Remove-SqlLogin "Z002\\sql2k8" "TestPSUnit"
This command removes the TestPSUnit login from the Z002\\sql2k8 server.
.EXAMPLE
$server = Get-SqlServer "Z002\\sql2k8"
Remove-SqlLogin $server "TestPSUnit"
This command removes the TestPSUnit login from the Z002\\sql2k8 server.
.LINK
Remove-SqlLogin
#>
function Remove-SqlLogin
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$name,
[Parameter(Position=2, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=3, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Remove-SqlLogin:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Remove-SqlLogin $($server.Name) $name"
try {
$login = $server.Logins["$name"]
if ($login) {
$login.Drop()
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "Login $name does not exist on server $($server.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
} #Remove-SqlLogin
#######################
<#
.SYNOPSIS
Removes a login from a SQL Server.
.DESCRIPTION
The Set-SqlLogin function changes a SQL Login Password.
.INPUTS
None
You cannot pipe objects to Set-SqlLogin
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
$pwd_secure_string = read-host "Enter a Password:" -assecurestring
Set-SqlLogin "Z002\\sql2k8" "TestPSUnit" $pwd_secure_string
This command sets the password for TestPSUnit login.
.LINK
Set-SqlLogin
#>
function Set-SqlLogin
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$name,
[Parameter(Position=2, Mandatory=$true)] [string]$password,
[Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=4, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Set-SqlLogin:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Set-SqlLogin $($server.Name) $name"
try {
$login = $server.Logins["$name"]
if ($login) {
if ($server.Information.Version.Major -eq '8') {
$login.ChangePassword($password)
}
else {
$login.ChangePassword($password,$true,$false)
}
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | ?{$_.Key -ne 'password'} | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "Login $name does not exist on server $($server.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | ?{$_.Key -ne 'password'} | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
} #Set-SqlLogin
#######################
<#
.SYNOPSIS
Removes a login from a SQL Server.
.DESCRIPTION
The Set-SqlLoginDefaultDatabase function changes a SQL Login default database.
.INPUTS
None
You cannot pipe objects to Set-SqlLoginDefaultDatabase
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Set-SqlLoginDefaultDatabase "Z002\\sql2k8" "TestPSUnit" 'master'
This command sets the default database for TestPSUnit login.
.LINK
Set-SqlLoginDefaultDatabase
#>
function Set-SqlLoginDefaultDatabase
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$name,
[Parameter(Position=2, Mandatory=$true)] [string]$DefaultDatabase,
[Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=4, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Set-SqlLoginDefaultDatabase:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Set-SqlLoginDefaultDatabase $($server.Name) $name"
try {
$login = $server.Logins["$name"]
if ($login) {
$login.DefaultDatabase = $DefaultDatabase
$login.Alter()
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "Login $name does not exist on server $($server.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
} #Set-SqlLoginDefaultDatabase
#######################
<#
.SYNOPSIS
Removes a login from a SQL Server.
.DESCRIPTION
The Rename-SqlLogin function renames a SQL Login.
.INPUTS
None
You cannot pipe objects to Rename-SqlLogin
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Rename-SqlLogin "Z002\\sql2k8" "TestPSUnit" "CheckPSUnit"
This command renames the login TestPSUnit.
.LINK
Rename-SqlLogin
#>
function Rename-SqlLogin
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$name,
[Parameter(Position=2, Mandatory=$true)] [string]$newname,
[Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=4, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Rename-SqlLogin:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Rename-SqlLogin $($server.Name) $name $newname"
try {
$login = $server.Logins["$name"]
if ($login) {
$login.Rename("$newName")
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "Login $name does not exist on server $($server.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
} #Rename-SqlLogin
#######################
<#
.SYNOPSIS
Adds a new user to a database.
.DESCRIPTION
The Add-SqlUser function adds a new user to the specified database.
.INPUTS
None
You cannot pipe objects to Add-SqlUser
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Add-SqlUser "Z002\\sql2k8" "pubs" "TestPSUnit"
This command adds the TestPSUnit login to the pubs database.
.EXAMPLE
$database = Get-SqlDatabase "Z002\\sql2k8" "pubs"
Add-SqlUser -dbname $database "TestPSUnit"
This command adds the TestPSUnit login to the pubs database.
.LINK
Add-SqlUser
#>
function Add-SqlUser
{
param(
[Parameter(Position=0, Mandatory=$false)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] $dbname,
[Parameter(Position=2, Mandatory=$true)] [string]$name,
[Parameter(Position=3, Mandatory=$false)] [string]$login=$name,
[Parameter(Position=4, Mandatory=$false)] [string]$defaultSchema='dbo',
[Parameter(Position=5, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=6, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($dbname.GetType().Name)
{
'String' { $database = Get-SqlDatabase $sqlserver $dbname }
'Database' { $database = $dbname }
default { throw "Add-SqlUser:Param '`$dbname' must be a String or Database object." }
}
Write-Verbose "Add-SqlUser $($database.Name) $name"
try {
$user = new-object ('Microsoft.SqlServer.Management.Smo.User') $database, $name
$user.Login = $login
$loginObject = $sqlserver.Logins["$login"]
if ($database.parent.Information.Version.Major -ne '8' -and $loginObject.LoginType -ne "WindowsGroup" )
{ $user.DefaultSchema = $defaultschema }
$user.Create()
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
} #Add-SqlUser
#######################
<#
.SYNOPSIS
Removes a user from a database.
.DESCRIPTION
The Remove-SqlUser function removes a user from the specified database.
.INPUTS
None
You cannot pipe objects to Remove-SqlUser
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Remove-SqlUser "Z002\\sql2k8" "pubs" "TestPSUnit"
This command Removes the TestPSUnit user from the pubs database.
.EXAMPLE
$database = Get-SqlDatabase "Z002\\sql2k8" "pubs"
Remove-SqlUser -dbname $database "TestPSUnit"
This command Removes the TestPSUnit user from the pubs database.
.LINK
Remove-SqlUser
#>
function Remove-SqlUser
{
param(
[Parameter(Position=0, Mandatory=$false)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] $dbname,
[Parameter(Position=2, Mandatory=$true)] [string]$name,
[Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=4, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($dbname.GetType().Name)
{
'String' { $database = Get-SqlDatabase $sqlserver $dbname }
'Database' { $database = $dbname }
default { throw "Remove-SqlUser:Param '`$dbname' must be a String or Database object." }
}
Write-Verbose "Remove-SqlUser $($database.Name) $name"
try {
$user = $database.Users[$name]
if ($user) {
$user.Drop()
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "User $name does not exist in database $($database.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
} #Remove-SqlUser
#######################
<#
.SYNOPSIS
Adds a login to a server role.
.DESCRIPTION
The Add-SqlServerRoleMember function adds a login to the specified server role.
.INPUTS
None
You cannot pipe objects to Add-SqlServerRoleMember
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Add-SqlServerRoleMember "Z002\\sql2k8" "TestPSUnit" "bulkadmin"
This command adds the TestPSUnit login to the bulkadmin server role.
.EXAMPLE
$server = Get-SqlServer "Z002\\sql2k8"
Add-SqlServerRoleMember $server "TestPSUnit" "bulkadmin"
This command adds the TestPSUnit login to the bulkadmin server role.
.LINK
Add-SqlServerRoleMember
#>
function Add-SqlServerRoleMember
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$loginame,
[Parameter(Position=2, Mandatory=$true)] [string]$rolename,
[Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=4, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Add-SqlServerRoleMember:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Add-SqlServerRoleMember $($server.Name) $name"
if($server.Logins["$loginame"])
{
try {
$svrole = $server.Roles["$rolename"]
if ($svrole) {
$svrole.AddMember($loginame)
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "ServerRole $rolename does not exist on server $($server.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
}
else
{ throw "Login $loginame does not exist on server $($server.Name)." }
} #Add-SqlServerRoleMember
#######################
<#
.SYNOPSIS
Removes a login from a server role.
.DESCRIPTION
The Remove-SqlServerRoleMember function removes a login from the specified server role.
.INPUTS
None
You cannot pipe objects to Remove-SqlServerRoleMember
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Remove-SqlServerRoleMember "Z002\\sql2k8" "TestPSUnit" "bulkadmin"
This command Removes the TestPSUnit login from the bulkadmin server role.
.EXAMPLE
$server = Get-SqlServer "Z002\\sql2k8"
Remove-SqlServerRoleMember $server "TestPSUnit" "bulkadmin"
This command Removes the TestPSUnit login from the bulkadmin server role.
.LINK
Remove-SqlServerRoleMember
#>
function Remove-SqlServerRoleMember
{
param(
[Parameter(Position=0, Mandatory=$true)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] [string]$loginame,
[Parameter(Position=2, Mandatory=$true)] [string]$rolename,
[Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=4, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($sqlserver.GetType().Name)
{
'String' { $server = Get-SqlServer $sqlserver }
'Server' { $server = $sqlserver }
default { throw 'Remove-SqlServerRoleMember:Param `$sqlserver must be a String or Server object.' }
}
Write-Verbose "Remove-SqlServerRoleMember $($server.Name) $name"
if($server.Logins["$loginame"])
{
try {
$svrole = $server.Roles["$rolename"]
if ($svrole) {
$svrole.DropMember($loginame)
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "ServerRole $rolename does not exist on server $($server.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
}
else
{ throw "Login $loginame does not exist on server $($server.Name)." }
} #Remove-SqlServerRoleMember
#######################
<#
.SYNOPSIS
Adds a user or role to a database role.
.DESCRIPTION
The Add-SqlDatabaseRoleMember function adds a user or role to the specified database role.
.INPUTS
None
You cannot pipe objects to Add-SqlDatabaseRoleMember
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Add-SqlDatabaseRoleMember "Z002\\sql2k8" "pubs" "TestPSUnit" "TestPSUnitDBRole"
This command adds the TestUnit user to the TestPSUnitDBRole database role.
.EXAMPLE
$database = Get-SqlDatabase "Z002\\sql2k8" "pubs"
Add-SqlDatabaseRoleMember -dbname $database -name "TestPSUnit" -rolename "TestPSUnitDBRole"
This command adds the TestUnit user to the TestPSUnitDBRole database role.
.LINK
Add-SqlDatabaseRoleMember
#>
function Add-SqlDatabaseRoleMember
{
param(
[Parameter(Position=0, Mandatory=$false)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] $dbname,
[Parameter(Position=2, Mandatory=$true)] [string]$name,
[Parameter(Position=3, Mandatory=$true)] [string]$rolename,
[Parameter(Position=4, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=5, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($dbname.GetType().Name)
{
'String' { $database = Get-SqlDatabase $sqlserver $dbname }
'Database' { $database = $dbname }
default { throw "Add-SqlDatabaseRoleMember:Param '`$dbname' must be a String or Database object." }
}
Write-Verbose "Add-SqlDatabaseRoleMember $($database.Name) $name $rolename"
if ($database.Users["$name"])
{
try {
$role = $database.Roles["$rolename"]
if ($role) {
$role.AddMember($name)
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "DatabaseRole $rolename does not exist in database $($database.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
}
else
{ throw "User $name does not exist in database $($database.Name)." }
} #Add-SqlDatabaseRoleMember
#######################
<#
.SYNOPSIS
Removes a user or role from a database role.
.DESCRIPTION
The Remove-SqlDatabaseRoleMember function removes a user or role from the specified database role.
.INPUTS
None
You cannot pipe objects to Remove-SqlDatabaseRoleMember
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
Remove-SqlDatabaseRoleMember "Z002\\sql2k8" "pubs" "TestPSUnit" "TestPSUnitDBRole"
This command removes the TestUnit user to the TestPSUnitDBRole database role.
.EXAMPLE
$database = Get-SqlDatabase "Z002\\sql2k8" "pubs"
Remove-SqlDatabaseRoleMember -dbname $database -name "TestPSUnit" -rolename "TestPSUnitDBRole"
This command removes the TestUnit user to the TestPSUnitDBRole database role.
.LINK
Remove-SqlDatabaseRoleMember
#>
function Remove-SqlDatabaseRoleMember
{
param(
[Parameter(Position=0, Mandatory=$false)] $sqlserver,
[Parameter(Position=1, Mandatory=$true)] $dbname,
[Parameter(Position=2, Mandatory=$true)] [string]$name,
[Parameter(Position=3, Mandatory=$true)] [string]$rolename,
[Parameter(Position=4, Mandatory=$true)] [string]$ChangeOrder,
[Parameter(Position=5, Mandatory=$false)] [string]$Description
)
$ErrorActionPreference = "Stop"
$PSUserName = $PSSenderInfo.UserInfo.Identity.Name
switch ($dbname.GetType().Name)
{
'String' { $database = Get-SqlDatabase $sqlserver $dbname }
'Database' { $database = $dbname }
default { throw "Remove-SqlDatabaseRoleMember:Param '`$dbname' must be a String or Database object." }
}
Write-Verbose "Remove-SqlDatabaseRoleMember $($database.Name) $name $rolename"
if ($database.Users["$name"])
{
try {
$role = $database.Roles["$rolename"]
if ($role) {
$role.DropMember($name)
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage
}
else
{ throw "DatabaseRole $rolename does not exist in database $($database.Name)." }
}
catch {
$message = $_.Exception.GetBaseException().Message
$logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message"
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error'
Write-Error $message
}
}
else
{ throw "User $name does not exist in database $($database.Name)." }
} #Remove-SqlDatabaseRoleMember
#######################
<#
.SYNOPSIS
Writes an entry to SqlProxy Log File.
.DESCRIPTION
The Write-SqlProxyLog function writes an entry to the SqlProxy Log File.
.INPUTS
None
You cannot pipe objects to Write-SqlProxyLog
.OUTPUTS
None
This function does not generate any output.
.EXAMPLE
$message = "PSUserName=$PSUserName`n" + $($psBoundParameters.GetEnumerator() | %{"$($_.Key)=$($_.Value)"})
write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message
This command writes a message to the SQLProxy Log
.NOTES
This must be run as administrator to create the new EventLog and EventLog Source!!!
New-EventLog -LogName SqlProxy -Source SqlProxy
.LINK
Write-SqlProxyLog
#>
function Write-SqlProxyLog
{
param(
[Parameter(Position=0, Mandatory=$true)] $EventID,
[Parameter(Position=1, Mandatory=$true)] $Message,
[Parameter(Position=2, Mandatory=$false)] $EntryType='SuccessAudit'
)
write-eventlog -logname SqlProxy -source SqlProxy -eventID $eventID -message $message -EntryType $EntryType
} #Write-SqlProxyLog
|
PowerShellCorpus/PoshCode/INICIAR-RDP_1.ps1
|
INICIAR-RDP_1.ps1
|
########################################################################################################################
# NAME
# Start-RDP
#
# SYNOPSIS
# Opens a remote desktop connection to another computer.
#
# SYNTAX
# Start-RDP [[-Server] <string>] [[-Width] <int>] [[-Height] <int>]
# Start-RDP -Path <string> [[-Width] <int>] [[-Height] <int>]
#
# DETAILED DESCRIPTION
# The Start-RDP cmdlet opens a new Remote Desktop connection using the Microsoft Terminal Services Client.
# Connection settings can be specified by argument or read from a standard RDP file.
#
# PARAMETERS
# -Server <string>
# Specifies the name of the server to connect to. May also include an IP address, domain, and/or port.
#
# Required? false
# Position? 1
# Default value
# Accept pipeline input? true
# Accept wildcard characters? false
#
# -Width <int>
# Specifies the desired width of the resolution for the connection (for non-full screen connections).
#
# Required? false
# Position? 2
# Default value
# Accept pipeline input? false
# Accept wildcard characters? false
#
# -Height <int>
# Specifies the desired height of the resolution for the connection (for non-full screen connections).
#
# Required? false
# Position? 3
# Default value
# Accept pipeline input? false
# Accept wildcard characters? false
#
# -Path <string>
# Specifies the path to an RDP file to connect with (resolution settings can be overridden using the
# -Width and -Height parameters.
#
# Required? false
# Position? 4
# Default value
# Accept pipeline input? true
# Accept wildcard characters? false
#
# -Console <SwitchParameter>
# Connect to a Windows Server 2003 console session.
#
# Required? false
# Position? named
# Default value false
# Accept pipeline input? false
# Accept wildcard characters? false
#
# -Admin <SwitchParameter>
# Connect to a Windows Server 2008 administrator session.
#
# Required? false
# Position? named
# Default value false
# Accept pipeline input? false
# Accept wildcard characters? false
#
# -Fullscreen <SwitchParameter>
# Open connection in full screen mode.
#
# Required? false
# Position? named
# Default value false
# Accept pipeline input? false
# Accept wildcard characters? false
#
# -Public <SwitchParameter>
# Run Remote Desktop in public mode.
#
# Required? false
# Position? named
# Default value false
# Accept pipeline input? false
# Accept wildcard characters? false
#
# -Span <SwitchParameter>
# Span the Remote Desktop connection across multiple monitors. Each monitor must have the same height
# and be arranged vertically.
#
# Required? false
# Position? named
# Default value false
# Accept pipeline input? false
# Accept wildcard characters? false
#
# INPUT TYPE
# String,System.IO.FileInfo
#
# RETURN TYPE
#
#
# NOTES
#
# -------------------------- EXAMPLE 1 --------------------------
#
# C:\\PS>Start-RDP
#
#
# This command opens the Terminal Services Client connection dialog to specify a connection.
#
#
# -------------------------- EXAMPLE 2 --------------------------
#
# C:\\PS>Start-RDP -Server myserver -Width 1024 -Height 768
#
#
# This command opens a new Remote Desktop connection to the server named "myserver" in a window with 1024x768 resolution.
#
#
# -------------------------- EXAMPLE 3 --------------------------
#
# C:\\PS>Start-RDP -Server myserver -Fullscreen
#
#
# This command opens a new full screen Remote Desktop connection to the server named "myserver".
#
#
# -------------------------- EXAMPLE 4 --------------------------
#
# C:\\PS>Start-RDP -Path C:\\myserver.rdp
#
#
# This command opens a new Remote Desktop connection using the specified RDP file.
#
#
#Function global:Start-RDP {
param(
[string]$Server = "",
[int]$Width = "",
[int]$Height = "",
[string]$Path = "",
[switch]$Console,
[switch]$Admin,
[switch]$Fullscreen,
[switch]$Public,
[switch]$Span
)
begin {
$arguments = ""
$dimensions = ""
$processed = $false
if ($admin) {
$arguments += "/admin "
} elseif ($console) {
$arguments += "/console "
}
if ($fullscreen) {
$arguments += "/f "
}
if ($public) {
$arguments += "/public "
}
if ($span) {
$arguments += "/span "
}
if ($width -and $height) {
$dimensions = "/w:$width /h:$height"
}
}
process {
Function script:executePath([string]$path) {
Invoke-Expression "mstsc.exe '$path' $dimensions $arguments"
}
Function script:executeArguments([string]$Server) {
Invoke-Expression "mstsc.exe /v:$server $dimensions $arguments"
}
if ($_) {
if ($_ -is [string]) {
if ($_ -imatch '\\.rdp$') {
if (Test-Path $_) {
executePath $_
$processed = $true
} else {
throw "Path does not exist."
}
} else {
executeArguments $_
$processed = $true
}
} elseif ($_ -is [System.IO.FileInfo]) {
if (Test-Path $_.FullName) {
executePath $_.FullName
$processed = $true
} else {
throw "Path does not exist."
}
} elseif ($_.Path) {
if (Test-Path $_.Path) {
executePath $_.Path
$processed = $true
} else {
throw "Path does not exist."
}
} elseif ($_.DnsName) {
executeArguments $_.DnsName
$processed = $true
} elseif ($_.Server) {
executeArguments $_.Server
$processed = $true
} elseif ($_.ServerName) {
executeArguments $_.ServerName
$processed = $true
} elseif ($_.Name) {
executeArguments $_.Name
$processed = $true
}
}
}
end {
if ($path) {
if (Test-Path $path) {
Invoke-Expression "mstsc.exe '$path' $dimensions $arguments"
} else {
throw "Path does not exist."
}
} elseif ($server) {
Invoke-Expression "mstsc.exe /v:$server $dimensions $arguments"
} elseif (-not $processed) {
Invoke-Expression "mstsc.exe $dimensions $arguments"
}
}
#}
|
PowerShellCorpus/PoshCode/Remove diacritics_1.ps1
|
Remove diacritics_1.ps1
|
### Grťgory Schiro, 2009
### <summary>
### Removes diacritics from string.
### </summary>
### <param name="String">String containing diacritics</param>
function Remove-Diacritics([string]$String)
{
$objD = $String.Normalize([Text.NormalizationForm]::FormD)
$sb = New-Object Text.StringBuilder
for ($i = 0; $i -lt $objD.Length; $i++) {
$c = [Globalization.CharUnicodeInfo]::GetUnicodeCategory($objD[$i])
if($c -ne [Globalization.UnicodeCategory]::NonSpacingMark) {
[void]$sb.Append($objD[$i])
}
}
return("$sb".Normalize([Text.NormalizationForm]::FormC))
}
|
PowerShellCorpus/PoshCode/group-byobject_2.ps1
|
group-byobject_2.ps1
|
function Group-ByObject {
#.Synopsis
# Groups by a set of properties, returning objects
#.Description
# A wrapper for the built-in Group-Object cmdlet which returns one of the original objects (with separate properties for each property used to group) rather than a simple string representation as the "name" of the group. Optionally adds _count and _details properties which are the original Count and Group properties returned from group-object
#.Example
# Get-Process svchost | Group-ByObject Name, BasePriority -Count
#
# Groups Service Hosts by their BasePriority
#
#.Parameter InputObject
# The input objects are the items to be grouped
#.Parameter Property
# One or more properties to group on
#.Parameter Details
# One or more properties to collect as an array on the output
#.Parameters Group
# If set, forces all of the grouped items to be included in the _group property
#.Parameters Count
# If set, shows a count of all the grouped items on each group as the _count property
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true,Mandatory=$true)]
$InputObject
,
[Parameter(Position=0)]
[object[]]$Property
,
[Parameter(Position=1)]
[object[]]$Details
,
[Alias("All","SD")]
[switch]$Group
,
[switch]$Count
)
begin {
$InputItems = @()
$select = $property
if ($Count){ $select += @{ n="_count"; e={$group.count} } }
if ($Details){ foreach($d in $details) { $select += @{ n="$d"; e={$group.group | Select -Expand "$d"} } } }
if ($Group){ $select += @{ n="_group"; e={$group.group} } }
}
process { $InputItems += $InputObject }
end {
foreach($group in $InputItems | Group-Object $property) {
$group.Group[0] | Select-Object $select
}
}
}
set-alias groupby group-byobject
set-alias grby group-byobject
|
PowerShellCorpus/PoshCode/VMWare Quick Migration_4.ps1
|
VMWare Quick Migration_4.ps1
|
#########################################
#Name: VMWare Quick Migration Function
#Author: Justin Grote <jgrote NOSPAMAT enpointe DOT com>
#Credit: Inspired by Mike DiPetrillo's Quick Migration Script: http://www.mikedipetrillo.com/mikedvirtualization/2008/10/quick-migration-for-vmware-the-power-of-powershell.html
#Version: 0.2
#Last Revised: 15 Dec 2009
#
#Description: Performs the fucntional equivalent of a Hyper-V Quick Migration by suspending a VM,
# moving it to a new host, and resuming it. This does not require vMotion licensing.
# it works by providing required VM objects via the pipeline or the second argument,
# and specifying the Destination host in the first argument.
# The commeand accepts both text strings and VMHost objects for the VMHost Parameter
#
#Prerequisites:
# Powershell v1
# VMWare PowerCLI 4.0 (May work with earlier version but not tested)
# VMWare Foundation Edition or Better (for API support). May work with VMWare Server 2 but not tested.
#
#Instructions to Install: Save this script and import into your session with, for example, . C:\\temp\\quickmigrate.ps1
# You can also include it in your PowerCLI profile to have it automatically included.
#Command Usage: get-vm MyTestVM | Quick-MigrateVM "MyTestHost2"
#########################################
function QuickMigrate-VM {
PARAM(
$NewVMHost = ""
, [VMware.VimAutomation.Client20.VirtualMachineImpl]$VMsToMigrate = $null
)
BEGIN {
if (!$NewVMHost){
Write-Error "No Destination VMHost Specified. You must specify a host to migrate to. `n Example: Get-VM `"Test`" | QuickMigrate-VM `"Host1`""
break
}
elseif ($VMsToMigrate) {
Write-Output $InputObject | &($MyInvocation.InvocationName) -NewVMHost $newVMHost
}
else {
#If NewVMHost was provided as a String, convert it into a VMHost Object.
if ($NewVMHost.GetType().Name -eq "String") {
set-variable -name destinationVMHost -value (get-vmhost $NewVMHost) -scope 1
}
#Make sure that we have a VMHost object to work with.
if (! $destinationVMHost -or (! $destinationVMHost.GetType().Name -eq "VMHostImpl")) {
write-error "Destination VM Host was not found or you provided the wrong object type. Please provide a VMHostImpl object or specify the fully qualified name of a VM Host"
break
}
write-host -fore white "===Begin Quick Migration==="
}
}
PROCESS {
$step = 0
$skip = $false
#In the Event of an error, output the error, and skip the rest of the current item.
#This is a workaround for the fact that "continue" doesn't work in a function process loop.
trap {
write-host -fore yellow "`tSKIPPED: "$_.Exception.Message
set-variable -name skip -value ($true) -scope 1
continue
}
$vmToMigrate = $_
### Validation Checks
if($_ -is [VMware.VimAutomation.Client20.VirtualMachineImpl]) {
write-host -fore white "Quick Migrating $($vmToMigrate.Name) to $NewVMHost..."
}
else {
throw "Object Passed was not a Virtual Machine object. Object must be of type VMware.VimAutomation.Client20.VirtualMachineImpl."
}
# Check for connected devices
if (! $skip -and (get-cddrive $vmToMigrate).ConnectionState.Connected -ieq "TRUE") {
throw "Connected CD Drive. Please disconnect and try again."
}
if (! $skip -and (get-floppydrive $vmToMigrate).ConnectionState.Connected -ieq "TRUE") {
throw "Connected Floppy Drive. Please disconnect and try again."
}
# Make sure the current VM Host and the Destination Host are different.
$sourceVMHost = get-vmhost -vm $vmToMigrate
if (! $skip -and ($sourceVMHost.Name -eq $destinationVMHost.Name)) {
throw "Source and Destination Hosts are the same."
}
###Validation Complete, begin Migration
if (! $skip) {
$step++
write-host -fore cyan "`t$($step). Suspending $($vmToMigrate.Name)..."
$suspend = Suspend-VM -VM $vmToMigrate -confirm:$false
}
if (! $skip) {
$step++
write-host -fore cyan "`t($step). Moving $($vmToMigrate.Name) "to" $($destinationVMHost.Name)"
$migrate = Get-VM $vmToMigrate | Move-VM -Destination $destinationVMHost
}
if (! $skip) {
$step++
write-host -fore cyan "`t($step). Resuming" $vmToMigrate.Name"..."
$resume = Start-VM -VM $vmToMigrate
}
write-host -fore green "`tCOMPLETED"
}
END { write-host -fore white "===END Quick Migration===" }
}
|
PowerShellCorpus/PoshCode/Get-Parameter_17.ps1
|
Get-Parameter_17.ps1
|
param (
$Cmdlet,
[switch]$ShowCommon,
[switch]$Full
)
$command = Get-Command $Cmdlet -ea silentlycontinue
# resolve aliases (an alias can point to another alias)
while ($command.CommandType -eq "Alias") {
$command = Get-Command ($command.definition)
}
if (-not $command) { return }
foreach ($paramset in $command.ParameterSets){
$Output = @()
foreach ($param in $paramset.Parameters) {
if ( ! $ShowCommon ) {
if ($param.aliases -match "vb|db|ea|wa|ev|wv|ov|ob|wi|cf") { continue }
}
$process = "" | Select-Object Name, Type, ParameterSet, Aliases, Position, IsMandatory,
Pipeline, PipelineByPropertyName
$process.Name = $param.Name
if ( $param.ParameterType.Name -eq "SwitchParameter" ) {
$process.Type = "Boolean"
}
else {
switch -regex ( $param.ParameterType ) {
"Nullable``1\\[(.+)\\]" { $process.Type = $matches[1].Split('.')[-1] + " (nullable)" ; break }
default { $process.Type = $param.ParameterType.Name }
}
}
if ( $paramset.name -eq "__AllParameterSets" ) { $process.ParameterSet = "Default" }
else { $process.ParameterSet = $paramset.Name }
$process.Aliases = $param.aliases
if ( $param.Position -lt 0 ) { $process.Position = $null }
else { $process.Position = $param.Position }
$process.IsMandatory = $param.IsMandatory
$process.Pipeline = $param.ValueFromPipeline
$process.PipelineByPropertyName = $param.ValueFromPipelineByPropertyName
$output += $process
}
if ( ! $Full ) {
$Output | ft name,type,IsMandatory,pipeline -GroupBy parameterset -AutoSize
}
else { Write-Output $Output }
}
|
PowerShellCorpus/PoshCode/Xml Module 6.6.ps1
|
Xml Module 6.6.ps1
|
#requires -version 2.0
# Improves over the built-in Select-XML by leveraging Remove-XmlNamespace http`://poshcode.org/1492
# to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations
# and prefixes are removed from all XML nodes (by an XSL transform) before searching.
# IMPORTANT: returned results *will not* have namespaces in them, even if the input XML did.
# Also, only raw XmlNodes are returned from this function, so the output isn't completely compatible
# with the built in Select-Xml. It's equivalent to using Select-Xml ... | Select-Object -Expand Node
# Version History:
# Select-Xml 2.0 This was the first script version I wrote.
# it didn't function identically to the built-in Select-Xml with regards to parameter parsing
# Select-Xml 2.1 Matched the built-in Select-Xml parameter sets, it's now a drop-in replacement
# BUT only if you were using the original with: Select-Xml ... | Select-Object -Expand Node
# Select-Xml 2.2 Fixes a bug in the -Content parameterset where -RemoveNamespace was *presumed*
# Version 3.0 Added New-XDocument and associated generation functions for my XML DSL
# Version 3.1 Fixed a really ugly bug in New-XDocument in 3.0 which I should not have released
# Version 4.0 Never content to leave well enough alone, I've completely reworked New-XDocument
# Version 4.1 Tweaked namespaces again so they don't cascade down when they shouldn't. Got rid of the unnecessary stack.
# Version 4.2 Tightened xml: only cmdlet, function, and external scripts, with "-" in their names are exempted from being converted into xml tags.
# Fixed some alias error messages caused when PSCX is already loaded (we overwrite their aliases for cvxml and fxml)
# Version 4.3 Added a Path parameter set to Format-Xml so you can specify xml files for prety printing
# Version 4.5 Fixed possible [Array]::Reverse call on a non-array in New-XElement (used by New-XDocument)
# Work around possible variable slipping on null values by:
# 1) allowing -param:$value syntax (which doesn't fail when $value is null)
# 2) testing for -name syntax on the value and using it as an attribute instead
# Version 4.6 Added -Arguments to Convert-Xml so that you can pass arguments to XSLT transforms!
# Note: when using strings for xslt, make sure you single quote them or escape the $ signs.
# Version 4.7 Fixed a typo in the namespace parameter of Select-Xml
# Version 4.8 Fixed up some uses of Select-Xml -RemoveNamespace
# Version 5.0 Added Update-Xml to allow setting xml attributes or node content
# Version 6.0 Major cleanup, breaking changes.
# - Added Get-XmlContent and Set-XmlContent for loading/saving XML from files or strings
# - Removed Path and Content parameters from the other functions (it greatly simplifies thost functions, and makes the whole thing more maintainable)
# - Updated Update-Xml to support adding nodes "before" and "after" other nodes, and to support "remove"ing nodes
# Version 6.1 Update for PowerShell 3.0
# Version 6.2 Minor tweak in exception handling for CliXml
# Version 6.3 Added Remove-XmlElement to allow removing nodes or attributes
# This is something I specifically needed to remove "ignorable" namespaces
# Specifically, the ones created by the Visual Studio Workflow designer (and perhaps other visual designers like Blend)
# Which I don't want to check into source control, because it makes diffing nearly impossible
# Version 6.4 Fixed a bug on New-XElement for Rudy Shockaert (nice bug report, thanks!)
# Version 6.5 Added -Parameters @{} parameter to New-XDocument to allow local variables to be passed into the module scope. *grumble*
# Version 6.6 Expose Convert-Xml and fix a couple of bugs (I can't figure how they got here)
function Add-Accelerator {
<#
.Synopsis
Add a type accelerator to the current session
.Description
The Add-Accelerator function allows you to add a simple type accelerator (like [regex]) for a longer type (like [System.Text.RegularExpressions.Regex]).
.Example
Add-Accelerator list System.Collections.Generic.List``1
$list = New-Object list[string]
Creates an accelerator for the generic List[T] collection type, and then creates a list of strings.
.Example
Add-Accelerator "List T", "GList" System.Collections.Generic.List``1
$list = New-Object "list t[string]"
Creates two accelerators for the Generic List[T] collection type.
.Parameter Accelerator
The short form accelerator should be just the name you want to use (without square brackets).
.Parameter Type
The type you want the accelerator to accelerate (without square brackets)
.Notes
When specifying multiple values for a parameter, use commas to separate the values.
For example, "-Accelerator string, regex".
PowerShell requires arguments that are "types" to NOT have the square bracket type notation, because of the way the parsing engine works. You can either just type in the type as System.Int64, or you can put parentheses around it to help the parser out: ([System.Int64])
Also see the help for Get-Accelerator and Remove-Accelerator
.Link
http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/
#>
[CmdletBinding()]
param(
[Parameter(Position=0,ValueFromPipelineByPropertyName=$true)]
[Alias("Key","Name")]
[string[]]$Accelerator
,
[Parameter(Position=1,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[Alias("Value","FullName")]
[type]$Type
)
process {
# add a user-defined accelerator
foreach($a in $Accelerator) {
if($xlr8r::AddReplace) {
$xlr8r::AddReplace( $a, $Type)
} else {
$null = $xlr8r::Remove( $a )
$xlr8r::Add( $a, $Type)
}
trap [System.Management.Automation.MethodInvocationException] {
if($xlr8r::get.keys -contains $a) {
if($xlr8r::get[$a] -ne $Type) {
Write-Error "Cannot add accelerator [$a] for [$($Type.FullName)]`n [$a] is already defined as [$($xlr8r::get[$a].FullName)]"
}
Continue;
}
throw
}
}
}
}
&{
$local:xlr8r = [psobject].assembly.gettype("System.Management.Automation.TypeAccelerators")
$local:xlinq = [Reflection.Assembly]::Load("System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
$xlinq.GetTypes() | ? { $_.IsPublic -and !$_.IsSerializable -and $_.Name -ne "Extensions" -and !$xlr8r::Get[$_.Name] } | Add-Accelerator
Add-Accelerator "Dictionary" "System.Collections.Generic.Dictionary``2, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
Add-Accelerator "PSParser" "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
}
function Get-XmlContent {
#.Synopsis
# Load an XML file as an XmlDocument
param(
# Specifies a string that contains the XML to load, or a path to a file which has the XML to load (wildcards are permitted).
[Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath","Path")]
[String[]]$Content
,
# If set, loads XML with all namespace qualifiers removed, and all entities expanded.
[Alias("Rn","Rm")]
[Switch]$RemoveNamespace
)
begin {
[Text.StringBuilder]$XmlContent = [String]::Empty
[bool]$Path = $true
}
process {
if($Path -and ($Path = Test-Path @($Content)[0] -EA 0)) {
foreach($file in Resolve-Path $Content) {
$xml = New-Object System.Xml.XmlDocument;
if($file.Provider.Name -eq "FileSystem") {
Write-Verbose $file.ProviderPath
$xml.Load( $file.ProviderPath )
} else {
$ofs = "`n"
$xml.LoadXml( ([String](Get-Content $file)) )
}
}
if($RemoveNamespace) {
$xml.LoadXml( (Remove-XmlNamespace -Xml $xml.DocumentElement) )
}
Write-Output $xml
} else {
# If the "path" parameter isn't actually a path, assume that it's actually content
foreach($line in $content) {
$null = $XmlContent.AppendLine( $line )
}
}
}
end {
if(!$Path) {
$xml = New-Object System.Xml.XmlDocument;
$xml.LoadXml( $XmlContent.ToString() )
if($RemoveNamespace) {
$xml.LoadXml( (Remove-XmlNamespace -Xml $xml.DocumentElement) )
}
Write-Output $xml
}
}}
Set-Alias Import-Xml Get-XmlContent
Set-Alias ipxml Get-XmlContent
Set-Alias ipx Get-XmlContent
Set-Alias Get-Xml Get-XmlContent
Set-Alias gxml Get-XmlContent
Set-Alias gx Get-XmlContent
function Set-XmlContent {
param(
[Parameter(Mandatory=$true, Position=1)]
[Alias("PSPath")]
[String]$Path
,
# Specifies one or more XML nodes to search.
[Parameter(Position=5,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[Xml]$Xml
)
process {
$xml.Save( $Path )
}
}
Set-Alias Export-Xml Set-XmlContent
Set-Alias epxml Set-XmlContent
Set-Alias epx Set-XmlContent
Set-Alias Set-Xml Set-XmlContent
Set-Alias sxml Set-XmlContent
Set-Alias sx Set-XmlContent
function Format-Xml {
#.Synopsis
# Pretty-print formatted XML source
#.Description
# Runs an XmlDocument through an auto-indenting XmlWriter
#.Parameter Xml
# The Xml Document
#.Parameter Path
# The path to an xml document (on disc or any other content provider).
#.Parameter Indent
# The indent level (defaults to 2 spaces)
#.Example
# [xml]$xml = get-content Data.xml
# C:\\PS>Format-Xml $xml
#.Example
# get-content Data.xml | Format-Xml
#.Example
# Format-Xml C:\\PS\\Data.xml
#.Example
# ls *.xml | Format-Xml
#
[CmdletBinding()]
param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Document")]
[xml]$Xml
,
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName="File")]
[Alias("PsPath")]
[string]$Path
,
[Parameter(Mandatory=$false)]
$Indent=2
)
process {
## Load from file, if necessary
if($Path) { [xml]$xml = Get-Content $Path }
$StringWriter = New-Object System.IO.StringWriter
$XmlWriter = New-Object System.Xml.XmlTextWriter $StringWriter
$xmlWriter.Formatting = "indented"
$xmlWriter.Indentation = $Indent
$xml.WriteContentTo($XmlWriter)
$XmlWriter.Flush()
$StringWriter.Flush()
Write-Output $StringWriter.ToString()
}}
Set-Alias fxml Format-Xml -EA 0
Set-Alias fx Format-Xml -EA 0
function Select-XmlNodeInternal {
[CmdletBinding()]
param([Xml.XmlNode[]]$Xml, [String[]]$XPath, [Hashtable]$NamespaceManager)
begin {
Write-Verbose "XPath = $($XPath -join ',')"
foreach($node in $xml) {
if($NamespaceManager) {
$nsManager = new-object System.Xml.XmlNamespaceManager $node.NameTable
foreach($ns in $NamespaceManager.GetEnumerator()) {
$nsManager.AddNamespace( $ns.Key, $ns.Value )
}
Write-Verbose "Names = $($nsManager | % { @{ $_ = $nsManager.LookupNamespace($_) } } | Out-String)"
}
foreach($path in $xpath) {
$node.SelectNodes($path, $nsManager)
}
}
}}
function Select-Xml {
#.Synopsis
# The Select-XML cmdlet lets you use XPath queries to search for text in XML strings and documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched.
#.Description
# Improves over the built-in Select-XML by leveraging Remove-XmlNamespace to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations and prefixes are removed from all XML nodes (by an XSL transform) before searching.
#
# However, only raw XmlNodes are returned from this function, so the output isn't currently compatible with the built in Select-Xml, but is equivalent to using Select-Xml ... | Select-Object -Expand Node
#
# Also note that if the -RemoveNamespace switch is supplied the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically.
[CmdletBinding(DefaultParameterSetName="Xml")]
param(
# Specifies an XPath search query. The query language is case-sensitive. This parameter is required.
[Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[Alias("Query")]
[String[]]$XPath
,
# Specifies a string that contains the XML to search. You can also pipe strings to Select-XML.
[Parameter(ParameterSetName="Content",Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$Content
,
# Specifies the path and file names of the XML files to search. Wildcards are permitted.
[Parameter(Position=5,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath")]
[String[]]$Path
,
# Specifies one or more XML nodes to search.
[Parameter(Position=5,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
# Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}.
[Parameter(Position=10,Mandatory=$false)]
[ValidateNotNullOrEmpty()]
[Alias("Ns")]
[Hashtable]$Namespace
,
# Allows the execution of XPath queries without namespace qualifiers.
#
# If you specify the -RemoveNamespace switch, all namespace declarations and prefixes are actually removed from the Xml before the XPath search query is evaluated, and your XPath query should therefore NOT contain any namespace prefixes.
#
# Note that this means that the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically.
[Alias("Rn","Rm")]
[Switch]$RemoveNamespace
)
begin {
$NSM = $Null; if($PSBoundParameters.ContainsKey("Namespace")) { $NSM = $Namespace }
$XmlNodes = New-Object System.Xml.XmlNode[] 1
if($PSCmdlet.ParameterSetName -eq "Content") {
$XmlNodes = Get-XmlContent $Content -RemoveNamespace:$RemoveNamespace
Select-XmlNodeInternal $XmlNodes $XPath $NSM
}
}
process {
switch($PSCmdlet.ParameterSetName) {
"Path" {
$node = Get-XmlContent $Path -RemoveNamespace:$RemoveNamespace
Select-XmlNodeInternal $node $XPath $NSM
}
"Xml" {
foreach($node in $Xml) {
if($RemoveNamespace) {
[Xml]$node = Remove-XmlNamespace -Xml $node
}
Select-XmlNodeInternal $node $XPath $NSM
}
}
}
}}
Set-Alias slxml Select-Xml -EA 0
Set-Alias slx Select-Xml -EA 0
function Update-Xml {
#.Synopsis
# The Update-XML cmdlet lets you use XPath queries to replace text in nodes in XML documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched.
#.Description
# Allows you to update an attribute value, xml node contents, etc.
#
#.Notes
# We still need to implement RemoveNode and RemoveAttribute and even ReplaceNode
[CmdletBinding(DefaultParameterSetName="Set")]
param(
# Specifies an XPath for an element where you want to insert the new node.
[Parameter(ParameterSetName="Before",Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[Switch]$Before
,
# Specifies an XPath for an element where you want to insert the new node.
[Parameter(ParameterSetName="After",Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[Switch]$After
,
# If set, the new value will be added as a new child of the node identified by the XPath
[Parameter(ParameterSetName="Append",Mandatory=$true)]
[Switch]$Append
,
# If set, the node identified by the XPath will be removed instead of set
[Parameter(ParameterSetName="Remove",Mandatory=$true)]
[Switch]$Remove
,
# If set, the node identified by the XPath will be Replace instead of set
[Parameter(ParameterSetName="Replace",Mandatory=$true)]
[Switch]$Replace
,
# Specifies an XPath for the node to update. This could be an element node *or* an attribute node (remember: //element/@attribute )
[Parameter(Position=1,Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$XPath
,
# The new value to place in the xml
[Parameter(Position=2,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[String]$Value
,
# Specifies one or more XML nodes to search.
[Parameter(Position=5,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
# Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}.
[Parameter(Position=10,Mandatory=$false)]
[ValidateNotNullOrEmpty()]
[Alias("Ns")]
[Hashtable]$Namespace
,
# Output the XML documents after adding updating them
[Switch]$Passthru
)
process
{
foreach($XmlNode in $Xml) {
$select = @{}
$select.Xml = $XmlNode
$select.XPath = $XPath
if($Namespace) {
$select.Namespace = $Namespace
}
$document =
if($XmlNode -is [System.Xml.XmlDocument]) {
$XmlNode
} else {
$XmlNode.get_OwnerDocument()
}
if($xValue = $Value -as [Xml]) {
$xValue = $document.ImportNode($xValue.SelectSingleNode("/*"), $true)
}
$nodes = Select-Xml @Select | Where-Object { $_ }
if(@($nodes).Count -eq 0) { Write-Warning "No nodes matched your XPath, nothing will be updated" }
foreach($node in $nodes) {
$select.XPath = "$XPath/parent::*"
$parent = Select-Xml @Select
if(!$xValue) {
if($node -is [System.Xml.XmlAttribute] -and $Value.Contains("=")) {
$aName, $aValue = $Value.Split("=",2)
if($aName.Contains(":")){
$ns,$name = $aName.Split(":",2)
$xValue = $document.CreateAttribute( $name, $Namespace[$ns] )
} else {
$xValue = $document.CreateAttribute( $aName )
}
$xValue.Value = $aValue
}
}
switch($PSCmdlet.ParameterSetName) {
"Before" {
$null = $parent.InsertBefore( $xValue, $node )
}
"After" {
$null = $parent.InsertAfter( $xValue, $node )
}
"Append" {
$null = $parent.AppendChild( $xValue )
}
"Remove" {
$null = $parent.RemoveChild( $node )
}
"Replace" {
if(!$xValue) {
$xValue = $document.CreateTextNode( $Value )
}
$null = $parent.ReplaceChild( $xValue, $node )
}
"Set" {
if(!$xValue -and $node."#text") {
$node."#text" = $Value
} else {
if($node -is [System.Xml.XmlElement]) {
if(!$xValue) {
$xValue = $document.CreateTextNode( $Value )
}
$null = $node.set_innerXml("")
$null = $node.AppendChild($xValue)
}
elseif($node -is [System.Xml.XmlAttribute]) {
$node.Value = $Value
} else {
Write-Warning "$XPath selects a node of type $($node.GetType()), which we haven't handled. Please add that handler!"
}
}
}
}
}
if($Passthru) {
Write-Output $XmlNode
}
}
}}
Set-Alias uxml Update-Xml -EA 0
Set-Alias ux Update-Xml -EA 0
function Convert-Node {
#.Synopsis
# Convert a single XML Node via XSL stylesheets
[CmdletBinding(DefaultParameterSetName="Reader")]
param(
[Parameter(ParameterSetName="ByNode",Mandatory=$true,ValueFromPipeline=$true)]
[System.Xml.XmlNode]$Node
,
[Parameter(ParameterSetName="Reader",Mandatory=$true,ValueFromPipeline=$true)]
[System.Xml.XmlReader]$XmlReader
,
[Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)]
[System.Xml.Xsl.XslCompiledTransform]$StyleSheet
,
[Parameter(Position=2,Mandatory=$false)]
[Alias("Parameters")]
[hashtable]$Arguments
)
PROCESS {
if($PSCmdlet.ParameterSetName -eq "ByNode") {
$XmlReader = New-Object Xml.XmlNodeReader $node
}
$output = New-Object IO.StringWriter
$argList = $null
if($Arguments) {
$argList = New-Object System.Xml.Xsl.XsltArgumentList
foreach($arg in $Arguments.GetEnumerator()) {
$namespace, $name = $arg.Key -split ":"
## Fix namespace
if(!$name) {
$name = $Namespace
$namespace = ""
}
Write-Verbose "ns:$namespace name:$name value:$($arg.Value)"
$argList.AddParam($name,"$namespace",$arg.Value)
}
}
$StyleSheet.Transform( $XmlReader, $argList, $output )
Write-Output $output.ToString()
}
}
function Convert-Xml {
#.Synopsis
# The Convert-XML function lets you use Xslt to transform XML strings and documents.
#.Description
# Documentation TODO
[CmdletBinding(DefaultParameterSetName="Xml")]
param(
# Specifies one or more XML nodes to process.
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
# Specifies an Xml StyleSheet to transform with...
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[Alias("StyleSheet")]
[String]$Xslt
,
# Specify arguments to the XSL Transformation
[Alias("Parameters")]
[hashtable]$Arguments
)
begin {
$StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform
if(Test-Path $Xslt -EA 0) {
Write-Verbose "Loading Stylesheet from $(Resolve-Path $Xslt)"
$StyleSheet.Load( (Resolve-Path $Xslt) )
} else {
$OFS = "`n"
Write-Verbose "$Xslt"
$StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader $Xslt))))
}
}
process {
foreach($node in $Xml) {
Convert-Node -Xml (New-Object Xml.XmlNodeReader $node) $StyleSheet $Arguments
}
}
}
Set-Alias cvxml Convert-Xml -EA 0
function Remove-XmlNamespace {
#.Synopsis
# Removes namespace definitions and prefixes from xml documents
#.Description
# Runs an xml document through an XSL Transformation to remove namespaces from it if they exist.
# Entities are also naturally expanded
#.Parameter Content
# Specifies a string that contains the XML to transform.
#.Parameter Path
# Specifies the path and file names of the XML files to transform. Wildcards are permitted.
#
# There will be one output document for each matching input file.
#.Parameter Xml
# Specifies one or more XML documents to transform
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
)
BEGIN {
$StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform
$StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader @"
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/|comment()|processing-instruction()">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
"@))))
[Text.StringBuilder]$XmlContent = [String]::Empty
}
PROCESS {
$Xml | Convert-Node $StyleSheet
}
}
Set-Alias rmns Remove-XmlNamespace -EA 0
Set-Alias rmxns Remove-XmlNamespace -EA 0
function Remove-XmlElement {
#.Synopsis
# Removes specified elements (tags or attributes) or all elements from a specified namespace from an Xml document
#.Description
# Runs an xml document through an XSL Transformation to remove tag namespaces from it if they exist.
# Entities are also naturally expanded
#.Parameter Content
# Specifies a string that contains the XML to transform.
#.Parameter Path
# Specifies the path and file names of the XML files to transform. Wildcards are permitted.
#
# There will be one output document for each matching input file.
#.Parameter Xml
# Specifies one or more XML documents to transform
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(Position=0,ParameterSetName="Xml")] #,Mandatory=$true
#[ValidateNotNullOrEmpty()]
[XNamespace[]]$Namespace
,
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
)
BEGIN {
foreach($Node in @($Xml)) {
$Allspaces += Get-Namespace -Xml $Node
$nsManager = new-object System.Xml.XmlNamespaceManager $node.NameTable
foreach($ns in $Allspaces.GetEnumerator()) {
$nsManager.AddNamespace( $ns.Key, $ns.Value )
}
# If no namespaces are passed in, use the "ignorable" ones from XAML if there are any
if(!$Namespace) {
$root = $Node.DocumentElement
# $nsManager = new-object System.Xml.XmlNamespaceManager $Node.NameTable
$nsManager.AddNamespace("compat", "http://schemas.openxmlformats.org/markup-compatibility/2006")
if($ignorable = $root.SelectSingleNode("@compat:Ignorable",$nsManager)) {
foreach($prefix in $ignorable.get_InnerText().Split(" ")) {
$Namespace += $root.GetNamespaceOfPrefix($prefix)
}
}
}
}
Write-Verbose "$Namespace"
$i = 0
$NSString = $(foreach($n in $Namespace) { "xmlns:n$i='$n'"; $i+=1 }) -Join " "
$EmptyTransforms = $(for($i =0; $i -lt $Namespace.Count;$i++) {
"<xsl:template match='n${i}:*'>
</xsl:template>
<xsl:template match='@n${i}:*'>
</xsl:template>"
})
$XSLT = @"
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" $NSString>
<xsl:output method="xml" indent="yes"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
$EmptyTransforms
</xsl:stylesheet>
"@
Write-Verbose $XSLT
$StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform
$StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader $XSLT))))
[Text.StringBuilder]$XmlContent = [String]::Empty
}
PROCESS {
$Xml | Convert-Node $StyleSheet
}
}
#Set-Alias rmns Remove-XmlNamespace -EA 0
#Set-Alias rmxns Remove-XmlNamespace -EA 0
function Get-Namespace {
param(
[Parameter(Position=0)]
[String[]]$Prefix = "*"
,
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
)
foreach($Node in @($Xml)) {
$results = @{}
if($Node -is [Xml.XmlDocument]) {
$Node = $Node.DocumentElement
}
foreach($ns in $Node.CreateNavigator().GetNamespacesInScope("All").GetEnumerator()) {
foreach($p in $Prefix) {
if($ns.Key -like $p) {
$results.Add($ns.Key, $ns.Value)
break;
}
}
}
$results
}
}
######## Helper functions for working with CliXml
function ConvertFrom-CliXml {
param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$InputObject
)
begin
{
$OFS = "`n"
[String]$xmlString = ""
}
process
{
$xmlString += $InputObject
}
end
{
$type = [psobject].assembly.gettype("System.Management.Automation.Deserializer")
$ctor = $type.getconstructor("instance,nonpublic", $null, @([xml.xmlreader]), $null)
$sr = new-object System.IO.StringReader $xmlString
$xr = new-object System.Xml.XmlTextReader $sr
$deserializer = $ctor.invoke($xr)
$method = @($type.getmethods("nonpublic,instance") | where-object {$_.name -like "Deserialize"})[1]
$done = $type.getmethod("Done", [System.Reflection.BindingFlags]"nonpublic,instance")
while (!$done.invoke($deserializer, @()))
{
try {
$method.invoke($deserializer, "")
} catch {
write-warning "Could not deserialize $xmlString"
}
}
$xr.Close()
$sr.Dispose()
}
}
function ConvertTo-CliXml {
param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[PSObject[]]$InputObject
)
begin {
$type = [psobject].assembly.gettype("System.Management.Automation.Serializer")
$ctor = $type.getconstructor("instance,nonpublic", $null, @([System.Xml.XmlWriter]), $null)
$sw = new-object System.IO.StringWriter
$xw = new-object System.Xml.XmlTextWriter $sw
$serializer = $ctor.invoke($xw)
$method = $type.getmethod("Serialize", "nonpublic,instance", $null, [type[]]@([object]), $null)
$done = $type.getmethod("Done", [System.Reflection.BindingFlags]"nonpublic,instance")
}
process {
try {
[void]$method.invoke($serializer, $InputObject)
} catch {
write-warning "Could not serialize $($InputObject.gettype()): $InputObject"
}
}
end {
[void]$done.invoke($serializer, @())
$sw.ToString()
$xw.Close()
$sw.Dispose()
}
}
######## From here down is all the code related to my XML DSL:
function New-XDocument {
#.Synopsis
# Creates a new XDocument (the new xml document type)
#.Description
# This is the root for a new XML mini-dsl, akin to New-BootsWindow for XAML
# It creates a new XDocument, and takes scritpblock(s) to define it's contents
#.Example
# [string]$xml = New-XDocument rss -version "2.0" {
# channel {
# title {"Test RSS Feed"}
# link {"http`://HuddledMasses.org"}
# description {"An RSS Feed generated simply to demonstrate my XML DSL"}
# item {
# title {"The First Item"}
# link {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"}
# guid -isPermaLink true {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"}
# description {"Ema Lazarus' Poem"}
# pubDate {(Get-Date 10/31/2003 -f u) -replace " ","T"}
# }
# }
# }
#
# C:\\PS>$xml.Declaration.ToString() ## I can't find a way to have this included in the $xml.ToString()
# C:\\PS>$xml.ToString()
#
# <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
# <rss version="2.0">
# <channel>
# <title>Test RSS Feed</title>
# <link>http ://HuddledMasses.org</link>
# <description>An RSS Feed generated simply to demonstrate my XML DSL</description>
# <item>
# <title>The First Item</title>
# <link>http ://huddledmasses.org/new-site-new-layout-lost-posts/</link>
# <guid isPermaLink="true">http ://huddledmasses.org/new-site-new-layout-lost-posts/</guid>
# <description>Ema Lazarus' Poem</description>
# <pubDate>2003-10-31T00:00:00Z</pubDate>
# </item>
# </channel>
# </rss>
#
#
# Description
# -----------
# This example shows the creation of a complete RSS feed with a single item in it.
#
# NOTE that the backtick in the http`: in the URLs in the input is unecessary, and I added the space after the http: in the URLs in the output -- these are accomodations to PoshCode's spam filter. Backticks are not need in the input, and spaces do not appear in the actual output.
#
#
#.Example
# [XNamespace]$atom="http`://www.w3.org/2005/Atom"
# C:\\PS>[XNamespace]$dc = "http`://purl.org/dc/elements/1.1"
#
# C:\\PS>New-XDocument ($atom + "feed") -Encoding "UTF-16" -$([XNamespace]::Xml +'lang') "en-US" -dc $dc {
# title {"Test First Entry"}
# link {"http`://HuddledMasses.org"}
# updated {(Get-Date -f u) -replace " ","T"}
# author {
# name {"Joel Bennett"}
# uri {"http`://HuddledMasses.org"}
# }
# id {"http`://huddledmasses.org/" }
#
# entry {
# title {"Test First Entry"}
# link {"http`://HuddledMasses.org/new-site-new-layout-lost-posts/" }
# id {"http`://huddledmasses.org/new-site-new-layout-lost-posts/" }
# updated {(Get-Date 10/31/2003 -f u) -replace " ","T"}
# summary {"Ema Lazarus' Poem"}
# link -rel license -href "http`://creativecommons.org/licenses/by/3.0/" -title "CC By-Attribution"
# dc:rights { "Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)" }
# category -scheme "http`://huddledmasses.org/tag/" -term "huddled-masses"
# }
# } | % { $_.Declaration.ToString(); $_.ToString() }
#
# <?xml version="1.0" encoding="UTF-16" standalone="yes"?>
# <feed xml:lang="en-US" xmlns="http ://www.w3.org/2005/Atom">
# <title>Test First Entry</title>
# <link>http ://HuddledMasses.org</link>
# <updated>2009-07-29T17:25:49Z</updated>
# <author>
# <name>Joel Bennett</name>
# <uri>http ://HuddledMasses.org</uri>
# </author>
# <id>http ://huddledmasses.org/</id>
# <entry>
# <title>Test First Entry</title>
# <link>http ://HuddledMasses.org/new-site-new-layout-lost-posts/</link>
# <id>http ://huddledmasses.org/new-site-new-layout-lost-posts/</id>
# <updated>2003-10-31T00:00:00Z</updated>
# <summary>Ema Lazarus' Poem</summary>
# <link rel="license" href="http ://creativecommons.org/licenses/by/3.0/" title="CC By-Attribution" />
# <dc:rights>Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)</dc:rights>
# <category scheme="http ://huddledmasses.org/tag/" term="huddled-masses" />
# </entry>
# </feed>
#
#
# Description
# -----------
# This example shows the use of a default namespace, as well as additional specific namespaces for the "dc" namespace. It also demonstrates how you can get the <?xml?> declaration which does not appear in a simple .ToString().
#
# NOTE that the backtick in the http`: in the URLs in the input is unecessary, and I added the space after the http: in the URLs in the output -- these are accomodations to PoshCode's spam filter. Backticks are not need in the input, and spaces do not appear in the actual output.#
#
[CmdletBinding()]
Param(
# The root node name
[Parameter(Mandatory = $true, Position = 0)]
[System.Xml.Linq.XName]$root
,
# Optional: the XML version. Defaults to 1.0
[Parameter(Mandatory = $false)]
[string]$Version = "1.0"
,
# Optional: the Encoding. Defaults to UTF-8
[Parameter(Mandatory = $false)]
[string]$Encoding = "UTF-8"
,
# Optional: whether to specify standalone in the xml declaration. Defaults to "yes"
[Parameter(Mandatory = $false)]
[string]$Standalone = "yes"
,
# A Hashtable of parameters which should be available as local variables to the scriptblock in args
[Parameter(Mandatory = $false)]
[hashtable]$Parameters
,
# this is where all the dsl magic happens. Please see the Examples. :)
[AllowNull()][AllowEmptyString()][AllowEmptyCollection()]
[Parameter(Position=99, Mandatory = $false, ValueFromRemainingArguments=$true)]
[PSObject[]]$args
)
BEGIN {
$script:NameSpaceHash = New-Object 'Dictionary[String,XNamespace]'
if($root.NamespaceName) {
$script:NameSpaceHash.Add("", $root.Namespace)
}
}
PROCESS {
if($Parameters) {
foreach($key in $Parameters.Keys) {
Set-Variable $key $Parameters.$key -Scope Script
}
}
New-Object XDocument (New-Object XDeclaration $Version, $Encoding, $standalone),(
New-Object XElement $(
$root
while($args) {
$attrib, $value, $args = $args
if($attrib -is [ScriptBlock]) {
# Write-Verbose "Preparsed DSL: $attrib"
$attrib = ConvertFrom-XmlDsl $attrib
Write-Verbose "Reparsed DSL: $attrib"
& $attrib
} elseif ( $value -is [ScriptBlock] -and "-CONTENT".StartsWith($attrib.TrimEnd(':').ToUpper())) {
$value = ConvertFrom-XmlDsl $value
Write-Verbose "Reparsed DSL: $value"
& $value
} elseif ( $value -is [XNamespace]) {
New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-").TrimEnd(':')), $value
$script:NameSpaceHash.Add($attrib.TrimStart("-").TrimEnd(':'), $value)
} else {
Write-Verbose "XAttribute $attrib = $value"
New-Object XAttribute $attrib.TrimStart("-").TrimEnd(':'), $value
}
}
))
}
}
Set-Alias xml New-XDocument -EA 0
Set-Alias New-Xml New-XDocument -EA 0
function New-XAttribute {
#.Synopsys
# Creates a new XAttribute (an xml attribute on an XElement for XDocument)
#.Description
# This is the work-horse for the XML mini-dsl
#.Parameter name
# The attribute name
#.Parameter value
# The attribute value
[CmdletBinding()]
Param([Parameter(Mandatory=$true)]$name,[Parameter(Mandatory=$true)]$value)
New-Object XAttribute $name, $value
}
Set-Alias xa New-XAttribute -EA 0
Set-Alias New-XmlAttribute New-XAttribute -EA 0
function New-XElement {
#.Synopsys
# Creates a new XElement (an xml tag for XDocument)
#.Description
# This is the work-horse for the XML mini-dsl
#.Parameter tag
# The name of the xml tag
#.Parameter args
# this is where all the dsl magic happens. Please see the Examples. :)
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true, Position = 0)]
[System.Xml.Linq.XName]$tag
,
[AllowNull()][AllowEmptyString()][AllowEmptyCollection()]
[Parameter(Position=99, Mandatory = $false, ValueFromRemainingArguments=$true)]
[PSObject[]]$args
)
PROCESS {
New-Object XElement $(
$tag
Write-Verbose "New-XElement $tag $($args -join ',')"
while($args) {
$attrib, $value, $args = $args
if($attrib -is [ScriptBlock]) { # then it's content
& $attrib
} elseif ( $value -is [ScriptBlock] -and "-CONTENT".StartsWith($attrib.TrimEnd(':').ToUpper())) { # then it's content
& $value
} elseif ( $value -is [XNamespace]) {
Write-Verbose "New XAttribute xmlns: $($attrib.TrimStart("-").TrimEnd(':')) = $value"
New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-").TrimEnd(':')), $value
$script:NameSpaceHash.Add($attrib.TrimStart("-").TrimEnd(':'), $value)
} elseif($value -match "^-(?!\\d)\\w") {
$args = @($value)+@($args)
} elseif($value -ne $null) {
Write-Verbose "New XAttribute $($attrib.TrimStart("-").TrimEnd(':')) = $value"
New-Object XAttribute $attrib.TrimStart("-").TrimEnd(':'), $value
}
}
)
}
}
Set-Alias xe New-XElement
Set-Alias New-XmlElement New-XElement
function ConvertFrom-XmlDsl {
Param([ScriptBlock]$script)
$parserrors = $null
$global:tokens = [PSParser]::Tokenize( $script, [ref]$parserrors )
[Array]$duds = $global:tokens | Where-Object { $_.Type -eq "Command" -and !$_.Content.Contains('-') -and ($(Get-Command $_.Content -Type Cmdlet,Function,ExternalScript -EA 0) -eq $Null) }
if($duds) {
[Array]::Reverse( $duds )
}
[string[]]$ScriptText = "$script" -split "`n"
ForEach($token in $duds ) {
# replace : notation with namespace notation
if( $token.Content.Contains(":") ) {
$key, $localname = $token.Content -split ":"
$ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Remove( $token.StartColumn -1, $token.Length ).Insert( $token.StartColumn -1, "'" + $($script:NameSpaceHash[$key] + $localname) + "'" )
} else {
$ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Remove( $token.StartColumn -1, $token.Length ).Insert( $token.StartColumn -1, "'" + $($script:NameSpaceHash[''] + $token.Content) + "'" )
}
# insert 'xe' before everything (unless it's a valid command)
$ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Insert( $token.StartColumn -1, "xe " )
}
Write-Output ([ScriptBlock]::Create( ($ScriptText -join "`n") ))
}
######## Xaml
# if($PSVersionTable.CLRVersion -ge "4.0"){
# trap { continue }
# [Reflection.Assembly]::LoadWithPartialName("System.Xaml") | Out-Null
# if("System.Xaml.XamlServices" -as [type]) {
# }
# }
Export-ModuleMember -alias * -function New-XDocument, New-XAttribute, New-XElement, Remove-XmlNamespace, Remove-XmlElement, Get-Namespace, Get-XmlContent, Set-XmlContent, Convert-Xml, Select-Xml, Update-Xml, Format-Xml, ConvertTo-CliXml, ConvertFrom-CliXml
# SIG # Begin signature block
# MIIfIAYJKoZIhvcNAQcCoIIfETCCHw0CAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUyHdevpWFnFH+l3PfnCoHIjum
# NvigghpSMIID7jCCA1egAwIBAgIQfpPr+3zGTlnqS5p31Ab8OzANBgkqhkiG9w0B
# AQUFADCBizELMAkGA1UEBhMCWkExFTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTEUMBIG
# A1UEBxMLRHVyYmFudmlsbGUxDzANBgNVBAoTBlRoYXd0ZTEdMBsGA1UECxMUVGhh
# d3RlIENlcnRpZmljYXRpb24xHzAdBgNVBAMTFlRoYXd0ZSBUaW1lc3RhbXBpbmcg
# Q0EwHhcNMTIxMjIxMDAwMDAwWhcNMjAxMjMwMjM1OTU5WjBeMQswCQYDVQQGEwJV
# UzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xMDAuBgNVBAMTJ1N5bWFu
# dGVjIFRpbWUgU3RhbXBpbmcgU2VydmljZXMgQ0EgLSBHMjCCASIwDQYJKoZIhvcN
# AQEBBQADggEPADCCAQoCggEBALGss0lUS5ccEgrYJXmRIlcqb9y4JsRDc2vCvy5Q
# WvsUwnaOQwElQ7Sh4kX06Ld7w3TMIte0lAAC903tv7S3RCRrzV9FO9FEzkMScxeC
# i2m0K8uZHqxyGyZNcR+xMd37UWECU6aq9UksBXhFpS+JzueZ5/6M4lc/PcaS3Er4
# ezPkeQr78HWIQZz/xQNRmarXbJ+TaYdlKYOFwmAUxMjJOxTawIHwHw103pIiq8r3
# +3R8J+b3Sht/p8OeLa6K6qbmqicWfWH3mHERvOJQoUvlXfrlDqcsn6plINPYlujI
# fKVOSET/GeJEB5IL12iEgF1qeGRFzWBGflTBE3zFefHJwXECAwEAAaOB+jCB9zAd
# BgNVHQ4EFgQUX5r1blzMzHSa1N197z/b7EyALt0wMgYIKwYBBQUHAQEEJjAkMCIG
# CCsGAQUFBzABhhZodHRwOi8vb2NzcC50aGF3dGUuY29tMBIGA1UdEwEB/wQIMAYB
# Af8CAQAwPwYDVR0fBDgwNjA0oDKgMIYuaHR0cDovL2NybC50aGF3dGUuY29tL1Ro
# YXd0ZVRpbWVzdGFtcGluZ0NBLmNybDATBgNVHSUEDDAKBggrBgEFBQcDCDAOBgNV
# HQ8BAf8EBAMCAQYwKAYDVR0RBCEwH6QdMBsxGTAXBgNVBAMTEFRpbWVTdGFtcC0y
# MDQ4LTEwDQYJKoZIhvcNAQEFBQADgYEAAwmbj3nvf1kwqu9otfrjCR27T4IGXTdf
# plKfFo3qHJIJRG71betYfDDo+WmNI3MLEm9Hqa45EfgqsZuwGsOO61mWAK3ODE2y
# 0DGmCFwqevzieh1XTKhlGOl5QGIllm7HxzdqgyEIjkHq3dlXPx13SYcqFgZepjhq
# IhKjURmDfrYwggRPMIIDuKADAgECAgQHJ1g9MA0GCSqGSIb3DQEBBQUAMHUxCzAJ
# BgNVBAYTAlVTMRgwFgYDVQQKEw9HVEUgQ29ycG9yYXRpb24xJzAlBgNVBAsTHkdU
# RSBDeWJlclRydXN0IFNvbHV0aW9ucywgSW5jLjEjMCEGA1UEAxMaR1RFIEN5YmVy
# VHJ1c3QgR2xvYmFsIFJvb3QwHhcNMTAwMTEzMTkyMDMyWhcNMTUwOTMwMTgxOTQ3
# WjBsMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQL
# ExB3d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3Vy
# YW5jZSBFViBSb290IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA
# xszlc+b71LvlLS0ypt/lgT/JzSVJtnEqw9WUNGeiChywX2mmQLHEt7KP0JikqUFZ
# OtPclNY823Q4pErMTSWC90qlUxI47vNJbXGRfmO2q6Zfw6SE+E9iUb74xezbOJLj
# BuUIkQzEKEFV+8taiRV+ceg1v01yCT2+OjhQW3cxG42zxyRFmqesbQAUWgS3uhPr
# UQqYQUEiTmVhh4FBUKZ5XIneGUpX1S7mXRxTLH6YzRoGFqRoc9A0BBNcoXHTWnxV
# 215k4TeHMFYE5RG0KYAS8Xk5iKICEXwnZreIt3jyygqoOKsKZMK/Zl2VhMGhJR6H
# XRpQCyASzEG7bgtROLhLywIDAQABo4IBbzCCAWswEgYDVR0TAQH/BAgwBgEB/wIB
# ATBTBgNVHSAETDBKMEgGCSsGAQQBsT4BADA7MDkGCCsGAQUFBwIBFi1odHRwOi8v
# Y3liZXJ0cnVzdC5vbW5pcm9vdC5jb20vcmVwb3NpdG9yeS5jZm0wDgYDVR0PAQH/
# BAQDAgEGMIGJBgNVHSMEgYEwf6F5pHcwdTELMAkGA1UEBhMCVVMxGDAWBgNVBAoT
# D0dURSBDb3Jwb3JhdGlvbjEnMCUGA1UECxMeR1RFIEN5YmVyVHJ1c3QgU29sdXRp
# b25zLCBJbmMuMSMwIQYDVQQDExpHVEUgQ3liZXJUcnVzdCBHbG9iYWwgUm9vdIIC
# AaUwRQYDVR0fBD4wPDA6oDigNoY0aHR0cDovL3d3dy5wdWJsaWMtdHJ1c3QuY29t
# L2NnaS1iaW4vQ1JMLzIwMTgvY2RwLmNybDAdBgNVHQ4EFgQUsT7DaQP4v0cB1Jgm
# GggC72NkK8MwDQYJKoZIhvcNAQEFBQADgYEALnaF2TeWba+J8wZ4gjHERgcfZcmO
# s8lUeObRQt91Lh5V6vf6mwTAdXvReTwF7HnEUt2mA9enUJk/BVnaxlX0hpwNZ6NJ
# BJUyHceH7IWvZG7VxV8Jp0B9FrpJDaL99t9VMGzXeMa5z1gpZBZMoyCBR7FEkoQW
# G29KvCHGCj3tM8owggSjMIIDi6ADAgECAhAOz/Q4yP6/NW4E2GqYGxpQMA0GCSqG
# SIb3DQEBBQUAMF4xCzAJBgNVBAYTAlVTMR0wGwYDVQQKExRTeW1hbnRlYyBDb3Jw
# b3JhdGlvbjEwMC4GA1UEAxMnU3ltYW50ZWMgVGltZSBTdGFtcGluZyBTZXJ2aWNl
# cyBDQSAtIEcyMB4XDTEyMTAxODAwMDAwMFoXDTIwMTIyOTIzNTk1OVowYjELMAkG
# A1UEBhMCVVMxHTAbBgNVBAoTFFN5bWFudGVjIENvcnBvcmF0aW9uMTQwMgYDVQQD
# EytTeW1hbnRlYyBUaW1lIFN0YW1waW5nIFNlcnZpY2VzIFNpZ25lciAtIEc0MIIB
# IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAomMLOUS4uyOnREm7Dv+h8GEK
# U5OwmNutLA9KxW7/hjxTVQ8VzgQ/K/2plpbZvmF5C1vJTIZ25eBDSyKV7sIrQ8Gf
# 2Gi0jkBP7oU4uRHFI/JkWPAVMm9OV6GuiKQC1yoezUvh3WPVF4kyW7BemVqonShQ
# DhfultthO0VRHc8SVguSR/yrrvZmPUescHLnkudfzRC5xINklBm9JYDh6NIipdC6
# Anqhd5NbZcPuF3S8QYYq3AhMjJKMkS2ed0QfaNaodHfbDlsyi1aLM73ZY8hJnTrF
# xeozC9Lxoxv0i77Zs1eLO94Ep3oisiSuLsdwxb5OgyYI+wu9qU+ZCOEQKHKqzQID
# AQABo4IBVzCCAVMwDAYDVR0TAQH/BAIwADAWBgNVHSUBAf8EDDAKBggrBgEFBQcD
# CDAOBgNVHQ8BAf8EBAMCB4AwcwYIKwYBBQUHAQEEZzBlMCoGCCsGAQUFBzABhh5o
# dHRwOi8vdHMtb2NzcC53cy5zeW1hbnRlYy5jb20wNwYIKwYBBQUHMAKGK2h0dHA6
# Ly90cy1haWEud3Muc3ltYW50ZWMuY29tL3Rzcy1jYS1nMi5jZXIwPAYDVR0fBDUw
# MzAxoC+gLYYraHR0cDovL3RzLWNybC53cy5zeW1hbnRlYy5jb20vdHNzLWNhLWcy
# LmNybDAoBgNVHREEITAfpB0wGzEZMBcGA1UEAxMQVGltZVN0YW1wLTIwNDgtMjAd
# BgNVHQ4EFgQURsZpow5KFB7VTNpSYxc/Xja8DeYwHwYDVR0jBBgwFoAUX5r1blzM
# zHSa1N197z/b7EyALt0wDQYJKoZIhvcNAQEFBQADggEBAHg7tJEqAEzwj2IwN3ij
# hCcHbxiy3iXcoNSUA6qGTiWfmkADHN3O43nLIWgG2rYytG2/9CwmYzPkSWRtDebD
# Zw73BaQ1bHyJFsbpst+y6d0gxnEPzZV03LZc3r03H0N45ni1zSgEIKOq8UvEiCmR
# DoDREfzdXHZuT14ORUZBbg2w6jiasTraCXEQ/Bx5tIB7rGn0/Zy2DBYr8X9bCT2b
# W+IWyhOBbQAuOA2oKY8s4bL0WqkBrxWcLC9JG9siu8P+eJRRw4axgohd8D20UaF5
# Mysue7ncIAkTcetqGVvP6KUwVyyJST+5z3/Jvz4iaGNTmr1pdKzFHTx/kuDDvBzY
# BHUwggafMIIFh6ADAgECAhAOaQaYwhTIerW2BLkWPNGQMA0GCSqGSIb3DQEBBQUA
# MHMxCzAJBgNVBAYTAlVTMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsT
# EHd3dy5kaWdpY2VydC5jb20xMjAwBgNVBAMTKURpZ2lDZXJ0IEhpZ2ggQXNzdXJh
# bmNlIENvZGUgU2lnbmluZyBDQS0xMB4XDTEyMDMyMDAwMDAwMFoXDTEzMDMyMjEy
# MDAwMFowbTELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5ldyBZb3JrMRcwFQYDVQQH
# Ew5XZXN0IEhlbnJpZXR0YTEYMBYGA1UEChMPSm9lbCBILiBCZW5uZXR0MRgwFgYD
# VQQDEw9Kb2VsIEguIEJlbm5ldHQwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
# AoIBAQDaiAYAbz13WMx9Em/Z3dTWUKxbyiTsaSOctgOfTMLUAurXWtY3k1XBVufX
# feL4pXQ7yQzm93YzvETwKdUCDJuOSu9EPYioy2nhKvBC6IaJUaw1VY7e9IsdxaxL
# 8js3RQilLk+FO4UHg9w7L8wdHgXaDoksysC2SlhbFq4AVl8XC4R+bq+pahsdMO3n
# Ab7Oo5PExKLVS8vl8QwOh6MaqquIjHmYoPOu9Rv8As0pnWsY9aVPs7T9QetXlW45
# +CKPhdUoEB1yD0kvGTIAQgn5W9VDYmfeVU40IIdt+7khWF10yu7zVT+/lauPzRmv
# CHZMfbmqVyVQqvp5dEu0/7EWbbcLAgMBAAGjggMzMIIDLzAfBgNVHSMEGDAWgBSX
# SAPrFQhrubJYI8yULvHGZdJkjjAdBgNVHQ4EFgQUmJxEqr9ewFZG4rNTp5NQIEIJ
# TrkwDgYDVR0PAQH/BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUFBwMDMGkGA1UdHwRi
# MGAwLqAsoCqGKGh0dHA6Ly9jcmwzLmRpZ2ljZXJ0LmNvbS9oYS1jcy0yMDExYS5j
# cmwwLqAsoCqGKGh0dHA6Ly9jcmw0LmRpZ2ljZXJ0LmNvbS9oYS1jcy0yMDExYS5j
# cmwwggHEBgNVHSAEggG7MIIBtzCCAbMGCWCGSAGG/WwDATCCAaQwOgYIKwYBBQUH
# AgEWLmh0dHA6Ly93d3cuZGlnaWNlcnQuY29tL3NzbC1jcHMtcmVwb3NpdG9yeS5o
# dG0wggFkBggrBgEFBQcCAjCCAVYeggFSAEEAbgB5ACAAdQBzAGUAIABvAGYAIAB0
# AGgAaQBzACAAQwBlAHIAdABpAGYAaQBjAGEAdABlACAAYwBvAG4AcwB0AGkAdAB1
# AHQAZQBzACAAYQBjAGMAZQBwAHQAYQBuAGMAZQAgAG8AZgAgAHQAaABlACAARABp
# AGcAaQBDAGUAcgB0ACAAQwBQAC8AQwBQAFMAIABhAG4AZAAgAHQAaABlACAAUgBl
# AGwAeQBpAG4AZwAgAFAAYQByAHQAeQAgAEEAZwByAGUAZQBtAGUAbgB0ACAAdwBo
# AGkAYwBoACAAbABpAG0AaQB0ACAAbABpAGEAYgBpAGwAaQB0AHkAIABhAG4AZAAg
# AGEAcgBlACAAaQBuAGMAbwByAHAAbwByAGEAdABlAGQAIABoAGUAcgBlAGkAbgAg
# AGIAeQAgAHIAZQBmAGUAcgBlAG4AYwBlAC4wgYYGCCsGAQUFBwEBBHoweDAkBggr
# BgEFBQcwAYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29tMFAGCCsGAQUFBzAChkRo
# dHRwOi8vY2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNlcnRIaWdoQXNzdXJhbmNl
# Q29kZVNpZ25pbmdDQS0xLmNydDAMBgNVHRMBAf8EAjAAMA0GCSqGSIb3DQEBBQUA
# A4IBAQAch95ik7Qm12L9Olwjp5ZAhhTYAs7zjtD3WMsTpaJTq7zA3q2QeqB46WzT
# vRINQr4LWtWhcopnQl5zaTV1i6Qo+TJ/epRE/KH9oLeEnRbBuN7t8rv0u31kfAk5
# Gl6wmvBrxPreXeossuU9ohij9uqIyk1lF85yW6QqDaE7rvIxpCXwMQv8PlQ/VdlK
# EXbNtq4frbvMQLkpcZljbJRuZYbY3SgfGv6rgbJ93Qw+1Tlq9Y4gsHRmw35uv5IJ
# VUrqcrNq5cyTgdeYodpftzKyqmZCIVvv8nu09DTfspAocJj9n5+XRqtEKIeKH9D/
# mjC/nVZIo+JpSuQG90nSYpUr4xwfMIIGvzCCBaegAwIBAgIQCBxX7l1w65ugsVIM
# cpwbCTANBgkqhkiG9w0BAQUFADBsMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGln
# aUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJE
# aWdpQ2VydCBIaWdoIEFzc3VyYW5jZSBFViBSb290IENBMB4XDTExMDIxMDEyMDAw
# MFoXDTI2MDIxMDEyMDAwMFowczELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lD
# ZXJ0IEluYzEZMBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEyMDAGA1UEAxMpRGln
# aUNlcnQgSGlnaCBBc3N1cmFuY2UgQ29kZSBTaWduaW5nIENBLTEwggEiMA0GCSqG
# SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDF+SPmlCfEgBSkgDJfQKONb3DA5TZxcTp1
# pKoakpSJXqwjcctOZ31BP6rjS7d7vp3BqDiPaS86JOl3WRLHZgRDwg0mgolAGfIs
# 6udM53wFGrj/iAlPJjfvOqT6ImyIyUobYfKuEF5vvNF5m1kYYOXuKbUDKqTO8YMZ
# T2kFcygJ+yIQkyKgkBkaTDHy0yvYhEOvPGP/mNsg0gkrVMHq/WqD5xCjEnH11tfh
# EnrV4FZazuoBW2hlW8E/WFIzqTVhTiLLgco2oxLLBtbPG00YfrmSuRLPQCbYmjaF
# sxWqR5OEawe7vNWz3iUAEYkAaMEpPOo+Le5Qq9ccMAZ4PKUQI2eRAgMBAAGjggNU
# MIIDUDAOBgNVHQ8BAf8EBAMCAQYwEwYDVR0lBAwwCgYIKwYBBQUHAwMwggHDBgNV
# HSAEggG6MIIBtjCCAbIGCGCGSAGG/WwDMIIBpDA6BggrBgEFBQcCARYuaHR0cDov
# L3d3dy5kaWdpY2VydC5jb20vc3NsLWNwcy1yZXBvc2l0b3J5Lmh0bTCCAWQGCCsG
# AQUFBwICMIIBVh6CAVIAQQBuAHkAIAB1AHMAZQAgAG8AZgAgAHQAaABpAHMAIABD
# AGUAcgB0AGkAZgBpAGMAYQB0AGUAIABjAG8AbgBzAHQAaQB0AHUAdABlAHMAIABh
# AGMAYwBlAHAAdABhAG4AYwBlACAAbwBmACAAdABoAGUAIABEAGkAZwBpAEMAZQBy
# AHQAIABFAFYAIABDAFAAUwAgAGEAbgBkACAAdABoAGUAIABSAGUAbAB5AGkAbgBn
# ACAAUABhAHIAdAB5ACAAQQBnAHIAZQBlAG0AZQBuAHQAIAB3AGgAaQBjAGgAIABs
# AGkAbQBpAHQAIABsAGkAYQBiAGkAbABpAHQAeQAgAGEAbgBkACAAYQByAGUAIABp
# AG4AYwBvAHIAcABvAHIAYQB0AGUAZAAgAGgAZQByAGUAaQBuACAAYgB5ACAAcgBl
# AGYAZQByAGUAbgBjAGUALjAPBgNVHRMBAf8EBTADAQH/MH8GCCsGAQUFBwEBBHMw
# cTAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29tMEkGCCsGAQUF
# BzAChj1odHRwOi8vY2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNlcnRIaWdoQXNz
# dXJhbmNlRVZSb290Q0EuY3J0MIGPBgNVHR8EgYcwgYQwQKA+oDyGOmh0dHA6Ly9j
# cmwzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEhpZ2hBc3N1cmFuY2VFVlJvb3RDQS5j
# cmwwQKA+oDyGOmh0dHA6Ly9jcmw0LmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydEhpZ2hB
# c3N1cmFuY2VFVlJvb3RDQS5jcmwwHQYDVR0OBBYEFJdIA+sVCGu5slgjzJQu8cZl
# 0mSOMB8GA1UdIwQYMBaAFLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEB
# BQUAA4IBAQCCBemFr6dMv6/OPbLqYLFo3mfC0ssm4MMvm7VrDlOQhfab4DUC//pp
# g6q0dDIUPC4QTCibCq0ICfnzhBGTj8tgQFbpdy9psoOZVatHJJbLf0uwELSXv8Sl
# mQb+juwUUB5eV5fLR7k02fw6ov9QKcIKYgTu3pY6b6DChQ9v/AjkMnvThK5pYAlG
# Jpzo8P//htnICTpmw6c2jxhP6LGWki5OvgunM5CuvG5P8X6NtEYOZPlZBiIhZABL
# 4noIA+e8iZCeQk8BwLYWf3XqRrKlVC+Mk80RNjRqKFfMlD/pfMgYAwMEfkPa+Zeh
# WUfaEqrgbTgAXTUrxSKGywbKvHpNPSZGMYIEODCCBDQCAQEwgYcwczELMAkGA1UE
# BhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3LmRpZ2lj
# ZXJ0LmNvbTEyMDAGA1UEAxMpRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2UgQ29kZSBT
# aWduaW5nIENBLTECEA5pBpjCFMh6tbYEuRY80ZAwCQYFKw4DAhoFAKB4MBgGCisG
# AQQBgjcCAQwxCjAIoAKAAKECgAAwGQYJKoZIhvcNAQkDMQwGCisGAQQBgjcCAQQw
# HAYKKwYBBAGCNwIBCzEOMAwGCisGAQQBgjcCARUwIwYJKoZIhvcNAQkEMRYEFPiX
# pwIkB3/2bW1OEputr5R6783fMA0GCSqGSIb3DQEBAQUABIIBAAPtJvZK1hsDyqw8
# IcPfF76/2UJL+eYQocJ4cRzW3Qzm7oaIe+Co/Wruxrz6wWGztKJIqG8mf/Yj9Eqt
# mlYyYQo2ra67G3OotFQZHI/KWe+HaYZx86czL9xv/pWpSvwecQsYD2YhM7Hi0Dfl
# wWtmOLJ0U+pedrQP8goXiXj70rBfFwl+yz7KkiPHrUANETbcfxUWt83INRJ/tgcq
# dV3h1vLfrPJPAw5YZ3SBD5n5NYfm790knKFHCnVCzjcgbpoeX0aVsBCUzs+orKkX
# zbNJOr0vG9B0vBqBBkwYkCFfurn9Bc24D9V/QCO7QpFdHL0MlRKq8O3D9meXGjNM
# vvp0IqahggILMIICBwYJKoZIhvcNAQkGMYIB+DCCAfQCAQEwcjBeMQswCQYDVQQG
# EwJVUzEdMBsGA1UEChMUU3ltYW50ZWMgQ29ycG9yYXRpb24xMDAuBgNVBAMTJ1N5
# bWFudGVjIFRpbWUgU3RhbXBpbmcgU2VydmljZXMgQ0EgLSBHMgIQDs/0OMj+vzVu
# BNhqmBsaUDAJBgUrDgMCGgUAoF0wGAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEHATAc
# BgkqhkiG9w0BCQUxDxcNMTMwMjAxMDY0ODQzWjAjBgkqhkiG9w0BCQQxFgQUm5wB
# DUFZvs+FwkJDoGcS62LO/lUwDQYJKoZIhvcNAQEBBQAEggEAXfq9dni7R3tT/jdw
# OfYO5EyK4BaR1GBy7q2tu280sZ+n4H6H88IEoIr4QokmyN2em3Dq8t4FQobzIG+n
# iW3Wg5GKD3Ijo9jcjz0CpvXVUqAq302BfhPxGKfVhhSlVOcOa1kCBfk/bQ8vFjYt
# O+LY7h/sa2t1MlrChcoSr3rcc5GUOFx2jTLnLXWLSpGVsOyaCnont5aM97HUmE8+
# NSYLET+4AIyJCTBVjL+6ERm7z9/ZqfTwy1pYcTnDJaV8ALqyjU/WVpMmlLFvPYnS
# ic/nKDE0HR7dOujxpMQsp816y1wWIZqWMOOMkUsz4SF9lJP31/ErE6EjaYIGQFQe
# KFsXtQ==
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Set-IPConfigv_1.ps1
|
Set-IPConfigv_1.ps1
|
# script parameters
param(
[Parameter(Position=0,ValueFromPipeline=$True)]
[ValidateNotNullorEmpty()][string[]] $Computers = $env:computername,
[switch] $ChangeSettings,
[switch] $EnableDHCP,
[switch] $IpRelease
)
# script variables
$nl = [Environment]::NewLine
$Domain = "domain.local"
$DNSSuffix = @("domain.local,domain.com") #split DNS setting
$DNSServers = @("10.10.0.1", "10.10.0.2", "10.10.0.3", "10.10.0.4")
$WINSServers = @("10.10.0.5", "10.10.0.6")
$Gateway = @("10.10.255.254")
# script functions
Function ProcessNIC($NIC, $Computer){
# Change settings for selected network card if option is true and show updated values
If ($ChangeSettings){
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")){
Write-Warning "You need Administrator rights to run this script!"
Break
}
If ($IpRelease){
#$NIC.ReleaseDHCPLease
$NIC.RenewDHCPLease
}
Else{
ChangeIPConfig $NIC $Computer
}
start-sleep -s 2
Write-Host $nl " ====NEW SETTINGS====" $nl
$UpdatedNIC = Get-WMIObject -Class Win32_NetworkAdapterConfiguration -Computername $Computer -Filter "Index=$($NIC.Index)"
Write-Output $(ShowDetails $UpdatedNIC $Computer)$($nl)
}
Else{
$nl
Write-Warning "For changing settings add -ChangeSettings as parameter, if not this script is output only"
$nl
}
}
Function ChangeIPConfig($NIC, $Computer){
if ($EnableDHCP){
$NIC.EnableDHCP()
$NIC.SetDNSServerSearchOrder()
}
else{
$DNSServers = Get-random $DNSservers -Count 4
$NIC.SetDNSServerSearchOrder($DNSServers) | Out-Null
#$x = 0
#$IPaddress = @()
#$NetMask = @()
#$Gateway = @()
#$Metric = @()
#foreach ($IP in $NIC.IPAddress){
#$IPaddress[$x] = $NIC.IPAddress[$x]
#$NetMask[$x] = $NIC.IPSubnet[$x]
#$Gateway[$x] = $NIC.DefaultIPGateway[$x]
#$Metric[$x] = $NIC.GatewayCostMetric[$x]
#$x++
#}
#$NIC.EnableStatic($IPaddress, $NetMask)
#$NIC.SetGateways($Gateway, $Metric)
#$NIC.SetWINSServer($WINSServers)
}
$NIC.SetDynamicDNSRegistration("TRUE") | Out-Null
$NIC.SetDNSDomain($Domain) | Out-Null
# remote WMI registry method for updating DNS Suffix SearchOrder
$registry = [WMIClass]"\\\\$computer\\root\\default:StdRegProv"
$HKLM = [UInt32] "0x80000002"
$registry.SetStringValue($HKLM, "SYSTEM\\CurrentControlSet\\Services\\TCPIP\\Parameters", "SearchList", $DNSSuffix) | Out-Null
}
Function ShowDetails($NIC, $Computer){
Write-Output "$($nl)$(" IP settings on: ")$($Computer.ToUpper())$($nl)$($nl)$(" for") $($NIC.Description)$(":")$($nl)"
Write-Output "$("Hostname = ")$($NIC.DNSHostName)"
Write-Output "$("DNSDomain= ")$($NIC.DNSDomain)"
Write-Output "$("Domain DNS Registration Enabled = ")$($NIC.DomainDNSRegistrationEnabled)"
Write-Output "$("Full DNS Registration Enabled = ")$($NIC.FullDNSRegistrationEnabled)"
Write-Output "$("DNS Domain Suffix Search Order = ")$($NIC.DNSDomainSuffixSearchOrder)"
Write-Output "$("MAC address = ")$($NIC.MACAddress)"
Write-Output "$("DHCP enabled = ")$($NIC.DHCPEnabled)"
# show all IP adresses on this NIC
$x = 0
foreach ($IP in $NIC.IPAddress){
Write-Output "$("IP address $x =")$($NIC.IPAddress[$x])$("/")$($NIC.IPSubnet[$x])"
$x++
}
Write-Output "$("Default IP Gateway = ")$($NIC.DefaultIPGateway)"
Write-Output "$("DNS Server Search Order = ")$($NIC.DNSServerSearchOrder)"
}
# actual script execution
foreach ($Computer in $Computers){
If (Test-connection $Computer -quiet -count 1){
Try {
[array]$NICs = Get-WMIObject -Class Win32_NetworkAdapterConfiguration -Computername $Computer -Filter "IPEnabled = TRUE" -EA Stop
}
Catch {
Write-Warning "$($error[0])"
Write-Output "$("INACCESIBLE: ")$($nl)$($Computer.ToUpper())"
Write-Host $nl
continue
}
# Generate selection menu
$NICindex = $NICs.count
Write-Host "$nl Selection for "$Computer.ToUpper() ": $nl"
For ($i=0;$i -lt $NICindex; $i++) {
Write-Host -ForegroundColor Green "$i --> $($NICs[$i].Description)"
Write-Output $(ShowDetails $NICs[$i] $Computer)
}
$nl
Write-Host -ForegroundColor Green "q --> Quit" $nl
# Wait for user selection input
Do {
$SelectIndex = Read-Host "Select connection by number or 'q' (=default) to quit"
Switch -regex ($SelectIndex){
"^q.*"{$SelectIndex="quit"; $kip = $true}
"\\d"{$SelectIndex = $SelectIndex -as [int];$kip = $false}
"^\\s*$"{$SelectIndex="quit"; $kip = $true}
}
}
Until (($SelectIndex -lt $NICindex) -OR $SelectIndex -like "q*")
$nl
Write-Host "You selected: $SelectIndex"
#skip current $computer if $true
If ($kip) {continue}
Else {ProcessNIC $NICs[$SelectIndex] $Computer}
}
}
|
PowerShellCorpus/PoshCode/CIM SMI-S Query Library.ps1
|
CIM SMI-S Query Library.ps1
|
function cim-ei {
<#
.SYNOPSIS
Enumerate Instances of a class on a CIMOM via CIM-XML interface
.DESCRIPTION
Primary use case of this function is to gather inventory and performance information from IT
infrastructure assets. The inventory information feeds into capacity planning, troubleshooting,
managing product life cycle, budgeting, vendor price negotiations and technology strategy in
large enterprise environments. The output from this function would typically go into a datawarehouse
front ended with a business intelligence platform such as COGNOS, QlikView, Business Objects, etc.
The function queries any CIM server, called CIMOM, that supports the CIM-XML interface. It
creates an XML message to encapsulate the CIM query, converts the message to byte stream and
then sends it using HTTP POST method. The response byte stream is converted back to XML message
and name value paris are parsed out. SMI-S is an instance of CIM, and is thus also fully supported.
Tested against SAN devices such as EMC Symmetrix VMAX Fibre Channel Storage Array and Cisco MDS
Fibre Channel switch. It can be used to query VMWARE vSphere vCenter, IBM XIV, NetApp Filer, EMC
VNX Storage Array, HP Insight Manager, Dell OpenManage, HDS: USP, USPV, VSP, AMS, etc.
.NOTES
Author: Parul Jain (paruljain@hotmail.com)
Version: 0.1, 14th April, 2012
Requires: PowerShell v2 or better
.EXAMPLE
cim-ei -Class CIM_ComputerSystem -Device switch1 -user admin -Pass securepass
.EXAMPLE
This works with EMC Symmetrix
cim-ei -Class CIM_ComputerSystem -Device seserver -user admin -Pass '#1Password' -ns 'root/emc'
.PARAMETER class
Mandatory. Information within CIM is classified into classes. The device documentation (or SNIA
documntation in case of SMI-S) should list all the classes supported by the CIMOM. CIM_ComputerSystem
class is available universally and is a good place to start testing.
.PARAMETER device
Mandatory. IP address or DNS name of the device or CIMOM server if CIMOM runs separately
.PARAMETER user
Mandatory. User ID authorized to perform queries. Most hardware vendors have a factory default
.PARAMETER pass
Mandatory. Password for the user. Again most hardware vendors have a factory default for servicing the equipment
.PARAMETER port
Optional. The TCP port number that the CIMOM is listening to. Default is used if not specified.
.PARAMETER ssl
Optional switch. When used function will use HTTPS instead of default HTTP
.PARAMETER ns
Optional. CIM namespace to use. Default is root/cimv2. EMC uses root/emc
.PARAMETER msg
Optional switch. Returns CIM-XML response message instead of parsed name-value pairs for
troubleshooting parsing if needed
.PARAMETER localOnly
Optional switch. LocalOnly and Deep (Inheritance) switches work together to define precisely the properties
that are to be returned. Properties from the specified class are always returned but properties from
subclasses and superclasses of the specified class can be included or excluded as required.
.PARAMETER deep
Optional switch. LocalOnly and Deep (Inheritance) switches work together to define precisely the properties
that are to be returned. Properties from the specified class are always returned but properties from
subclasses and superclasses of the specified class can be included or excluded as required.
.PARAMETER classOrigin
Optional switch. Specifies whether the name of the class in which the property or method was defined
(possibly a superclass of this one) should be included in the response.
.PARAMETER qualifiers
Optional switch. Specifies whether or not qualifiers for each instance and property are to be returned.
#>
[CmdletBinding()]
Param (
[parameter(Mandatory=$true, ValueFromPipeline=$true)][String]$Class,
[parameter(Mandatory=$true, ValueFromPipeline=$false)][String]$User,
[parameter(Mandatory=$true, ValueFromPipeline=$false)][String]$Pass,
[parameter(Mandatory=$true, ValueFromPipeline=$false)][String]$Device,
[parameter(Mandatory=$false, ValueFromPipeline=$false)][String]$Port = '',
[parameter(Mandatory=$false, ValueFromPipeline=$false)][Switch]$ssl,
[parameter(Mandatory=$false, ValueFromPipeline=$false)][String]$ns = 'root/cimv2',
[parameter(Mandatory=$false, ValueFromPipeline=$false)][Switch]$localOnly,
[parameter(Mandatory=$false, ValueFromPipeline=$false)][Switch]$classOrigin,
[parameter(Mandatory=$false, ValueFromPipeline=$false)][Switch]$deep,
[parameter(Mandatory=$false, ValueFromPipeline=$false)][Switch]$qualifiers,
[parameter(Mandatory=$false, ValueFromPipeline=$false)][Switch]$msg
)
# CIM-XML message template
$messageText = @'
<?xml version="1.0" encoding="utf-8" ?>
<CIM CIMVERSION="2.0" DTDVERSION="2.0">
<MESSAGE ID="1000" PROTOCOLVERSION="1.0">
<SIMPLEREQ>
<IMETHODCALL NAME="EnumerateInstances">
</IMETHODCALL>
</SIMPLEREQ>
</MESSAGE>
</CIM>
'@
# Parse the XML text into XMLDocument
$message = [xml]($messageText)
# Transform CIM-XML message based on supplied parameters
$nsPathNode = $message.cim.message.SIMPLEREQ.IMETHODCALL.AppendChild($message.CreateElement('LOCALNAMESPACEPATH'))
foreach ($path in $ns.split('/')) {
$pathElement = $nsPathNode.AppendChild($message.CreateElement('NAMESPACE'))
$pathElement.SetAttribute('NAME', $path)
}
$paramNode = $message.CIM.MESSAGE.SIMPLEREQ.IMETHODCALL
$param = $paramNode.AppendChild($message.CreateElement('IPARAMVALUE'))
$param.SetAttribute('NAME', 'ClassName')
$paramValue = $param.AppendChild($message.CreateElement('CLASSNAME'))
$paramValue.SetAttribute('NAME', $class)
$param = $paramNode.AppendChild($message.CreateElement('IPARAMVALUE'))
$param.SetAttribute('NAME', 'LocalOnly')
$paramValue = $param.AppendChild($message.CreateElement('VALUE'))
if ($localOnly) { $paramValue.InnerText = 'TRUE' } else { $paramValue.InnerText = 'FALSE' }
$param = $paramNode.AppendChild($message.CreateElement('IPARAMVALUE'))
$param.SetAttribute('NAME', 'IncludeClassOrigin')
$paramValue = $param.AppendChild($message.CreateElement('VALUE'))
if ($classOrigin) { $paramValue.InnerText = 'TRUE' } else { $paramValue.InnerText = 'FALSE' }
$param = $paramNode.AppendChild($message.CreateElement('IPARAMVALUE'))
$param.SetAttribute('NAME', 'DeepInheritance')
$paramValue = $param.AppendChild($message.CreateElement('VALUE'))
if ($deep) { $paramValue.InnerText = 'TRUE' } else { $paramValue.InnerText = 'FALSE' }
$param = $paramNode.AppendChild($message.CreateElement('IPARAMVALUE'))
$param.SetAttribute('NAME', 'IncludeQualifiers')
$paramValue = $param.AppendChild($message.CreateElement('VALUE'))
if ($qualifiers) { $paramValue.InnerText = 'TRUE' } else { $paramValue.InnerText = 'FALSE' }
# Do not validate server certificate when using HTTPS
# Amazing how easy it is to create a delegated function in PowerShell!
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
# Process other parameters and switches
$protocol = 'http://'
if ($ssl) { $protocol = 'https://' }
if ($port -eq '' -and !$ssl) { $port = '5988' }
if ($port -eq '' -and $ssl) { $port = '5989' }
$url = $protocol + $device + ":" + $port
# Instantiate .Net WebRequest class
$req = [System.Net.WebRequest]::Create($url + '/cimom')
$req.Method ='POST'
# Add headers required by CIMOM
$req.ContentType = 'application/xml;charset="UTF-8"'
$req.Headers.Add("CIMProtocolVersion", "1.0")
$req.Headers.Add('CIMOperation', 'MethodCall')
$req.Headers.Add('CIMMethod', 'EnumerateInstances')
$req.Headers.Add('CIMObject', $ns)
# Encode and attach userID and password
$uri = New-Object System.Uri($url)
$nc = New-Object System.Net.NetworkCredential($user, $pass)
$cc = New-Object System.Net.CredentialCache
$cc.add($uri, 'Basic', $nc)
$req.Credentials = $cc
$enc = New-Object System.Text.UTF8Encoding
$bytes = $enc.GetBytes($message.OuterXML)
$req.ContentLength = $bytes.Length
$reqStream = $req.GetRequestStream()
$reqStream.Write($bytes, 0, $bytes.Length)
$reqStream.Close()
# Send the request
try {
$resp = $req.GetResponse()
} catch [Net.WebException] { throw($_.Exception.Message) }
# Parse the response XML
$reader = new-object System.IO.StreamReader($resp.GetResponseStream())
$result = [xml]($reader.ReadToEnd())
$reader.Close()
# Create a temporary XML document to help parse out name value pairs
# There are several other ways this can be accomplished
$xdoc = new-object xml
$rootnode = $xdoc.AppendChild($xdoc.CreateElement($class))
foreach ($instance in @($result.CIM.MESSAGE.SIMPLERSP.IMETHODRESPONSE.IRETURNVALUE.'Value.NamedInstance')) {
$node = $rootnode.AppendChild($xDoc.CreateElement('Property'))
foreach ($prop in @($instance.instance.property)) {
if ($prop.value -ne $null -and $prop.value -ne '') {
$node.SetAttribute($prop.Name, $prop.value)
}
}
}
# Return CIM-XML response message or parsed out array of name value pairs
if ($msg) { $result } else { $xdoc.$class.property }
}
|
PowerShellCorpus/PoshCode/Patch-VMHost_1.ps1
|
Patch-VMHost_1.ps1
|
Add-PSSnapin "VMware.VimAutomation.Core"
Add-PSSnapIn "VMware.VumAutomation"
# Connect to vCenter
$VC = Connect-VIServer (Read-Host "Enter vCenter server")
$vumConfig = Get-VumConfig
$EsxHost = Get-Inventory -Name (Read-Host "Enter ESX Host")
$CriticalHost = Get-Baseline -Name "Critical Host Updates"
$NonCriticalHost = Get-Baseline -Name "Non-critical Host Updates"
# Enter Maintenance mode
Set-VMHost $EsxHost -State Maintenance
# Attach baseline
Attach-Baseline -Entity $EsxHost -Baseline $CriticalHost, $NonCriticalHost
# Check Compliance
$ScanTask = Scan-Inventory $EsxHost -RunAsync
Wait-Task -Task $ScanTask
Get-Compliance -Entity $EsxHost
# Remediate the ESX Host
$RemediateTask = Remediate-Inventory -Entity $EsxHost -Baseline $CriticalHost, $NonCriticalHost -HostFailureAction $vumConfig.HostFailureAction -Confirm:$false
Wait-Task -Task $RemediateTask
# Detach Baseline
Detach-Baseline -Baseline $CriticalHost, $NonCriticalHost -Entity $EsxHost
# Exit Mantenance mode
Set-VMHost $EsxHost -State Connected
# Disconnect from vCenter
Disconnect-VIServer -Confirm:$False
|
PowerShellCorpus/PoshCode/group-byobject_3.ps1
|
group-byobject_3.ps1
|
function Group-ByObject {
#.Synopsis
# Groups by a set of properties, returning objects
#.Description
# A wrapper for the built-in Group-Object cmdlet which returns one of the original objects (with separate properties for each property used to group) rather than a simple string representation as the "name" of the group. Optionally adds _count and _details properties which are the original Count and Group properties returned from group-object
#.Example
# Get-Process svchost | Group-ByObject Name, BasePriority -Count
#
# Groups Service Hosts by their BasePriority
#
#.Example
# Get-Process svchost | Group-ByObject Name, BasePriority -Details Id, WS -Count
#
# Groups Service Hosts by their BasePriority
#
#.Parameter InputObject
# The input objects are the items to be grouped
#.Parameter Property
# One or more properties to group on
#.Parameter Details
# One or more properties to collect as an array on the output
#.Parameters Group
# If set, forces all of the grouped items to be included in the _group property
#.Parameters Count
# If set, shows a count of all the grouped items on each group as the _count property
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true,Mandatory=$true)]
$InputObject
,
[Parameter(Position=0)]
[object[]]$Property
,
[Parameter(Position=1)]
[object[]]$Details
,
[Alias("All","SD")]
[switch]$Group
,
[switch]$Count
)
begin {
$InputItems = @()
$select = $property
if ($Count){ $select += @{ n="_count"; e={$group.count} } }
if ($Details){ foreach($d in $details) {
$select += @{ n="$d"; e=[ScriptBlock]::Create("`$group.group | Select -Expand '$d'")} } }
if ($Group){ $select += @{ n="_group"; e={$group.group} } }
}
process { $InputItems += $InputObject }
end {
foreach($group in $InputItems | Group-Object $property) {
$group.Group[0] | Select-Object $select
}
}
}
set-alias groupby group-byobject
set-alias grby group-byobject
|
PowerShellCorpus/PoshCode/fb0323a1-dc73-453e-975e-ec2b354c78d1.ps1
|
fb0323a1-dc73-453e-975e-ec2b354c78d1.ps1
|
# Glenn Sizemore ~ www . Get-Admin . Com
# Example Powershell function to get the NFS Exports from a NetApp Filer
# First you'll need to download the OnTap SDK 3.5 : http://communities.netapp.com/docs/DOC-1365
# within the download your interested in .\\manage-ontap-sdk-3.5\\lib\\DotNet\\ManageOntap.dll
# Next load the library...
# $Path = 'C:\\Users\\glnsize\\Downloads\\manage-ontap-sdk-3.5\\lib\\DotNet\\ManageOntap.dll'
# [Reflection.Assembly]::LoadFile($Path)
#
# Almost there next step create a NaServer connection object
# Here we are connecting to the NetApp Filer TOASTER1, and setting the api to V1.8
# $NaServer = New-Object NetApp.Manage.NaServer("TOASTER1",1,8)
# Call the setAdminUser Method and supply some credentials
# $NaServer.SetAdminUser('root', 'password')
#
# Now we're ready to go simply call the function passing your NAServer object as a parameter.
# Get-NaNfsExport -Server $NaServer
#
# Get-NaNfsExport -Server $NaServer -Path /vol/vol0
Function Get-NaNfsExport {
Param(
[NetApp.Manage.NaServer]
$Server,
[String]
$Path
)
Begin {
$out = @()
}
Process {
trap [NetApp.Manage.NaAuthException] {
# Example trap to catch bad credentials
Write-Error "Bad login/password".
break
}
#generate a new naelement request
$NaOut = New-Object NetApp.Manage.NaElement("nfs-exportfs-list-rules")
#if path or literalpath were supplied add them as parameters.
if ($Path) {
$NaOut.AddNewChild('pathname',$path)
}
# $NaServer.InvokeElem($NaOut) -> retrieve the results of the $NaOut request
# ..($NaOut).GetChildByName("rules") -> select the rules element from results
# ..GetChildByName("rules").getchildren() -> get any child elements under rules.
$NaResults = $Server.InvokeElem($NaOut).GetChildByName("rules").getchildren()
#ForEach NFS Rule returned, serialize the output into a PSObject.
foreach ($NaElement in $NaResults) {
$NaNFS = "" | Select-Object Path, ActualPath, ReadOnly, ReadWrite, Root, Security
$NaNFS.Path = $NaElement.GetChildContent("pathname")
# This is where the OnTap SDK can get a little nuts...
# if you perfer XML then simply try $NaElement.ToPrettyString('')
switch ($NaElement) {
# if Read-Only is present
{$_.GetChildByName("read-only")}
{
# Get all child elements
$ReadOnly = ($_.GetChildByName("read-only")).getchildren()
#Foreach elm in read-only
foreach ($read in $ReadOnly) {
# [bool] if exists "all-hosts"
If ($read.GetChildContent("all-hosts")) {
$roList = 'All-Hosts'
}
# Else get the name of the export!
Elseif ($read.GetChildContent("name")) {
$roList += $read.GetChildContent("name")
}
}
# add our new list to the output
$NaNFS.ReadOnly = $roList
}
# if Read-write is present
{$_.GetChildByName("read-write")}
{
$ReadWrite = ($_.GetChildByName("read-write")).getchildren()
foreach ($write in $ReadWrite) {
If ($write.GetChildContent("all-hosts")) {
$rwList = 'All-Hosts'
}
Elseif ($r.GetChildContent("name")) {
$rwList += $write.GetChildContent("name")
}
}
$NaNFS.ReadWrite = $rwList
}
# if root is present
{$_.GetChildByName("root")}
{
$Root = ($_.GetChildByName("root")).getchildren()
foreach ($r in $Root) {
If ($r.GetChildContent("all-hosts")) {
$rrList = 'All-Hosts'
}
Elseif ($r.GetChildContent("name")) {
$rrList += $r.GetChildContent("name")
}
}
$NaNFS.Root = $rrList
}
{$_.GetChildByName("sec-flavor")}
{
$Security = ($_.GetChildByName("sec-flavor")).getchildren()
foreach ($s in $Security) {
if ($r.GetChildContent("flavor")) {
$SecList += $r.GetChildContent("flavor")
}
}
$NaNFS.Security = $SecList
}
{$_.GetChildByName("actual-pathname")}
{
$NaNFS.ActualPath = $_.GetChildByName("actual-pathname")
}
}
$out += $NaNFS
}
}
End {
If ($Path) {
return $out | ?{$_.Path -match $Patch}
}
else {
return $out
}
}
}
|
PowerShellCorpus/PoshCode/target.local.ps1
|
target.local.ps1
|
#alias,addnewemailaddress
import-csv .\\source.csv | foreach {
$user = Get-Mailbox $_.alias
$user.emailAddresses+= $_.addnewemailaddress
$user.primarysmtpaddress = $_.addnewemailaddress
Set-Mailbox $user -emailAddresses $user.emailAddresses
set-Mailbox $user -PrimarySmtpAddress $user.primarysmtpaddress
}
|
PowerShellCorpus/PoshCode/Export-ScreenShot.ps1
|
Export-ScreenShot.ps1
|
## Export-Screenshot to take a screenshot and save it to disk
#####################################################################################
## Usage:
## Export-Screenshot sshot.png
## Export-Screenshot screen.jpg (New-Object Drawing.Rectangle 0, 0, 640, 480)
#####################################################################################
$null = [Reflection.Assembly]::LoadWithPartialName( "System.Windows.Forms" )
# Get a screenshot as a bitmap
function Get-Screenshot ([Drawing.Rectangle]$bounds) {
$screenshot = new-object Drawing.Bitmap $bounds.width, $bounds.height
$graphics = [Drawing.Graphics]::FromImage($screenshot)
# $bounds.Location.Offset(50,50)
$graphics.CopyFromScreen( $bounds.Location, [Drawing.Point]::Empty, $bounds.size)
$graphics.Dispose()
return $screenshot
}
# Save a screenshot to file
function Export-Screenshot {
PARAM (
[string]$FilePath,
[Drawing.Rectangle]$bounds = [Windows.Forms.SystemInformation]::VirtualScreen
)
write-host "FilePath: $($FilePath)" -fore green
# Fix paths, in case they don't set [Environment]::CurrentDirectory
if(!(split-path $FilePath).Length) {
$FilePath = join-path $pwd (split-path $FilePath -leaf)
Write-Host "FilePath: $($FilePath)" -fore magenta
}
write-host "FilePath: $($FilePath)" -fore cyan
$screenshot = Get-Screenshot $bounds
$screenshot.Save( $($FilePath) )
$screenshot.Dispose()
gci $FilePath
}
|
PowerShellCorpus/PoshCode/DHCP Backup_2.ps1
|
DHCP Backup_2.ps1
|
param (
[Parameter(Position=1)]
$searchBase = "cn=configuration,dc=domain,dc=com",
[Parameter(Position=2)]
$backupDestRoot = "\\\\network\\share\\"
)
Import-Module ActiveDirectory
function Get-OnlineDhcpServers {
param (
[Parameter(Mandatory=$true,Position=1)]
$dhcpSearchBase
)
$arrDhcpServers = Get-ADObject -SearchBase $dhcpSearchBase -Filter "objectclass -eq 'dhcpclass' -AND name -ne 'dhcproot'"
ForEach ($dhcpServer in $arrDhcpServers) {
if (!(Test-Connection -ComputerName $dhcpServer.name -Count 2 -Quiet -ErrorAction SilentlyContinue)) {
$arrDhcpServers = @($arrDhcpServers | Where-Object {$_.name -ne $dhcpServer.name})
}
}
return $arrDhcpServers
}
function Backup-DhcpServers {
param (
[Parameter(Mandatory=$true,Position=1)]
$arrDhcpBackupSrcNames,
[Parameter(Mandatory=$true,Position=2)]
$dhcpBackupDestRoot
)
ForEach ($dhcpBackupSrcName in $arrDhcpBackupSrcNames) {
$dhcpBackupSrc = "\\\\" + $dhcpBackupSrcName + "\\c$\\Windows\\System32\\Dhcp\\Backup"
$dhcpBackupDest = $dhcpBackupDestRoot + $dhcpBackupSrcName
if (Test-Path -Path $dhcpBackupSrc) {
Remove-Item -Path $dhcpBackupDest -Recurse -Force -Verbose
New-Item -Path $dhcpBackupDest -ItemType Directory
Copy-Item -Path $dhcpBackupSrc -Destination $dhcpBackupDest -Recurse -Verbose
}
}
}
$onlineDhcpServers = Get-OnlineDhcpServers -dhcpSearchBase $searchBase
$onlineDhcpServerNames = $onlineDhcpServers | ForEach-Object {$_.name.Split(".")[0]}
Backup-DhcpServers -arrDhcpBackupSrcNames $onlineDhcpServerNames -dhcpBackupDestRoot $backupDestRoot
|
PowerShellCorpus/PoshCode/TabExpansion_7.ps1
|
TabExpansion_7.ps1
|
## Tab-Completion
#################
## Please dot souce this script file.
## In first loading, it may take a several minutes, in order to generate ProgIDs and TypeNames list.
## Some features(relate to '$_' expansion) require the latest Get-PipelineObject.ps1 in a same diretory. (from http://poshcode.org/author/foobar)
##
## What this can do is:
##
## [datetime]::n<tab>
## [datetime]::now.d<tab>
## $a = New-Object "Int32[,]" 2,3; $b = "PowerShell","PowerShell"
## $c = [ref]$a; $d = [ref]$b,$c
## $d[0].V<tab>[0][0].Get<tab>
## $d[1].V<tab>[0,0].tos<tab>
## $function:a<tab>
## $env:a<tab>
## [System.Type].a<tab>
## [datetime].Assembly.a<tab>
## ).a<tab> # shows System.Type properties and methods...
## #native command name expansion
## fsu<tab>
## #command option name expansion (for fsutil ipconfig net powershell only)
## fsutil <tab>
## ipconfig <tab>
## net <tab>
## powershell <tab>
## #TypeNames expansion
## [Dec<tab>
## [Microsoft.PowerShell.Com<tab>
## New-Object -TypeName IO.Dir<tab>
## New-Object System.Management.Auto<tab>
## #ProgIDs expansion
## New-Object -Com shel<tab>
## #Enum option expansion
## Set-ExecutionPolicy <tab>
## Set-ExecutionPolicy All<tab>
## Set-ExcusionPolisy -ex <tab>
## Get-TraceSource Inte<tab>
## iex -Errora <tab> -wa Sil<tab>
## #WmiClasses expansion
## Get-WmiObject -class Win32_<tab>
## gwmi __Instance<tab>
## #Encoding expansion
## [Out-File | Export-CSV | Select-String | Export-Clixml] -enc <tab>
## [Add-Content | Get-Content | Set-Content} -Encoding Big<tab>
## #PSProvider name expansion
## [Get-Location | Get-PSDrive | Get-PSProvider | New-PSDrive | Remove-PSDrive] -PSProvider <tab>
## Get-PSProvider <tab>
## pwd -psp al<tab>
## #PSDrive name expansion
## [Get-PSDrive | New-PSDrive | Remove-PSDrive] [-Name] <tab>
## Get-PSDrive <tab>
## pwd -psd <tab>
## #PSSnapin name expansion
## [Add-PSSnapin | Get-PSSnapin | Remove-PSSnapin ] [-Name] <tab>
## Get-Command -PSSnapin <tab>
## Remove-PSSnapin <tab>
## Get-PSSnapin M<tab>
## #Eventlog name and expansion
## Get-Eventlog -Log <tab>
## Get-Eventlog w<tab>
## #Eventlog's entrytype expansion
## Get-EventLog -EntryType <tab>
## Get-EventLog -EntryType Er<tab>
## Get-EventLog -Ent <tab>
## #Service name expansion
## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-Name] <tab>
## New-Service -DependsOn <tab>
## New-Service -Dep e<tab>
## Get-Service -n <tab>
## Get-Service <tab>,a<tab>,p<tab>
## gsv <tab>
## #Service display name expansion
## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-DisplayName] <tab>
## Get-Service -Dis <tab>
## gsv -Dis <tab>,w<tab>,b<tab>
## #Cmdlet and Topic name expansion
## Get-Help [-Name] about_<tab>
## Get-Help <tab>
## #Category name expansion
## Get-Help -Category c<tab>,<tab>
## #Command name expansion
## Get-Command [-Name] <tab>
## Get-Command -Name <tab>
## gcm a<tab>,<tab>
## #Scope expansion
## [Clear-Variable | Export-Alias | Get-Alias | Get-PSDrive | Get-Variable | Import-Alias
## New-Alias | New-PSDrive | New-Variable | Remove-Variable | Set-Alias | Set-Variable] -Scope <tab>
## Clear-Variable -Scope G<tab>
## Set-Alias -s <tab>
## #Process name expansion
## [Get-Process | Stop-Process] [-Name] <tab>
## Stop-Process -Name <tab>
## Stop-Process -N pow<tab>
## Get-Process <tab>
## ps power<tab>
## #Trace sources expansion
## [Trace-Command | Get-TraceSource | Set-TraceSource] [-Name] <tab>,a<tab>,p<tab>
## #Trace -ListenerOption expansion
## [Set-TraceSource | Trace-Command] -ListenerOption <tab>
## Set-TraceSource -Lis <tab>,n<tab>
## #Trace -Option expansion
## [Set-TraceSource | Trace-Command] -Option <tab>
## Set-TraceSource -op <tab>,con<tab>
## #ItemType expansion
## New-Item -Item <tab>
## ni -ItemType d<tab>
## #ErrorAction and WarningAction option expansion
## CMDLET [-ErrorAction | -WarningAction] <tab>
## CMDLET -Errora s<tab>
## CMDLET -ea con<tab>
## CMDLET -wa <tab>
## #Continuous expansion with comma when parameter can treat multiple option
## # if there are spaces, occur display bug in the line
## # if strings contains '$' or '-', not work
## Get-Command -CommandType <tab>,<tab><tab>,cm<tab>
## pwd -psp <tab>,f<tab>,va<tab>
## Get-EventLog -EntryType <tab>,i<tab>,s<tab>
## #Enum expansion in method call expression
## # this needs one or more spaces after left parenthesis or comma
## $str = "day night"
## $str.Split( " ",<space>rem<tab>
## >>> $str.Split( " ", "RemoveEmptyEntries" ) <Enter> ERROR
## $str.Split( " ", "RemoveEmptyEntries" -as<space><tab>
## >>> $str.Split( " ", "RemoveEmptyEntries" -as [System.StringSplitOptions] ) <Enter> Success
## $type = [System.Type]
## $type.GetMembers(<space>Def<tab>
## [IO.Directory]::GetFiles( "C:\\", "*",<space>All<tab>
## # this can do continuous enum expansion with comma and no spaces
## $type.GetMembers( "IgnoreCase<comma>Dec<tab><comma>In<tab>"
## [IO.Directory]::GetAccessControl( "C:\\",<space>au<tab><comma>ac<tab><comma>G<tab>
## #Better '$_.' expansion when cmdlet output objects or method return objects
## ls |group { $_.Cr<tab>.Tost<tab>"y")} | tee -var foo| ? { $_.G<tab>.c<tab> -gt 5 } | % { md $_.N<tab> ; copy $_.G<tab> $_.N<tab> }
## [IO.DriveInfo]::GetDrives() | ? { $_.A<tab> -gt 1GB }
## $Host.UI.RawUI.GetBufferContents($rect) | % { $str += $_.c<tab> }
## gcm Add-Content |select -exp Par<tab>| select -ExpandProperty Par<tab> | ? { $_.Par<tab>.N<tab> -eq "string" }
## $data = Get-Process
## $data[2,4,5] | % { $_.<tab>
## #when Get-PipeLineObject failed, '$_.' shows methods and properties name of FileInfo and String and Type
## #Property name expansion by -Property parameter
## [ Format-List | Format-Custom | Format-Table | Format-Wide | Compare-Object |
## ConvertTo-Html | Measure-Object | Select-Object | Group-Object | Sort-Object ] [-Property] <tab>
## Select-Object -ExcludeProperty <tab>
## Select-Object -ExpandProperty <tab>
## gcm Get-Acl|select -exp Par<tab>
## ps |group na<tab>
## ls | ft A<tab>,M<tab>,L<tab>
## #Hashtable key expansion in the variable name and '.<tab>'
## Get-Process | Get-Unique | % { $hash += @{$_.ProcessName=$_} }
## $hash.pow<tab>.pro<tab>
## #Parameter expansion for function, filter and script
## man -f<tab>
## 'param([System.StringSplitOptions]$foo,[System.Management.Automation.ActionPreference]$bar,[System.Management.Automation.CommandTypes]$baz) {}' > foobar.ps1
## .\\foobar.ps1 -<tab> -b<tab>
## #Enum expansion for function, filter and scripts
## # this can do continuous enum expansion with comma and no spaces
## .\\foobar.ps1 -foo rem<tab> -bar <tab><comma>c<tab><comma>sc<tab> -ea silent<tab> -wa con<tab>
## #Enum expansion for assignment expression
## #needs space(s) after '=' and comma
## #strongly-typed with -as operator and space(s)
## $ErrorActionPreference =<space><tab>
## $cmdtypes = New-Object System.Management.Automation.CommandTypes[] 3
## $cmdtypes =<space><tab><comma><space>func<tab><comma><space>cmd<tab> -as<space><tab>
## #Path expansion with variable and '\\' or '/'
## $PWD\\../../<tab>\\<tab>
## "$env:SystemDrive/pro<tab>/<tab>
## #Operator expansion which starts with '-'
## "Power","Shell" -m<tab> "Power" -r<tab> '(Pow)(er)','$1d$2'
## 1..9 -co<tab> 5
## #Keyword expansion
## fu<tab> test { p<tab> $foo, $bar ) b<tab> "foo" } pr<tab> $_ } en<tab> "$bar" } }
## #Variable name expansion (only global scope)
## [Clear-Variable | Get-Variable | New-Variable | Remove-Variable | Set-Variable] [-Name] <tab>
## [Cmdlet | Function | Filter | ExternalScript] -ErrorVariable <tab>
## [Cmdlet | Function | Filter | ExternalScript] -OutVariable <tab>
## Tee-Object -Variable <tab>
## gv pro<tab>,<tab>
## Remove-Variable -Name out<tab>,<tab>,ps<tab>
## ... | ... | tee -v <tab>
## #Alias name expansion
## [Get-Alias | New-Alias | Set-Alias] [-Name] <tab>
## Export-Alias -Name <tab>
## Get-Alias i<tab>,e<tab>,a<tab>
## epal -n for<tab>
## #Property name expansion with -groupBy parameter
## [Format-List | Format-Custom | Format-Table | Format-Wide] -groupBy <tab>
## ps | ft -g <tab>
## gcm | Format-Wide -GroupBy Par<tab>
### Generate ProgIDs list...
if ($_ProgID -eq $null) {
$_HKCR = [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\")
[Object[]] $_ProgID = $null
foreach ( $_subkey in $_HKCR.GetSubKeyNames() )
{
foreach ( $_i in [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\$_subkey\\ProgID") )
{
if ($_i -ne $null)
{
$_ProgID += $_i.GetValue("")
}
}
}
'$_ProgID was updated...' | Out-Host
$_ProgID = $_ProgID|sort -Unique
Set-Content -Value $_ProgID -Path $PSHOME\\ProgIDs.txt
Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_ProgID = Get-Content -Path C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\ProgIDs.txt;'
}
### Generate TypeNames list...
if ( $_TypeNames -eq $null ) {
[Object[]] $_TypeNames = $null
foreach ( $_asm in [AppDomain]::CurrentDomain.GetAssemblies() )
{
foreach ( $_type in $_asm.GetTypes() )
{
$_TypeNames += $_type.FullName
}
}
'$_TypeNames was updated...' | Out-Host
$_TypeNames = $_TypeNames | sort -Unique
Set-Content -Value $_TypeNames -Path $PSHOME\\TypeNames.txt
Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_TypeNames = Get-Content -Path $PSHOME\\TypeNames.txt;'
}
if ( $_TypeNames_System -eq $null ) {
[Object[]] $_TypeNames_System = $null
foreach ( $_type in $_TypeNames -like "System.*" )
{
$_TypeNames_System += $_type.Substring(7)
}
'$_TypeNames_System was updated...' | Out-Host
Set-Content -Value $_TypeNames_System -Path $PSHOME\\TypeNames_System.txt
Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_TypeNames_System = Get-Content -Path $PSHOME\\TypeNames_System.txt;'
}
### Generate WMIClasses list...
if ( $_WMIClasses -eq $null ) {
[Object[]] $_WMIClasses = $null
foreach ( $_class in gwmi -List )
{
$_WMIClasses += $_class.Name
}
$_WMIClasses = $_WMIClasses | sort -Unique
'$_WMIClasses was updated...' | Out-Host
Set-Content -Value $_WMIClasses -Path $PSHOME\\WMIClasses.txt
Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_WMIClasses = Get-Content -Path $PSHOME\\WMIClasses.txt;'
}
$global:_snapin = $null
# Load Get-PipeLineObject function for $_ and property name expansion.
$_scriptpath = gi $MyInvocation.MyCommand.Path
iex (". " + (Join-Path $_scriptpath.DirectoryName "Get-PipeLineObject.ps1"))
function TabExpansion {
param($line, $lastWord)
& {
# Helper function to write out the matching set of members. It depends
# on dynamic scoping to get $_base, _$expression and $_pat
function Write-Members ($sep='.')
{
# evaluate the expression to get the object to examine...
Invoke-Expression ('$_val=' + $_expression)
if ( $_expression -match '^\\$global:_dummy' )
{
$temp = $_expression -replace '^\\$global:_dummy(.*)','$1'
$_expression = '$_' + $temp
}
$_method = [Management.Automation.PSMemberTypes] `
'Method,CodeMethod,ScriptMethod,ParameterizedProperty'
if ($sep -eq '.')
{
$members =
(
[Object[]](Get-Member -InputObject $_val.PSextended $_pat) +
[Object[]](Get-Member -InputObject $_val.PSadapted $_pat) +
[Object[]](Get-Member -InputObject $_val.PSbase $_pat)
)
if ( $_val -is [Hashtable] )
{
[Microsoft.PowerShell.Commands.MemberDefinition[]]$_keys = $null
foreach ( $_name in $_val.Keys )
{
$_keys += `
New-Object Microsoft.PowerShell.Commands.MemberDefinition `
[int],$_name,"Property",0
}
$members += [Object[]]$_keys | ? { $_.Name -like $_pat }
}
foreach ($_m in $members | sort membertype,name -Unique)
{
if ($_m.MemberType -band $_method)
{
# Return a method...
$_base + $_expression + $sep + $_m.name + '('
}
else {
# Return a property...
$_base + $_expression + $sep + $_m.name
}
}
}
else
{
foreach ($_m in Get-Member -Static -InputObject $_val $_pat |
Sort-Object membertype,name)
{
if ($_m.MemberType -band $_method)
{
# Return a method...
$_base + $_expression + $sep + $_m.name + '('
}
else {
# Return a property...
$_base + $_expression + $sep + $_m.name
}
}
}
}
switch -regex ($lastWord)
{
# Handle property and method expansion at '$_'
'(^.*)(\\$_\\.)(\\w*)$' {
$_base = $matches[1]
$_expression = '$global:_dummy'
$_pat = $matches[3] + '*'
$global:_dummy = $null
Get-PipeLineObject
if ( $global:_dummy -eq $null )
{
if ( $global:_exp -match '^\\$.*\\(.*$' )
{
$type = ( iex $_exp.Split("(")[0] ).OverloadDefinitions[0].Split(" ")[0] -replace '\\[[^\\[\\]]*\\]$' -as [type]
if ( $_expression -match '^\\$global:_dummy' )
{
$temp = $_expression -replace '^\\$global:_dummy(.*)','$1'
$_expression = '$_' + $temp
}
foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } )
{
if ($_m.MemberType -eq "Method")
{
$_base + $_expression + '.' + $_m.name + '('
}
else {
$_base + $_expression + '.' + $_m.name
}
}
break;
}
elseif ( $global:_exp -match '^\\[.*\\:\\:.*\\(.*$' )
{
$tname, $mname = $_exp.Split(":(", "RemoveEmptyEntries"-as [System.StringSplitOptions])[0,1]
$type = @(iex ($tname + '.GetMember("' + $mname + '")'))[0].ReturnType.FullName -replace '\\[[^\\[\\]]*\\]$' -as [type]
if ( $_expression -match '^\\$global:_dummy' )
{
$temp = $_expression -replace '^\\$global:_dummy(.*)','$1'
$_expression = '$_' + $temp
}
foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } )
{
if ($_m.MemberType -eq "Method")
{
$_base + $_expression + '.' + $_m.name + '('
}
else {
$_base + $_expression + '.' + $_m.name
}
}
break;
}
elseif ( $global:_exp -match '^(\\$\\w+(\\[[0-9,\\.]+\\])*(\\.\\w+(\\[[0-9,\\.]+\\])*)*)$' )
{
$global:_dummy = @(iex $Matches[1])[0]
}
else
{
$global:_dummy = $global:_mix
}
}
Write-Members
break;
}
# Handle property and method expansion rooted at variables...
# e.g. $a.b.<tab>
'(^.*)(\\$(\\w|\\.)+)\\.(\\w*)$' {
$_base = $matches[1]
$_expression = $matches[2]
[void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock]
$_pat = $matches[4] + '*'
if ( $_expression -match '^\\$_\\.' )
{
$_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1')
}
Write-Members
break;
}
# Handle simple property and method expansion on static members...
# e.g. [datetime]::n<tab>
'(^.*)(\\[(\\w|\\.)+\\])\\:\\:(\\w*)$' {
$_base = $matches[1]
$_expression = $matches[2]
$_pat = $matches[4] + '*'
Write-Members '::'
break;
}
# Handle complex property and method expansion on static members
# where there are intermediate properties...
# e.g. [datetime]::now.d<tab>
'(^.*)(\\[(\\w|\\.)+\\]\\:\\:(\\w+\\.)+)(\\w*)$' {
$_base = $matches[1] # everything before the expression
$_expression = $matches[2].TrimEnd('.') # expression less trailing '.'
$_pat = $matches[5] + '*' # the member to look for...
Write-Members
break;
}
# Handle variable name expansion...
'(^.*\\$)(\\w+)$' {
$_prefix = $matches[1]
$_varName = $matches[2]
foreach ($_v in Get-ChildItem ('variable:' + $_varName + '*'))
{
$_prefix + $_v.name
}
break;
}
# Handle env&function drives variable name expansion...
'(^.*\\$)(.*\\:)(\\w+)$' {
$_prefix = $matches[1]
$_drive = $matches[2]
$_varName = $matches[3]
if ($_drive -eq "env:" -or $_drive -eq "function:")
{
foreach ($_v in Get-ChildItem ($_drive + $_varName + '*'))
{
$_prefix + $_drive + $_v.name
}
}
break;
}
# Handle array's element property and method expansion
# where there are intermediate properties...
# e.g. foo[0].n.b<tab>
'(^.*)(\\$((\\w+\\.)|(\\w+(\\[(\\w|,)+\\])+\\.))+)(\\w*)$'
{
$_base = $matches[1]
$_expression = $matches[2].TrimEnd('.')
$_pat = $Matches[8] + '*'
[void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock]
if ( $_expression -match '^\\$_\\.' )
{
$_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1')
}
Write-Members
break;
}
# Handle property and method expansion rooted at type object...
# e.g. [System.Type].a<tab>
'(^\\[(\\w|\\.)+\\])\\.(\\w*)$'
{
if ( $(iex $Matches[1]) -isnot [System.Type] ) { break; }
$_expression = $Matches[1]
$_pat = $Matches[$matches.Count-1] + '*'
Write-Members
break;
}
# Handle complex property and method expansion on type object members
# where there are intermediate properties...
# e.g. [datetime].Assembly.a<tab>
'^(\\[(\\w|\\.)+\\]\\.(\\w+\\.)+)(\\w*)$' {
$_expression = $matches[1].TrimEnd('.') # expression less trailing '.'
$_pat = $matches[4] + '*' # the member to look for...
if ( $(iex $_expression) -eq $null ) { break; }
Write-Members
break;
}
# Handle property and method expansion rooted at close parenthes...
# e.g. (123).a<tab>
'^(.*)\\)((\\w|\\.)*)\\.(\\w*)$' {
$_base = $Matches[1] + ")"
if ( $matches[3] -eq $null) { $_expression = '[System.Type]' }
else { $_expression = '[System.Type]' + $Matches[2] }
$_pat = $matches[4] + '*'
iex "$_expression | Get-Member $_pat | sort MemberType,Name" |
% {
if ( $_.MemberType -like "*Method*" -or $_.MemberType -like "*Parameterized*" ) { $parenthes = "(" }
if ( $Matches[2] -eq "" ) { $_base + "." + $_.Name + $parenthes }
else { $_base + $Matches[2] + "." + $_.Name + $parenthes }
}
break;
}
# Handle .NET type name expansion ...
# e.g. [Microsoft.PowerShell.Com<tab>
'^\\[((\\w+\\.?)+)$' {
$_opt = $matches[1] + '*'
foreach ( $_exp in $_TypeNames_System -like $_opt )
{
'[' + $_exp
}
foreach ( $_exp in $_TypeNames -like $_opt )
{
'[' + $_exp
}
break;
}
# Handle file/directory name which contains $env: variable
# e.g. $env:windir\\<tab>
'^\\$(env:)?\\w+([\\\\/][^\\\\/]*)*$' {
$path = iex ('"' + $Matches[0] + '"')
if ( $Matches[2].Length -gt 1 )
{
$parent = Split-Path $path -Parent
$leaf = (Split-Path $path -Leaf) + '*'
}
else
{
$parent = $path
$leaf = '*'
}
if ( Test-Path $parent )
{
$i = $Matches[0].LastIndexOfAny("/\\")
$_base = $Matches[0].Substring(0,$i+1)
[IO.Directory]::GetFileSystemEntries( $parent, $leaf ) | % { $_base + ($_.Split("\\/")[-1] -replace '([\\$\\s&])','`$1' -replace '([[\\]])', '````$1') }
}
}
# Do completion on parameters...
'^-([\\w0-9]*)' {
$_pat = $matches[1] + '*'
$_cmdlet = [regex]::Split($line, '[|;=]')[-1]
if ($_cmdlet -match '\\{([^\\{\\}]*)$')
{
$_cmdlet = $matches[1]
}
if ($_cmdlet -match '\\(([^()]*)$')
{
$_cmdlet = $matches[1]
}
$_cmdlet = $_cmdlet.Trim().Split()[0]
$_cmdlet = @(Get-Command -type 'cmdlet,alias,function,filter,ExternalScript' $_cmdlet)[0]
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias,function,filter,ExternalScript' $_cmdlet.Definition)[0]
}
if ( $_cmdlet.CommandType -eq "Cmdlet" )
{
foreach ($_n in $_cmdlet.ParameterSets |
Select-Object -expand parameters | Sort-Object -Unique name)
{
$_n = $_n.name
if ($_n -like $_pat) { '-' + $_n }
}
break;
}
elseif ( "ExternalScript", "Function", "Filter" -contains $_cmdlet.CommandType )
{
if ( $_cmdlet.CommandType -eq "ExternalScript" )
{
$_fsr = New-Object IO.StreamReader $_cmdlet.Definition
$_def = "Function _Dummy { $($_fsr.ReadToEnd()) }"
$_fsr.Close()
iex $_def
$_cmdlet = "_Dummy"
}
if ( ((gi "Function:$_cmdlet").Definition -replace '\\n').Split("{")[0] -match 'param\\((.*\\))\\s*[;\\.&a-zA-Z]*\\s*$' )
{
( ( ( $Matches[1].Split('$', "RemoveEmptyEntries" -as [System.StringSplitOptions]) -replace `
'^(\\w+)(.*)','$1' ) -notmatch '^\\s+$' ) -notmatch '^\\s*\\[.*\\]\\s*$' ) -like $_pat | sort | % { '-' + $_ }
}
break;
}
elseif ( $_command -eq $null )
{
"-and", "-as", "-band", "-bnot", "-bor", "-bxor", "-ccontains", "-ceq", "-cge", "-cgt", "-cle", "-clike", "-clt",
"-cmatch", "-cne", "-cnotcontains", "-cnotlike", "-cnotmatch", "-contains", "-creplace", "-csplit", "-eq", "-f", "-ge",
"-gt", "-icontains", "-ieq", "-ige", "-igt", "-ile", "-ilike", "-ilt", "-imatch", "-ine", "-inotcontains", "-inotlike",
"-inotmatch", "-ireplace", "-is", "-isnot", "-isplit", "-join", "-le", "-like", "-lt", "-match", "-ne", "-not", "-notcontains",
"-notlike", "-notmatch", "-or", "-replace", "-split", "-xor" -like "-$_pat"
}
break;
}
# try to find a matching command...
default {
$lastex = [regex]::Split($line, '[|;]')[-1]
if ( $lastex -match '^\\s*(\\$\\w+(\\[[0-9,]+\\])*(\\.\\w+(\\[[0-9,]+\\])*)*)\\s*=\\s+(("\\w+"\\s*,\\s+)*)"\\w+"\\s*-as\\s+$' )
{
if ( $Matches[6] -ne $nul )
{
$brackets = "[]"
}
'['+ $global:_enum + $brackets + ']'
break;
}
if ( $lastex -match '^\\s*(\\$\\w+(\\[[0-9,]+\\])*(\\.\\w+(\\[[0-9,]+\\])*)*)\\s*=\\s+(("\\w+"\\s*,\\s+)*)\\s*(\\w*)$' )
{
$_pat = $Matches[7] + '*'
$_type = @(iex $Matches[1])[0].GetType()
if ( $_type.IsEnum )
{
$global:_enum = $_type.FullName
[Enum]::GetValues($_type) -like $_pat -replace '^(.*)$','"$1"'
break;
}
}
$lastex = [regex]::Split($line, '[|;=]')[-1]
if ($lastex -match '[[$].*\\w+\\(.*-as\\s*$')
{
'['+ $global:_enum + ']'
}
elseif ( $lastex -match '([[$].*(\\w+))\\((.*)$' )
#elseif ( $lastex -match '([[$].*(\\w+))\\(([^)]*)$' )
{
$_method = $Matches[1]
if ( $Matches[3] -match "(.*)((`"|')(\\w+,)+(\\w*))$" )
{
$continuous = $true
$_opt = $Matches[5] + '*'
$_base = $Matches[2].TrimStart('"') -replace '(.*,)\\w+$','$1'
$position = $Matches[1].Split(",").Length
}
else
{
$continuous = $false
$_opt = ($Matches[3].Split(',')[-1] -replace '^\\s*','') + "*"
$position = $Matches[3].Split(",").Length
}
if ( ($_mdefs = iex ($_method + ".OverloadDefinitions")) -eq $null )
{
$tname, $mname = $_method.Split(":", "RemoveEmptyEntries" -as [System.StringSplitOptions])
$_mdefs = iex ($tname + '.GetMember("' + $mname + '") | % { $_.ToString() }')
}
foreach ( $def in $_mdefs )
{
[void] ($def -match '\\((.*)\\)')
foreach ( $param in [regex]::Split($Matches[1], ', ')[$position-1] )
{
if ($param -eq $null -or $param -eq "")
{
continue;
}
$type = $param.split()[0]
if ( $type -like '*`[*' -or $type -eq "Params" -or $type -eq "" )
{
continue;
}
$fullname = @($_typenames -like "*$type*")
foreach ( $name in $fullname )
{
if ( $continuous -eq $true -and ( $name -as [System.Type] ).IsEnum )
{
$output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$',($_base + '$1')
$output | sort
}
elseif ( ( $name -as [System.Type] ).IsEnum )
{
$global:_enum = $name
$output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$','"$1"'
$output | sort
}
}
}
}
if ( $output -ne $null )
{
break;
}
}
if ( $line[-1] -eq " " )
{
$_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-1]
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0]
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0]
}
if ( "Set-ExecutionPolicy" -eq $_cmdlet.Name )
{
"Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" | sort
break;
}
if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name )
{
Get-TraceSource | % { $_.Name } | sort -Unique
break;
}
if ( "New-Object" -eq $_cmdlet.Name )
{
$_TypeNames_System
$_TypeNames
break;
}
if ( $_cmdlet.Noun -like "*WMI*" )
{
$_WMIClasses
break;
}
if ( "Get-Process" -eq $_cmdlet.Name )
{
Get-Process | % { $_.Name } | sort
break;
}
if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name )
{
if ( $global:_snapin -ne $null )
{
$global:_snapin
break;
}
else
{
$global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique;
$global:_snapin
break;
}
}
if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" `
-contains $_cmdlet.Name -and "Name" )
{
Get-PSDrive | sort
break;
}
if ( "Get-Eventlog" -eq $_cmdlet.Name )
{
Get-EventLog -List | % { $_base + ($_.Log -replace '\\s','` ') }
break;
}
if ( "Get-Help" -eq $_cmdlet.Name )
{
Get-Help -Category all | % { $_.Name } | sort -Unique
break;
}
if ( "Get-Service", "Restart-Service", "Resume-Service",
"Start-Service", "Stop-Service", "Suspend-Service" `
-contains $_cmdlet.Name )
{
Get-Service | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Get-Command" -eq $_cmdlet.Name )
{
Get-Command -CommandType All | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object",
"ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" `
-contains $_cmdlet.Name )
{
Get-PipeLineObject
$_dummy | Get-Member -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name )
{
Get-Variable -Scope Global | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name )
{
Get-Alias | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
}
if ( $line[-1] -eq " " )
{
$_cmdlet = [regex]::Split($line, '[|;=]')[-1]
if ($_cmdlet -match '\\{([^\\{\\}]*)$')
{
$_cmdlet = $matches[1]
}
if ($_cmdlet -match '\\(([^()]*)$')
{
$_cmdlet = $matches[1]
}
$_cmdlet = $_cmdlet.Trim().Split()[0]
$_cmdlet = @(Get-Command -type 'Application' $_cmdlet)[0]
if ( $_cmdlet.Name -eq "powershell.exe" )
{
"-PSConsoleFile", "-Version", "-NoLogo", "-NoExit", "-Sta", "-NoProfile", "-NonInteractive",
"-InputFormat", "-OutputFormat", "-EncodedCommand", "-File", "-Command" | sort
break;
}
if ( $_cmdlet.Name -eq "fsutil.exe" )
{
"behavior query", "behavior set", "dirty query", "dirty set",
"file findbysid", "file queryallocranges", "file setshortname", "file setvaliddata", "file setzerodata", "file createnew",
"fsinfo drives", "fsinfo drivetype", "fsinfo volumeinfo", "fsinfo ntfsinfo", "fsinfo statistics",
"hardlink create", "objectid query", "objectid set", "objectid delete", "objectid create",
"quota disable", "quota track", "quota enforce", "quota violations", "quota modify", "quota query",
"reparsepoint query", "reparsepoint delete", "sparse setflag", "sparse queryflag", "sparse queryrange", "sparse setrange",
"usn createjournal", "usn deletejournal", "usn enumdata", "usn queryjournal", "usn readdata", "volume dismount", "volume diskfree" | sort
break;
}
if ( $_cmdlet.Name -eq "net.exe" )
{
"ACCOUNTS ", " COMPUTER ", " CONFIG ", " CONTINUE ", " FILE ", " GROUP ", " HELP ",
"HELPMSG ", " LOCALGROUP ", " NAME ", " PAUSE ", " PRINT ", " SEND ", " SESSION ",
"SHARE ", " START ", " STATISTICS ", " STOP ", " TIME ", " USE ", " USER ", " VIEW" | sort
break;
}
if ( $_cmdlet.Name -eq "ipconfig.exe" )
{
"/?", "/all", "/renew", "/release", "/flushdns", "/displaydns",
"/registerdns", "/showclassid", "/setclassid"
break;
}
}
if ( $line -match '\\w+\\s+(\\w+(\\.|[^\\s\\.])*)$' )
{
$_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-2]
$_opt = $Matches[1].Split(" ,")[-1] + '*'
$_base = $Matches[1].Substring(0,$Matches[1].Length-$Matches[1].Split(" ,")[-1].length)
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0]
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0]
}
if ( "Set-ExecutionPolicy" -eq $_cmdlet.Name )
{
"Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" -like $_opt | sort
break;
}
if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name )
{
Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "New-Object" -eq $_cmdlet.Name )
{
$_TypeNames_System -like $_opt
$_TypeNames -like $_opt
break;
}
if ( $_cmdlet.Name -like "*WMI*" )
{
$_WMIClasses -like $_opt
break;
}
if ( "Get-Process" -eq $_cmdlet.Name )
{
Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name )
{
if ( $global:_snapin -ne $null )
{
$global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') }
break;
}
else
{
$global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique;
$global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') }
break;
}
}
if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" `
-contains $_cmdlet.Name -and "Name" )
{
Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-PSProvider" -eq $_cmdlet.Name )
{
Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Eventlog" -eq $_cmdlet.Name )
{
Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') }
break;
}
if ( "Get-Help" -eq $_cmdlet.Name )
{
Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique
break;
}
if ( "Get-Service", "Restart-Service", "Resume-Service",
"Start-Service", "Stop-Service", "Suspend-Service" `
-contains $_cmdlet.Name )
{
Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Get-Command" -eq $_cmdlet.Name )
{
Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object",
"ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" `
-contains $_cmdlet.Name )
{
Get-PipeLineObject
$_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name )
{
Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name )
{
Get-Alias -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
}
if ( $line -match '(-(\\w+))\\s+([^-]*$)' )
{
$_param = $matches[2] + '*'
$_opt = $Matches[3].Split(" ,")[-1] + '*'
$_base = $Matches[3].Substring(0,$Matches[3].Length-$Matches[3].Split(" ,")[-1].length)
$_cmdlet = [regex]::Split($line, '[|;=]')[-1]
if ($_cmdlet -match '\\{([^\\{\\}]*)$')
{
$_cmdlet = $matches[1]
}
# Extract the longest unclosed parenthetical expression...
if ($_cmdlet -match '\\(([^()]*)$')
{
$_cmdlet = $matches[1]
}
$_cmdlet = $_cmdlet.Trim().Split()[0]
$_cmdlet = @(Get-Command -type 'cmdlet,alias,ExternalScript,Filter,Function' $_cmdlet)[0]
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias,ExternalScript,Filter,Function' $_cmdlet.Definition)[0]
}
if ( $_param.TrimEnd("*") -eq "ea" -or $_param.TrimEnd("*") -eq "wa" )
{
"SilentlyContinue", "Stop", "Continue", "Inquire" |
? { $_ -like $_opt } | sort -Unique
break;
}
if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide" -contains $_cmdlet.Name `
-and "groupBy" -like $_param )
{
Get-PipeLineObject
$_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_.Name }
break;
}
if ( $_param.TrimEnd("*") -eq "ev" -or $_param.TrimEnd("*") -eq "ov" -or
"ErrorVariable" -like $_param -or "OutVariable" -like $_param)
{
Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort
break;
}
if ( "Tee-Object" -eq $_cmdlet.Name -and "Variable" -like $_param )
{
Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort
break;
}
if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name `
-and "Name" -like $_param)
{
Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Export-Alias", "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name `
-and "Name" -like $_param)
{
Get-Alias -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Out-File","Export-CSV","Select-String","Export-Clixml" -contains $_cmdlet.Name `
-and "Encoding" -like $_param)
{
"Unicode", "UTF7", "UTF8", "ASCII", "UTF32", "BigEndianUnicode", "Default", "OEM" |
? { $_ -like $_opt } | sort -Unique
break;
}
if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name `
-and "Name" -like $_param)
{
Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "New-Object" -like $_cmdlet.Name )
{
if ( "ComObject" -like $_param )
{
$_ProgID -like $_opt | % { $_ -replace '\\s','` ' }
break;
}
if ( "TypeName" -like $_param )
{
$_TypeNames_System -like $_opt
$_TypeNames -like $_opt
break;
}
}
if ( "New-Item" -eq $_cmdlet.Name )
{
if ( "ItemType" -like $_param )
{
"directory", "file" -like $_opt
break;
}
}
if ( "Get-Location", "Get-PSDrive", "Get-PSProvider", "New-PSDrive", "Remove-PSDrive" `
-contains $_cmdlet.Name `
-and "PSProvider" -like $_param )
{
Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Location" -eq $_cmdlet.Name -and "PSDrive" -like $_param )
{
Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" `
-contains $_cmdlet.Name -and "Name" -like $_param )
{
Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Command" -eq $_cmdlet.Name -and "PSSnapin" -like $_param)
{
if ( $global:_snapin -ne $null )
{
$global:_snapin -like $_opt | % { $_base + $_ }
break;
}
else
{
$global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique;
$global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') }
break;
}
}
if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" `
-contains $_cmdlet.Name -and "Name" -like $_param )
{
if ( $global:_snapin -ne $null )
{
$global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') }
break;
}
else
{
$global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique;
$global:_snapin -like $_opt | % { $_base + $_ }
break;
}
}
if ( "Clear-Variable", "Export-Alias", "Get-Alias", "Get-PSDrive", "Get-Variable", "Import-Alias",
" New-Alias", "New-PSDrive", "New-Variable", "Remove-Variable", "Set-Alias", "Set-Variable" `
-contains $_cmdlet.Name -and "Scope" -like $_param )
{
"Global", "Local", "Script" -like $_opt
break;
}
if ( "Get-Process", "Stop-Process", "Wait-Process" -contains $_cmdlet.Name -and "Name" -like $_param )
{
Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Eventlog" -eq $_cmdlet.Name -and "LogName" -like $_param )
{
Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') }
break;
}
if ( "Get-Help" -eq $_cmdlet.Name )
{
if ( "Name" -like $_param )
{
Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique
break;
}
if ( "Category" -like $_param )
{
"Alias", "Cmdlet", "Provider", "General", "FAQ",
"Glossary", "HelpFile", "All" -like $_opt | sort | % { $_base + $_ }
break;
}
}
if ( "Get-Service", "Restart-Service", "Resume-Service",
"Start-Service", "Stop-Service", "Suspend-Service" `
-contains $_cmdlet.Name )
{
if ( "Name" -like $_param )
{
Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "DisplayName" -like $_param )
{
Get-Service -Name $_opt | sort DisplayName | % { $_base + ($_.DisplayName -replace '\\s','` ') }
break;
}
}
if ( "New-Service" -eq $_cmdlet.Name -and "dependsOn" -like $_param )
{
Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Get-EventLog" -eq $_cmdlet.Name -and "EntryType" -like $_param )
{
"Error", "Information", "FailureAudit", "SuccessAudit", "Warning" -like $_opt | sort | % { $_base + $_ }
break;
}
if ( "Get-Command" -eq $_cmdlet.Name -and "Name" -like $_param )
{
Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( $_cmdlet.Noun -like "*WMI*" )
{
if ( "Class" -like $_param )
{
$_WMIClasses -like $_opt
break;
}
}
if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object",
"ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" `
-contains $_cmdlet.Name -and "Property" -like $_param )
{
Get-PipeLineObject
$_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Select-Object" -eq $_cmdlet.Name )
{
if ( "ExcludeProperty" -like $_param )
{
Get-PipeLineObject
$_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "ExpandProperty" -like $_param )
{
Get-PipeLineObject
$_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_.Name }
break;
}
}
if ( "ExternalScript", "Function", "Filter" -contains $_cmdlet.CommandType )
{
if ( $_cmdlet.CommandType -eq "ExternalScript" )
{
$_fsr = New-Object IO.StreamReader $_cmdlet.Definition
$_def = "Function _Dummy { $($_fsr.ReadToEnd()) }"
$_fsr.Close()
iex $_def
$_cmdlet = "_Dummy"
}
if ( ((gi "Function:$_cmdlet").Definition -replace '\\n').Split("{")[0] -match 'param\\((.*\\))\\s*[;\\.&a-zA-Z]*\\s*$' )
{
$Matches[1].Split(',', "RemoveEmptyEntries" -as [System.StringSplitOptions]) -like "*$_param" |
% { $_.Split("$ )`r`n", "RemoveEmptyEntries" -as [System.StringSplitOptions])[0] -replace '^\\[(.*)\\]$','$1' -as "System.Type" } |
? { $_.IsEnum } | % { [Enum]::GetNames($_) -like $_opt | sort } | % { $_base + $_ }
}
break;
}
select -InputObject $_cmdlet -ExpandProperty ParameterSets | select -ExpandProperty Parameters |
? { $_.Name -like $_param } | ? { $_.ParameterType.IsEnum } |
% { [Enum]::GetNames($_.ParameterType) } | ? { $_ -like $_opt } | sort -Unique | % { $_base + $_ }
}
if ( $line[-1] -match "\\s" ) { break; }
if ( $lastWord -ne $null -and $lastWord.IndexOfAny('/\\') -eq -1 ) {
$command = $lastWord.Substring( ($lastWord -replace '([^\\|\\(;={]*)$').Length )
$_base = $lastWord.Substring( 0, ($lastWord -replace '([^\\|\\(;={]*)$').Length )
$pattern = $command + "*"
"begin {", "break", "catch {", "continue", "data {", "do {", "else {", "elseif (",
"end {", "exit", "filter ", "for (", "foreach ", "from", "function ", "if (", "in",
"param (", "process {", "return", "switch ", "throw ", "trap ", "until (", "while (" `
-like $pattern | % { $_base + $_ }
gcm -Name $pattern -CommandType All | % { $_base + $_.Name } | sort -Unique
}
}
}
}
}
|
PowerShellCorpus/PoshCode/Backup all ESXi_2.ps1
|
Backup all ESXi_2.ps1
|
# Change this to where you would like your backups to go.
# There is no versioning so backup theses backups with real backup software (e.g. on an SMB share).
$backupDir = "c:\\backups"
# Get just your ESXi hosts.
$esxiHosts = Get-VMHost | Where { $_ | Get-View -Property Config | Where { $_.Config.Product.ProductLineId -eq "embeddedEsx" } }
# Back them all up.
$esxiHosts | Foreach {
$fullPath = $backupDir + "\\" + $_.Name
mkdir $fullPath -ea SilentlyContinue | Out-Null
Set-VMHostFirmware -VMHost $_ -BackupConfiguration -DestinationPath $fullPath
}
|
PowerShellCorpus/PoshCode/16ca876b7bb7ac8c2f362b_1.ps1
|
16ca876b7bb7ac8c2f362b_1.ps1
|
#.Synopsis
# Test the HMAC hash(es) of a file
#.Description
# Takes the HMAC hash of a file using specified algorithm, and optionally, compare it to a baseline hash
#.Example
# Test-Hash npp.5.3.1.Installer.exe -HashFile npp.5.3.1.release.md5
#
# Searches the provided hash file for a line matching the "npp.5.3.1.Installer.exe" file name
# and take the hash of the file (using the extension of the HashFile as the Type of Hash).
#
#.Example
# Test-Hash npp.5.3.1.Installer.exe 360293affe09ffc229a3f75411ffa9a1 MD5
#
# Takes the MD5 hash and compares it to the provided hash
#
#.Example
# Test-Hash npp.5.3.1.Installer.exe 5e6c2045f4ddffd459e6282f3ff1bd32b7f67517
#
# Tests all of the hashes against the provided (Sha1) hash
#
function Test-Hash {
#[CmdletBinding(DefaultParameterSetName="NoExpectation")]
PARAM(
#[Parameter(Position=0,Mandatory=$true)]
[string]$FileName
,
#[Parameter(Position=2,Mandatory=$true,ParameterSetName="ManualHash")]
[string]$ExpectedHash = $(if($HashFileName){ ((Get-Content $HashFileName) -match $FileName)[0].split(" ")[0] })
,
#[Parameter(Position=1,Mandatory=$true,ParameterSetName="FromHashFile")]
[string]$HashFileName
,
#[Parameter(Position=1,Mandatory=$true,ParameterSetName="ManualHash")]
[string[]]$TypeOfHash = $(if($HashFileName){
[IO.Path]::GetExtension((Convert-Path $HashFileName)).Substring(1)
} else { "MD5","SHA1","SHA256","SHA384","SHA512","RIPEMD160" })
)
$ofs=""
$hashes = @{}
foreach($Type in $TypeOfHash) {
[string]$hash = [Security.Cryptography.HashAlgorithm]::Create(
$Type
).ComputeHash(
[IO.File]::ReadAllBytes( (Convert-Path $FileName) )
) | ForEach { "{0:x2}" -f $_ }
$hashes.$Type = $hash
}
if($ExpectedHash) {
($hashes.Values -eq $hash).Count -ge 1
} else {
foreach($hash in $hashes.GetEnumerator()) {
"{0,-8}{1}" -f $hash.Name, $hash.Value
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.