full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PoshCode/BridgeBot 1.0.ps1
|
BridgeBot 1.0.ps1
|
## Depends on the PoshXmpp.dll from http://CodePlex.com/PowerXmpp
#requires -pssnapin PoshXmpp
## Requires System.Web for the RSS-feed option
[Reflection.Assembly]::LoadWithPartialName("System.Web") | Out-Null
##########################################################################################
# @Author: Joel Bennnett
# @Usage:
# Start-JabberMirror.ps1 User@JabberServer.com Password "groupchat@oneserver.com" "groupchat@anotherserver.com" "BridgeBot" "http://rssfeed"
##########################################################################################
param (
$JabberId = #$(Read-Host "Jabber Login")
,$Password = #$(Read-Host "Password")
,$IRC = # $(Read-Host "First Jabber conference address")
,$JabberConf = # $(Read-Host "Second Jabber conference address")
,$ChatNick = # $(Read-Host "The nickname you want to use")
[string[]]$AtomFeeds = @()
)
function Start-PowerBot {
$global:LastNewsCheck = $([DateTime]::Now.AddHours(-5))
$global:feedReader = new-object Xml.XmlDocument
$global:PoshXmppClient = PoshXmpp\\New-Client $JabberId $Password # http://im.flosoft.biz:5280/http-poll/
PoshXmpp\\Connect-Chat $IRC $ChatNick
PoshXmpp\\Connect-Chat $JabberConf $ChatNick
PoshXmpp\\Send-Message $IRC "Starting Mirror to $('{0}@{1}' -f $JabberConf.Split(@('%','@'),3))"
PoshXmpp\\Send-Message $JabberConf "Starting Mirror to $('{0}@{1}' -f $IRC.Split(@('%','@'),3))"
PoshXmpp\\Send-Message $IRC "/msg nickserv id Sup3rB0t"
}
function Process-Command($Chat, $Message) {
$split = $message.Body.Split(" ")
switch( $split[0] ) {
"!list" {
Write-Host "!LIST COMMAND. Send users of [$Chat] to [$($Message.From.Bare)]" -fore Magenta
PoshXmpp\\Send-Message $Message.From.Bare.ToLower() (@($PoshXmppClient.ChatManager.GetUsers( $Chat ).Values) -join ", ")
}
}
}
# Max IRC Message Length http://www.faqs.org/rfcs/rfc1459.html
# PRIVMSG CHANNEL MSG
$IrcMaxLen = 510 - ("PRIVMSG :".Length + $IRC.Length + $JabberId.split('@')[0].Length)
function Get-Feeds([string[]]$JIDs,[string[]]$AtomFeeds) {
Write-Verbose "Checking feeds..."
foreach($feed in $AtomFeeds) {
$feedReader.Load($feed)
for($i = $feedReader.feed.entry.count - 1; $i -ge 0; $i--) {
$e = $feedReader.feed.entry[$i]
if([datetime]$e.updated -gt $global:LastNewsCheck) {
foreach($jid in $JIDs) {
$msg = ([System.Web.HttpUtility]::HtmlDecode($e.summary."#text") -replace "<br>", "").Trim()
$template = "{0} (Posted at {1:hh:mm} by {2}) {{0}} :: {3}" -f
$e.title."#text", [datetime]$e.updated, $e.author.name, $e.link.href
$len = [math]::Min($IrcMaxLen,($template.Length + $msg.Length)) - ($template.Length +3)
PoshXmpp\\Send-Message $jid $($template -f $msg.SubString(0,$len))
}
[Threading.Thread]::Sleep( 500 )
}
}
}
$global:LastNewsCheck = [DateTime]::Now
}
function Bridge {
PoshXmpp\\Receive-Message -All | foreach-object {
Write-Verbose ("MESSAGE: {0} {1} {2}" -f $_.From.Bare, $_.From.Resource, $_.Body)
if( $_.Type -eq "Error" ) {
Write-Error $_.Error
}
if( $_.From.Resource -ne $ChatNick ) {
$Chat = $null;
if( $_.From.Bare -eq $IRC )
{
$Chat = $JabberConf;
}
elseif( $_.From.Bare -eq $JabberConf )
{
$Chat = $IRC;
}
else
{
$_
}
if($Chat){
if(![String]::IsNullOrEmpty($_.Body) -and ($_.Body[0] -eq '!')) {
Process-Command $Chat $_
}
elseif( ![String]::IsNullOrEmpty($_.Subject) )
{
$_.To = $Chat
# Send it directly using a method on the PoshXmppClient
$PoshXmppClient.Send($_)
}
else
{
PoshXmpp\\Send-Message $Chat ("<{0}> {1}" -f $_.From.Resource, $_.Body)
}
}
}
}
}
function Start-Bridge {
"PRESS ANY KEY TO STOP"
while(!$Host.UI.RawUI.KeyAvailable) {
Bridge
Get-Feeds @($IRC,$JabberConf) $AtomFeeds
$counter = 0
Write-Verbose "PRESS ANY KEY TO STOP" # we're going to wait 3 * 60 seconds
while(!$Host.UI.RawUI.KeyAvailable -and ($counter++ -lt 1800)) {
Bridge
[Threading.Thread]::Sleep( 100 )
}
}
}
function Stop-PowerBot {
PoshXmpp\\Disconnect-Chat $IRC $ChatNick
PoshXmpp\\Disconnect-Chat $JabberConf $ChatNick
$global:PoshXmppClient.Close();
}
|
PowerShellCorpus/PoshCode/VMware and NetApp file f.ps1
|
VMware and NetApp file f.ps1
|
Add-PSSnapin VMware.VimAutomation.Core
Import-Module DataOntap
$cred = Get-VICredentialStoreItem -Host nau-vc.naucom.com -File c:\\users\\aaworkman\\powershell\\credentials.xml
Connect-VIServer nau-vc -User $cred.User -Password $cred.Password
$esxhost = "fargo-esx2.naucom.com"
$numberofclones = 10
$loc = Get-Folder -Location "FargoND" | Where-Object { $_.Name -cmatch "Discovered" }
New-Folder -Location $loc -Name "agro_desktops"
New-ResourcePool -Location $esxhost -Name agro -CpuSharesLevel Low -MemSharesLevel Low
$folderdsk = Get-View (Get-Datacenter -Name "FargoND" | Get-Folder -Name "agro_desktops").ID
$pool = Get-View (Get-VMHost -name $esxhost -Location FargoND | Get-ResourcePool -Name "agro").ID
Connect-NaController -Name fargo-nas1.naucom.com
cd vmstore:\\FargoND\\agrovms\\agro-gld-win7
$vmfiles = ls -Name
$i=1
cd vmstore:\\FargoND\\agrovms\\
#Create Folders and Clone Template Image
do {
$vmname = "agro-win7-"
$vmname += "$i"
mkdir $vmname
foreach($vmfile in $vmfiles){
Start-NaClone -SourcePath /vol/agrovm_integration/agro-gld-win7/${vmfile} -DestinationPath /vol/agrovm_integration/$vmname/${vmfile}
}
$i++
}
while ($i -le $numberofclones)
$clones = Get-NaClone
while ($clones -ne $null) {sleep -Seconds 5; $clones = Get-NaClone}
#Register VM's
$esxImpl = Get-VMHost -Location FargoND | Select-Object -First 1
$esx = Get-View $esxImpl.ID
$dsBrowser = Get-View $esx.DatastoreBrowser
$ds = Get-Datastore -Name "agrovms"
$dsView = Get-View $ds
$datastorepath = "[" + $dsView.Summary.Name + "]"
$searchspec = New-Object VMware.Vim.HostDatastoreBrowserSearchSpec
$searchSpec.matchpattern = "*.vmx"
$taskMoRef = $dsBrowser.SearchDatastoreSubFolders_Task($datastorePath, $searchSpec)
$task = Get-View $taskMoRef
while ($task.Info.State -eq "running"){$task = Get-View $taskMoRef}
$i = 1
foreach ($file in $task.info.Result){
$vmx = $file.FolderPath + $file.File[0].Path
$path = $file.File[0].Path
$guestname = [regex]"\\[agrovms\\] (.*)\\/agro-gld-win7.vmx"
$value = $vmx -cmatch $guestname
$vmname = $matches[1]
if($vmname -cmatch "win7"){ $folder = $folderdsk }
Else { $folder = $foldersrv }
$folder.RegisterVM_Task($vmx,$vmname,$FALSE,$pool.MoRef,$null)
$i++
}
##Customize Guests
$serviceInstance = get-view ServiceInstance
$csMgr = get-view $serviceInstance.Content.CustomizationSpecManager
$foldername = $folderdsk
$specname = Get-OSCustomizationSpec -Name Win7-MAK-MSDN
$spec = $csMgr.GetCustomizationSpec($specname)
$goldens = Get-View -Viewtype VirtualMachine -Searchroot $folderdsk.MoRef
foreach($vm in $goldens){
$custtask = $vm.CustomizeVM_Task($spec.Spec)
}
|
PowerShellCorpus/PoshCode/Import-Certificate_1.ps1
|
Import-Certificate_1.ps1
|
function Import-Certificate
{
param
(
[IO.FileInfo] $CertFile = $(throw "Paramerter -CertFile [System.IO.FileInfo] is required."),
[string[]] $StoreNames = $(throw "Paramerter -StoreNames [System.String] is required."),
[switch] $LocalMachine,
[switch] $CurrentUser,
[string] $CertPassword,
[switch] $Verbose
)
begin
{
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Security")
}
process
{
if (-not $LocalMachine -and -not $CurrentUser)
{
Write-Warning "One or both of the following parameters are required: '-LocalMachine' '-CurrentUser'. Skipping certificate '$CertFile'."
}
try
{
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $certfile,$CertPassword
}
catch
{
Write-Error ("Error importing '$certfile': $_ .") -ErrorAction:Continue
}
if ($cert -and $LocalMachine)
{
$StoreScope = "LocalMachine"
$StoreNames | ForEach-Object {
$StoreName = $_
if (Test-Path "cert:\\$StoreScope\\$StoreName")
{
try
{
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store $StoreName, $StoreScope
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$store.Add($cert)
$store.Close()
if ($Verbose -or $VerbosePreference -ne 'SilentlyContinue')
{
Write-Verbose "Successfully added '$certfile' to 'cert:\\$StoreScope\\$StoreName'."
}
}
catch
{
Write-Error ("Error adding '$certfile' to 'cert:\\$StoreScope\\$StoreName': $_ .") -ErrorAction:Continue
}
}
else
{
Write-Warning "Certificate store '$StoreName' does not exist. Skipping..."
}
}
}
if ($cert -and $CurrentUser)
{
$StoreScope = "CurrentUser"
$StoreNames | ForEach-Object {
$StoreName = $_
if (Test-Path "cert:\\$StoreScope\\$StoreName")
{
try
{
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store $StoreName, $StoreScope
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$store.Add($cert)
$store.Close()
if ($Verbose -or $VerbosePreference -ne 'SilentlyContinue')
{
Write-Verbose "Successfully added '$certfile' to 'cert:\\$StoreScope\\$StoreName'."
}
}
catch
{
Write-Error ("Error adding '$certfile' to 'cert:\\$StoreScope\\$StoreName': $_ .") -ErrorAction:Continue
}
}
else
{
Write-Warning "Certificate store '$StoreName' does not exist. Skipping..."
}
}
}
}
end
{ }
}
|
PowerShellCorpus/PoshCode/Check Modules path_2..ps1
|
Check Modules path_2..ps1
|
function Update-ModulePath {
<#
.Synopsis
Command insures that path and the name of psm1 file are alike.
.Description
This function should help to troubleshoot modules. It loooks up path that should contain modules.
For each .psm1 file found it checks if parent folder containing this file has same name.
I created this function after I was banging my head for few hours why my module won't show up.
After several approaches it came out clear that it was simple TYPO in file.psm1 name...
.Example
Update-ModulePath -Fix Files
Will look all files and rename .psm1 files to match parent folder
.Example
Update-ModulePath -Fix Folder
Will look all files and rename parent folder to match file names
.Parameter Fix
Switch to decide if we prefer to name folders or files to get all matches.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[ValidateSet("Files","Folders")]
[string]$Fix
)
<# Steps to be taken:
* enumerate all .psm1 files
* check which one is misconfigured
* rename file/ folder to fix this issue
#>
ForEach ($ModuleFile in @(Get-ChildItem -Recurse @($($env:PSModulePath).Split(";")) -filter *.psm1)) {
if (($file = $ModuleFile.BaseName) -eq ($folder = $ModuleFile.Directory.ToString().Split('\\')[-1])) {
Write-Verbose "$Modulefile.Name is fine"
} else {
Write-Verbose "$ModuleFile.Name is BAD"
switch ($Fix) {
"Files" {
Write-Verbose "We rename file $file"
$OldName = $ModuleFile.FullName
$NewName = $OldName -replace "$file.psm1$", "$folder.psm1"
}
"Folders" {
Write-Verbose "We rename folder $folder"
$OldName = $ModuleFile.FullName -replace "\\\\$file.psm1", ""
$NewName = $OldName -replace "$folder$", $file
}
}
Write-Host "Renaming $OldName to $NewName"
Rename-Item -Force $OldName $NewName
}
}
}
|
PowerShellCorpus/PoshCode/Find-String_2.ps1
|
Find-String_2.ps1
|
<#
.Synopsis
Searches text files by pattern and displays the results.
.Description
Searches text files by pattern and displays the results.
.Notes
Based on versions from http://weblogs.asp.net/whaggard/archive/2007/03/23/powershell-script-to-find-strings-and-highlight-them-in-the-output.aspx and from http://poshcode.org/426
Makes use of Out-ColorMatchInfo found at http://poshcode.org/1095.
#>
#requires -version 2
param (
[Parameter(Mandatory=$true)]
[regex] $pattern,
[string] $filter = "*.*",
[switch] $recurse = $true,
[switch] $caseSensitive = $false,
[int[]] $context = 0
)
if ((-not $caseSensitive) -and (-not $pattern.Options -match "IgnoreCase")) {
$pattern = New-Object regex $pattern.ToString(),@($pattern.Options,"IgnoreCase")
}
Get-ChildItem -recurse:$recurse -filter:$filter |
Select-String -caseSensitive:$caseSensitive -pattern:$pattern -AllMatches -context $context |
Out-ColorMatchInfo
|
PowerShellCorpus/PoshCode/Write-Log.ps1
|
Write-Log.ps1
|
function Write-Log {
#region Parameters
[cmdletbinding()]
Param(
[Parameter(ValueFromPipeline=$true,Mandatory=$true)] [ValidateNotNullOrEmpty()]
[string] $Message,
[Parameter()] [ValidateSet(“Error”, “Warn”, “Info”)]
[string] $Level = “Info”,
[Parameter()] [ValidateRange(1,30)]
[Int16] $Indent = 0,
[Parameter()]
[IO.FileInfo] $Path = ”$env:temp\\PowerShellLog.txt”,
[Parameter()]
[Switch] $Clobber,
[Parameter()]
[String] $EventLogName,
[Parameter()]
[String] $EventSource = ([IO.FileInfo] $MyInvocation.ScriptName).Name,
[Parameter()]
[Int32] $EventID = 1
)
#endregion
Begin {}
Process {
try {
$msg = '{0}{1} : {2} : {3}' -f (" " * $Indent), (Get-Date -Format “yyyy-MM-dd HH:mm:ss”), $Level.ToUpper(), $Message
switch ($Level) {
'Error' { Write-Error $Message }
'Warn' { Write-Warning $Message }
'Info' { Write-Host ('{0}{1}' -f (" " * $Indent), $Message) -ForegroundColor White}
}
if ($Clobber) {
$msg | Out-File -FilePath $Path
} else {
$msg | Out-File -FilePath $Path -Append
}
if ($EventLogName) {
if(-not [Diagnostics.EventLog]::SourceExists($EventSource)) {
[Diagnostics.EventLog]::CreateEventSource($EventSource, $EventLogName)
}
$log = New-Object System.Diagnostics.EventLog
$log.set_log($EventLogName)
$log.set_source($EventSource)
switch ($Level) {
“Error” { $log.WriteEntry($Message, 'Error', $EventID) }
“Warn” { $log.WriteEntry($Message, 'Warning', $EventID) }
“Info” { $log.WriteEntry($Message, 'Information', $EventID) }
}
}
} catch {
throw “Failed to create log entry in: ‘$Path’. The error was: ‘$_’.”
}
}
End {}
<#
.SYNOPSIS
Writes logging information to screen and log file simultaneously.
.DESCRIPTION
Writes logging information to screen and log file simultaneously. Supports multiple log levels.
.PARAMETER Message
The message to be logged.
.PARAMETER Level
The type of message to be logged.
.PARAMETER Indent
The number of spaces to indent the line in the log file.
.PARAMETER Path
The log file path.
.PARAMETER Clobber
Existing log file is deleted when this is specified.
.PARAMETER EventLogName
The name of the system event log, e.g. 'Application'.
.PARAMETER EventSource
The name to appear as the source attribute for the system event log entry. This is ignored unless 'EventLogName' is specified.
.PARAMETER EventID
The ID to appear as the event ID attribute for the system event log entry. This is ignored unless 'EventLogName' is specified.
.EXAMPLE
PS C:\\> Write-Log -Message "It's all good!" -Path C:\\MyLog.log -Clobber -EventLogName 'Application'
.EXAMPLE
PS C:\\> Write-Log -Message "Oops, not so good!" -Level Error -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "My Script"
.INPUTS
System.String
.OUTPUTS
No output.
#>
}
|
PowerShellCorpus/PoshCode/Wake-OrphanedVMHost.ps1
|
Wake-OrphanedVMHost.ps1
|
#requires -pssnapin VMware.VimAutomation.Core
# http://get-admin.com/blog/?p=342
#Get any cluster that has DPM Enabled
$Clusters = @()
$Clusters += Get-Cluster -verbose:$false | Where-Object { (Get-View -VIObject $_ -verbose:$false).ConfigurationEx.DpmConfigInfo.Enabled }
Write-Verbose "$(get-date -uformat %T) Found $($Clusters.Count) DPM Enabled DRS Clusters ..."
Foreach ($cluster in $Clusters) {
Write-Verbose "$(get-date -uformat %T) Processing $($Cluster.Name) Cluster"
#Get any hosts that have a state of disconnected
$VMHosts = @()
$VMHosts = $cluster | Get-VMHost -verbose:$false | Where-Object { $_.State -eq "NotResponding" }
Write-Verbose "$(get-date -uformat %T) Found $($VMHosts.Count) Suspended Hosts"
#Wake 'em up!
Foreach ($VMHost in $VMHosts){
#Get the mac address of any WOL enabled Pnic
$VMHostNetworkSystem = (Get-view -VIObject $VMHost -verbose:$false).ConfigManager.NetworkSystem
$Pnics = (Get-view -ID $VMHostNetworkSystem -verbose:$false).NetworkInfo.Pnic | Where-Object {$_.WakeOnLanSupported}
#Send the WOL Majic Packet...
Foreach ($Pnic in $Pnics) {
$MAC = $Pnic.Mac.split(':') | %{ [byte]('0x' + $_) }
$UDPclient = new-Object System.Net.Sockets.UdpClient
$UDPclient.Connect(([System.Net.IPAddress]::Broadcast),4000)
$packet = [byte[]](,0xFF * 6)
$packet += $mac * 16
[void] $UDPclient.Send($packet, $packet.Length)
Write-Verbose "$(get-date -uformat %T) Magic Packet sent to $($VMHost.Name) $($Pnic.Device)"
}
}
}
|
PowerShellCorpus/PoshCode/104237c9-a8e9-419e-b285-638b60444a56.ps1
|
104237c9-a8e9-419e-b285-638b60444a56.ps1
|
# by @bernd_k aka @sqlsulidae http://sqlsulidae.blogspot.com/
#
# This is an extension of the script you find at
# http://www.sqlmusings.com/2009/08/21/sql-server-powershell-how-to-view-your-ssrs-reports-rdl-using-powershell-and-reportviewer/
# I show how to provide parameters and how to catch the navigate event
# [void]
[System.Reflection.Assembly]::Load("Microsoft.ReportViewer.WinForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
$rv = New-Object Microsoft.Reporting.WinForms.ReportViewer
$eventHandler = [Microsoft.Reporting.WinForms.HyperlinkEventHandler]{
#$this # $this is sender
Write-Host "Hyperlink Event fired"
Write-Host $_.Hyperlink # $_ are the event args
$_.Cancel = $true
}
$rv.Add_Hyperlink($eventHandler)
$rv.ProcessingMode = "Remote"
$rv.ServerReport.ReportServerUrl = "http://localhost/reportserver"
$rv.ServerReport.ReportPath = "/Reports/Sample Report"
#if you need to provide basic credentials, use the following
#$rv.ServerReport.ReportServerCredentials.NetworkCredentials=
# New-Object System.Net.NetworkCredential("myuser", "mypassword")
$rv.Height = 800
$rv.Width = 1200
$rv.Dock = [System.Windows.Forms.DockStyle]::Fill
# if you have more than 1 parameters
# $params = new-object 'Microsoft.Reporting.WinForms.ReportParameter[]' 2
# $params[0] = new-Object Microsoft.Reporting.WinForms.ReportParameter("Par1", "3159", $false)
# $params[1] = new-Object Microsoft.Reporting.WinForms.ReportParameter("par2", "3159", $false)
# my report has only 1 parameter
$params = new-object 'Microsoft.Reporting.WinForms.ReportParameter[]' 1
$params[0] = new-Object Microsoft.Reporting.WinForms.ReportParameter("Par1", "3159", $false)
$rv.ServerReport.SetParameters($params);
$rv.ShowParameterPrompts = $false
$rv.RefreshReport()
#--------------------------------------------------------------
#Show as Dialog Using Windows Form
#--------------------------------------------------------------
#create a new form
$form = New-Object Windows.Forms.Form
#we're going to make it just slightly bigger than
$form.Height = 810
$form.Width= 1210
$form.Controls.Add($rv)
$rv.Show()
$form.ShowDialog()
<#
http://blogs.msdn.com/b/powershell/archive/2008/05/24/wpf-powershell-part-3-handling-events.aspx
http://social.msdn.microsoft.com/Forums/en-US/vsreportcontrols/thread/693694bc-bfbc-4786-98ee-a99826e78739
#>
|
PowerShellCorpus/PoshCode/7fb49cb3-a349-4afb-ac39-1027dd643188.ps1
|
7fb49cb3-a349-4afb-ac39-1027dd643188.ps1
|
function Get-Parameter
{
[OutputType('System.String')]
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)]
[String]$Command,
[Parameter(Position=1)]
[String[]]$Name=@('*'),
[Parameter()]
[ValidateSet('Name','Type','Pos','BV','BP','Aliases','Mandatory','Dynamic')]
[String]$SortBy='Name',
[Parameter()]
[switch]$Descending,
[Parameter()]
[ValidateSet('Cmdlet','Function','Alias','ExternalScript')]
[String]$CommandType,
[switch]$IncludeCommonParameters
)
Process
{
if($CommandType)
{
switch($CommandType)
{
"function"
{
$cmd = Get-Command -Name $Command -CommandType $CommandType -ErrorAction SilentlyContinue | Where-Object {$_.CommandType -eq $CommandType}
}
"filter"
{
$cmd = Get-Command -Name $Command -CommandType $CommandType -ErrorAction SilentlyContinue | Where-Object {$_.CommandType -eq $CommandType}
}
default
{
$cmd = Get-Command -Name $Command -CommandType $CommandType -ErrorAction SilentlyContinue
}
}
}
else
{
$cmd = Get-Command -Name $Command -CommandType Cmdlet,Function,Alias,ExternalScript -ErrorAction SilentlyContinue
}
if(!$cmd)
{
Throw "'$Name' is not a Cmdlet,Function,Filter,Alias or ExternalScript"
}
if($cmd.length -gt 1)
{
$types = $cmd | Select-Object -ExpandProperty CommandType -Unique
Throw "'$Command' is ambiguous and matches one of $($types -join ","). Use -CommandType to get only a specified type of command."
}
if($cmd.CommandType -eq 'Alias')
{
Write-Verbose "'$Name' refers to an Alias, reolving command."
$cmd = Get-Command -Name $cmd.ResolvedCommandName
}
foreach($set in $cmd.ParameterSets)
{
if($IncludeCommonParameters)
{
$p = $set.Parameters | Select-Object *
}
else
{
# Get a list of common parameters
$cp = [System.Management.Automation.Internal.CommonParameters].GetProperties() | Select-Object -ExpandProperty Name
$p = $set.Parameters | Where-Object {$cp -notcontains $_.Name} | Select-Object *
}
$params = $p | Foreach-Object {$_.Name}
for($i=0;$i -le $p.length;$i++)
{
$flag=$false
for($x=0;$x -le $params[$i].length -and !($flag);$x++)
{
$regex = "^" + $params[$i].substring(0,$x)
if(($params -match $regex).count -eq 1)
{
$flag=$true
$p[$i].Aliases += $regex.substring(1).ToLower()
}
}
}
if($params.count -le 0 -and !$IncludeCommonParameters)
{
Write-Error "$cmd, No parameters found"
return
}
$p | Where-Object {$_.Name -like $Name} | Foreach-Object {
$PropertyName = $_.Name
$psn = $_.Attributes | Where-Object {$_.ParameterSetName}
if($cmd.CommandType -eq 'cmdlet')
{
$DefaultValue = $dv.PSObject.Properties[$PropertyName].Value
}
else
{
$DefaultValue = $null
}
if($psn.ParameterSetName -notmatch '__AllParameterSets')
{
$PropertyName="*$PropertyName"
}
New-Object PSObject -Property @{
ParameterSet = $set.Name
Name = $PropertyName
BV = $_.ValueFromPipeline
BP = $_.ValueFromPipelineByPropertyName
Type = $_.ParameterType.Name
Aliases = $_.Aliases
Pos = if($_.Position -lt 0) {'Named'} else {$_.Position+1}
Mandatory = $_.IsMandatory
Dynamic = $_.IsDynamic
}
} | Sort-Object -Descending:$Descending {$_.$SortBy -replace '\\*'} | Format-Table Name,Type,Pos,BV,BP,Aliases,Mandatory,Dynamic -AutoSize -GroupBy ParameterSet | Out-String
}
}
}
Set-Alias -Name gprm -Value Get-Parameter
|
PowerShellCorpus/PoshCode/Set-Domain_1.ps1
|
Set-Domain_1.ps1
|
function Set-Domain {
param( [switch]$help,
[string]$domain=$(read-host "Please specify the domain to join"),
[System.Management.Automation.PSCredential]$credential = $(Get-Crdential)
)
$usage = "`$cred = get-credential `n"
$usage += "Set-AvaDomain -domain corp.avanade.org -credential `$cred`n"
if ($help) {Write-Host $usage;exit}
$username = $credential.GetNetworkCredential().UserName
$password = $credential.GetNetworkCredential().Password
$computer = Get-WmiObject Win32_ComputerSystem
$computer.JoinDomainOrWorkGroup($domain ,$password, $username, $null, 3)
}
|
PowerShellCorpus/PoshCode/scriptable telnet client_1.ps1
|
scriptable telnet client_1.ps1
|
@@function read-stream ([Parameter(Posistion=0,Mandatory=$true)][validatenotnull()]
[System.Net.Sockets.NetworkStream]$stream,
[String]$expect = "")
{
$buffer = new-object system.byte[] 1024
$enc = new-object system.text.asciiEncoding
## Read all the data available from the stream, writing it to the
## screen when done.
## Allow data to buffer
start-sleep -m 100
$output = ""
while($stream.DataAvailable -or $output -notmatch $expect)
{
$read = $stream.Read($buffer, 0, 1024)
$output = "$output$($enc.GetString($buffer, 0, $read))"
## Allow data to buffer for a bit
start-sleep -m 100
}
$output.split("`n")
}
function send-command ([parameter(position=0,Mandatory=$true)][validatenotnull()]
[String]$hostname,
[parameter(position=1,Mandatory=$true)][validatenotnull()]
[String]$User,
[parameter(position=2,Mandatory=$true)][validatenotnull()]
[String]$Password,
[parameter(position=3,Mandatory=$true,valuefrompipeline=$true)][validatenotnull()]
[String]$InputObject,
[string]$Expect = "")
{
begin
{
$sock = new-object system.net.sockets.tcpclient($hostname,23)
$str = $sock.GetStream()
$wrt = new-object system.io.streamwriter($str)
read-stream($str)
$wrt.writeline($user)
$wrt.flush()
read-stream($str)
$wrt.writeline($password)
$wrt.flush()
read-stream($str, $expect)
}
process
{
$wrt.writeline($InputObject)
$wrt.flush()
read-stream($str, $expect)
}
end
{
$wrt.writeline("exit")
$wrt.flush()
read-stream($str)
## Close the streams
$wrt.Close()
$str.Close()
$sock.close()
}
}
|
PowerShellCorpus/PoshCode/Get-StaticMethodDefin.ps1
|
Get-StaticMethodDefin.ps1
|
#Steven Murawski
#http://blog.usepowershell.com
#03/20/2009
function Get-StaticMethodDefinition()
{
param ($Method, [Type]$Type=$null)
BEGIN
{
if ($Type -ne $null)
{
$Type | Get-StaticMethodDefinition $Method
}
}
PROCESS
{
if ($_ -ne $null)
{
$_ | Get-Member -Name $Method -Static -MemberType Method | ForEach-Object {$_.Definition -replace '\\), ', "), `n"}
}
}
}
|
PowerShellCorpus/PoshCode/VMtoolsUpgrade-disable_2.ps1
|
VMtoolsUpgrade-disable_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 " - Disabling VMTools Update at Power Cycle"
$vmConfig = New-Object VMware.Vim.VirtualMachineConfigSpec
$vmConfig.Tools = New-Object VMware.Vim.ToolsConfigInfo
$vmConfig.Tools.ToolsUpgradePolicy = "Manual"
Get-VM $vm.name | where {$_.Extensiondata.ReconfigVM($vmconfig)}
}
|
PowerShellCorpus/PoshCode/Set-Computername_2.ps1
|
Set-Computername_2.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/Log4Net.xslt.ps1
|
Log4Net.xslt.ps1
|
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:log4net="http://logging.apache.org/log4net/schemas/log4net-events-1.2"
version="1.0">
<xsl:output method="html" indent="yes" encoding="US-ASCII"/>
<xsl:template match="log4net:events">
<html><head><style>
.FATAL { color: white; background: #ff0000;}
.ERROR { background: #ee0000; }
.WARN { background: #ffffcc; }
.DEBUG { color: white; background: #003300; }
.INFO { background: #eeffee; }
</style></head><body>
<table>
<xsl:apply-templates/>
</table>
</body></html>
</xsl:template>
<xsl:template match="log4net:event">
<tr class="{@level}">
<td class="logger"><xsl:value-of select="@logger"/></td>
<td class="timestamp"><xsl:value-of select="@timestamp"/></td>
<td class="level"><xsl:value-of select="@level"/></td>
<td class="thread"><xsl:value-of select="@thread"/></td>
<xsl:apply-templates/>
</tr>
</xsl:template>
<xsl:template match="log4net:message">
<td class="message">
<xsl:apply-templates/>
</td>
</xsl:template>
<xsl:template match="log4net:NDC">
<td class="NDC">
<xsl:apply-templates/>
</td>
</xsl:template>
<xsl:template match="log4net:locationInfo">
<td class="{@class}" method="{@method}" file="{@file}" line="{@line}"/>
</xsl:template>
<xsl:template match="log4net:properties">
<td class="properties">
<xsl:apply-templates/>
</td>
</xsl:template>
<xsl:template match="log4net:data">
<td class="data"><xsl:value-of select="@name"/>: <xsl:value-of select="@value"/></td>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{name()}" namespace="{namespace-uri()}">
<xsl:apply-templates select="@*"/>
<xsl:apply-templates select="*|text()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="{name()}" namespace="{namespace-uri()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
<xsl:template match="text()">
<xsl:value-of select="."/>
</xsl:template>
</xsl:transform>
|
PowerShellCorpus/PoshCode/chkhash_7.ps1
|
chkhash_7.ps1
|
# calculate SHA512 of file.
function Get-SHA512([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]'))
{
$stream = $null;
$cryptoServiceProvider = [System.Security.Cryptography.SHA512CryptoServiceProvider];
$hashAlgorithm = new-object $cryptoServiceProvider
$stream = $file.OpenRead();
$hashByteArray = $hashAlgorithm.ComputeHash($stream);
$stream.Close();
## We have to be sure that we close the file stream if any exceptions are thrown.
trap
{
if ($stream -ne $null)
{
$stream.Close();
}
break;
}
foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }}
return [string]$result;
}
function noequal ( $first, $second)
{
foreach($s in $second)
{
if ($first -eq $s) {return $false}
}
return $true
}
# chkhash.ps1 [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #3] [-u] [-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
$upd = $false
$create = $false
for($i=0;$i -lt $args2.count; $i++)
{
if ($args2[$i] -like "-h*") # -help specified?
{
"Usage: .\\chkhash.ps1 [-h] [-u] [-c] [-x <file path of hashes .xml database>] [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #n] [-e <Dirs>]"
"Options: -h - Help display."
" -c - Create hash database. If .xml hash database does not exist, -c will be assumed."
" -u - Update changed files and add new files to existing database."
" -x - specifies .xml database file path to use. Default is .\\hashes.xml"
" -e - exclude dirs. Put this after the files/dirs you want to check with SHA512 and needs to be fullpath (e.g. c:\\users\\bob not ..\\bob)."
""
"Examples: PS>.\\chkhash.ps1 c:\\ d:\\ -c -x c:\\users\\bob\\hashes\\hashes.xml"
" PS>.\\chkhash.ps1 c:\\users\\alice\\pictures\\sunset.jpg -u -x c:\\users\\alice\\hashes\\pictureshashes.xml"
" PS>.\\chkhash.ps1 c:\\users\\eve\\documents d:\\media\\movies -x c:\\users\\eve\\hashes\\private.xml"
" PS>.\\chkhash.ps1 c:\\users\\eve -x c:\\users\\eve\\hashes\\private.xml -e c:\\users\\eve\\hashes"
""
"Note: files in subdirectories of any specified directory are automatically processed."
" if you specify only an -x option, or no option and .\\hash.xml exists, only files in the database will be checked."
exit
}
if ($args2[$i] -like "-u*") {$upd=$true;continue} # Update and Add new files to database?
if ($args2[$i] -like "-c*") {$create=$true;continue} # Create database specified?
if ($args2[$i] -like "-x*") {$i++;$hashespath=$args2[$i];continue} # Get hashes xml database path
if ($args2[$i] -like "-e*") # Exclude files, dirs
{
do {
$i++
if ($i -ge $args2.count) {break}
$exclude+=@($args2[$i]) # collect array of excluded directories.
if (($i+1) -ge $args2.count) {break}
} while ($args2[$i+1] -notlike "-*")
continue
}
$args3+=@($args2[$i]) # Add files/dirs
}
"ChkHash.ps1 - .\\chkhash.ps1 -h for usage."
""
if ($args3.count -ne 0)
{
# Get list of files and SHA512 hash them.
"Enumerating files from specified locations..."
$files=@(dir -literalpath $args3 -recurse -ea 0 | ?{$_.mode -notmatch "d"} | ?{noequal $_.directoryname $exclude}) # Get list of files
if ($files.count -eq 0) {"No files found. Exiting."; exit}
if ($create -eq $true -or !(test-path $hashespath)) # Create database?
{
# Create SHA512 hashes of files and write to new database
$files = $files | %{write-host "Hashing $($_.fullname) ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
$files |export-clixml $hashespath
"Created $hashespath"
"$($files.count) file hash(es) saved. Exiting."
exit
}
$xfiles=@(import-clixml $hashespath) # Load database
}
else
{
if (!(test-path $hashespath)) {"No database found or specified, exiting."; exit}
$xfiles=@(import-clixml $hashespath) # Load database and check it
if ($xfiles.count -eq 0) {"No files specified and no files in Database."}
$files=$xfiles
}
"Loaded $($xfiles.count) file hash(es) from $hashespath"
$hash=@{}
for($x=0;$x -lt $xfiles.count; $x++) # Build dictionary (hash) of filenames and indexes into file array
{
if ($hash.contains($xfiles[$x].fullname)) {continue}
$hash.Add($xfiles[$x].fullname,$x)
}
foreach($f in $files)
{
$n=($hash.($f.fullname))
if ($n -eq $null)
{
$nu++ # increment needs/needed updating count
if ($upd -eq $false) {"Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue
"Hashing $($f.fullname) ..."
# Create SHA512 hash of file
if ($f.SHA512)
{
$f.SHA512 = (get-SHA512 $f.fullname)
}
else
{
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
}
$xfiles+=@($f) # then add file + hash to list
continue
}
if ($f.SHA512)
{
$f.SHA512 = (get-SHA512 $f.fullname)
}
else
{
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
}
# Update and continue is specified.
$fc++ # increment files checked.
if ($xfiles[$n].SHA512 -eq $f.SHA512) # Check SHA512 for mixmatch.
{
continue
}
$errs++ # increment mixmatches
if ($upd -eq $true) { $xfiles[$n]=$f; "Updated `"$($f.fullname)`"";continue}
"Bad SHA-512 found: `"$($f.fullname)`""
}
if ($upd -eq $true) # if database updated
{
$xfiles|export-clixml $hashespath # write xml database
"Updated $hashespath"
"$nu file hash(es) added to database."
"$errs file hash(es) updated in database."
exit
}
"$errs SHA-512 mixmatch(es) found."
"$fc file(s) SHA512 matched."
if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
|
PowerShellCorpus/PoshCode/Manual DNS Scavenging.ps1
|
Manual DNS Scavenging.ps1
|
#==========================================================================
#
# PowerShell Source File
#
# AUTHOR: Stephen Wheet
# NAME: dnsscavenge.ps1
# Version: 1.2
# Date: 8/12/10
#
# COMMENT:
# This script was created to manually scavenge DNS records for a given
# period. Specify the date of last registration and everything older
# than that will be deleted.
#
# v1.1 - Added Network Range to filter based on network range (good for
# doing one site/floor at a time)
# v1.2 - Added the ability to do multiple ranges at the same time.
#
#==========================================================================
$DeleteKey = 0 #change to 0 for only a report, 1 to delete the records
#Define network range to filter on
$NetworkRange = "192.168.1.*","192.168.2.*"
# No-Refresh + Refresh (in Days)
$TotalAgingInterval = 60
$ServerName = "DNSSERVER" #DC to connect to
$ContainerName = "Domain.local" #domain name to scavenge from
#Place Headers on out-put file
ForEach ($Network in $NetworkRange){
$filename = "DC-" + $ServerName + "--DOMAIN-" + $ContainerName + "--AGE-" + $TotalAgingInterval + `
"--RANGE-" + $Network.Replace("*","") + ".csv"
$logfile = "D:\\reports\\DNSscavenge\\$filename"
$list = "Ownername,TimeStamp,Deleted"
$list | format-table | Out-File "$logfile"
} #end for each
$MinTimeStamp = [Int](New-TimeSpan `
-Start $(Get-Date("01/01/1601 00:00")) `
-End $((Get-Date).AddDays(-$TotalAgingInterval))).TotalHours
$records = Get-WMIObject -Computer $ServerName `
-Namespace "root\\MicrosoftDNS" -Class "MicrosoftDNS_AType" `
-Filter `
"ContainerName='$ContainerName' AND TimeStamp<$MinTimeStamp AND TimeStamp<>0 "
ForEach ($record in $records){
$IPA = $record.IPAddress
ForEach ($Network in $NetworkRange){
If ( $IPA -like $Network ){
$Ownername = $record.Ownername
$TimeStamp = (Get-Date("01/01/1601")).AddHours($record.TimeStamp)
Write-host "$Ownername,$IPA,$TimeStamp"
$filename = "DC-" + $ServerName + "--DOMAIN-" + $ContainerName + "--AGE-" + $TotalAgingInterval + `
"--RANGE-" + $Network.Replace("*","") + ".csv"
$logfile = "D:\\reports\\DNSscavenge\\$filename" # Logfile location
If ($DeleteKey){
$record.psbase.Delete()
If($?) {
Write-host "Successfully deleted A record: $Ownername"
}Else {
Write-host "Could not delete A record: $Ownername, error: $($error[0])"
}
$list = ("$Ownername,$TimeStamp,$?")
$list | format-table | Out-File -append "$logfile"
}Else{
$list = ("$Ownername,$TimeStamp,No")
$list | format-table | Out-File -append "$logfile"
} #end if/else
} #end if
} #end for each
} #end for each
|
PowerShellCorpus/PoshCode/Netapp SDK.ps1
|
Netapp SDK.ps1
|
#Jason Ochoa 9/16/09
#Set up NaServerObject
$null = [reflection.assembly]::loadfile('C:\\DotNet\\ManageOntap.dll')
$Toaster1 = new-Object netapp.manage.naserver('Toaster1',1,0)
$Toaster1.setadminuser("admin",'password')
#-------------------functions to be remade
function global:Get-DF-s ($NaServer){#this data can be gathered directly from the volume-info package
$NaElement = New-Object NetApp.Manage.NaElement(”system-cli”)
$arg = New-Object NetApp.Manage.NaElement(”args”)
$arg.AddNewChild(’arg’,'df’)
$arg.AddNewChild(’arg’,'-s’)
$NaElement.AddChildElement($arg)
$results= $NaServer.InvokeElem($naelement).GetChildContent(”cli-output”)
$results = $results.Split("`n")
$ResultsObj = $results| ?{$_ -match "vol"}| %{$null = $_ -match "(?<FileSystem>(\\S+))\\s+(?<used>(\\d+))\\s+(?<saved>(\\d+))\\s+(?<PercentSave>(\\d+))";
$myobj = "" | Select-Object filesystem, usedGB, savedGB, percentsave;
$myobj.filesystem = $matches.Filesystem;
$myobj.usedGB = [Math]::Round([double]$matches.used /1mb, 2);
$myobj.savedGB = [Math]::Round([double]$matches.saved /1mb, 2);
$myobj.percentsave = [int]$matches.percentsave;
,$myobj}
,($ResultsObj| Sort-Object filesystem)
}
#------------------------------sis functions
function global:Get-SIS-Status ($NaServer){
$naelement = New-Object netapp.manage.naelement("sis-status")
$NaElement.AddNewChild('verbose','true')
$Output = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.'sis-object'.'dense-status'
$Output = $output | Add-Member -MemberType NoteProperty -Name "StartTime" -Value $null -PassThru |
Add-Member -MemberType NoteProperty -Name "Duration" -Value $null -PassThru
$Output| %{$_.Duration =(((get-date -date 1/1/1970).addhours(-7)).addseconds($_.'last-operation-end-timestamp') - ((get-date -date 1/1/1970).addhours(-7)).addseconds($_.'last-operation-begin-timestamp') )}
$Output| %{$_.StartTime = (((get-date -date 1/1/1970).addhours(-7)).addseconds($_.'last-operation-begin-timestamp'))}
$Output
}
function global:Get-SIS-LongJobs ($NaServer){
$output = Get-SIS-Status ($NaServer)
$output |Sort-Object State, duration -descending| Select-Object path, duration, schedule, 'last-operation-size', State| ft -AutoSize
}
function global:Set-SIS-config ($NaServer, $volume, $schedule){
$naelement = New-Object netapp.manage.naelement("sis-set-config")
$NaElement.AddNewChild('path',$volume)
$NaElement.AddNewChild('schedule',$schedule)
([xml]($NaServer.invokeelem($naelement)).tostring()).results.'sis-object'
}
function global:start-SIS ($NaServer, $volume){
$naelement = New-Object netapp.manage.naelement("sis-start")
$NaElement.AddNewChild('path',$volume)
$null = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.'sis-object'
}
function global:stop-SIS ($NaServer, $volume){
$naelement = New-Object netapp.manage.naelement("sis-stop")
$NaElement.AddNewChild('path',$volume)
$null = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.'sis-object'
}
function global:Set-SIS-ON($NaServer, $volume, [switch]$SISOFF )
{
if (-not $SISOFF){
$naelement = New-Object netapp.manage.naelement("sis-enable")
$NaElement.AddNewChild('path',$volume)
$null = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.'sis-object'
}
else{
$naelement = New-Object netapp.manage.naelement("sis-disable")
$NaElement.AddNewChild('path',$volume)
$null = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.'sis-object'
}
}
function global:Start-SIS-All ($NaServer, $MaxJobs = 4){
$StartTime = get-date
foreach ($path in (Get-SIS-status $NaServer|%{$_.path})){
while (@(Get-SIS-status $NaServer|?{$_.status -eq "Active"}).count -ge $MaxJobs){start-sleep 15; write-host "." -nonewline}
write-host "Starting $Path"
start-sis $NaServer $Path
Start-Sleep 5}
Write-Host "This task took: $((get-date) - $StartTime)"
}
#-----------------------Snapshot functions
function global:get-Snap-AutoDeleteInfo ($NaServer)
{
$naelement = New-Object netapp.manage.naelement("volume-list-info")
$volumes = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.volumes.'volume-info'
foreach ($vol in $volumes){
$naelement = New-Object netapp.manage.naelement("snapshot-autodelete-list-info")
$NaElement.AddNewChild('volume',$Vol.name)
$snapInfo = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.options.'snapshot-autodelete-info'
$myobj = "" | Select-Object Volume, state, commitment, trigger, target_free_space, delete_order, defer_delete, destroy_list
$myobj.Volume = $vol.name
foreach ($option in $snapInfo){$myobj.($option.'option-name') = $option.'option-value'}
$myobj
}
}
function global:set-Snap-AutoDeleteInfo ($NaServer, $volume, $state="on", $commitment="try", $trigger="volume", $targer_free_space="15", $delete_order="oldest_first", $defer_delete="user_created"){
$Options = @($state, $commitment, $trigger, $targer_free_space, $delete_order, $defer_delete)
$OptionNames = @("state", "commitment", "trigger", "target_free_space", "delete_order", "defer_delete")
foreach ($Counter in (0..5)){
$naelement = New-Object netapp.manage.naelement("snapshot-autodelete-set-option")
$NaElement.AddNewChild('volume',$volume)
$NaElement.AddNewChild('option-name', $OptionNames[$counter])
$NaElement.AddNewChild('option-value',$Options[$counter])
$null = $NaServer.invokeelem($naelement)
}
}
function global:get-Snap-List ($NaServer)
{
$naelement = New-Object netapp.manage.naelement("volume-list-info")
$volumes = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.volumes.'volume-info'
foreach ($vol in $volumes){
$naelement = New-Object netapp.manage.naelement("snapshot-list-info")
$NaElement.AddNewChild('target-type','volume’)
$NaElement.AddNewChild('target-name',$Vol.name)
$snapshots = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.snapshots.'snapshot-info'
foreach ($Snap in $snapshots){
$myobj = "" | Select-Object Volume, Name, accesstime, totalMB, CTotalMB, POfUsedB, CPOfUsedB
$myobj.Volume = $vol.name
$myobj.name = $Snap.name
$myobj.accesstime = ((get-date -date 1/1/1970).addhours(-7)).addseconds($Snap.'access-time')
$myobj.totalMB = [Math]::round($Snap.total / 1kb, 2)
$myobj.CTotalMB = [Math]::round($Snap.'cumulative-total' /1kb, 2)
$myobj.POfUsedB = $Snap.'percentage-of-used-blocks'
$myobj.CPOfUsedB = $Snap.'cumulative-percentage-of-used-blocks'
$myobj
}
}
}
function global:get-SnapList-Top-Total(){
$Snaps = (get-Snap-List $1504) + (get-Snap-List $1505)
"Top 20 Large Snapshots"
$Snaps|sort-object -prop totalMB -desc| select-object -first 20 | ft -AutoSize
"Top 20 Snapshot footprint"
$Snaps| Group-Object -Property volume|%{$_.group|sort-object -prop accesstime|select-object -First 1 }| sort-object -prop CtotalMB -desc| select-object -first 20|ft -AutoSize
"Top 5 Oldest Snapshots"
$Snaps| Group-Object -Property volume|%{$_.group|sort-object -prop accesstime|select-object -First 1 }| ?{$_.name -ne $null}|sort-object -prop accesstime| select-object -first 5 | ft -AutoSize
}
function global:rename-Snap($NaServer, $CurrentName, $newName, $volume){
$naelement = New-Object netapp.manage.naelement("snapshot-rename")
$NaElement.AddNewChild('current-name',$CurrentName)
$NaElement.AddNewChild('new-name',$newName)
$NaElement.AddNewChild('volume',$volume)
$null = $NaServer.invokeelem($naelement)
}
function global:remove-Snap($NaServer, $Snapshot, $volume){
$naelement = New-Object netapp.manage.naelement("snapshot-delete")
$NaElement.AddNewChild('snapshot',$Snapshot)
$NaElement.AddNewChild('volume',$volume)
$null = $NaServer.invokeelem($naelement)
}
function global:get-snap ($NaServer, $volume){
$naelement = New-Object netapp.manage.naelement("snapshot-list-info")
$NaElement.AddNewChild('target-type','volume’)
$NaElement.AddNewChild('target-name',$volume)
$snapshots = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.snapshots.'snapshot-info'
foreach ($Snap in $snapshots){
$myobj = "" | Select-Object Volume, Name, accesstime, totalMB, CTotalMB, POfUsedB, CPOfUsedB
$myobj.Volume = $volume
$myobj.name = $Snap.name
$myobj.accesstime = ((get-date -date 1/1/1970).addhours(-7)).addseconds($Snap.'access-time')
$myobj.totalMB = [Math]::round($Snap.total / 1kb, 2)
$myobj.CTotalMB = [Math]::round($Snap.'cumulative-total' /1kb, 2)
$myobj.POfUsedB = $Snap.'percentage-of-used-blocks'
$myobj.CPOfUsedB = $Snap.'cumulative-percentage-of-used-blocks'
$myobj
}
}
function global:New-Snap ($NaServer, $SnapPrefix, $volume, $MaxSave = 5){
if ([int]$MaxSave -lt 1) {return -1}
$CurrentSnaps = get-snap $NaServer $volume
$CurrentSnaps = @($CurrentSnaps| ?{$_.name -match "^$SnapPrefix\\.\\d+$"}| Sort-Object -Property accesstime )
#"count: $($CurrentSnaps.count) - $MaxSave = $($CurrentSnaps.count - $MaxSave)"
if ($CurrentSnaps.count -gt $MaxSave-1 -and $CurrentSnaps.count -gt 0) {#remove Oldest Snap
#"hit cleanup process"
foreach ($i in 0..($CurrentSnaps.count - $MaxSave )){
#"Removing: $($CurrentSnaps[0].Name)"
remove-snap $NaServer $CurrentSnaps[0].Name $volume
$CurrentSnaps = @($CurrentSnaps| ?{$_.name -ne $CurrentSnaps[0].Name})
}
}
#"current snaps after removals"
#$CurrentSnaps|%{$_.name}
if ($CurrentSnaps -ne $null){
foreach ($Snap in $CurrentSnaps){
$null = $Snap.name -match "^$SnapPrefix\\.(?<digit>\\d+)$"
rename-snap $NaServer $Snap.name "$SnapPrefix.$([int]$matches.digit+1)" $volume
#"Renaming: $($Snap.name) -> $SnapPrefix.$([int]$matches.digit+1)"
}
}
$naelement = New-Object netapp.manage.naelement("snapshot-create")
$NaElement.AddNewChild('snapshot',"$SnapPrefix.0")
$NaElement.AddNewChild('volume',$volume)
$null = $NaServer.invokeelem($naelement)
}
# --------------- Lun functions
function Set-LUN-Caption ($NaServer, $LUNpath, $Comment){
$naelement = New-Object netapp.manage.naelement("lun-set-comment")
$NaElement.AddNewChild('comment',$comment)
$NaElement.AddNewChild('path',$LUNpath)
$null = ($NaServer.invokeelem($naelement)).tostring()
}
function global:get-Lun-Info ($NaServer, $LUNpattern='.*'){
$naelement = New-Object netapp.manage.naelement("lun-list-info")
$LUNs = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.luns.'lun-info'
$LUNs| ?{$_.path -match $LUNpattern}| Sort-Object path
}
function global:Map-Lun ($NaServer, $LUNpath, $iGroup, $LUNid){
$naelement = New-Object netapp.manage.naelement("lun-map")
$NaElement.AddNewChild('path',$LUNpath)
$NaElement.AddNewChild('initiator-group',$iGroup)
$NaElement.AddNewChild('lun-id',$LUNid)
$null = ($NaServer.invokeelem($naelement)).tostring()
}
function global:Get-LUN-Map ($NaServer, $filter ='.*'){
$LUNs = get-Lun-Info $NaServer
$Maps = foreach ($LUN in $LUNs){
$naelement = New-Object netapp.manage.naelement("lun-map-list-info")
$NaElement.AddNewChild('path',$LUN.path)
$Groups = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.'initiator-groups'.'initiator-group-info'
$groups | Add-Member -MemberType noteproperty -Name path -Value $LUN.path -Force -PassThru
}
$Maps| ?{$_.'initiator-group-name' -match $filter -or $_.path -match $filter}|Sort-Object path, 'lun-id'
}
function global:copy-LUN-Map ($NaServer, $SourceiGroup, $DestinationiGroup, $filter = '.*'){
$LUNmaps = Get-LUN-Map $NaServer $SourceiGroup $filter
foreach ($LUNmap in $LUNmaps){
Map-Lun $NaServer $LUNmap.path $DestinationiGroup $LUNmap.'lun-id'
}
}
#------------- Performance functions
function list {$args}
function global:Print-NaMatrix($values){
$c =list b c c c c d d d g g c d d d d g g g y y c d d d d g g g y y c d d d d g g g y y c d d d d g g g y y d g g g g y y y m m d g g g g y y y m m d g g g g y y y m m g y y y y m m m r r g y y y y m m m r r
$d = $c|%{ switch ($_) { "b" {"cyan"}; "c" {"cyan"}; "d" {"darkgreen"}; "g" {"Green"}; "y" {"Yellow"}; "m" {"magenta"}; "r" {"Red"}}}
$x=0;$values|%{$x=$x+$_}
1..100|%{if ($_ % 10 -eq 0){write-host ("{0:P2}" -f (($values[$_-1])/$x)) -for $d[$_-1]} else {write-host ("{0:P2}" -f (($values[$_-1])/$x)) -for $d[$_-1] -no}}
}
function global:Get-NaCounter($Filer, $counter){
$naelement = New-Object netapp.manage.naelement("perf-object-get-instances")
$NaElement.AddNewChild(’objectname’,'perf’)
$results = [xml]($Filer.invokeelem($naelement)).tostring()
$myobj = "" | Select-Object Value, Timestamp
$myobj.TimeStamp = ((get-date -date 1/1/1970).addhours(-7)).addseconds($results.results.timestamp)
$value = ($results.results.instances.'instance-data'.counters.'counter-data'|?{$_.name -eq $counter}).value
$myobj.Value = if ($value){$value} else{"Missing Counter"}
$myObj
}
function global:Get-NaCounter-TimeSlice($NaServer, $counter = 'disk_user_reads_latency_histogram', $timeSample = 10){
$values1 = (Get-NaCounter $NaServer $counter).Value
$values1= [regex]::split($values1,",")
Start-Sleep $timeSample
$values2 = (Get-NaCounter $NaServer $counter).Value
$values2= [regex]::split($values2,",")
$values =(0..($values1.count))|%{($values2[$_] - $values1[$_])}
$values
}
function global:Get-NaMatrix-Full($NaServer){
$values = (Get-NaCounter $NaServer 'cpu_disk_util_matrix').Value
$values= [regex]::split($values,",")
Print-NaMatrix $values
}
function global:Get-NaMatrix-TimeSlice($NaServer,$timeSample = 10){
Print-NaMatrix (Get-NaCounter-TimeSlice $NaServer 'cpu_disk_util_matrix' $timeSample)
}
#------------- Get and Set netapp options functions
function global:Set-NaOption ($NaServer, $OptionName, $OptionValue){
$naelement = New-Object netapp.manage.naelement("options-set")
$NaElement.AddNewChild('name',$OptionName)
$NaElement.AddNewChild('value',$OptionValue)
$null = [xml]($NaServer.invokeelem($naelement)).tostring()
Get-NaOption $NaServer "^$OptionName"
}
function global:Get-NaOption ($NaServer, $Search = '.*'){
$naelement = New-Object netapp.manage.naelement("options-list-info")
$Options = ([xml]($NaServer.invokeelem($naelement)).tostring()).results.options.'option-info'
$Options|?{$_.name -match $Search}
}
|
PowerShellCorpus/PoshCode/chkhash_27.ps1
|
chkhash_27.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 ($files.count -eq 0) {"No files found. Exiting."; exit}
if ($create -eq $true -or !(test-path $hashespath)) # Create database?
{
# Create SHA512 hashes of files and write to new database
$files = $files | %{WriteFileName "SHA-512 Hashing: `"$($_.fullname)`" ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
WriteFileNameEnd
$files |export-clixml $hashespath
"Created $hashespath"
"$($files.count) file hash(es) saved. Exiting."
exit
}
write-host "Loading file hashes from $hashespath..." -nonewline
$xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database
if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit}
}
else
{
if (!(test-path $hashespath)) {"No database found or specified, exiting."; exit}
write-host "Loading file hashes from $hashespath..." -nonewline
$xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database and check it
if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit}
$files=$xfiles
}
"Loaded $($xfiles.count) file hash(es)."
$hash=@{}
for($x=0;$x -lt $xfiles.count; $x++) # Build dictionary (hash) of filenames and indexes into file array
{
if ($hash.contains($xfiles[$x].fullname)) {continue}
$hash.Add($xfiles[$x].fullname,$x)
}
foreach($f in $files)
{
if ((get-item -ea 0 -literalpath $f.fullname) -eq $null) {continue} # skip if file no longer exists.
$n=($hash.($f.fullname))
if ($n -eq $null)
{
$nu++ # increment needs/needed updating count
if ($upd -eq $false) {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/Dir for days.ps1
|
Dir for days.ps1
|
#Initialize Global Variables
$NumYears = 0
$NumMonths = 0
$NumDays = 0
$LeapYearTest = 0
$FirstDate = ''
$LastDate = ''
$LastDateFeb = ''
$destination = Join-Path $env:USERPROFILE '\\Desktop\\Export Data' #Tells program where to write directory structure
#Get the first date from user
$FirstDate = Read-host "Please enter the beginning date in the format 'YYYY/MM/DD' "
#Error checking date input
$FirstDate = $FirstDate -as [DateTime];
if (!$FirstDate) #If not valid date, give error and exit
{
Write-host 'You have entered an invalid date, please check the date format and try again'
exit 1
}
#Get the last date from user
$LastDate = Read-host "Please enter the beginning date in the format 'YYYY/MM/DD' "
#Error checking date input
$LastDate = $LastDate -as [DateTime];
if (!$LastDate) #If not valid date, give error and exit
{
Write-host 'You have entered an invalid date, please check the date format and try again'
exit 1
}
#Loop Structure for Creation of Directores
While ( ( Get-Date $FirstDate ).AddDays( $NumDays ) -le ( Get-Date $LastDate ) ) {
#Next line creates path in the form of YYYY\\MM-MMMM\\YYYY-MM-DD
$path = Join-Path -Path (Join-Path -Path ( Join-Path -Path $destination -ChildPath ( Get-Date $FirstDate ).AddYears( $NumYears ).ToString( 'yyyy' ) ) -ChildPath ( Get-Date $FirstDate ).AddMonths( $NumMonths ).ToString( 'MM-MMMM' ))-ChildPath ( Get-Date $FirstDate ).AddDays( $NumDays ).ToString( 'yyyy-MM-dd' )
#Next line creates the directory using the path
New-Item -Path $path -ItemType 'Directory'
#Leap Year Testing to get correct end date for the month of February calling on dotNet Framework function IsLeapYear
$LeapYearTest = ( Get-Date $FirstDate ).AddYears( $NumYears )
if ([datetime]::IsLeapYear($LeapYearTest.Year) -eq 'True') { $LastDateFeb = '29-Feb' } #If leap year test is true then end of Feb is 29th
else { $LastDateFeb = '28-Feb' } #If leap year test is false then end of Feb is 28th
#Condition testing to determine the end of the month, switching to next month and next year
switch ((Get-Date $FirstDate).AddDays($NumDays).ToString('dd-MMM'))
{
'31-Jan' {$NumMonths++ }
"$LastDateFeb" {$NumMonths++ }
'31-Mar' {$NumMonths++ }
'30-Apr' {$NumMonths++ }
'31-May' {$NumMonths++ }
'30-Jun' {$NumMonths++ }
'31-Jul' {$NumMonths++ }
'31-Aug' {$NumMonths++ }
'30-Sep' {$NumMonths++ }
'31-Oct' {$NumMonths++ }
'30-Nov' {$NumMonths++ }
'31-Dec' {
$NumMonths++
$NumYears++
}
}
$NumDays++
}
|
PowerShellCorpus/PoshCode/chkhash_2.ps1
|
chkhash_2.ps1
|
# calculate SHA512 of file.
function Get-SHA512([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]'))
{
$stream = $null;
$cryptoServiceProvider = [System.Security.Cryptography.SHA512CryptoServiceProvider];
$hashAlgorithm = new-object $cryptoServiceProvider
$stream = $file.OpenRead();
$hashByteArray = $hashAlgorithm.ComputeHash($stream);
$stream.Close();
## We have to be sure that we close the file stream if any exceptions are thrown.
trap
{
if ($stream -ne $null)
{
$stream.Close();
}
break;
}
foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }}
return [string]$result;
}
function noequal ( $first, $second)
{
foreach($s in $second)
{
if ($first -eq $s) {return $false}
}
return $true
}
# chkhash.ps1 [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #3] [-u] [-h [path of .xml database]]
# -u updates the XML file database and exits
# otherwise, all files are checked against the XML file database.
# -x specifies location of xml hash database
$hashespath=".\\hashes.xml"
del variable:\\args3 -ea 0
del variable:\\args2 -ea 0
del variable:\\xfiles -ea 0
del variable:\\files -ea 0
del variable:\\exclude -ea 0
$args3=@()
$args2=$args
$nu = 0
$errs = 0
$fc = 0
$upd = $false
$create = $false
for($i=0;$i -lt $args2.count; $i++)
{
if ($args2[$i] -like "-h*") # -help specified?
{
"Usage: .\\chkhash.ps1 [-h] [-u] [-c] [-x <file path of hashes .xml database>] [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #n] [-e <Dirs>]"
"Options: -h - Help display."
" -c - Create hash database. If .xml hash database does not exist, -c will be assumed."
" -u - Update changed files and add new files to existing database."
" -x - specifies .xml database file path to use. Default is .\\hashes.xml"
" -e - exclude dirs. Put this after the files/dirs you want to check with SHA512 and needs to be fullpath (e.g. c:\\users\\bob not ..\\bob)."
""
"Examples: PS>.\\chkhash.ps1 c:\\ d:\\ -c -x c:\\users\\bob\\hashes\\hashes.xml"
" PS>.\\chkhash.ps1 c:\\users\\alice\\pictures\\sunset.jpg -a -x c:\\users\\alice\\hashes\\pictureshashes.xml"
" PS>.\\chkhash.ps1 c:\\users\\eve\\documents d:\\media\\movies -x c:\\users\\eve\\hashes\\private.xml"
" PS>.\\chkhash.ps1 c:\\users\\eve -x c:\\users\\eve\\hashes\\private.xml -e c:\\users\\eve\\hashes"
""
"Note: files in subdirectories of any specified directory are automatically processed."
exit
}
if ($args2[$i] -like "-u*") {$upd=$true;continue} # Update and Add new files to database?
if ($args2[$i] -like "-c*") {$create=$true;continue} # Create database specified?
if ($args2[$i] -like "-x*") {$i++;$hashespath=$args2[$i];continue} # Get hashes xml database path
if ($args2[$i] -like "-e*") # Exclude files, dirs
{
do {
$i++
$exclude+=@($args2[$i])
} while ($args2[$i] -notlike "-*" -and $i -lt $args2.count-1)
continue
}
$args3+=@($args2[$i]) # Add files/dirs
}
"ChkHash.ps1 - .\\chkhash.ps1 -h for usage."
""
if ($args3.count -eq 0) {exit}
# Get list of files and SHA512 hash them.
"Enumerating files from specified locations..."
$files=@(dir -literalpath $args3 -recurse -ea 0 | ?{$_.mode -notmatch "d"} | ?{noequal $_.directoryname $exclude}) # Get list of files
if ($files.count -eq 0) {"No files found. Exiting."; exit}
if ($create -eq $true -or !(test-path $hashespath)) # Create database?
{
# Create SHA512 hashes of files and write to new database
$files = $files | %{write-host "Hashing $($_.fullname) ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
$files |export-clixml $hashespath
"Created $hashespath"
"$($files.count) file hashes saved. Exiting."
exit
}
$xfiles=@(import-clixml $hashespath)
"Loaded $($xfiles.count) file hash(es) from $hashespath"
$hash=@{}
for($x=0;$x -lt $xfiles.count; $x++)
{
if ($hash.contains($xfiles[$x].fullname)) {continue}
$hash.Add($xfiles[$x].fullname,$x)
}
foreach($f in $files)
{
$n=($hash.($f.fullname))
if ($n -eq $null)
{
$nu++ # increment needs/needed updating count
if ($upd -eq $false) {"Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue
"Hashing $($f.fullname) ..."
# Create SHA512 hash of file
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
$xfiles+=@($f) # then add file + hash to list
continue
}
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
# Update and continue is specified.
$fc++ # increment files checked.
if ($xfiles[$n].SHA512 -eq $f.SHA512) # Check SHA512 for mixmatch.
{
continue
}
$errs++ # increment mixmatches
if ($upd -eq $true) { $xfiles[$n]=$f; "Updated `"$($f.fullname)`"";continue}
"Bad SHA-512 found: `"$($f.fullname)`""
}
if ($upd -eq $true) # if database updated
{
$xfiles|export-clixml $hashespath # write xml database
"Updated $hashespath"
"$nu file hash(es) added to database."
"$errs file hash(es) updated in database."
exit
}
"$errs SHA-512 mixmatch(es) found."
"$fc file(s) SHA512 matched."
if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
|
PowerShellCorpus/PoshCode/Get_Set Signature _2.0.ps1
|
Get_Set Signature _2.0.ps1
|
#Requires -version 2.0
## Authenticode.psm1 updated for PowerShell 2.0 (with time stamping)
####################################################################################################
## Wrappers for the Get-AuthenticodeSignature and Set-AuthenticodeSignature cmdlets
## These properly parse paths, so they don't kill your pipeline and script if you include a folder
##
## Usage:
## ls | Get-AuthenticodeSignature
## Get all the signatures
##
## ls | Select-AuthenticodeSigned -Mine -Broken | Set-AuthenticodeSignature
## Re-sign anything you signed before that has changed
##
## ls | Select-AuthenticodeSigned -NotMine -ValidOnly | Set-AuthenticodeSignature
## Re-sign scripts that are hash-correct but not signed by me or by someone trusted
##
####################################################################################################
## History:
## 2.2 - Added sorting and filtering the displayed certs, and the option to save your choice
## 2.1 - Added some extra exports and aliases, and included my Start-AutoSign script...
## 2.0 - Updated to work with PowerShell 2.0 RTM and add -TimeStampUrl support
## 1.7 - Modified the reading of certs to better support people who only have one :)
## 1.6 - Converted to work with CTP 3, and added function help comments
## 1.5 - Moved the default certificate setting into the module info Authenticode.psd1 file
## Note: If you get this off PoshCode, you'll have to create it yourself, see below:
## 1.4 - Moved the default certificate setting into an external psd1 file.
## 1.3 - Fixed some bugs in If-Signed and renamed it to Select-AuthenticodeSigned
## - Added -MineOnly and -NotMineOnly switches to Select-AuthenticodeSigned
## 1.2 - Added a hack workaround to make it appear as though we can sign and check PSM1 files
## It's important to remember that the signatures are NOT checked by PowerShell yet...
## 1.1 - Added a filter "If-Signed" that can be used like: ls | If-Signed
## - With optional switches: ValidOnly, InvalidOnly, BrokenOnly, TrustedOnly, UnsignedOnly
## - commented out the default Certificate which won't work for "you"
## 1.0 - first working version, includes wrappers for Get and Set
##
####################################################################################################
####################################################################################################
function Get-UserCertificate {
<#.SYNOPSIS
Gets the user's default signing certificate so we don't have to ask them over and over...
.DESCRIPTION
The Get-UserCertificate function retrieves and returns a certificate from the user. It also stores the certificate so it can be reused without re-querying for the location and/or password ...
.RETURNVALUE
An X509Certificate2 suitable for code-signing
#>
[CmdletBinding()]
Param()
Write-Debug "PrivateData: $($ExecutionContext.SessionState.Module | fl * | Out-String)"
$UserCertificate = Get-AuthenticodeCertificate $ExecutionContext.SessionState.Module.PrivateData
$ExecutionContext.SessionState.Module.PrivateData = $UserCertificate.Thumbprint
return $UserCertificate
}
function Get-AuthenticodeCertificate {
[CmdletBinding()]
PARAM (
$Name = $ExecutionContext.SessionState.Module.PrivateData
)
END {
trap {
Write-Host "The authenticode module requires a code-signing certificate, and can't find yours!"
Write-Host
Write-Host "If this is the first time you've seen this error, please run Get-AuthenticodeCertificate by hand and specify the full path to your PFX file, or the Thumbprint of a cert in your OS Cert store -- and then answer YES to save that cert in the 'PrivateData' of the Authenticode Module metadata."
Write-Host
Write-Host "If you have seen this error multiple times, you may need to manually create a module manifest for this module with the path to your cert, and/or specify the certificate name each time you use it."
Write-Error $_
return
}
# Import-LocalizedData -bindingVariable CertificatePath -EA "STOP"
if(!$Name) {
$certs = Get-ChildItem Cert:\\ -Recurse -CodeSign | Sort NotAfter
if($certs.Count) {
Write-Host "You have $($certs.Count) certs in your local cert storage which you can specify by Thumbprint:" -fore cyan
$certs | Out-Host
}
$Name = $(Read-Host "Please specify a user certificate (wildcards allowed)")
}
if($Name -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2]) {
Write-Debug "CertificatePath: $Name"
$ResolvedPath = $Null
$ResolvedPath = Resolve-Path $Name -ErrorAction "SilentlyContinue"
if(!$ResolvedPath -or !(Test-Path $ResolvedPath -ErrorAction "SilentlyContinue")) {
Write-Debug "Not a full path: $ResolvedPath"
$ResolvedPath = Resolve-Path (Join-Path $PsScriptRoot $Name -ErrorAction "SilentlyContinue") -ErrorAction "SilentlyContinue"
}
if(!$ResolvedPath -or !(Test-Path $ResolvedPath -ErrorAction "SilentlyContinue")) {
Write-Debug "Not a file Path: $ResolvedPath"
$ResolvedPath = Get-ChildItem Cert:\\ -Recurse -CodeSign | Where {$_.ThumbPrint -like $Name } | Select -Expand PSPath
Write-Debug "ResolvedPath: $ResolvedPath"
}
if(@($ResolvedPath).Count -gt 1) {
throw "You need to specify enough of the name to narrow it to a single certificate"
}
$Certificate = get-item $ResolvedPath -ErrorAction "SilentlyContinue"
if($Certificate -is [System.IO.FileInfo]) {
$Certificate = Get-PfxCertificate $Certificate -ErrorAction "SilentlyContinue"
}
Write-Verbose "Certificate: $($Certificate | Out-String)"
$Name = $Certificate
}
if(!$ExecutionContext.SessionState.Module.PrivateData -and $Name) {
if($Host.UI -and $Host.UI.PromptForChoice -and (0 -eq
$Host.UI.PromptForChoice("Keep this certificate for future sessions?", $Name,
[Management.Automation.Host.ChoiceDescription[]]@("&Yes","&No"), 0))
) {
$mVersion = $PSCmdlet.MyInvocation.MyCommand.Module.Version
if(!$MVersion) { $MVersion = 2.2 }
New-ModuleManifest $PSScriptRoot\\Authenticode.psd1 `
-ModuleToProcess $PSScriptRoot\\Authenticode.psm1 `
-Author 'Joel Bennett' -Company 'HuddledMasses.org' `
-ModuleVersion $MVersion `
-PowerShellVersion '2.0' `
-Copyright '(c) 2008-2010, Joel Bennett' `
-Desc 'Function wrappers for Authenticode Signing cmdlets' `
-Types @() -Formats @() -RequiredModules @() `
-RequiredAssemblies @() -FileList @() -NestedModules @() `
-PrivateData $Name.Thumbprint
$null = Sign $PSScriptRoot\\Authenticode.psd1 -Cert $Name
}
$ExecutionContext.SessionState.Module.PrivateData = $Name
}
return $Name
}
}
####################################################################################################
function Test-AuthenticodeSignature {
<#.SYNOPSIS
Tests a script signature to see if it is valid, or at least unaltered.
.DESCRIPTION
The Test-AuthenticodeSignature function processes the output of Get-AuthenticodeSignature to determine if it
is Valid, OR **unaltered** and signed by the user's certificate
.NOTES
Test-AuthenticodeSignature returns TRUE even if the root CA certificate can't be verified, as long as the signing certificate's thumbnail matches the one specified by Get-UserCertificate.
.EXAMPLE
ls *.ps1 | Get-AuthenticodeSignature | Where {Test-AuthenticodeSignature $_}
To get the signature reports for all the scripts that we consider safely signed.
.EXAMPLE
ls | ? { gas $_ | Test-AuthenticodeSignature }
List all the valid signed scripts (or scripts signed by our cert)
.INPUTTYPE
System.Management.Automation.Signature
.PARAMETER Signature
Specifies the signature object to test. This should be the output of Get-AuthenticodeSignature.
.PARAMETER ForceValid
Switch parameter, forces the signature to be valid -- otherwise, even if the certificate chain can't be verified, we will accept the cert which matches the "user" certificate (see Get-UserCertificate).
Aliases Valid
.RETURNVALUE
Boolean value representing whether the script's signature is valid, or YOUR certificate
##################################################################################################
#>
[CmdletBinding()]
PARAM (
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
# The signature to test.
$Signature
,
[Alias("Valid")]
[Switch]$ForceValid
)
return ( $Signature.Status -eq "Valid" -or
( !$ForceValid -and
($Signature.Status -eq "UnknownError") -and
($_.SignerCertificate.Thumbprint -eq $(Get-UserCertificate).Thumbprint)
) )
}
####################################################################################################
function Set-AuthenticodeSignature {
<#.SYNOPSIS
Adds an Authenticode signature to a Windows PowerShell script or other file.
.DESCRIPTION
The Set-AuthenticodeSignature function adds an Authenticode signature to any file that supports Subject Interface Package (SIP).
In a Windows PowerShell script file, the signature takes the form of a block of text that indicates the end of the instructions that are executed in the script. If there is a signature in the file when this cmdlet runs, that signature is removed.
.NOTES
After the certificate has been validated, but before a signature is added to the file, the function checks the value of the $SigningApproved preference variable. If this variable is not set, or has a value other than TRUE, you are prompted to confirm the signing of the script.
When specifying multiple values for a parameter, use commas to separate the values. For example, "<parameter-name> <value1>, <value2>".
.EXAMPLE
ls *.ps1 | Set-AuthenticodeSignature -Certificate $Certificate
To sign all of the files with the specified certificate
.EXAMPLE
ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature | Where {!(Test-AuthenticodeSignature $_ -Valid)} | gci | Set-AuthenticodeSignature
List all the script files, and get and test their signatures, and then sign all of the ones that are not valid, using the user's default certificate.
.INPUTTYPE
String. You can pipe a file path to Set-AuthenticodeSignature.
.PARAMETER FilePath
Specifies the path to a file that is being signed.
Aliases Path, FullName
.PARAMETER Certificate
Specifies the certificate that will be used to sign the script or file. Enter a variable that stores an object representing the certificate or an expression that gets the certificate.
To find a certificate, use Get-PfxCertificate or use the Get-ChildItem cmdlet in the Certificate (Cert:) drive. If the certificate is not valid or does not have code-signing authority, the command fails.
.PARAMETER Force
Allows the cmdlet to append a signature to a read-only file. Even using the Force parameter, the cmdlet cannot override security restrictions.
.Parameter HashAlgorithm
Specifies the hashing algorithm that Windows uses to compute the digital signature for the file. The default is SHA1, which is the Windows default hashing algorithm.
Files that are signed with a different hashing algorithm might not be recognized on other systems.
.PARAMETER IncludeChain
Determines which certificates in the certificate trust chain are included in the digital signature. "NotRoot" is the default.
Valid values are:
-- Signer: Includes only the signer's certificate.
-- NotRoot: Includes all of the certificates in the certificate chain, except for the root authority.
--All: Includes all the certificates in the certificate chain.
.PARAMETER TimestampServer
Uses the specified time stamp server to add a time stamp to the signature. Type the URL of the time stamp server as a string.
Defaults to Verisign's server: http://timestamp.verisign.com/scripts/timstamp.dll
The time stamp represents the exact time that the certificate was added to the file. A time stamp prevents the script from failing if the certificate expires because users and programs can verify that the certificate was valid atthe time of signing.
.RETURNVALUE
System.Management.Automation.Signature
###################################################################################################>
[CmdletBinding()]
PARAM (
[Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ValueFromPipeline=$true)]
[Alias("FullName","Path")]
[ValidateScript({
if((resolve-path $_).Provider.Name -ne "FileSystem") {
throw "Specified Path is not in the FileSystem: '$_'"
}
return $true
})]
[string[]]
$FilePath
,
[Parameter(Position=2, Mandatory=$false)]
$Certificate = $(Get-UserCertificate)
,
[Switch]$Force
,
[ValidateSet("SHA","MD5","SHA1","SHA256","SHA384","SHA512")]
[String]$HashAlgorithm #="SHA1"
,
[ValidateSet("Signer","NotRoot","All")]
[String]$IncludeChain #="NotRoot"
,
[String]$TimestampServer = "http://timestamp.verisign.com/scripts/timstamp.dll"
)
BEGIN {
if($Certificate -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2]) {
$Certificate = Get-AuthenticodeCertificate $Certificate
}
$PSBoundParameters["Certificate"] = $Certificate
}
PROCESS {
Write-Verbose "Set Authenticode Signature on $FilePath with $($Certificate | Out-String)"
$PSBoundParameters["FilePath"] = $FilePath = $(Resolve-Path $FilePath)
if(Test-Path $FilePath -Type Leaf) {
Microsoft.PowerShell.Security\\Set-AuthenticodeSignature @PSBoundParameters
} else {
Write-Warning "Cannot sign folders: '$FilePath'"
}
}
}
####################################################################################################
function Get-AuthenticodeSignature {
<#.SYNOPSIS
Gets information about the Authenticode signature in a file.
.DESCRIPTION
The Get-AuthenticodeSignature function gets information about the Authenticode signature in a file. If the file is not signed, the information is retrieved, but the fields are blank.
.NOTES
For information about Authenticode signatures in Windows PowerShell, type "get-help About_Signing".
When specifying multiple values for a parameter, use commas to separate the values. For example, "-<parameter-name> <value1>, <value2>".
.EXAMPLE
Get-AuthenticodeSignature script.ps1
To get the signature information about the script.ps1 script file.
.EXAMPLE
ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature
Get the signature information for all the script and data files
.EXAMPLE
ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature | Where {!(Test-AuthenticodeSignature $_ -Valid)} | gci | Set-AuthenticodeSignature
This command gets information about the Authenticode signature in all of the script and module files, and tests the signatures, then signs all of the ones that are not valid.
.INPUTTYPE
String. You can pipe the path to a file to Get-AuthenticodeSignature.
.PARAMETER FilePath
The path to the file being examined. Wildcards are permitted, but they must lead to a single file. The parameter name ("-FilePath") is optional.
Aliases Path, FullName
.RETURNVALUE
System.Management.Automation.Signature
###################################################################################################>
[CmdletBinding()]
PARAM (
[Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName","Path")]
[ValidateScript({
if((resolve-path $_).Provider.Name -ne "FileSystem") {
throw "Specified Path is not in the FileSystem: '$_'"
}
if(!(Test-Path -PathType Leaf $_)) {
throw "Specified Path is not a File: '$_'"
}
return $true
})]
[string[]]
$FilePath
)
PROCESS {
Microsoft.PowerShell.Security\\Get-AuthenticodeSignature -FilePath $FilePath
}
}
####################################################################################################
function Select-AuthenticodeSigned {
<#.SYNOPSIS
Select files based on the status of their Authenticode Signature.
.DESCRIPTION
The Select-AuthenticodeSigned function filters files on the pipeline based on the state of their authenticode signature.
.NOTES
For information about Authenticode signatures in Windows PowerShell, type "get-help About_Signing".
When specifying multiple values for a parameter, use commas to separate the values. For example, "-<parameter-name> <value1>, <value2>".
.EXAMPLE
ls *.ps1,*.ps[dm]1 | Select-AuthenticodeSigned
To get the signature information about the script.ps1 script file.
.EXAMPLE
ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature
Get the signature information for all the script and data files
.EXAMPLE
ls *.ps1,*.psm1,*.psd1 | Get-AuthenticodeSignature | Where {!(Test-AuthenticodeSignature $_ -Valid)} | gci | Set-AuthenticodeSignature
This command gets information about the Authenticode signature in all of the script and module files, and tests the signatures, then signs all of the ones that are not valid.
.INPUTTYPE
String. You can pipe the path to a file to Get-AuthenticodeSignature.
.PARAMETER FilePath
The path to the file being examined. Wildcards are permitted, but they must lead to a single file. The parameter name ("-FilePath") is optional.
Aliases Path, FullName
.RETURNVALUE
System.Management.Automation.Signature
###################################################################################################>
[CmdletBinding()]
PARAM (
[Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[ValidateScript({
if((resolve-path $_).Provider.Name -ne "FileSystem") {
throw "Specified Path is not in the FileSystem: '$_'"
}
return $true
})]
[string[]]
$FilePath
,
[Parameter()]
# Return only files that are signed with the users' certificate (as returned by Get-UserCertificate).
[switch]$MineOnly
,
[Parameter()]
# Return only files that are NOT signed with the users' certificate (as returned by Get-UserCertificate).
[switch]$NotMineOnly
,
[Parameter()]
[Alias("HashMismatch")]
# Return only files with signatures that are broken (where the file has been edited, and the hash doesn't match).
[switch]$BrokenOnly
,
[Parameter()]
# Returns the files that are Valid OR signed with the users' certificate (as returned by Get-UserCertificate).
#
# That is, TrustedOnly returns files returned by -ValidOnly OR -MineOnly (if you specify both parameters, you get only files that are BOTH -ValidOnly AND -MineOnly)
[switch]$TrustedOnly
,
[Parameter()]
# Return only files that are "Valid": This means signed with any cert where the certificate chain is verifiable to a trusted root certificate. This may or may not include files signed with the user's certificate.
[switch]$ValidOnly
,
[Parameter()]
# Return only files that doesn't have a "Valid" signature, which includes files that aren't signed, or that have a hash mismatch, or are signed by untrusted certs (possibly including the user's certificate).
[switch]$InvalidOnly
,
[Parameter()]
# Return only signable files that aren't signed at all. That is, only files that support Subject Interface Package (SIP) but aren't signed.
[switch]$UnsignedOnly
)
PROCESS {
if(!(Test-Path -PathType Leaf $FilePath)) {
# if($ErrorAction -ne "SilentlyContinue") {
# Write-Error "Specified Path is not a File: '$FilePath'"
# }
} else {
foreach($sig in Get-AuthenticodeSignature -FilePath $FilePath) {
# Broken only returns ONLY things which are HashMismatch
if($BrokenOnly -and $sig.Status -ne "HashMismatch")
{
Write-Debug "$($sig.Status) - Not Broken: $FilePath"
return
}
# Trusted only returns ONLY things which are Valid
if($ValidOnly -and $sig.Status -ne "Valid")
{
Write-Debug "$($sig.Status) - Not Trusted: $FilePath"
return
}
# AllValid returns only things that are SIGNED and not HashMismatch
if($TrustedOnly -and (($sig.Status -ne "HashMismatch") -or !$sig.SignerCertificate) )
{
Write-Debug "$($sig.Status) - Not Valid: $FilePath"
return
}
# InvalidOnly returns things that are Either NotSigned OR HashMismatch ...
if($InvalidOnly -and ($sig.Status -eq "Valid"))
{
Write-Debug "$($sig.Status) - Valid: $FilePath"
return
}
# Unsigned returns only things that aren't signed
# NOTE: we don't test using NotSigned, because that's only set for .ps1 or .exe files??
if($UnsignedOnly -and $sig.SignerCertificate )
{
Write-Debug "$($sig.Status) - Signed: $FilePath"
return
}
# Mine returns only things that were signed by MY CertificateThumbprint
if($MineOnly -and (!($sig.SignerCertificate) -or ($sig.SignerCertificate.Thumbprint -ne $((Get-UserCertificate).Thumbprint))))
{
Write-Debug "Originally signed by someone else, thumbprint: $($sig.SignerCertificate.Thumbprint)"
Write-Debug "Does not match your default certificate print: $((Get-UserCertificate).Thumbprint)"
Write-Debug " $FilePath"
return
}
# NotMine returns only things that were NOT signed by MY CertificateThumbprint
if($NotMineOnly -and (!($sig.SignerCertificate) -or ($sig.SignerCertificate.Thumbprint -eq $((Get-UserCertificate).Thumbprint))))
{
if($sig.SignerCertificate) {
Write-Debug "Originally signed by you, thumbprint: $($sig.SignerCertificate.Thumbprint)"
Write-Debug "Matches your default certificate print: $((Get-UserCertificate).Thumbprint)"
Write-Debug " $FilePath"
}
return
}
if(!$BrokenOnly -and !$TrustedOnly -and !$ValidOnly -and !$InvalidOnly -and !$UnsignedOnly -and !($sig.SignerCertificate) )
{
Write-Debug "$($sig.Status) - Not Signed: $FilePath"
return
}
get-childItem $sig.Path
}}
}
}
function Start-AutoSign {
# .Synopsis
# Start a FileSystemWatcher to automatically sign scripts when you save them
# .Description
# Create a FileSystemWatcher with a scriptblock that uses the Authenticode script Module to sign anything that changes
# .Parameter Path
# The path to the folder you want to monitor
# .Parameter Filter
# A filter to select only certain files: by default, *.ps* (because we can only sign .ps1, .psm1, .psd1, and .ps1xml
# .Parameter Recurse
# Whether we should also watch autosign files in subdirectories
# .Parameter CertPath
# The path or name of a certain certificate, to override the defaults from the Authenticode Module
# .Parameter NoNotify
# Whether wo should avoid using Growl to notify the user each time we sign something.
# .NOTE
# Don't run this on a location where you're going to be generating dozens or hundreds of files ;)
PARAM($Path=".", $Filter= "*.ps*", [Switch]$Recurse, $CertPath, [Switch]$NoNotify)
if(!$NoNotify -and (Get-Module Growl -ListAvailable -ErrorAction 0)) {
Import-Module Growl
Register-GrowlType AutoSign "Signing File" -ErrorAction 0
} else { $NoNotify = $false }
$realItem = Get-Item $Path -ErrorAction Stop
if (-not $realItem) { return }
$Action = {
## Files that can't be signed show up as "UnknownError" with this message:
$InvalidForm = "The form specified for the subject is not one supported or known by the specified trust provider"
## Files that are signed with a cert we don't trust also show up as UnknownError, but with different messages:
# $UntrustedCert = "A certificate chain could not be built to a trusted root authority"
# $InvalidCert = "A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider"
# $ExpiredCert = "A required certificate is not within its validity period when verifying against the current system clock or the timestamp in the signed file"
ForEach($file in Get-ChildItem $eventArgs.FullPath | Get-AuthenticodeSignature |
Where-Object { $_.Status -ne "Valid" -and $_.StatusMessage -ne $invalidForm } |
Select-Object -ExpandProperty Path )
{
if(!$NoNotify) {
Send-Growl AutoSign "Signing File" "File $($eventArgs.ChangeType), signing:" "$file"
}
if($CertPath) {
Set-AuthenticodeSignature -FilePath $file -Certificate $CertPath
} else {
Set-AuthenticodeSignature -FilePath $file
}
}
}
$watcher = New-Object IO.FileSystemWatcher $realItem.Fullname, $filter -Property @{ IncludeSubdirectories = $Recurse }
Register-ObjectEvent $watcher "Created" "AutoSignCreated$($realItem.Fullname)" -Action $Action > $null
Register-ObjectEvent $watcher "Changed" "AutoSignChanged$($realItem.Fullname)" -Action $Action > $null
Register-ObjectEvent $watcher "Renamed" "AutoSignChanged$($realItem.Fullname)" -Action $Action > $null
}
Set-Alias gas Get-AuthenticodeSignature -Description "Authenticode Module Alias"
Set-Alias sas Set-AuthenticodeSignature -Description "Authenticode Module Alias"
Set-Alias slas Select-AuthenticodeSigned -Description "Authenticode Module Alias"
Set-Alias sign Set-AuthenticodeSignature -Description "Authenticode Module Alias"
Export-ModuleMember -Alias gas,sas,slas,sign -Function Set-AuthenticodeSignature, Get-AuthenticodeSignature, Test-AuthenticodeSignature, Select-AuthenticodeSigned, Get-UserCertificate, Get-AuthenticodeCertificate, Start-AutoSign
# SIG # Begin signature block
# MIIIPAYJKoZIhvcNAQcCoIIILTCCCCkCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU0tI8MdRYrPgGbk0OfxXiog9F
# IJigggVaMIIFVjCCBD6gAwIBAgIQSX2g7+3+PL1oSJra3tEBIzANBgkqhkiG9w0B
# AQUFADCBlTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0
# IExha2UgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYD
# VQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHTAbBgNVBAMTFFVUTi1VU0VS
# Rmlyc3QtT2JqZWN0MB4XDTA5MTAxNjAwMDAwMFoXDTEwMTAxNjIzNTk1OVowgcQx
# CzAJBgNVBAYTAlVTMQ4wDAYDVQQRDAUxNDYyMzERMA8GA1UECAwITmV3IFlvcmsx
# EjAQBgNVBAcMCVJvY2hlc3RlcjEUMBIGA1UECQwLTVMgMDgwMS0xN0ExGjAYBgNV
# BAkMETEzNTAgSmVmZmVyc29uIFJkMRowGAYDVQQKDBFYZXJveCBDb3Jwb3JhdGlv
# bjEUMBIGA1UECwwLU0VFRFUgVG9vbHMxGjAYBgNVBAMMEVhlcm94IENvcnBvcmF0
# aW9uMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA+BtkDUSRsr9qshYW
# 6mBLwe62RdoKaBiCZh1whKQbAqN58lmbN3fP2Qf6eheR03EyqPXq5gGQO8SpeeOn
# tDmlgR47dKFfawWKLEM4H189FJ6VHKD8Hmk1+/OAv/6F45HvbXOrGmisUgKplmzl
# tmot9uv04nyFlRXMPbHwKxNlWOdSSs1N9Y+q7y3kuSBm4bCqquqEFnm7gAzHt/A1
# 1CkT8f/0UP0ODKj0Cs/hc+b/xOCCL06SALYOYtMdBFwluBs85p2Bv1WcdUIELprz
# jnOjgoF4vk29UIUNkDZ5j2d0W0FCNd61ukm9faJMuU2/yw348sxclSoT18yOeC+Z
# vKc4lQIDAQABo4IBbzCCAWswHwYDVR0jBBgwFoAU2u1kdBScFDyr3ZmpvVsoTYs8
# ydgwHQYDVR0OBBYEFAu07ifjpHK32XeSDsdjIK4/R25LMA4GA1UdDwEB/wQEAwIH
# gDAMBgNVHRMBAf8EAjAAMBMGA1UdJQQMMAoGCCsGAQUFBwMDMBEGCWCGSAGG+EIB
# AQQEAwIEEDBGBgNVHSAEPzA9MDsGDCsGAQQBsjEBAgEDAjArMCkGCCsGAQUFBwIB
# Fh1odHRwczovL3NlY3VyZS5jb21vZG8ubmV0L0NQUzBCBgNVHR8EOzA5MDegNaAz
# hjFodHRwOi8vY3JsLnVzZXJ0cnVzdC5jb20vVVROLVVTRVJGaXJzdC1PYmplY3Qu
# Y3JsMDQGCCsGAQUFBwEBBCgwJjAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AuY29t
# b2RvY2EuY29tMCEGA1UdEQQaMBiBFkpvZWwuQmVubmV0dEBYZXJveC5jb20wDQYJ
# KoZIhvcNAQEFBQADggEBAG5+It5AFsnqx1GDTuHxuExJGtpRYH6OatSs3eV507zz
# 5tyKbtCros6j92rvJOUfefk38saqbk81o5vMvEyQ/lQ7tp06NV0QBdt5WtoOnUZk
# u2lG4NcxiSz5vxQRF4+3mUZ77K3kRu6zY+zrauTTONmRPOdhYMMbKfZ67kePVNNv
# gnueXBxhd+xj5FJUVTW0qlks6+uYMKNM+MLvRxV83WUYwpnfcQyyvVILsVdw56qp
# OzOxIsQDc2flhqYVktPjL80fOXAPWzs88VXxoEkO3fvqHXi3VlWxMVV/861RORzk
# 5aleuMEp/2Ue1dJG279ATD1QDCHiG11Vz34Pdptf3FYxggJMMIICSAIBATCBqjCB
# lTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2Ug
# Q2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExho
# dHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHTAbBgNVBAMTFFVUTi1VU0VSRmlyc3Qt
# T2JqZWN0AhBJfaDv7f48vWhImtre0QEjMAkGBSsOAwIaBQCgeDAYBgorBgEEAYI3
# AgEMMQowCKACgAChAoAAMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3AgEEMBwGCisG
# AQQBgjcCAQsxDjAMBgorBgEEAYI3AgEVMCMGCSqGSIb3DQEJBDEWBBRfh5JdQ29J
# 9Uc79ppuJEJLRp5tCTANBgkqhkiG9w0BAQEFAASCAQBGarkiFDUgoQJBLuOyfY6k
# LZzx3XBcHzaon1DiGXR2llvEVdglgOUsyXhXnckBwV4nD44PYmCAXLIZze92oHN4
# ytxkl/wSwhxoZ3NYG7XXVg+X7CVL7PKXBKkEYofneeFYjF2F6UlkutjiObsos4Cv
# LYEMGk/K6hU5DSu2yJY9aCKMhms30nhGc1ov/wBI5b9HhQYVYrOdw9Bq3LpyDpXL
# 2C0kDMrZYHudp50q1l9JufzeWDdhGm7Oc9RcdV96enBFrlDPLDuMRzXCuNavsgva
# lHCK2G7L8QiF/eMrlxn1jIfXTCH11NuQOAZ+FPDZGtrpxlS/MQ3eZRX+O2FqLW8F
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Reflection Module.ps1
|
Reflection Module.ps1
|
#requires -version 2.0
#History:
# 1.0 - First public release (March 19, 2010)
# 2.0 - Private Build
# - Included the Accelerator function inline
# - Added a few default aliases
# 3.0 - September 3, 2010
# - Included the New-ConstructorFunction feature (ripped from PowerBoots to serve a more generic and powerful purpose!)
# - New-ConstructorFunction and Import-ConstructorFunctions depend on the Autoload Module: http://poshcode.org/2312
# - NOTE: You should really have a Reflection.psd1 with the contents: @{ RequiredModules = @("Autoload"); GUID="64b5f609-970f-4e65-b02f-93ccf3e60cbb"; ModuleVersion="3.0.0.0" }
function Get-Type {
<#
.Synopsis
Gets the types that are currenty loaded in .NET, or gets information about a specific type
.Description
Gets information about one or more loaded types, or gets the possible values for an enumerated type or value.
.Parameter Assembly
The Assemblies to search for types.
Can be an actual Assembly object or a regex to pass to Get-Assembly.
.Parameter TypeName
The type name(s) to search for (wildcard patterns allowed).
.Parameter BaseType
A Base type they should derive from (wildcard patterns allowed).
.Parameter Enum
An enumeration to list all of enumeration values for
.Parameter Namespace
A namespace to restrict where we selsect types from (wildcard patterns allowed).
.Parameter Force
Causes Private types to be included
.Example
Get-Type
Gets all loaded types (takes a VERY long time to print out)
.Example
Get-Type -Assembly ([PSObject].Assembly)
Gets types from System.Management.Automation
.Example
[Threading.Thread]::CurrentThread.ApartmentState | Get-Type
Gets all of the possible values for the ApartmentState property
.Example
[Threading.ApartmentState] | Get-Type
Gets all of the possible values for an apartmentstate
#>
[CmdletBinding(DefaultParameterSetName="Assembly")]
param(
# The assembly to collect types from
[Parameter(ValueFromPipeline=$true)]
[PsObject[]]$Assembly
,
# The type names to return from
[Parameter(Mandatory=$false)]
[String[]]$TypeName
,
# The type names to return from
[Parameter(Mandatory=$false)]
[String[]]$Namespace
,
# A Base Type they should derive from
[Parameter(Mandatory=$false)]
[String[]]$BaseType
,
# The enumerated value to get all of the possibilties of
[Parameter(ParameterSetName="Enum", ValueFromPipeline=$true)]
[PSObject]$Enum
,
[Parameter()][Alias("Private","ShowPrivate")]
[Switch]$Force
)
process {
if($psCmdlet.ParameterSetName -eq 'Enum') {
if($Enum -is [Enum]) {
[Enum]::GetValues($enum.GetType())
} elseif($Enum -is [Type] -and $Enum.IsEnum) {
[Enum]::GetValues($enum)
} else {
throw "Specified Enum is neither an enum value nor an enumerable type"
}
}
else {
if($Assembly -as [Reflection.Assembly[]]) {
## This is what we expected, move along
} elseif($Assembly -as [String[]]) {
$Assembly = Get-Assembly $Assembly
} elseif(!$Assembly) {
$Assembly = [AppDomain]::CurrentDomain.GetAssemblies()
}
:asm foreach ($asm in $assembly) {
Write-Verbose "Testing Types from Assembly: $($asm.Location)"
if ($asm) {
$asm.GetTypes() | Where {
( $Force -or $_.IsPublic ) -AND
( !$Namespace -or $( foreach($n in $Namespace) { $_.Namespace -like $n } ) ) -AND
( !$TypeName -or $( foreach($n in $TypeName) { $_.Name -like $n -or $_.FullName -like $n } ) -contains $True ) -AND
( !$BaseType -or $( foreach($n in $BaseType) { $_.BaseType -like $n } ) -contains $True )
}
}
}
}
}
}
function Add-Assembly {
#.Synopsis
# Load assemblies
#.Description
# Load assemblies from a folder
#.Parameter Path
# Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.).
#.Parameter Passthru
# Returns System.Runtime objects that represent the types that were added. By default, this cmdlet does not generate any output.
# Aliased to -Types
#.Parameter Recurse
# Gets the items in the specified locations and in all child items of the locations.
#
# Recurse works only when the path points to a container that has child items, such as C:\\Windows or C:\\Windows\\*, and not when it points to items that do not have child items, such as C:\\Windows\\*.dll
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true, Position=0)]
[Alias("PSPath")]
[string[]]$Path = "."
,
[Alias("Types")]
[Switch]$Passthru
,
[Switch]$Recurse
)
process {
foreach($file in Get-ChildItem $Path -Filter *.dll -Recurse:$Recurse) {
Add-Type -Path $file.FullName -Passthru:$Passthru | Where { $_.IsPublic }
}
}
}
function Get-Assembly {
<#
.Synopsis
Get a list of assemblies available in the runspace
.Description
Returns AssemblyInfo for all the assemblies available in the current AppDomain, optionally filtered by partial name match
.Parameter Name
A regex to filter the returned assemblies. This is matched against the .FullName or Location (path) of the assembly.
#>
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true, Position=0)]
[string[]]$Name = ''
)
process {
[appdomain]::CurrentDomain.GetAssemblies() | Where { $(foreach($n in $Name){$_.FullName -match $n -or $_.Location -match $n }) -contains $True }
}
}
function Get-Constructor {
<#
.Synopsis
Returns RuntimeConstructorInfo for the (public) constructor methods of the specified Type.
.Description
Get the RuntimeConstructorInfo for a type and add members "Syntax," "SimpleSyntax," and "Definition" to each one containing the syntax information that can use to call that constructor.
.Parameter Type
The type to get the constructor for
.Parameter Force
Force inclusion of Private and Static constructors which are hidden by default.
.Parameter NoWarn
Serves as the replacement for the broken -WarningAction. If specified, no warnings will be written for types without public constructors.
.Example
Get-Constructor System.IO.FileInfo
Description
-----------
Gets all the information about the single constructor for a FileInfo object.
.Example
Get-Type System.IO.*info mscorlib | Get-Constructor -NoWarn | Select Syntax
Description
-----------
Displays the constructor syntax for all of the *Info objects in the System.IO namespace.
Using -NoWarn supresses the warning about System.IO.FileSystemInfo not having constructors.
.Example
$path = $pwd
$driveName = $pwd.Drive
$fileName = "$Profile"
Get-Type System.IO.*info mscorlib | Get-Constructor -NoWarn | ForEach-Object { Invoke-Expression $_.Syntax }
Description
-----------
Finds and invokes the constructors for DirectoryInfo, DriveInfo, and FileInfo.
Note that we pre-set the parameters for the constructors, otherwise they would fail with null arguments, so this example isn't really very practical.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$true, Position=0)]
[Alias("ParameterType")]
[Type]$Type
, [Switch]$Force
, [Switch]$NoWarn
)
process {
$type.GetConstructors() | Where-Object { $Force -or $_.IsPublic -and -not $_.IsStatic } -OutVariable ctor | Select *,
@{ name = "TypeName"; expression = { $_.ReflectedType.FullName } },
@{ name = "Definition";
expression = {Get-MemberSignature $_ -Simple}
},
@{ name = "Syntax";
expression = {Get-MemberSignature $_ -Simple}
},
@{ name = "SafeSyntax";
expression = {Get-MemberSignature $_}
}
if(!$ctor -and !$NoWarn) { Write-Warning "There are no public constructors for $($type.FullName)" }
}
}
function Get-Method {
<#
.Synopsis
Returns MethodInfo for the (public) constructor methods of the specified Type.
.Description
Get the MethodInfo for a type and add members "Syntax," "SimpleSyntax," and "Definition" to each one containing the syntax information that can use to call that constructor.
.Parameter Type
The type to get methods on
.Parameter Name
The name(s) of the method(s) you want to retrieve (Accepts Wildcard Patterns)
.Parameter Force
Force inclusion of Private methods and property accessors which are hidden by default.
#>
[CmdletBinding(DefaultParameterSetName="Type")]
param(
[Parameter(ParameterSetName="Type", Mandatory=$true, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$true, Position=0)]
[Type]$Type
,
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, Position=1)]
[String[]]$Name ="*"
, [Switch]$Definition
, [Switch]$Force
)
process {
foreach($method in
$type.GetMethods() + $type.GetConstructors() | Where-Object { $Force -or $_.IsPublic } |
# Hide the Property accessor methods
Where-Object { $Force -or !$_.IsSpecialName -or $_.Name -notmatch "^get_|^set_" } |
Where-Object { $( foreach($n in $Name) { $_.Name -like $n } ) -contains $True } )
{
$method |
Add-Member NoteProperty TypeName -Value $($method.ReflectedType.FullName ) -Passthru |
Add-Member NoteProperty Definition -Value $(Get-MemberSignature $method -Simple) -Passthru |
Add-Member AliasProperty Syntax Definition -Passthru |
#Add-Member NoteProperty Syntax -Value $(Get-MemberSignature $method -Simple) -Passthru |
Add-Member NoteProperty SafeSyntax -Value $(Get-MemberSignature $method ) -Passthru
}
}
}
function Get-MemberSignature {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true,Mandatory=$true)]
[System.Reflection.MethodBase]$MethodBase,
[Switch]$Simple
)
process {
$parameters = $(
foreach($param in $MethodBase.GetParameters()) {
# Write-Host $param.ParameterType.FullName.TrimEnd('&'), $param.Name -fore cyan
if($param.ParameterType.Name.EndsWith('&')) { $ref = '[ref]' } else { $ref = '' }
if($param.ParameterType.IsArray) { $array = ',' } else { $array = '' }
if($Simple) {
'{0} {1}' -f $parm.ParameterType.FullName, $param.Name
} else {
'{0}({1}[{2}]${3})' -f $ref, $array, $param.ParameterType.FullName.TrimEnd('&'), $param.Name
}
}
)
if($MethodBase.IsConstructor) {
"New-Object $($MethodBase.ReflectedType.FullName) $($parameters -join ', ')"
} elseif($Simple) {
"$($MethodBase.ReturnType.FullName) $($MethodBase.Name)($($parameters -join ', '))"
} elseif($MethodBase.IsStatic) {
"[$($MethodBase.ReturnType.FullName)] [$($MethodBase.ReflectedType.FullName)]::$($MethodBase.Name)($($parameters -join ', '))"
} else {
"[$($MethodBase.ReturnType.FullName)] `$$($MethodBase.ReflectedType.Name)Object.$($MethodBase.Name)($($parameters -join ', '))"
}
}
}
function Read-Choice {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, ValueFromRemainingArguments=$true)]
[hashtable[]]$Choices
,
[Parameter(Mandatory=$False)]
[string]$Caption = "Please choose!"
,
[Parameter(Mandatory=$False)]
[string]$Message = "Choose one of the following options:"
,
[Parameter(Mandatory=$False)]
[int[]]$Default = 0
,
[Switch]$MultipleChoice
,
[Switch]$Passthru
)
begin {
[System.Collections.DictionaryEntry[]]$choices = $choices | % { $_.GetEnumerator() }
}
process {
$Descriptions = [System.Management.Automation.Host.ChoiceDescription[]]( $(
foreach($choice in $choices) {
New-Object System.Management.Automation.Host.ChoiceDescription $choice.Key,$choice.Value
}
) )
if(!$MultipleChoice) { [int]$Default = $Default[0] }
[int[]]$Answer = $Host.UI.PromptForChoice($Caption,$Message,$Descriptions,$Default)
if($Passthru) {
Write-Verbose "$Answer"
Write-Output $Descriptions[$Answer]
} else {
Write-Output $Answer
}
}
}
function Get-Argument {
param(
[Type]$Target
, [String]$Method
, $Arguments
)
end {
trap {
write-error $_
break
}
Write-Verbose "Get $Method Method on $($Target.FullName):"
$MethodBase = Get-Method $target $Method
Write-Verbose $($MethodBase | Out-String)
if(@($MethodBase).Count -gt 1) {
$i = 0
$i = Read-Choice -Choices $(foreach($mb in $MethodBase) { @{ "$($mb.SafeSyntax) &$($i = $i+1;$i)`b`n" = $mb.SafeSyntax } }) -Default ($MethodBase.Count-1) -Caption "Choose a Method." -Message "Please choose which method overload to invoke:"
[System.Reflection.MethodBase]$MethodBase = $MethodBase[$i]
}
ForEach($parameter in $MethodBase.GetParameters()) {
$found = $false
For($a =0;$a -lt $Arguments.Count;$a++) {
if($argument[$a] -as $parameter.ParameterType) {
Write-Output $argument[$a]
if($a -gt 0 -and $a -lt $Arguments.Count) {
$Arguments = $Arguments | Select -First ($a-1) -Last ($Arguments.Count -$a)
} elseif($a -eq 0) {
$Arguments = $Arguments | Select -Last ($Arguments.Count - 1)
} else { # a -eq count
$Arguments = $Arguments | Select -First ($Arguments.Count - 1)
}
$found = $true
break
}
}
if(!$Found) {
$userInput = Read-Host "Please enter a [$($parameter.ParameterType.FullName)] value for $($parameter.Name)"
if($userInput -match '^{.*}$' -and !($userInput -as $parameter.ParameterType)) {
Write-Output ((Invoke-Expression $userInput) -as $parameter.ParameterType)
} else {
Write-Output ($userInput -as $parameter.ParameterType)
}
}
}
}
}
function Invoke-Member {
[CmdletBinding()]
param(
[parameter(position=0, valuefrompipeline=$true, mandatory=$true)]
[allownull()]
[allowemptystring()]
$InputObject
,
[parameter(position=1, mandatory=$true)]
[validatenotnullorempty()]
$Method
,
[parameter(valuefromremainingarguments=$true)]
[allowemptycollection()]
[object[]]$Arguments
,
[parameter()]
[switch]$Static
)
# begin {
# if(!(get-member SafeSyntax -input $method -type Property)){
# if(get-member Name -inpup $Method -Type Property) {
# $Method = Get-Method $InputObject $Method.Name
# } else {
# $Method = Get-Method $InputObject $Method
# }
# }
# $SafeSyntax = [ScriptBlock]::Create( $Method.SafeSyntax )
# }
process {
# if ($InputObject)
# {
# if ($InputObject | Get-Member $Method -static:$static)
# {
if ($InputObject -is [type]) {
$target = $InputObject
} else {
$target = $InputObject.GetType()
}
if($Method -match "ctor|constructor") {
$Method = ".ctor"
[System.Reflection.BindingFlags]$flags = "CreateInstance"
$InputObject = $Null
} else {
[System.Reflection.BindingFlags]$flags = "IgnoreCase,Public,InvokeMethod"
if($Static) { $flags += "Static" } else { $flags += "Instance" }
}
[Object[]]$Parameters = Get-Argument $target $Method $Arguments
Write-Verbose "$($Parameters | %{ '[' + $_.GetType().FullName + ']' + $_ })"
try {
Write-Verbose "Invoking $Method on [$target]$InputObject with $flags and $Parameters"
Write-Verbose "[$($target.FullName)].InvokeMember('$Method', '$flags', `$null, '$InputObject', ([object[]]($(($Parameters | %{ '[' + $_.GetType().FullName + ']''' + $_ + ''''}) -join', '))))"
$target.InvokeMember($Method, $flags, $null, $InputObject, $Parameters)
} catch {
if ($_.Exception.Innerexception -is [MissingMethodException]) {
write-warning "Method argument count (or type) mismatch."
}
}
# } else {
# write-warning "Method $Method not found."
# }
# }
}
}
function Invoke-Generic {
#.Synopsis
# Invoke Generic method definitions via reflection:
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[Alias('On','Type')]
$InputObject
,
[Parameter(Position=1,ValueFromPipelineByPropertyName=$true)]
[Alias('Named')]
[string]$MethodName
,
[Parameter(Position=2)]
[Alias('Returns')]
[Type]$ReturnType
,
[Parameter(Position=3, ValueFromPipelineByPropertyName=$true)]
[Type[]]$ArgumentTypes
,
[Parameter(Position=4, ValueFromRemainingArguments=$true, ValueFromPipelineByPropertyName=$true)]
[Object[]]$WithArgs
)
process {
$Type = $InputObject -as [Type]
if(!$Type) { $Type = $InputObject.GetType() }
if($WithArgs) {
if(!$ArgumentTypes) {
[Type[]]$ArgumentTypes = $withArgs | % { $_.GetType() }
}
[Object[]]$Arguments = $withArgs | %{ $_.PSObject.BaseObject }
$Type.GetMethod($MethodName, $ArgumentTypes).MakeGenericMethod($returnType).Invoke( $on, $Arguments )
} else {
[Type[]]$ArgumentTypes = New-Object Type[] 0
$Type.GetMethod($MethodName, $ArgumentTypes).MakeGenericMethod($returnType).Invoke( $on )
}
} }
# get a reference to the Type
$xlr8r = [type]::gettype("System.Management.Automation.TypeAccelerators")
function Import-Namespace {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[string]$Namespace
,
[Switch]$Force
)
Get-Type -Namespace $Namespace -Force:$Force | Add-Accelerator
}
function Add-Accelerator {
<#
.Synopsis
Add a type accelerator to the current session
.Description
The Add-Accelerator function allows you to add a simple type accelerator (like [regex]) for a longer type (like [System.Text.RegularExpressions.Regex]).
.Example
Add-Accelerator list System.Collections.Generic.List``1
$list = New-Object list[string]
Creates an accelerator for the generic List[T] collection type, and then creates a list of strings.
.Example
Add-Accelerator "List T", "GList" System.Collections.Generic.List``1
$list = New-Object "list t[string]"
Creates two accelerators for the Generic List[T] collection type.
.Parameter Accelerator
The short form accelerator should be just the name you want to use (without square brackets).
.Parameter Type
The type you want the accelerator to accelerate (without square brackets)
.Notes
When specifying multiple values for a parameter, use commas to separate the values.
For example, "-Accelerator string, regex".
PowerShell requires arguments that are "types" to NOT have the square bracket type notation, because of the way the parsing engine works. You can either just type in the type as System.Int64, or you can put parentheses around it to help the parser out: ([System.Int64])
Also see the help for Get-Accelerator and Remove-Accelerator
.Link
http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/
#>
[CmdletBinding()]
param(
[Parameter(Position=0,ValueFromPipelineByPropertyName=$true)]
[Alias("Key","Name")]
[string[]]$Accelerator
,
[Parameter(Position=1,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[Alias("Value","FullName")]
[type]$Type
)
process {
# add a user-defined accelerator
foreach($a in $Accelerator) {
$xlr8r::Add( $a, $Type)
trap [System.Management.Automation.MethodInvocationException] {
if($xlr8r::get.keys -contains $a) {
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
}
}
}
}
function Get-Accelerator {
<#
.Synopsis
Get one or more type accelerator definitions
.Description
The Get-Accelerator function allows you to look up the type accelerators (like [regex]) defined on your system by their short form or by type
.Example
Get-Accelerator System.String
Returns the KeyValue pair for the [System.String] accelerator(s)
.Example
Get-Accelerator ps*,wmi*
Returns the KeyValue pairs for the matching accelerator definition(s)
.Parameter Accelerator
One or more short form accelerators to search for (Accept wildcard characters).
.Parameter Type
One or more types to search for.
.Notes
When specifying multiple values for a parameter, use commas to separate the values.
For example, "-Accelerator string, regex".
Also see the help for Add-Accelerator and Remove-Accelerator
.Link
http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/
#>
[CmdletBinding(DefaultParameterSetName="ByType")]
param(
[Parameter(Position=0, ParameterSetName="ByAccelerator", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("Key","Name")]
[string[]]$Accelerator
,
[Parameter(Position=0, ParameterSetName="ByType", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("Value","FullName")]
[type[]]$Type
)
process {
# add a user-defined accelerator
switch($PSCmdlet.ParameterSetName) {
"ByAccelerator" {
$xlr8r::get.GetEnumerator() | % {
foreach($a in $Accelerator) {
if($_.Key -like $a) { $_ }
}
}
break
}
"ByType" {
if($Type -and $Type.Count) {
$xlr8r::get.GetEnumerator() | ? { $Type -contains $_.Value }
}
else {
$xlr8r::get.GetEnumerator() | %{ $_ }
}
break
}
}
}
}
function Remove-Accelerator {
<#
.Synopsis
Remove a type accelerator from the current session
.Description
The Remove-Accelerator function allows you to remove a simple type accelerator (like [regex]) from the current session. You can pass one or more accelerators, and even wildcards, but you should be aware that you can remove even the built-in accelerators.
.Example
Remove-Accelerator int
Add-Accelerator int Int64
Removes the "int" accelerator for Int32 and adds a new one for Int64. I can't recommend doing this, but it's pretty cool that it works:
So now, "$(([int]3.4).GetType().FullName)" would return "System.Int64"
.Example
Get-Accelerator System.Single | Remove-Accelerator
Removes both of the default accelerators for System.Single: [float] and [single]
.Example
Get-Accelerator System.Single | Remove-Accelerator -WhatIf
Demonstrates that Remove-Accelerator supports -Confirm and -Whatif. Will Print:
What if: Removes the alias [float] for type [System.Single]
What if: Removes the alias [single] for type [System.Single]
.Parameter Accelerator
The short form accelerator that you want to remove (Accept wildcard characters).
.Notes
When specifying multiple values for a parameter, use commas to separate the values.
For example, "-Accel string, regex".
Also see the help for Add-Accelerator and Get-Accelerator
.Link
http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/
#>
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("Key","FullName")]
[string[]]$Accelerator
)
process {
foreach($a in $Accelerator) {
foreach($key in $xlr8r::Get.Keys -like $a) {
if($PSCmdlet.ShouldProcess( "Removes the alias [$($Key)] for type [$($xlr8r::Get[$key].FullName)]",
"Remove the alias [$($Key)] for type [$($xlr8r::Get[$key].FullName)]?",
"Removing Type Accelerator" )) {
# remove a user-defined accelerator
$xlr8r::remove($key)
}
}
}
}
}
###############################################################################
##### Imported from PowerBoots
$Script:CodeGenContentProperties = 'Content','Child','Children','Frames','Items','Pages','Blocks','Inlines','GradientStops','Source','DataPoints', 'Series', 'VisualTree'
$DependencyProperties = @{}
if(Test-Path $PSScriptRoot\\DependencyPropertyCache.xml) {
#$DependencyProperties = [System.Windows.Markup.XamlReader]::Parse( (gc $PSScriptRoot\\DependencyPropertyCache.xml) )
$DependencyProperties = Import-CliXml $PSScriptRoot\\DependencyPropertyCache.xml
}
function Get-ReflectionModule { $executioncontext.sessionstate.module }
function Set-ObjectProperties {
[CmdletBinding()]
param( $Parameters, [ref]$DObject )
if($DObject.Value -is [System.ComponentModel.ISupportInitialize]) { $DObject.Value.BeginInit() }
if($DebugPreference -ne "SilentlyContinue") { Write-Host; Write-Host ">>>> $($Dobject.Value.GetType().FullName)" -fore Black -back White }
foreach ($param in $Parameters) {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Processing Param: $($param|Out-String )" }
## INGORE DEPENDENCY PROPERTIES FOR NOW :)
if($param.Key -eq "DependencyProps") {
## HANDLE EVENTS ....
}
elseif ($param.Key.StartsWith("On_")) {
$EventName = $param.Key.SubString(3)
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Event handler $($param.Key) Type: $(@($param.Value)[0].GetType().FullName)" }
$sb = $param.Value -as [ScriptBlock]
if(!$sb) {
$sb = (Get-Command $param.Value -CommandType Function,ExternalScript).ScriptBlock
}
$Dobject.Value."Add_$EventName".Invoke( $sb );
# $Dobject.Value."Add_$EventName".Invoke( ($sb.GetNewClosure()) );
# $Dobject.Value."Add_$EventName".Invoke( $PSCmdlet.MyInvocation.MyCommand.Module.NewBoundScriptBlock( $sb.GetNewClosure() ) );
} ## HANDLE PROPERTIES ....
else {
try {
## TODO: File a BUG because Write-DEBUG and Write-VERBOSE die here.
if($DebugPreference -ne "SilentlyContinue") {
Write-Host "Setting $($param.Key) of $($Dobject.Value.GetType().Name) to $($param.Value.GetType().FullName): $($param.Value)" -fore Gray
}
if(@(foreach($sb in $param.Value) { $sb -is [ScriptBlock] }) -contains $true) {
$Values = @()
foreach($sb in $param.Value) {
$Values += & (Get-ReflectionModule) $sb
}
} else {
$Values = $param.Value
}
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject.Value )) -foreground green }
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( @($Values)[0] )) -foreground green }
Set-Property $Dobject $Param.Key $Values
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject.Value )) -foreground magenta }
if($DebugPreference -ne "SilentlyContinue") {
if( $Dobject.Value.$($param.Key) -ne $null ) {
Write-Host $Dobject.Value.$($param.Key).GetType().FullName -fore Green
}
}
}
catch [Exception]
{
Write-Host "COUGHT AN EXCEPTION" -fore Red
Write-Host $_ -fore Red
Write-Host $this -fore DarkRed
}
}
while($DependencyProps) {
$name, $value, $DependencyProps = $DependencyProps
$name = ([string]@($name)[0]).Trim("-")
if($name -and $value) {
Set-DependencyProperty -Element $Dobject.Value -Property $name -Value $Value
}
}
}
if($DebugPreference -ne "SilentlyContinue") { Write-Host "<<<< $($Dobject.Value.GetType().FullName)" -fore Black -back White; Write-Host }
if($DObject.Value -is [System.ComponentModel.ISupportInitialize]) { $DObject.Value.EndInit() }
}
function Set-Property {
PARAM([ref]$TheObject, $Name, $Values)
$DObject = $TheObject.Value
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $DObject )) -foreground DarkMagenta }
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( @($Values)[0] )) -foreground DarkMagenta }
$PropertyType = $DObject.GetType().GetProperty($Name).PropertyType
if('System.Windows.FrameworkElementFactory' -as [Type] -and $PropertyType -eq [System.Windows.FrameworkElementFactory] -and $DObject -is [System.Windows.FrameworkTemplate]) {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Loading a FrameworkElementFactory" -foreground Green}
# [Xml]$Template = [PoshWpf.XamlHelper]::ConvertToXaml( $DObject )
# [Xml]$Content = [PoshWpf.XamlHelper]::ConvertToXaml( (@($Values)[0]) )
# In .Net 3.5 the recommended way to programmatically create a template is to load XAML from a string or a memory stream using the Load method of the XamlReader class.
[Xml]$Template = [System.Windows.Markup.XamlWriter]::Save( $DObject )
[Xml]$Content = [System.Windows.Markup.XamlWriter]::Save( (@($Values)[0]) )
$Template.DocumentElement.PrependChild( $Template.ImportNode($Content.DocumentElement, $true) ) | Out-Null
$TheObject.Value = [System.Windows.Markup.XamlReader]::Parse( $Template.get_OuterXml() )
}
elseif('System.Windows.Data.Binding' -as [Type] -and @($Values)[0] -is [System.Windows.Data.Binding] -and !$PropertyType.IsAssignableFrom([System.Windows.Data.BindingBase])) {
$Binding = @($Values)[0];
if($DebugPreference -ne "SilentlyContinue") { Write-Host "$($DObject.GetType())::$Name is $PropertyType and the value is a Binding: $Binding" -fore Cyan}
if(!$Binding.Source -and !$Binding.ElementName) {
$Binding.Source = $DObject.DataContext
}
if($DependencyProperties.ContainsKey($Name)) {
$field = @($DependencyProperties.$Name.Keys | Where { $DObject -is $_ -and $PropertyType -eq ([type]$DependencyProperties.$Name.$_.PropertyType)})[0] # -or -like "*$Class" -and ($Param1.Value -as ([type]$_.PropertyType)
if($field) {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "$($field)" -fore Blue }
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Binding: ($field)::`"$($DependencyProperties.$Name.$field.Name)`" to $Binding" -fore Blue}
$DObject.SetBinding( ([type]$field)::"$($DependencyProperties.$Name.$field.Name)", $Binding ) | Out-Null
} else {
throw "Couldn't figure out $( @($DependencyProperties.$Name.Keys) -join ', ' )"
}
} else {
if($DebugPreference -ne "SilentlyContinue") {
Write-Host "But $($DObject.GetType())::${Name}Property is not a Dependency Property, so it probably can't be bound?" -fore Cyan
}
try {
$DObject.SetBinding( ($DObject.GetType()::"${Name}Property"), $Binding ) | Out-Null
# $DObject.Add_Loaded( {
# $this.SetBinding( ($this.GetType())::ItemsSourceProperty, (Binding -Source $this.DataContext) )
# } )
if($DebugPreference -ne "SilentlyContinue") {
Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject )) -foreground yellow
}
} catch {
Write-Host "Nope, was not able to set it." -fore Red
Write-Host $_ -fore Red
Write-Host $this -fore DarkRed
}
}
}
elseif($PropertyType -ne [Object] -and $PropertyType.IsAssignableFrom( [System.Collections.IEnumerable] ) -and ($DObject.$($Name) -eq $null)) {
if($Values -is [System.Collections.IEnumerable]) {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "$Name is $PropertyType which is IEnumerable, and the value is too!" -fore Cyan }
$DObject.$($Name) = $Values
} else {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "$Name is $PropertyType which is IEnumerable, but the value is not." -fore Cyan }
$DObject.$($Name) = new-object "System.Collections.ObjectModel.ObservableCollection[$(@($Values)[0].GetType().FullName)]"
$DObject.$($Name).Add($Values)
}
}
elseif($DObject.$($Name) -is [System.Collections.IList]) {
foreach ($value in @($Values)) {
try {
$null = $DObject.$($Name).Add($value)
}
catch
{
# Write-Host "CAUGHT array problem" -fore Red
if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") {
$null = $DObject.$($Name).Add( (New-System.Windows.Controls.TextBlock $value) )
} else {
Write-Error $_.Exception
throw
}
}
}
}
else {
## If they pass an array of 1 when we only want one, we just use the first value
if($Values -is [System.Collections.IList] -and $Values.Count -eq 1) {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Value is an IList ($($Values.GetType().FullName))" -fore Cyan}
if($DebugPreference -ne "SilentlyContinue") { Write-Host "But we'll just use the first ($($Values[0].GetType().FullName))" -fore Cyan}
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Values[0] )) -foreground White}
try {
$DObject.$($Name) = $Values[0]
}
catch [Exception]
{
# Write-Host "CAUGHT collection value problem" -fore Red
if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") {
$null = $DObject.$($Name).Add( (TextBlock $Values[0]) )
}else {
throw
}
}
}
else ## If they pass an array when we only want one, we try to use it, and failing that, cast it to strings
{
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Value is just $Values" -fore Cyan}
try {
$DObject.$($Name) = $Values
} catch [Exception]
{
# Write-Host "CAUGHT value problem" -fore Red
if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") {
$null = $DObject.$($Name).Add( (TextBlock $values) )
}else {
throw
}
}
}
}
}
function Set-DependencyProperty {
[CmdletBinding()]
PARAM(
[Parameter(Position=0,Mandatory=$true)]
$Property
,
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
$Element
,
[Parameter()]
[Switch]$Passthru
)
DYNAMICPARAM {
$paramDictionary = new-object System.Management.Automation.RuntimeDefinedParameterDictionary
$Param1 = new-object System.Management.Automation.RuntimeDefinedParameter
$Param1.Name = "Value"
# $Param1.Attributes.Add( (New-ParameterAttribute -Position 1) )
$Param1.Attributes.Add( (New-Object System.Management.Automation.ParameterAttribute -Property @{ Position = 1 }) )
if( $Property ) {
if($Property.GetType() -eq ([System.Windows.DependencyProperty]) -or
$Property.GetType().IsSubclassOf(([System.Windows.DependencyProperty])))
{
$Param1.ParameterType = $Property.PropertyType
}
elseif($Property -is [string] -and $Property.Contains(".")) {
$Class,$Property = $Property.Split(".")
if($DependencyProperties.ContainsKey($Property)){
$type = $DependencyProperties.$Property.Keys -like "*$Class"
if($type) {
$Param1.ParameterType = [type]@($DependencyProperties.$Property.$type)[0].PropertyType
}
}
} elseif($DependencyProperties.ContainsKey($Property)){
if($Element) {
if($DependencyProperties.$Property.ContainsKey( $element.GetType().FullName )) {
$Param1.ParameterType = [type]$DependencyProperties.$Property.($element.GetType().FullName).PropertyType
}
} else {
$Param1.ParameterType = [type]$DependencyProperties.$Property.Values[0].PropertyType
}
}
else
{
$Param1.ParameterType = [PSObject]
}
}
else
{
$Param1.ParameterType = [PSObject]
}
$paramDictionary.Add("Value", $Param1)
return $paramDictionary
}
PROCESS {
trap {
Write-Host "ERROR Setting Dependency Property" -Fore Red
Write-Host "Trying to set $Property to $($Param1.Value)" -Fore Red
continue
}
if($Property.GetType() -eq ([System.Windows.DependencyProperty]) -or
$Property.GetType().IsSubclassOf(([System.Windows.DependencyProperty]))
){
trap {
Write-Host "ERROR Setting Dependency Property" -Fore Red
Write-Host "Trying to set $($Property.FullName) to $($Param1.Value)" -Fore Red
continue
}
$Element.SetValue($Property, ($Param1.Value -as $Property.PropertyType))
}
else {
if("$Property".Contains(".")) {
$Class,$Property = "$Property".Split(".")
}
if( $DependencyProperties.ContainsKey("$Property" ) ) {
$fields = @( $DependencyProperties.$Property.Keys -like "*$Class" | ? { $Param1.Value -as ([type]$DependencyProperties.$Property.$_.PropertyType) } )
if($fields.Count -eq 0 ) {
$fields = @($DependencyProperties.$Property.Keys -like "*$Class" )
}
if($fields.Count) {
$success = $false
foreach($field in $fields) {
trap {
Write-Host "ERROR Setting Dependency Property" -Fore Red
Write-Host "Trying to set $($field)::$($DependencyProperties.$Property.$field.Name) to $($Param1.Value) -as $($DependencyProperties.$Property.$field.PropertyType)" -Fore Red
continue
}
$Element.SetValue( ([type]$field)::"$($DependencyProperties.$Property.$field.Name)", ($Param1.Value -as ([type]$DependencyProperties.$Property.$field.PropertyType)))
if($?) { $success = $true; break }
}
if(!$success) {
throw "food"
}
} else {
Write-Host "Couldn't find the right property: $Class.$Property on $( $Element.GetType().Name ) of type $( $Param1.Value.GetType().FullName )" -Fore Red
}
}
else {
Write-Host "Unknown Dependency Property Key: $Property on $($Element.GetType().Name)" -Fore Red
}
}
if( $Passthru ) { $Element }
}
}
function Add-ConstructorFunction {
<#
.Synopsis
Add support for a new class by creating the dynamic constructor function(s).
.Description
Creates a New-Namespace.Type function for each type passed in, as well as a short form "Type" alias.
Exposes all of the properties and events of the type as perameters to the function.
NOTE: The Type MUST have a default parameterless constructor.
.Parameter Assembly
The Assembly you want to generate constructors for. All public types within it will be generated if possible.
.Parameter Type
The type you want to create a constructor function for. It must have a default parameterless constructor.
.Example
Add-ConstructorFunction System.Windows.Controls.Button
Creates a new function for the Button control.
.Example
[Reflection.Assembly]::LoadWithPartialName( "PresentationFramework" ).GetTypes() | Add-ConstructorFunction
Will create constructor functions for all the WPF components in the PresentationFramework assembly. Note that you could also load that assembly using GetAssembly( "System.Windows.Controls.Button" ) or Load( "PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" )
.Example
Add-ConstructorFunction -Assembly PresentationFramework
Will create constructor functions for all the WPF components in the PresentationFramework assembly.
.Links
http://HuddledMasses.org/powerboots
.ReturnValue
The name(s) of the function(s) created -- so you can export them, if necessary.
.Notes
AUTHOR: Joel Bennett http://HuddledMasses.org
LASTEDIT: 2009-01-13 16:35:23
#>
[CmdletBinding(DefaultParameterSetName="FromType")]
PARAM(
[Parameter(Position=0,ValueFromPipeline=$true,ParameterSetName="FromType",Mandatory=$true)]
[type[]]$type
,
[Alias("FullName")]
[Parameter(Position=0,ValueFromPipelineByPropertyName=$true,ParameterSetName="FromAssembly",Mandatory=$true)]
[string[]]$Assembly
,
[Parameter()]
[string]$Path = "$PSScriptRoot\\Types_Generated"
,
[switch]$Force
,
[switch]$ShortAliases
,
[Switch]$Quiet
)
BEGIN {
[Type[]]$Empty=@()
if(!(Test-Path $Path)) {
MkDir $Path
}
$ErrorList = @()
}
END {
#Set-Content -Literal $PSScriptRoot\\DependencyPropertyCache.xml -Value ([System.Windows.Markup.XamlWriter]::Save( $DependencyProperties ))
Export-CliXml -Path $PSScriptRoot\\DependencyPropertyCache.xml -InputObject $DependencyProperties
if($ErrorList.Count) { Write-Warning "Some New-* functions not aliased." }
$ErrorList | Write-Error
}
PROCESS {
if($PSCmdlet.ParameterSetName -eq "FromAssembly") {
[type[]]$type = @()
foreach($lib in $Assembly) {
$asm = $null
trap { continue }
if(Test-Path $lib) {
$asm = [Reflection.Assembly]::LoadFrom( (Convert-Path (Resolve-Path $lib -EA "SilentlyContinue") -EA "SilentlyContinue") )
}
if(!$asm) {
## BUGBUG: LoadWithPartialName is "Obsolete" -- but it still works in 2.0/3.5
$asm = [Reflection.Assembly]::LoadWithPartialName( $lib )
}
if($asm) {
$type += $asm.GetTypes() | ?{ $_.IsPublic -and !$_.IsEnum -and
!$_.IsAbstract -and !$_.IsInterface -and
$_.GetConstructor( "Instance,Public", $Null, $Empty, @() )}
} else {
Write-Error "Can't find the assembly $lib, please check your spelling and try again"
}
}
}
foreach($T in $type) {
$TypeName = $T.FullName
$ScriptPath = Join-Path $Path "New-$TypeName.ps1"
Write-Verbose $TypeName
## Collect all dependency properties ....
$T.GetFields() |
Where-Object { $_.FieldType -eq [System.Windows.DependencyProperty] } |
ForEach-Object {
[string]$Field = $_.DeclaringType::"$($_.Name)".Name
[string]$TypeName = $_.DeclaringType.FullName
if(!$DependencyProperties.ContainsKey( $Field )) {
$DependencyProperties.$Field = @{}
}
$DependencyProperties.$Field.$TypeName = @{
Name = [string]$_.Name
PropertyType = [string]$_.DeclaringType::"$($_.Name)".PropertyType.FullName
}
}
if(!( Test-Path $ScriptPath ) -OR $Force) {
$Pipelineable = @();
## Get (or generate) a set of parameters based on the the Type Name
$PropertyNames = New-Object System.Text.StringBuilder "@("
$Parameters = New-Object System.Text.StringBuilder "[CmdletBinding(DefaultParameterSetName='Default')]`nPARAM(`n"
## Add all properties
$Properties = $T.GetProperties("Public,Instance,FlattenHierarchy") |
Where-Object { $_.CanWrite -Or $_.PropertyType.GetInterface([System.Collections.IList]) }
$Properties = ($T.GetEvents("Public,Instance,FlattenHierarchy") + $Properties) | Sort-Object Name -Unique
foreach ($p in $Properties) {
$null = $PropertyNames.AppendFormat(",'{0}'",$p.Name)
switch( $p.MemberType ) {
Event {
$null = $PropertyNames.AppendFormat(",'{0}__'",$p.Name)
$null = $Parameters.AppendFormat(@'
[Parameter()]
[PSObject]${{On_{0}}}
,
'@, $p.Name)
}
Property {
if($p.Name -match "^$($CodeGenContentProperties -Join '$|^')`$") {
$null = $Parameters.AppendFormat(@'
[Parameter(Position=1,ValueFromPipeline=$true)]
[Object[]]${{{0}}}
,
'@, $p.Name)
$Pipelineable += @(Add-Member -in $p.Name -Type NoteProperty -Name "IsCollection" -Value $($p.PropertyType.GetInterface([System.Collections.IList]) -ne $null) -Passthru)
}
elseif($p.PropertyType -eq [System.Boolean])
{
$null = $Parameters.AppendFormat(@'
[Parameter()]
[Switch]${{{0}}}
,
'@, $p.Name)
}
else
{
$null = $Parameters.AppendFormat(@'
[Parameter()]
[Object[]]${{{0}}}
,
'@, $p.Name)
}
}
}
}
$null = $Parameters.Append(' [Parameter(ValueFromRemainingArguments=$true)]
[string[]]$DependencyProps
)')
$null = $PropertyNames.Remove(2,1).Append(')')
$collectable = [bool]$(@(foreach($p in @($Pipelineable)){$p.IsCollection}) -contains $true)
$ofs = "`n";
$function = $(
"
if(!( '$TypeName' -as [Type] )) {
$(
if( $T.Assembly.GlobalAssemblyCache ) {
" `$null = [Reflection.Assembly]::Load( '$($T.Assembly.FullName)' ) "
} else {
" `$null = [Reflection.Assembly]::LoadFrom( '$($T.Assembly.Location)' ) "
}
)
}
## if(`$ExecutionContext.SessionState.Module.Guid -ne (Get-ReflectionModule).Guid) {
## Write-Warning `"$($T.Name) not invoked in ReflectionModule context. Attempting to reinvoke.`"
## # `$scriptParam = `$PSBoundParameters
## # return iex `"& (Get-ReflectionModule) '`$(`$MyInvocation.MyCommand.Path)' ```@PSBoundParameters`"
## }
Write-Verbose ""$($T.Name) in module `$(`$executioncontext.sessionstate.module) context!""
function New-$TypeName {
<#
.Synopsis
Create a new $($T.Name) object
.Description
Generates a new $TypeName object, and allows setting all of it's properties.
(From the $($T.Assembly.GetName().Name) assembly v$($T.Assembly.GetName().Version))
.Notes
GENERATOR : $((Get-ReflectionModule).Name) v$((Get-ReflectionModule).Version) by Joel Bennett http://HuddledMasses.org
GENERATED : $(Get-Date)
ASSEMBLY : $($T.Assembly.FullName)
FULLPATH : $($T.Assembly.Location)
#>
$Parameters
BEGIN {
`$DObject = New-Object $TypeName
`$All = $PropertyNames
}
PROCESS {
"
if(!$collectable) {
"
# The content of $TypeName is not a collection
# So if we're in a pipeline, make a new $($T.Name) each time
if(`$_) {
`$DObject = New-Object $TypeName
}
"
}
@'
foreach($key in @($PSBoundParameters.Keys) | where { $PSBoundParameters[$_] -is [ScriptBlock] }) {
$PSBoundParameters[$key] = $PSBoundParameters[$key].GetNewClosure()
}
Set-ObjectProperties @($PSBoundParameters.GetEnumerator() | Where { [Array]::BinarySearch($All,($_.Key -replace "^On_(.*)",'$1__')) -ge 0 } ) ([ref]$DObject)
'@
if(!$collectable) {
@'
Microsoft.PowerShell.Utility\\Write-Output $DObject
} #Process
'@
} else {
@'
} #Process
END {
Microsoft.PowerShell.Utility\\Write-Output $DObject
}
'@
}
@"
}
## New-$TypeName `@PSBoundParameters
"@
)
Set-Content -Path $ScriptPath -Value $Function
}
# Note: set the aliases global for now, because it's too late to export them
# E.g.: New-Button = New-System.Windows.Controls.Button
Set-Alias -Name "New-$($T.Name)" "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet)
if($ShortAliases) {
# E.g.: Button = New-System.Windows.Controls.Button
Set-Alias -Name $T.Name "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet)
}
New-AutoLoad -Name $ScriptPath -Alias "New-$TypeName"
}
}#PROCESS
}
function Import-ConstructorFunctions {
#.Synopsis
# Autoload pre-generated constructor functions and generate aliases for them.
#.Description
# Parses the New-* scripts in the specified path, and uses the Autoload module to pre-load them as commands and set up aliases for them, without parsing them into memory.
#.Parameter Path
# The path to a folder with functions to preload
param(
[Parameter()]
[Alias("PSPath")]
[string[]]$Path = "$PSScriptRoot\\Types_Generated"
)
end {
$Paths = $(foreach($p in $Path) { Join-Path $p "New-*.ps1" })
Write-Verbose "Importing Constructors from: `n`t$($Paths -join "`n`t")"
foreach($script in Get-ChildItem $Paths -ErrorAction 0) {
$TypeName = $script.Name -replace 'New-(.*).ps1','$1'
$ShortName = ($TypeName -split '\\.')[-1]
Write-Verbose "Importing constructor for type: $TypeName ($ShortName)"
# Note: set the aliases global for now, because it's too late to export them
# E.g.: New-Button = New-System.Windows.Controls.Button
Set-Alias -Name "New-$ShortName" "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet)
if($ShortAliases) {
# E.g.: Button = New-System.Windows.Controls.Button
Set-Alias -Name $ShortName "New-$TypeName" -ErrorAction SilentlyContinue -ErrorVariable +ErrorList -Scope Global -Passthru:(!$Quiet)
}
New-Autoload -Name $Script.FullName -Alias "New-$TypeName"
# Write-Host -fore yellow $(Get-Command "New-$TypeName" | Out-String)
Get-Command "New-$TypeName"
}
}
}
###############################################################################
Add-Accelerator list System.Collections.Generic.List``1
Add-Accelerator dictionary System.Collections.Generic.Dictionary``2
Set-Alias aasm Add-Assembly -Option AllScope
Set-Alias gt Get-Type -Option AllScope
Set-Alias gasm Get-Assembly -Option AllScope
Set-Alias gctor Get-Constructor -Option AllScope
Set-Alias gax Get-Accelerator -Option AllScope
Set-Alias aax Add-Accelerator -Option AllScope
Set-Alias rax Remove-Accelerator -Option AllScope
Export-ModuleMember -Function * -Alias *
# SIG # Begin signature block
# MIIIDQYJKoZIhvcNAQcCoIIH/jCCB/oCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUOPmSsbNp7OA8QrGW9LDLkUk4
# Ni+gggUrMIIFJzCCBA+gAwIBAgIQKQm90jYWUDdv7EgFkuELajANBgkqhkiG9w0B
# AQUFADCBlTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0
# IExha2UgQ2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYD
# VQQLExhodHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xHTAbBgNVBAMTFFVUTi1VU0VS
# Rmlyc3QtT2JqZWN0MB4XDTEwMDUxNDAwMDAwMFoXDTExMDUxNDIzNTk1OVowgZUx
# CzAJBgNVBAYTAlVTMQ4wDAYDVQQRDAUwNjg1MDEUMBIGA1UECAwLQ29ubmVjdGlj
# dXQxEDAOBgNVBAcMB05vcndhbGsxFjAUBgNVBAkMDTQ1IEdsb3ZlciBBdmUxGjAY
# BgNVBAoMEVhlcm94IENvcnBvcmF0aW9uMRowGAYDVQQDDBFYZXJveCBDb3Jwb3Jh
# dGlvbjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMfUdxwiuWDb8zId
# KuMg/jw0HndEcIsP5Mebw56t3+Rb5g4QGMBoa8a/N8EKbj3BnBQDJiY5Z2DGjf1P
# n27g2shrDaNT1MygjYfLDntYzNKMJk4EjbBOlR5QBXPM0ODJDROg53yHcvVaXSMl
# 498SBhXVSzPmgprBJ8FDL00o1IIAAhYUN3vNCKPBXsPETsKtnezfzBg7lOjzmljC
# mEOoBGT1g2NrYTq3XqNo8UbbDR8KYq5G101Vl0jZEnLGdQFyh8EWpeEeksv7V+YD
# /i/iXMSG8HiHY7vl+x8mtBCf0MYxd8u1IWif0kGgkaJeTCVwh1isMrjiUnpWX2NX
# +3PeTmsCAwEAAaOCAW8wggFrMB8GA1UdIwQYMBaAFNrtZHQUnBQ8q92Zqb1bKE2L
# PMnYMB0GA1UdDgQWBBTK0OAaUIi5wvnE8JonXlTXKWENvTAOBgNVHQ8BAf8EBAMC
# B4AwDAYDVR0TAQH/BAIwADATBgNVHSUEDDAKBggrBgEFBQcDAzARBglghkgBhvhC
# AQEEBAMCBBAwRgYDVR0gBD8wPTA7BgwrBgEEAbIxAQIBAwIwKzApBggrBgEFBQcC
# ARYdaHR0cHM6Ly9zZWN1cmUuY29tb2RvLm5ldC9DUFMwQgYDVR0fBDswOTA3oDWg
# M4YxaHR0cDovL2NybC51c2VydHJ1c3QuY29tL1VUTi1VU0VSRmlyc3QtT2JqZWN0
# LmNybDA0BggrBgEFBQcBAQQoMCYwJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmNv
# bW9kb2NhLmNvbTAhBgNVHREEGjAYgRZKb2VsLkJlbm5ldHRAWGVyb3guY29tMA0G
# CSqGSIb3DQEBBQUAA4IBAQAEss8yuj+rZvx2UFAgkz/DueB8gwqUTzFbw2prxqee
# zdCEbnrsGQMNdPMJ6v9g36MRdvAOXqAYnf1RdjNp5L4NlUvEZkcvQUTF90Gh7OA4
# rC4+BjH8BA++qTfg8fgNx0T+MnQuWrMcoLR5ttJaWOGpcppcptdWwMNJ0X6R2WY7
# bBPwa/CdV0CIGRRjtASbGQEadlWoc1wOfR+d3rENDg5FPTAIdeRVIeA6a1ZYDCYb
# 32UxoNGArb70TCpV/mTWeJhZmrPFoJvT+Lx8ttp1bH2/nq6BDAIvu0VGgKGxN4bA
# T3WE6MuMS2fTc1F8PCGO3DAeA9Onks3Ufuy16RhHqeNcMYICTDCCAkgCAQEwgaow
# gZUxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJVVDEXMBUGA1UEBxMOU2FsdCBMYWtl
# IENpdHkxHjAcBgNVBAoTFVRoZSBVU0VSVFJVU1QgTmV0d29yazEhMB8GA1UECxMY
# aHR0cDovL3d3dy51c2VydHJ1c3QuY29tMR0wGwYDVQQDExRVVE4tVVNFUkZpcnN0
# LU9iamVjdAIQKQm90jYWUDdv7EgFkuELajAJBgUrDgMCGgUAoHgwGAYKKwYBBAGC
# NwIBDDEKMAigAoAAoQKAADAZBgkqhkiG9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgor
# BgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQUT5+I/cl2
# XCMwrqk7nr22uBFwAuwwDQYJKoZIhvcNAQEBBQAEggEAX0OJXKRNvY/GKPVbMj1Q
# V0UYJdKTM17Oca5Bvbj0BTcwbuoToM4mAH8s8ZJrZldIfcIdVsr89SQ+s9UwhE5W
# 1FsBl3smgVWjc8o9j3LTi/BssTOg2pgFaMwdR4GRmUgQjznAXFb3Np0FoB+RieAN
# IR6XXYoVSfMRg1Qa5M7MIy84ww4oGDE8ssBlterqR9VOSSKiHYvlbDHO9cVH1FJ3
# 8ulz1RPl2BA3iwDK6J0w74FNTXILJE85OEXAcxXwGPlgvtOqKFOpNf1/ji1iE9iO
# kysIFde1Amdq5Qx6nDNYkvWYj59vBH0SgcvJj5k2EieQEecraca10q95BE+oXmaK
# 1Q==
# SIG # End signature block
|
PowerShellCorpus/PoshCode/ESX Lun Latencies.ps1
|
ESX Lun Latencies.ps1
|
function Get-VMHostLunLatency {
param($VMHost)
$luns = $VMHost | Get-ScsiLun
foreach ($lun in $luns) {
$stats = $VMHost |
Get-Stat -stat disk.totalreadlatency.average,disk.totalwritelatency.average -maxsamples 1 -realtime |
Where { $_.Instance -eq $Lun.CanonicalName }
if ($stats.length -ne $null) {
$obj = New-Object PSObject
$obj | Add-Member -MemberType NoteProperty -Name Lun -Value $lun.CanonicalName
$obj | Add-Member -MemberType NoteProperty -Name ReadLatency -Value ($stats[0].Value)
$obj | Add-Member -MemberType NoteProperty -Name WriteLatency -Value ($stats[1].Value)
Write-Output $obj
}
}
}
|
PowerShellCorpus/PoshCode/DHCP Backup_1.ps1
|
DHCP Backup_1.ps1
|
Import-Module ActiveDirectory
param (
[Parameter(Position=1)]
$searchBase = "cn=configuration,dc=domain,dc=com",
[Parameter(Position=2)]
$backupDestRoot = "\\\\network\\share\\"
)
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/Find Installed .NET ver.ps1
|
Find Installed .NET ver.ps1
|
# Svendsen Tech's .Net version finding script.
# See the full documentation at:
# http://www.powershelladmin.com/wiki/Script_for_finding_which_dot_net_versions_are_installed_on_remote_workstations
param([Parameter(Mandatory=$true)][string[]] $ComputerName,
[switch] $Clobber)
##### START OF FUNCTIONS #####
function ql { $args }
function Quote-And-Comma-Join {
param([Parameter(Mandatory=$true)][string[]] $Strings)
# Replace all double quotes in the text with single quotes so the CSV isn't messed up,
# and remove the trailing newline (all newlines and carriage returns).
$Strings = $Strings | ForEach-Object { $_ -replace '[\\r\\n]', '' }
($Strings | ForEach-Object { '"' + ($_ -replace '"', "'") + '"' }) -join ','
}
##### END OF FUNCTIONS #####
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$StartTime = Get-Date
"Script start time: $StartTime"
$Date = (Get-Date).ToString('yyyy-MM-dd')
$OutputOnlineFile = ".\\DotNetOnline-${date}.txt"
$OutputOfflineFile = ".\\DotNetOffline-${date}.txt"
$CsvOutputFile = ".\\DotNet-Versions-${date}.csv"
if (-not $Clobber) {
$FoundExistingLog = $false
foreach ($File in $OutputOnlineFile, $OutputOfflineFile, $CsvOutputFile) {
if (Test-Path -PathType Leaf -Path $File) {
$FoundExistingLog = $true
"$File already exists"
}
}
if ($FoundExistingLog -eq $true) {
$Answer = Read-Host "The above mentioned log file(s) exist. Overwrite? [yes]"
if ($Answer -imatch '^n') { 'Aborted'; exit 1 }
}
}
# Deleting existing log files if they exist (assume they can be deleted...)
Remove-Item $OutputOnlineFile -ErrorAction SilentlyContinue
Remove-Item $OutputOfflineFile -ErrorAction SilentlyContinue
Remove-Item $CsvOutputFile -ErrorAction SilentlyContinue
$Counter = 0
$DotNetData = @{}
$DotNetVersionStrings = ql v4\\Client v4\\Full v3.5 v3.0 v2.0.50727 v1.1.4322
$DotNetRegistryBase = 'SOFTWARE\\Microsoft\\NET Framework Setup\\NDP'
foreach ($Computer in $ComputerName) {
$Counter++
$DotNetData.$Computer = New-Object PSObject
# Skip malformed lines (well, some of them)
if ($Computer -notmatch '^\\S') {
Write-Host -Fore Red "Skipping malformed item/line ${Counter}: '$Computer'"
Add-Member -Name Error -Value "Malformed argument ${Counter}: '$Computer'" -MemberType NoteProperty -InputObject $DotNetData.$Computer
continue
}
if (Test-Connection -Quiet -Count 1 $Computer) {
Write-Host -Fore Green "$Computer is online. Trying to read registry."
$Computer | Add-Content $OutputOnlineFile
# Suppress errors when trying to open the remote key
$ErrorActionPreference = 'SilentlyContinue'
$Registry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $Computer)
$RegSuccess = $?
$ErrorActionPreference = 'Stop'
if ($RegSuccess) {
Write-Host -Fore Green "Successfully connected to registry of ${Computer}. Trying to open keys."
foreach ($VerString in $DotNetVersionStrings) {
if ($RegKey = $Registry.OpenSubKey("$DotNetRegistryBase\\$VerString")) {
#"Successfully opened .NET registry key (SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\$verString)."
if ($RegKey.GetValue('Install') -eq '1') {
#"$computer has .NET $verString"
Add-Member -Name $VerString -Value 'Installed' -MemberType NoteProperty -InputObject $DotNetData.$Computer
}
else {
Add-Member -Name $VerString -Value 'Not installed' -MemberType NoteProperty -InputObject $DotNetData.$Computer
}
}
else {
Add-Member -Name $VerString -Value 'Not installed (no key)' -MemberType NoteProperty -InputObject $DotNetData.$Computer
}
}
}
# Error opening remote registry
else {
Write-Host -Fore Yellow "${Computer}: Unable to open remote registry key."
Add-Member -Name Error -Value "Unable to open remote registry: $($Error[0].ToString())" -MemberType NoteProperty -InputObject $DotNetData.$Computer
}
}
# Failed ping test
else {
Write-Host -Fore Yellow "${Computer} is offline."
Add-Member -Name Error -Value "No ping reply" -MemberType NoteProperty -InputObject $DotNetData.$Computer
$Computer | Add-Content $OutputOfflineFile
}
}
$CsvHeaders = @('Computer') + @($DotNetVersionStrings) + @('Error')
$HeaderLine = Quote-And-Comma-Join $CsvHeaders
Add-Content -Path $CsvOutputFile -Value $HeaderLine
# Process the data and output to manually crafted CSV.
$DotNetData.GetEnumerator() | ForEach-Object {
$Computer = $_.Name
# I'm building a temporary hashtable with all $CsvHeaders
$TempData = @{}
$TempData.'Computer' = $Computer
# This means there's an "Error" note property.
if (Get-Member -InputObject $DotNetData.$Computer -MemberType NoteProperty -Name Error) {
# Add the error to the temp hash.
$TempData.'Error' = $DotNetData.$Computer.Error
# Populate the .NET version strings with "Unknown".
foreach ($VerString in $DotNetVersionStrings) {
$TempData.$VerString = 'Unknown'
}
}
# No errors. Assume all .NET version fields are populated.
else {
# Set the error key in the temp hash to "-"
$TempData.'Error' = '-'
foreach ($VerString in $DotNetVersionStrings) {
$TempData.$VerString = $DotNetData.$Computer.$VerString
}
}
# Now we should have "complete" $TempData hashes.
# Manually craft CSV data. Headers were added before the loop.
# The array is for ordering the output predictably.
$TempArray = @()
foreach ($Header in $CsvHeaders) {
$TempArray += $TempData.$Header
}
$CsvLine = Quote-And-Comma-Join $TempArray
Add-Content -Path $CsvOutputFile -Value $CsvLine
}
@"
Script start time: $StartTime
Script end time: $(Get-Date)
Output files: $CsvOutputFile, $OutputOnlineFile, $OutputOfflineFile
"@
|
PowerShellCorpus/PoshCode/Get-PSPVersion.ps1
|
Get-PSPVersion.ps1
|
$ServerInstance = "YourCMSServerInstance"
$query = @"
SELECT DISTINCT s.name
FROM msdb.dbo.sysmanagement_shared_registered_servers s
JOIN msdb.dbo.sysmanagement_shared_server_groups g
ON s.server_group_id = g.server_group_id
"@
$servers = sqlcmd -S "$ServerInstance" -d "master" -Q "SET NOCOUNT ON; $query" -h -1 -W | % {$_ -replace "\\\\.*",""} | sort -unique
$servers | % { Get-WMIObject -ComputerName $_ -Query "SELECT * FROM CIM_DataFile WHERE Drive ='C:' AND Path='\\\\WINDOWS\\\\system32\\\\CpqMgmt\\\\' AND FileName='agentver' AND Extension='dll'" } |
Select CSName, Version, @{n='OS';e={(gwmi win32_operatingsystem -ComputerName $_.CSName).Version}} | ogv
|
PowerShellCorpus/PoshCode/1dd696a1-0d97-40cd-9cdf-5cbe5b7fe4a4.ps1
|
1dd696a1-0d97-40cd-9cdf-5cbe5b7fe4a4.ps1
|
function Write-Host
{
<#
.SYNOPSIS
Replacement of Write-Host function to work around an issue where use of Write-Host can
cause an eventual problem with launching EXEs from within the same Powershell session.
.DESCRIPTION
This Write-Host replacement can act as a temporary workaround to an issue with some
PowerShell versions currently released. The high-level description of the problem
is that excessive use of Write-Host eventually leads to failures to execute EXEs
from the same PowerShell session.
For platforms where the problem exists, the following has been seen to reproduce the issue:
for( $i = 0; $i -lt 1000; $i += 1 ) { Write-Host line }; whoami.exe; "0x{0:X}" -f $LASTEXITCODE
On repro, the $LASTEXITCODE will be 0xC0000142.
This issue is described by the following Connect article:
https://connect.microsoft.com/PowerShell/feedback/details/496326/stability-problem-any-application-run-fails-with-lastexitcode-1073741502
Some folks workaround the issue by simply using pipeline output to display status messages.
Use the pipeline in this manner may be ideal for situations where it is not used for other
purposes.
If you have scripts that use the pipeline for other purposes, and rely on Write-Host
for non-pipeline status output, where your scripts hit this issue, perhaps this workaround
may be of use.
.PARAMETER Object
Object to be outputed to stdout.
.PARAMETER NoNewLine
Specify this flag if you don't what the output to end with NewLine character
.PARAMETER ForegroundColor
Specifies the text color. There is no default.
Use Get-Colors command to output all available colors in color.
Possible color names taken from '[ConsoleColor] | gm -Static' are:
Blue | DarkBlue
Cyan | DarkCyan
Gray | DarkGray
Green | DarkGreen
Magenta | DarkMagenta
Red | DarkRed
Yellow | DarkYellow
White | Black
.PARAMETER BackgroundColor
Specifies the background color. There is no default.
Use Get-Colors command to output all available colors in color.
Possible color names taken from '[ConsoleColor] | gm -Static' are:
Blue | DarkBlue
Cyan | DarkCyan
Gray | DarkGray
Green | DarkGreen
Magenta | DarkMagenta
Red | DarkRed
Yellow | DarkYellow
White | Black
.EXAMPLE
Write-Console "=)", "test" -ForegroundColor Green -NoNewLine
Prints all items in passed string array to stdout with green color used in console.
.LINK
Write-Colorized
Write-Host
Get-Colors
#>
param
(
[Parameter(Mandatory = $true, Position = 0, ValueFromRemainingArguments = $true, ValueFromPipeline = $true)]
[object] $Object,
[object] $Separator = " ",
[ConsoleColor] $ForegroundColor,
[ConsoleColor] $BackgroundColor,
[switch] $NoNewLine
)
begin
{
function printObject($o)
{
function WriteObject([string]$s)
{
if ($s.Length -gt 0)
{
if ($consoleHost) {
[Console]::Write($s);
} else {
$host.UI.Write($ForegroundColor, $BackgroundColor, $s)
}
}
}
# If null, exit.
if ($o -eq $null) {
return;
}
# If type is directly a string, write it directly.
if ($o -is [string]) {
WriteObject $o
} else {
# Object is not a string. See if it is enumerable.
if ($o -is [System.Collections.IEnumerable]) {
# Access the enumerator and print each item with any defined separation.
$objectEnumerator = $o.GetEnumerator();
$printSeparator = $false;
foreach ($element in $objectEnumerator) {
# If separator defined, print it if this is not first item.
if ($Separator -ne $null -and $printSeparator) {
WriteObject $Separator
}
# Recursive.
printObject $element
# Print separator after first item.
$printSeparator = $true;
}
} else {
# Object was not a string, and it did not have a
# GetEnumerator() method, so simply use the object's
# ToString() method to access the printable content.
WriteObject $o.ToString()
}
}
}
$consoleHost = $host.Name -eq "ConsoleHost"
if (!$consoleHost)
{
if (!$ForegroundColor)
{
$ForegroundColor = $host.UI.RawUI.ForegroundColor
}
if (!$BackgroundColor)
{
$BackgroundColor = $host.ui.RawUI.BackgroundColor
}
}
}
process
{
if ($consoleHost)
{
if( $ForegroundColor )
{
$previousForegroundColor = [Console]::ForegroundColor
[Console]::ForegroundColor = $ForegroundColor
}
if( $BackgroundColor )
{
$previousBackgroundColor = [Console]::BackgroundColor
[Console]::BackgroundColor = $BackgroundColor
}
}
try
{
printObject $Object $consoleHost
if( $NoNewLine -eq $false)
{
[Console]::WriteLine('') # Parameterless WriteLine seems to not print a newline from ISE whereas empty string works on both cmd line/ISE.
}
}
finally
{
if ($consoleHost)
{
if( $ForegroundColor )
{
[Console]::ForegroundColor = $previousForegroundColor
}
if( $BackgroundColor )
{
[Console]::BackgroundColor = $previousBackgroundColor
}
}
}
}
}
# Simple test...
function Test-WriteConsole {
Write-Host 'new console write';
Write-Host @(1,2,3,4) -Separator '-sep-'
Write-Host @(1,2,3,4) -Separator '-sep-' -ForegroundColor Yellow
Write-Host @(1,2,3,4) -Separator '-sep-' -ForegroundColor Black -BackgroundColor White
Write-Host ([int32]123) -Separator '-sep-' -ForegroundColor Cyan -BackgroundColor DarkGreen
Write-Host '123' -Separator '-sep-' -ForegroundColor Green -BackgroundColor Black
Write-Host @([int32]123,[int32]123,[int32]123,[int32]123,[int32]123) -Separator '-sep-' -ForegroundColor Cyan -BackgroundColor DarkGreen
Write-Host 'This is one write. ' -NoNewLine;
Write-Host 'This is another write on the same line. ' -NoNewLine -ForegroundColor Black -BackgroundColor White
Write-Host @('abc', [uint32]123, 'def', ' array on same line. ') -Separator ',' -NoNewLine -ForegroundColor Cyan -BackgroundColor DarkMagenta
Write-Host 'This is the last sentence on this line.'
Write-Host 'This should be on a new line.';
1..5 | Write-Host
Write-Host 1 2 3 4 5
}
Test-WriteConsole
|
PowerShellCorpus/PoshCode/Office 365 wasted Lics.ps1
|
Office 365 wasted Lics.ps1
|
$AD = 'C:\\temp\\ad.csv'
$o365 = 'C:\\temp\\o365.csv'
$duplicates = 'C:\\temp\\Duplicate Office 365 users.csv'
$log = 'C:\\temp\\Duplicate Office 365 users.log'
$PSEmailServer = 'MAILSERVER'
$EmailTo = 'TO-EMAILADDRESS'
$EmailFrom = 'FROM-EMAILADDRESS'
Import-Module ActiveDirectory
Import-Module MSOnline
$password = ConvertTo-SecureString 'PASSWORD' -AsPlainText -Force
$LiveCred = New-Object System.Management.Automation.PSCredential ("O365-USERNAME", $password)
New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection
Connect-MsolService -Credential $Livecred
Search-ADAccount -AccountDisabled | Select-Object UserPrincipalName | where-object {$_.UserPrincipalName -like "*@*" } | Export-Csv $AD
Get-MsolUser -all | Where-Object { $_.isLicensed -eq "TRUE"} | Select-Object UserPrincipalName | Export-Csv $o365
$Import = Import-Csv $o365
$Import | Out-File -Append $AD -encoding ASCII
$content = Get-Content $AD
$content | Foreach {$_.TrimEnd()} | Set-Content $AD
$RMVQuotes = Get-Content $AD
$RMVQuotes -replace('"','') | Sort-Object | Out-File $AD -Force
Get-Content $AD | Group-Object -NoElement | Where-Object {$_.Count -gt 1} | Select-Object Count, Name | Export-Csv $duplicates
get-pssession | where-object {$_.ComputerName -Like "*.outlook.com"} | remove-pssession
copy-item $duplicates $log
$DupLic = Import-Csv $duplicates | Measure-Object | Select-Object -Expand count
$subject = "There are " + $DupLic + " office 365 Licenses being used by disabled users"
if ($DupLic -gt 3){
Send-MailMessage -To $EmailTo -From $EamilFrom -Subject $Subject -attachments $log -Body "There are O365 Licenses being used by disabled users. Please remove theses licenses from Office 365 as each one costs. The attached is a list of all users that have an office 365 license assigned to them but are disabled in AD. Confirm the account and email is not in use and the license can be deleted. "
}
Remove-Item $AD
Remove-Item $o365
Remove-Item $Duplicates
Remove-Item $Log
|
PowerShellCorpus/PoshCode/New-PSOCustomObject.ps1
|
New-PSOCustomObject.ps1
|
# References:
# http://blogs.msdn.com/powershell/archive/2009/12/05/new-object-psobject-property-hashtable.aspx
# http://poshoholic.com/2008/07/03/essential-powershell-name-your-custom-object-types/
# http://poshoholic.com/2008/07/05/essential-powershell-define-default-properties-for-custom-objects/
function New-PSOCustomObject {
param(
[Parameter(Mandatory=$true)]
[string]$Name,
[Parameter(Mandatory=$true)]
[hashtable]$Properties,
[Parameter()]
[string[]]$DefaultProperties,
[Parameter()]
[hashtable]$ScriptMethods
)
$object = New-Object PSObject -Property $Properties
$object.PSObject.TypeNames[0] = "System.Management.Automation.PSCustomObject.$($Name)"
# Move Script Methods to Set-PSObjectDefaultProperties.
#
if( $ScriptMethods ) {
foreach( $key in $ScriptMethods.Keys ) {
$object | Add-Member -MemberType ScriptMethod -Name $key -Value $ScriptMethods[$key]
}
}
if( $DefaultProperties ) {
Set-PSODefaultProperties -Object $object -DefaultProperties $DefaultProperties
}
return $object
}
|
PowerShellCorpus/PoshCode/c439471e-f811-4037-9472-dde03db24534.ps1
|
c439471e-f811-4037-9472-dde03db24534.ps1
|
$WarningPreference = "SilentlyContinue"
$password = Get-Content C:\\securestring.txt | convertto-securestring
$username = "PROD\\administrator"
$credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
$uucenter = "uu-lillebaelt.dk"
$totalSize = 0
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://prod-exch1.prod.local/PowerShell/ -Credential $credentials
Import-PSSession $session -DisableNameChecking | out-null
foreach ($mbx in Get-Mailbox)
{
if($mbx.PrimarySMTPAddress -like '*uu-lillebaelt.dk*')
{
$size = (Get-MailboxStatistics $mbx.Identity).TotalItemSize
$position = $size.IndexOf("(")
$size = $size.Substring($position+1)
$position = $size.IndexOf(" ")
$size = $size.Substring(0, $position)
$totalSize = [long]$totalSize + [long]$size
}
}
$totalSize = $totalSize/1000000
Write-Host "<prtg>"
Write-Host " <result>"
Write-Host " <channel>$uucenter</channel>"
Write-Host " <value>$totalSize</value>"
Write-Host " <float>1</float>"
Write-Host " </result>"
Write-Host "</prtg>"
Remove-PSSession $session
Exit 0
|
PowerShellCorpus/PoshCode/Get-ExchangeDBSizes_3.ps1
|
Get-ExchangeDBSizes_3.ps1
|
<#
.SYNOPSIS
Get-ExchangeDBSizes - Gather data on Exchange 2007 / 2010 Mailbox Databases.
.DESCRIPTION
Gathers data from Exchange mailbox servers.
These data include:
Server\\StorageGroup\\Database (2007) or Database (2010),
Total Size (in GB) of the disk,
Size of the .edb file (in GB),
Free disk space,
Percent Disk Free,
Total Mailboxes on the database,
White Space,
Total Free disk space,
Total Percent Free disk space
.EXAMPLE
Get-ExchangeDBSizes
.LINK
http://unlockpowershell.wordpress.com/
http://poshcode.org/2025
.NOTES
File Name: Get-ExchangeDBSizes.ps1
Author: Karl Mitschke
Requires: Exchange Managemnent Shell
Requires: Powershell V2
Created: 6/14/2010
Modified: 7/28/2010 to convert .EdbFilePath to String
Modified: 7/28/2010 - Changed whitespace to a [double]
#>
Function Get-MountPointInfo($ServerName) {
$Summary = @()
$VolumeHash = @{}
$VolumeCapacityHash = @{}
$DatabaseSizeHash = @{}
$DatabaseFreeHash = @{}
$MountPoints = Get-WmiObject -Class Win32_Mountpoint -ComputerName $ServerName
$MailboxDatabases = Get-MailboxDatabase -Server $ServerName
$Volumes = Get-WmiObject -Class Win32_Volume -ComputerName $ServerName | Where-Object {$_.DriveType -eq 3}| Select-Object Name,FreeSpace,Capacity
$DatabaseLetters = $MailboxDatabases | Select-Object edbfilepath
foreach ($Volume in $Volumes) {
$VolumeHash.Add($Volume.name.TrimEnd("\\"),$Volume.FreeSpace)
$VolumeCapacityHash.Add($Volume.name.TrimEnd("\\"),$Volume.Capacity)
}
foreach ($drive in $DatabaseLetters)
{
$letter = $drive.EdbFilePath.ToString().Substring(0,$drive.EdbFilePath.ToString().LastIndexOf("\\"))
$DatabaseSizeHash.Add($letter.TrimEnd("\\"),$VolumeCapacityHash[$letter])
$DatabaseFreeHash.Add($letter.TrimEnd("\\"),$VolumeHash[$letter])
}
$VolumeHash.Clear()
$VolumeCapacityHash.Clear()
#Now I have all mailbox databases, along with the OS reported free space and capacity
foreach ($MP in $Mountpoints) {
$MP.directory = $MP.directory.replace("\\\\","\\").Split("=")[1].Replace("`"","")
if($DatabaseSizeHash[$MP.directory])
{
#This mountpoint is a database
$Record = new-Object PSObject
$OSfree = $DatabaseFreeHash[$MP.directory]
$OSCapacity = $DatabaseSizeHash[$MP.directory]
$DestFolder = "\\\\"+$ServerName + "\\" + $MP.directory
$colItems = (Get-ChildItem $destfolder.Replace(":","$") -Recurse| where{$_.length -ne $null} |Measure-Object -property length -sum)
if($colItems.sum -eq $null) {
$fsize = 0
} else {
$fsize = $colItems.sum
}
$TotFolderSize = $fsize + $OSfree
$percFree = "{0:P0}" -f ( $OSfree/$TotFolderSize)
$Record | add-Member -memberType noteProperty -name Server -Value $ServerName
$Record | add-Member -memberType noteProperty -name "Mount Point" -Value $MP.directory
$Record | add-Member -memberType noteProperty -name "Capacity" -Value ("{0:N2}" -f ($OSCapacity /1gb))
$Record | add-Member -memberType noteProperty -name "Used" -Value ("{0:N2}" -f ($fsize / 1gb))
$Record | add-Member -memberType noteProperty -name "Free" -Value ("{0:N2}" -f ($OSfree / 1gb))
$Record | add-Member -memberType noteProperty -name "Percent Free" -Value $percFree
$Summary += $Record
}
}
return $Summary
}
function Get-ExchangeWhiteSpace {
param(
$ComputerName = $(throw "ComputerName cannot be empty.")
)
# Convert Dates to WMI CIM dates
$tc = [System.Management.ManagementDateTimeconverter]
$Start =$tc::ToDmtfDateTime( (Get-Date).AddDays(-1).Date )
$End =$tc::ToDmtfDateTime( (Get-Date).Date)
$whiteSpace = @{}
# Create two claculated properties for InsertionStrings values
$DB = @{Name="DB";Expression={$_.InsertionStrings[1]}}
$FreeMB = @{Name="FreeMB";Expression={[int]$_.InsertionStrings[0]}}
$freespace = Get-WMIObject Win32_NTLogEvent -ComputerName $ComputerName -Filter "LogFile='Application' AND EventCode=1221 AND TimeWritten>='$Start' AND TimeWritten<='$End'" | Select-Object $DB,$FreeMB | Sort-Object DB –Unique –Descending
$freespace | ForEach-Object {$whiteSpace.Add($_.DB,$_.FreeMB)}
#Preceding function from Shay Levy http://blogs.microsoft.co.il/blogs/scriptfanatic/archive/2009/08/13/exchange-white-space.aspx
}
$AllServers = @()
$ServerVersion = @{}
foreach ($server in Get-MailboxServer)
{
$ServerName = $server.name
$version = Get-ExchangeServer -Identity $ServerName | Select-Object AdminDisplayVersion
if($version.admindisplayversion.major)
{
$ServerVersion.Add($ServerName,$version.admindisplayversion.major)
}
else
{
$ServerVersion.Add($ServerName,$version.admindisplayversion.Split()[1].split(".")[0])
}
}
foreach ($server in Get-MailboxServer)
{
$ServerName = $server.Name
if ([int]$ServerVersion[$ServerName] -gt 8)
{ #An Exchange 2010 server, so use Get-MailboxDatabase <database> -Status | Select-Object AvailableNewMailboxSpace
$whiteSpace = @{}
$Free = Get-MailboxDatabase -Server $ServerName -Status | Select-Object Server,Name,AvailableNewMailboxSpace
foreach ($item in $free)
{
$db = $ServerName+"\\"+$item.Name
$whiteSpace.Add($item.Name,[double]$item.AvailableNewMailboxSpace.split("(")[1].Split()[0]/1mb)
}
}
Else
{#not an Exchange 2010 server
. Get-ExchangeWhiteSpace $ServerName
}
$MountPoint = . Get-MountPointInfo $ServerName
foreach ($objItem in Get-MailboxDatabase -Server $ServerName)
{
$edbfilepath = $objItem.edbfilepath
$path = "`\\`\\" + $ServerName + "`\\" + $objItem.EdbFilePath.ToString().Split(":")[0] + "$"+ $objItem.EdbFilePath.ToString().Split(":")[1]
$dbsize = Get-ChildItem $path
$dbpath=(Split-Path $EdbFilePath.ToString().Split(":")[1] -Leaf).trimend(".edb")
if (!$MountPoint)
{
$mailboxpath = $ServerName + $EdbFilePath.ToString().Split(":")[1].trimend(".edb")
$size = get-wmiobject -computername $ServerName win32_logicaldisk |where-object {$_.deviceid -eq $objItem.EdbFilePath.ToString().Split("\\")[0]} |select-object deviceID, Freespace, Size
$freespace = ($size.freespace / 1GB)
$total = ($size.size / 1GB)
}
if ($MountPoint)
{
$mailboxpath = "$ServerName\\$dbpath"
$MPPath = $EdbFilePath.ToString().Substring(0,$EdbFilePath.ToString().LastIndexOf("\\"))
$freespace = $DatabaseFreeHash[$MPPath ] /1GB
$total = $DatabaseSizeHash[$MPPath] /1GB
}
$PercentFree = "{0:n2}" -f ($freespace / $total *100)
if (!$MountPoint)
{
$mailboxcount = Get-MailboxStatistics -database "$mailboxpath" |Where {$_.DisconnectDate -eq $null -and $_.ObjectClass -eq 'Mailbox'} |measure-object
}
if($MountPoint)
{
$mailboxcount = Get-MailboxStatistics -database $mailboxpath.Split("\\")[1] |Where {$_.DisconnectDate -eq $null -and $_.ObjectClass -eq 'Mailbox'} |measure-object
}
$ReturnedObj = New-Object PSObject
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Server\\StorageGroup\\Database" -Value $objItem.Identity
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Total Size (GB)" -Value ("{0:n2}" -f ($total))
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Used Space (GB)" -Value ("{0:n2}" -f ($dbsize.Length/1024MB))
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Free Space (GB)" -Value ("{0:n2}" -f ($freespace))
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Percent Disk Free" -Value $percentfree
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "User Mailbox Count" -Value $mailboxcount.count
if ($objitem.Identity.Split("\\").Count -eq 3){$dbasename = $objitem.Identity.Substring($objitem.Identity.IndexOf("\\")+1)}
else{$dbasename = $objitem.Identity}
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "White Space (GB)" -Value ("{0:n2}" -f ($whiteSpace[$dbasename]/1024))
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Total Free (GB)" -Value ("{0:n2}" -f ($freespace + $whiteSpace[$dbasename]/1024))
$TotalPercent = ($freespace + $whiteSpace[$dbasename]/1024) / $total *100
$ReturnedObj | Add-Member -MemberType NoteProperty -Name "Total Percent Free" -Value ("{0:n2}" -f ($TotalPercent))
$AllServers += $ReturnedObj
}
}
$AllServers |Export-Csv C:\\scripts\\MailboxDatabaseSizeReport.csv -NoTypeInformation
|
PowerShellCorpus/PoshCode/New-ISEMenu_2.ps1
|
New-ISEMenu_2.ps1
|
Import-Module ShowUI
Function New-ISEMenu {
New-Grid -AllowDrop:$true -Name "ISEAddonCreator" -columns Auto, * -rows Auto,Auto,Auto,*,Auto,Auto -Margin 5 {
New-Label -Name Warning -Foreground Red -FontWeight Bold -Column 1
($target = New-TextBox -Name txtName -Column 1 -Row ($Row=1))
New-Label "Addon Menu _Name" -Target $target -Row $Row
($target = New-TextBox -Name txtShortcut -Column 1 -Row ($Row+=1))
New-Label "Shortcut _Key" -Row $Row -Target $target
($target = New-TextBox -Name txtScriptBlock -Column 1 -Row ($Row+=1) -MinHeight 141 -MinWidth 336 -AcceptsReturn:$true -HorizontalScrollBarVisibility Auto -VerticalScrollBarVisibility Auto)
New-Label "Script _Block" -Row $Row -Target $target
New-CheckBox "_Add to ISE Profile" -Name chkProfile -Row ($Row+=1)
New-StackPanel -Orientation Horizontal -Column 1 -Row ($Row+=1) -HorizontalAlignment Right {
New-Button "_Save" -Name btnSave -Width 75 -Margin "0,0,5,0" -IsDefault -On_Click {
if ($txtName.Text.Trim() -eq "" -or $txtShortcut.text.Trim() -eq "" -or $txtScriptBlock.text.Trim() -eq "") {
$Warning.Content = "You must supply all parameters"
} else {
$menuItems = $psise.CurrentPowerShellTab.AddOnsMenu.Submenus | Select -ExpandProperty DisplayName
if ($menuItems -Contains $txtName.Text) {
$Warning.Content = "Select another Name for the menu"
return
}
try {
$ScriptBlock = [ScriptBlock]::Create($txtScriptBlock.Text)
$psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add($txtName.Text,$ScriptBlock,$txtShortcut.Text) | Out-Null
}
catch {
$Warning.Content = "Fatal Error Creating MenuItem:`n$_"
return
}
if ($chkProfile.IsChecked) {
$profileText = "`n`#Added by ISE Menu Creator Addon if (`$psISE) { `$psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add(`"$($txtName.Text)`",`{$ScriptBlock`},`"$($txtShortcut.Text)`") | Out-Null } "
Add-Content -Path $profile -Value $profileText
}
$window.Close()
}
}
New-Button "Cancel" -Name btnCancel -Width 75 -IsCancel
}
} -show -On_Load { $txtName.Focus() }
}
# this will add a the "New ISE menu" menu item and load it every time you run this script!
$psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("New ISE menu",{New-ISEMenu},"ALT+M") | Out-Null
|
PowerShellCorpus/PoshCode/Get-ExcludedCsprojJavasc.ps1
|
Get-ExcludedCsprojJavasc.ps1
|
param(
$projectDirectoryName = "MyProject"
)
$thisDir = Split-Path $MyInvocation.MyCommand.Path
$projectDir = "$thisDir/../$projectDirectoryName"
$csproj = [xml](cat $projectDir/*.csproj)
$csprojScripts = $csproj.Project.ItemGroup.Content.Include | ? {$_ -match '\\.js$'}
"$($csprojScripts.length) scripts included in csproj file"
$scripts = ls $projectDir -rec -inc *.js
$scripts = $scripts.FullName | % {($_ -match "$projectDirectoryName\\\\(.*)" | out-null); $matches[1]}
"$($scripts.length) scripts contained in scripts directory"
$diff = $scripts |? {-not ($csprojScripts -contains $_)}
"Scripts in directory but not in csproj:"
$diff
return $diff.length
|
PowerShellCorpus/PoshCode/Get-WebFile _1.7.3.ps1
|
Get-WebFile _1.7.3.ps1
|
## Get-WebFile (aka wget for PowerShell)
##############################################################################################################
## Downloads a file or page from the web
## History:
## v3.7.3 - Checks to see if URL is formatted properly (contains http or https)
## v3.7.2 - Puts a try-catch block around $writer = new-object System.IO.FileStream and returns/breaks to
## prevent further execution if fso creation fails (e.g. if path is invalid). Note: known issue --
## Script hangs if you try to connect to a good FQDN (e.g. www.google.com) with a bad port (e.g. 81).
## It will work fine if you use "http://192.168.1.1:81" but hang/crash if you use
## "http://www.google.com:81".
## v3.7.1 - Puts a try-catch block around the $req.GetResponse() call to prevent further execution if
## the page does not exist, cannot connect to server, can't resolve host, etc.
## v3.7 - [int] to [long] to support files larger than 2.0 GB
## v3.6 - Add -Passthru switch to output TEXT files
## v3.5 - Add -Quiet switch to turn off the progress reports ...
## v3.4 - Add progress report for files which don't report size
## v3.3 - Add progress report for files which report their size
## v3.2 - Use the pure Stream object because StreamWriter is based on TextWriter:
## it was messing up binary files, and making mistakes with extended characters in text
## v3.1 - Unwrap the filename when it has quotes around it
## v3 - rewritten completely using HttpWebRequest + HttpWebResponse to figure out the file name, if possible
## v2 - adds a ton of parsing to make the output pretty
## added measuring the scripts involved in the command, (uses Tokenizer)
##############################################################################################################
function Get-WebFile {
param(
$url = (Read-Host "The URL to download"),
$fileName = $null,
[switch]$Passthru,
[switch]$quiet
)
if($url.contains("http"))
{
$req = [System.Net.HttpWebRequest]::Create($url);
}
else
{
$URL_Format_Error = [string]"Connection protocol not specified. Recommended action: Try again using protocol (for example 'http://" + $url + "') instead. Function aborting...";
Write-Error $URL_Format_Error;
return;
}
# http://stackoverflow.com/questions/518181/too-many-automatic-redirections-were-attempted-error-message-when-using-a-httpw
$req.CookieContainer = New-Object System.Net.CookieContainer
try{
$res = $req.GetResponse();
}
catch
{
Write-Error $error[0].Exception.InnerException.Message;
return;
}
if($fileName -and !(Split-Path $fileName)) {
$fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName
}
elseif((!$Passthru -and ($fileName -eq $null)) -or (($fileName -ne $null) -and (Test-Path -PathType "Container" $fileName)))
{
[string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $res.Headers["Content-Disposition"] ).Groups[1].Value
$fileName = $fileName.trim("\\/""'")
if(!$fileName) {
$fileName = $res.ResponseUri.Segments[-1]
$fileName = $fileName.trim("\\/")
if(!$fileName) {
$fileName = Read-Host "Please provide a file name"
}
$fileName = $fileName.trim("\\/")
if(!([IO.FileInfo]$fileName).Extension) {
$fileName = $fileName + "." + $res.ContentType.Split(";")[0].Split("/")[1]
}
}
$fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName
}
@@if ( $Passthru ) {
@@try {
@@#Can't encode if character set is $null (e.g. where ContentType is application/xml)
@@if ( $responce.CharacterSet ) {
@@$encoding = [System.Text.Encoding]::GetEncoding( $responce.CharacterSet )
@@[string]$output = ""
@@} else {
@@Write-Warning "Can't output ContentType: $($responce.ContentType) to the pipeline."
@@$Passthru = $false
@@}
@}
@catch {
@Write-Error $error[0].Exception.InnerException.Message
@return
@}
@}
if($res.StatusCode -eq 200) {
[long]$goal = $res.ContentLength
$reader = $res.GetResponseStream()
if($fileName) {
try{
$writer = new-object System.IO.FileStream $fileName, "Create"
}
catch{
Write-Error $error[0].Exception.InnerException.Message;
return;
}
}
[byte[]]$buffer = new-object byte[] 4096
[long]$total = [long]$count = 0
do
{
$count = $reader.Read($buffer, 0, $buffer.Length);
if($fileName) {
$writer.Write($buffer, 0, $count);
}
if($Passthru){
$output += $encoding.GetString($buffer,0,$count)
} elseif(!$quiet) {
$total += $count
if($goal -gt 0) {
Write-Progress "Downloading $url" "Saving $total of $goal" -id 0 -percentComplete (($total/$goal)*100)
} else {
Write-Progress "Downloading $url" "Saving $total bytes..." -id 0
}
}
} while ($count -gt 0)
$reader.Close()
if($fileName) {
$writer.Flush()
$writer.Close()
}
if($Passthru){
$output
}
}
$res.Close();
if($fileName) {
ls $fileName
}
}
|
PowerShellCorpus/PoshCode/Email-ExpiringADAccounts_1.ps1
|
Email-ExpiringADAccounts_1.ps1
|
Function GetMsgBody {
Write-Output @"
<p>Dear $name,</p>
Your ABC network account is about to expire.<br/>
Please email helpdesk@abc.com or simply hit 'reply', and include the following details to have your account extended.<br/>
<br/>
Your name:<br/>
The department you currently volunteer in:<br/>
The staff supervisor's name you currently report to:<br/>
The current status of your involvement with ABC (Staff/Student/Volunteer):<br/>
<br/>
Kind Regards,<br/>
ABC IT Services
"@
}
Get-QADUser -AccountExpiresBefore "31/01/2012" -Enabled -SizeLimit 0 | ForEach-Object {
#Setup email variables
$smtpserver= "" # Enter your smtp server
$from= "" # Enter your from address
Subject= "" # Enter your email subject
$email= $_.mail
$name= $_.givenName
[string]$body= GetMsgBody
#Execute PowerShell's Send-MailMessage Function
Send-MailMessage -BodyAsHtml:$true -Body $body -To $email -From $from -SmtpServer $smtp -Subject $subject
}
|
PowerShellCorpus/PoshCode/Add new smtp_set prmary_1.ps1
|
Add new smtp_set prmary_1.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/Set-Computername_7.ps1
|
Set-Computername_7.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/Enable_Disable FusionLog.ps1
|
Enable_Disable FusionLog.ps1
|
function global:Enable-FusionLog {
Remove-ItemProperty HKLM:Software\\Microsoft\\Fusion -name EnableLog -ErrorAction SilentlyContinue
[void](New-ItemProperty HKLM:Software\\Microsoft\\Fusion -name EnableLog -propertyType dword -ErrorAction Stop)
Set-ItemProperty HKLM:Software\\Microsoft\\Fusion -name EnableLog -value 1 -ErrorAction Stop
Write-Host "Fusion log enabled. Do not forget to disable it when you are done"
}
function global:Disable-FusionLog {
Remove-ItemProperty HKLM:Software\\Microsoft\\Fusion -name EnableLog -ErrorAction SilentlyContinue
Write-Host "Fusion log disabled"
}
|
PowerShellCorpus/PoshCode/Interact with in-VM UI.ps1
|
Interact with in-VM UI.ps1
|
# First, start asynchronous tools update. We need to do it in a separate process
# because the update is a beta version which contains unsigned drivers and will
# be blocked by Windows' driver confirmation prompt
$updateScript = "
Add-PSSnapin VMware.VimAutomation*
Connect-VIServer $DefaultVIServer
Get-VM 'OldVMTools' | Update-Tools
"
# Start the parallel process
[System.Diagnostics.Process]::Start('powershell.exe', $updateScript)
# This script will be executed inside the VM's guest OS.
# Note that WASP is preinstalled on the VM to keep the script simpler.
$confirmationScript = "
Add-PSSnapin WASP
# VMware tools includes multiple drivers so we need to click many times
for (`$i = 0; `$i -lt 5; ) {
# In WASP, you usually find windows with Select-Window. The driver
# confirmation is a bit strange though so we need to use Select-Control.
# '-Window 0' means the desktop
`$driverConfirmationWindow = `
Select-Control -Window 0 -Recurse -Title 'Hardware Installation'
if (`$driverConfirmationWindow -ne `$null) {
`$driverConfirmationWindow |
Select-Control -title '&Continue Anyway' | Send-Click
`$i++;
}
Start-Sleep 5;
}
"
#Send confirmation script to the guest
Invoke-VMScript `
-vm 'OldVMTools' -guestUser 'user1' -guestPassword 'pass1' `
-hostUser 'root' -hostPassword 'pass2' -script $confirmationScript
|
PowerShellCorpus/PoshCode/New-AdUserAccount.ps1
|
New-AdUserAccount.ps1
|
function New-AdUserAccount {
param (
[string] $Username = $(throw "Parameter -Username [System.String] is required."),
[string] $Password = $(throw "Parameter -Password [System.String] is required."),
[string] $OrganizationalUnit = "Users",
[string] $DisplayName,
[string] $FirstName,
[string] $LastName,
[string] $Initials,
[string] $Description,
[switch] $CannotChangePassword,
[switch] $PasswordNeverExpires,
[switch] $Disabled
)
try {
$currentDomain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$dn = $currentDomain.GetDirectoryEntry().distinguishedName
$ou = [ADSI] "LDAP://CN=$OrganizationalUnit,$dn"
$userAccount = $ou.Create("user", "cn=$Username")
$userAccount.SetInfo()
$userAccount.userAccountControl = ($userAccount.userAccountControl.Item(0) -bxor 0x0002) #Enable the account
$userAccount.SetInfo()
# Properties
$userAccount.sAMAccountName = $Username
$userAccount.SetInfo()
$userAccount.userPrincipalName = ("{0}@{1}" -f $Username, $currentDomain.Name)
if ($DisplayName) {
$userAccount.displayName = $DisplayName
}
if ($Description) {
$userAccount.description = $Description
}
if ($FirstName) {
$userAccount.givenname = $FirstName
}
if ($LastName) {
$userAccount.sn = $LastName
}
if ($Initials) {
$userAccount.initials = $Initials
}
$userAccount.SetInfo()
$userAccount.SetPassword($Password)
# Password
if ($PasswordNeverExpires) {
$userAccount.userAccountControl = ($userAccount.userAccountControl.Item(0) -bxor 0x10000)
}
if ($CannotChangePassword) {
$everyOne = [System.Security.Principal.SecurityIdentifier]'S-1-1-0'
$EveryoneDeny = new-object System.DirectoryServices.ActiveDirectoryAccessRule ($Everyone,'ExtendedRight','Deny', [System.Guid]'ab721a53-1e2f-11d0-9819-00aa0040529b')
$self = [System.Security.Principal.SecurityIdentifier]'S-1-5-10'
$SelfDeny = new-object System.DirectoryServices.ActiveDirectoryAccessRule ($self,'ExtendedRight','Deny', [System.Guid]'ab721a53-1e2f-11d0-9819-00aa0040529b')
$userAccount.get_ObjectSecurity().AddAccessRule($selfDeny)
$userAccount.get_ObjectSecurity().AddAccessRule($EveryoneDeny)
$userAccount.CommitChanges()
}
$userAccount.SetInfo()
if ($Disabled) {
$userAccount.userAccountControl = ($userAccount.userAccountControl.Item(0) -bxor 0x0002)
}
$userAccount.SetInfo()
} catch {
Write-Error $_
#$ou.Delete("user", "cn=$Username")
return $false
}
return $true
}
New-AdUserAccount -Username bob -Password 'B0bsP4$$W0rD!@#$%' -Description "Bob's account" -FirstName Bob -LastName Doe -DisplayName "Bob Doe" -Initials R -PasswordNeverExpires -CannotChangePassword -Disabled
|
PowerShellCorpus/PoshCode/5d8d9270-3bf2-4dc4-8257-653fd32f8a8c.ps1
|
5d8d9270-3bf2-4dc4-8257-653fd32f8a8c.ps1
|
function Set-Domain {
param( [switch]$help,
[string]$domain=$(read-host "Please specify the domain to join"),
[System.Management.Automation.PSCredential]$credential = $(Get-Credential)
)
$usage = "`$cred = get-credential `n"
$usage += "Set-Domain -domain MyDomain -credential `$cred`n"
if ($help) {Write-Host $usage;exit}
$username = $credential.GetNetworkCredential().UserName
$password = $credential.GetNetworkCredential().Password
$computer = Get-WmiObject Win32_ComputerSystem
$computer.JoinDomainOrWorkGroup($domain ,$password, $username, $null, 3)
}
|
PowerShellCorpus/PoshCode/Get-GroupMembership_4.ps1
|
Get-GroupMembership_4.ps1
|
## Get-DistinguishedName -- look up a DN from a user's (login) name
function Get-DistinguishedName {
Param($UserName)
$ads = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'')
$ads.filter = "(&(objectClass=Person)(samAccountName=$UserName))"
$s = $ads.FindOne()
return $s.GetDirectoryEntry().DistinguishedName
}
## Get-GroupMembership -- Get AD group membership recursively
function Get-GroupMembership {
Param($DNName,[int]$RecurseLimit=-1)
$groups = ([adsi]"LDAP://$DNName").MemberOf
if ($groups -and $RecurseLimit) {
Foreach ($gr in $groups) {
$groups += @(Get-GroupMembership $gr -RecurseLimit:$($RecurseLimit-1) |
? {$groups -notcontains $_})
}
}
return $groups
}
## Usage:
#################################################################################
## $groups = Get-GroupMembership (Get-DistinguishedName Jaykul)
## # To turn recursion off:
## $groups = Get-GroupMembership (Get-DistinguishedName Jaykul) -RecurseLimit 0
|
PowerShellCorpus/PoshCode/Pivot-Object_1.ps1
|
Pivot-Object_1.ps1
|
#.Synopsis
# Pivot multiple objects which are normalized with properties that are name, value pairs.
#.Description
# Takes a series of objects where there are multiple rows to represent each object, with a pair of columns with the name and value of an additional property, and outputs new objects which have those new properties on them.
#.Example
# Import-CSV data.csv | Pivot-Objects SamAccountName Attribute Value
#
# Imports csv data containing multiple rows per-record such that a pair of columns named "Attribute" and "Value" are actually different in each row, and contain a name and value pair for attributes you want to add to the output objects.
#.Example
# @"
# ID, Attribute, Value, SamAccountName
# , HoursPerWeek, 40, J8329029
# , LastDay, 20 Feb 2010, J8329029
# 12276, Job, Sw Eng, J8329029
# 2479, HoursPerWeek, 35, X5969731
# 2479, LastDay, 20 Feb 2009, X5969731
# 2479, Job, Sr. SW Eng, X5969731
# 2479, Rate, 40, X5969731
# 2479, Bonus, 10000, X5969731
# "@.Split("`n") | ConvertFrom-Csv | Pivot-Object -Group SamAccountName -Name Attribute -Value Value -Jagged
#
# This provides a full example, with data, and demonstrates how -Jagged works:
# * Without -Jagged, you get two objects which each have the same properties.
# * With Jagged, only one one of the object output will have the Rate and Bonus properties, because there's values for the J8329029 user.
#.Notes
# Author: Joel Bennett
# function Pivot-Object {
[CmdletBinding()]
param(
# The name of the property to merge on. Items with the same value in this column will be combined.
[Parameter(Mandatory=$true)]
[Alias("GroupBy")]
[string]$GroupOnColumn,
# The name of the property that has the names of the new properties to create.
[Parameter(Mandatory=$true)]
[string]$NameColumn,
# The name of the property that has the values of the new properties to create.
[string]$ValueColumn,
[Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
# The input objects. These can be passed on the pipeline as well (or instead).
[object[]]$InputObject=@(),
# If set, the objects that return only have the properties which were defined for them.
# Otherwise, all properties that are defined for any object are assigned (even if that means they get null values) on all objects that are output.
# See the examples for more information
[switch]$Jagged
)
begin {
[string[]]$Extra = @()
[string[]]$NamedColumns = @()
$CollectedInput = New-Object 'System.Collections.Generic.List[PSObject]'
}
process{
$Extra += $InputObject | Get-Member -Type Properties |
Select-Object -Expand Name -Unique |
Where-Object {($Extra + @($GroupOnColumn,$NameColumn,$ValueColumn)) -NotContains $_}
foreach($Incoming in $InputObject) {
$NamedColumns += $Incoming.$NameColumn
$null = $CollectedInput.Add($Incoming)
}
}
end {
$Columns = $NamedColumns | Select-Object -Unique | Where-Object { $_ }
$Extra = $Extra | Select-Object -Unique | Where-Object { $_ -and ($Columns -NotContains $_) }
ForEach($item in $CollectedInput | Group-Object $GroupOnColumn) {
$thing = New-Object PSObject |
Add-Member -Type NoteProperty -Name $GroupOnColumn -Value $Item.Name -passthru
Write-Verbose "Group $($Item.Name)"
foreach($c in $Extra) {
$Value = $item.Group | Select-Object -Expand $c -Unique | Where-Object { $_ } | Select-Object -First 1
Write-Verbose "Value $($Value)"
if($Value) {
Add-Member -input $thing -MemberType NoteProperty -Name $c -Value $Value
}
}
foreach($i in $item.Group) {
Add-Member -Input $thing -Type NoteProperty -Name $i.$NameColumn -Value $i.$ValueColumn
}
if($Jagged) {
Write-Output $thing
} else {
# Note: I add the GroupOnColumn and Extra columns when -Jagged isn't specified ... I assume that's what you want.
Write-Output $thing | select ([string[]]@(@($GroupOnColumn) + $columns + $extra))
}
}
}
#}
|
PowerShellCorpus/PoshCode/List AD Users CSV.ps1
|
List AD Users CSV.ps1
|
$NumDays = 0
$LogDir = ".\\User-Accounts.csv"
$currentDate = [System.DateTime]::Now
$currentDateUtc = $currentDate.ToUniversalTime()
$lltstamplimit = $currentDateUtc.AddDays(- $NumDays)
$lltIntLimit = $lltstampLimit.ToFileTime()
$adobjroot = [adsi]''
$objstalesearcher = New-Object System.DirectoryServices.DirectorySearcher($adobjroot)
$objstalesearcher.filter = "(&(objectCategory=person)(objectClass=user)(lastLogonTimeStamp<=" + $lltIntLimit + "))"
$users = $objstalesearcher.findall() | select `
@{e={$_.properties.cn};n='Display Name'},`
@{e={$_.properties.samaccountname};n='Username'},`
@{e={[datetime]::FromFileTimeUtc([int64]$_.properties.lastlogontimestamp[0])};n='Last Logon'},`
@{e={[string]$adspath=$_.properties.adspath;$account=[ADSI]$adspath;$account.psbase.invokeget('AccountDisabled')};n='Account Is Disabled'}
$users | Export-CSV -NoType $LogDir
|
PowerShellCorpus/PoshCode/Audit Script_3.ps1
|
Audit Script_3.ps1
|
#####################################################
# #
# Audit script by Alan Renouf - Virtu-Al #
# Blog: http://teckinfo.blogspot.com/ #
# #
# Usage: Audit.ps1 'pathtolistofservers' #
# #
# The file is optional and needs to be a #
# plain text list of computers to be audited #
# one on each line. #
# #
#####################################################
param( [string] $auditlist)
if ($auditlist -eq ""){
Write-Host "No list specified, using $env:computername"
$targets = $env:computername
}
else
{
if ((Test-Path $auditlist) -eq $false)
{
Write-Host "Invalid audit path specified: $auditlist"
exit
}
else
{
Write-Host "Using Audit list: $auditlist"
$Targets = Get-Content $auditlist
}
}
$Date = Get-Date
Foreach ($Target in $Targets){
Write-Output "Collating Detail for $Target"
$ComputerSystem = Get-WmiObject -computername $Target Win32_ComputerSystem
switch ($ComputerSystem.DomainRole){
0 { $ComputerRole = "Standalone Workstation" }
1 { $ComputerRole = "Member Workstation" }
2 { $ComputerRole = "Standalone Server" }
3 { $ComputerRole = "Member Server" }
4 { $ComputerRole = "Domain Controller" }
5 { $ComputerRole = "Domain Controller" }
default { $ComputerRole = "Information not available" }
}
$OperatingSystems = Get-WmiObject -computername $Target Win32_OperatingSystem
$TimeZone = Get-WmiObject -computername $Target Win32_Timezone
$Keyboards = Get-WmiObject -computername $Target Win32_Keyboard
$SchedTasks = Get-WmiObject -computername $Target Win32_ScheduledJob
$BootINI = $OperatingSystems.SystemDrive + "boot.ini"
$RecoveryOptions = Get-WmiObject -computername $Target Win32_OSRecoveryConfiguration
switch ($ComputerRole){
"Member Workstation" { $CompType = "Computer Domain"; break }
"Domain Controller" { $CompType = "Computer Domain"; break }
"Member Server" { $CompType = "Computer Domain"; break }
default { $CompType = "Computer Workgroup"; break }
}
$LBTime=$OperatingSystems.ConvertToDateTime($OperatingSystems.Lastbootuptime)
Write-Output "..Hotfix Information"
$colQuickFixes = Get-WmiObject Win32_QuickFixEngineering
Write-Output "..Logical Disks"
$colDisks = Get-WmiObject -ComputerName $Target Win32_LogicalDisk
Write-Output "..Network Configuration"
$NICCount = 0
$colAdapters = Get-WmiObject -ComputerName $Target Win32_NetworkAdapterConfiguration
Write-Output "..Local Shares"
$colShares = Get-wmiobject -ComputerName $Target Win32_Share
Write-Output "..Printers"
$colInstalledPrinters = Get-WmiObject -ComputerName $Target Win32_Printer
Write-Output "..Services"
$colListOfServices = Get-WmiObject -ComputerName $Target Win32_Service
Write-Output "..Regional Options"
$ObjKeyboards = Get-WmiObject -ComputerName $Target Win32_Keyboard
$keyboardmap = @{
"00000402" = "BG"
"00000404" = "CH"
"00000405" = "CZ"
"00000406" = "DK"
"00000407" = "GR"
"00000408" = "GK"
"00000409" = "US"
"0000040A" = "SP"
"0000040B" = "SU"
"0000040C" = "FR"
"0000040E" = "HU"
"0000040F" = "IS"
"00000410" = "IT"
"00000411" = "JP"
"00000412" = "KO"
"00000413" = "NL"
"00000414" = "NO"
"00000415" = "PL"
"00000416" = "BR"
"00000418" = "RO"
"00000419" = "RU"
"0000041A" = "YU"
"0000041B" = "SL"
"0000041C" = "US"
"0000041D" = "SV"
"0000041F" = "TR"
"00000422" = "US"
"00000423" = "US"
"00000424" = "YU"
"00000425" = "ET"
"00000426" = "US"
"00000427" = "US"
"00000804" = "CH"
"00000809" = "UK"
"0000080A" = "LA"
"0000080C" = "BE"
"00000813" = "BE"
"00000816" = "PO"
"00000C0C" = "CF"
"00000C1A" = "US"
"00001009" = "US"
"0000100C" = "SF"
"00001809" = "US"
"00010402" = "US"
"00010405" = "CZ"
"00010407" = "GR"
"00010408" = "GK"
"00010409" = "DV"
"0001040A" = "SP"
"0001040E" = "HU"
"00010410" = "IT"
"00010415" = "PL"
"00010419" = "RU"
"0001041B" = "SL"
"0001041F" = "TR"
"00010426" = "US"
"00010C0C" = "CF"
"00010C1A" = "US"
"00020408" = "GK"
"00020409" = "US"
"00030409" = "USL"
"00040409" = "USR"
"00050408" = "GK"
}
$keyb = $keyboardmap.$($ObjKeyboards.Layout)
if (!$keyb)
{ $keyb = "Unknown"
}
Write-Output "..Event Log Settings"
$colLogFiles = Get-WmiObject -ComputerName $Target Win32_NTEventLogFile
Write-Output "..Event Log Errors"
$WmidtQueryDT = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime([DateTime]::Now.AddDays(-14))
$colLoggedEvents = Get-WmiObject -computer $Target -query ("Select * from Win32_NTLogEvent Where Type='Error' and TimeWritten >='" + $WmidtQueryDT + "'")
Write-Output "..Event Log Warnings"
$WmidtQueryDT = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime([DateTime]::Now.AddDays(-14))
$colLoggedEvents = Get-WmiObject -computer $Target -query ("Select * from Win32_NTLogEvent Where Type='Warning' and TimeWritten >='" + $WmidtQueryDT + "'")
$Filename = ".\\" + $Target + "_" + $date.Hour + $date.Minute + "_" + $Date.Day + "-" + $Date.Month + "-" + $Date.Year + ".htm"
$Report = @"
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html ES_auditInitialized='false'><head><title>Audit</title>
<META http-equiv=Content-Type content='text/html; charset=windows-1252'>
<STYLE type=text/css>
DIV .expando {DISPLAY: block; FONT-WEIGHT: normal; FONT-SIZE: 8pt; RIGHT: 10px; COLOR: #ffffff; FONT-FAMILY: Tahoma; POSITION: absolute; TEXT-DECORATION: underline}
TABLE {TABLE-LAYOUT: fixed; FONT-SIZE: 100%; WIDTH: 100%}
#objshowhide {PADDING-RIGHT: 10px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; Z-INDEX: 2; CURSOR: hand; COLOR: #000000; MARGIN-RIGHT: 0px; FONT-FAMILY: Tahoma; TEXT-ALIGN: right; TEXT-DECORATION: underline; WORD-WRAP: normal}
.heading0_expanded {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 8px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; WIDTH: 100%; CURSOR: hand; COLOR: #FFFFFF; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; BACKGROUND-COLOR: #cc0000}
.heading1 {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 16px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 5px; BORDER-LEFT: #bbbbbb 1px solid; WIDTH: 100%; CURSOR: hand; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; BACKGROUND-COLOR: #7BA7C7}
.heading2 {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 16px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 5px; BORDER-LEFT: #bbbbbb 1px solid; WIDTH: 100%; CURSOR: hand; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; BACKGROUND-COLOR: #A5A5A5}
.tableDetail {BORDER-RIGHT: #bbbbbb 1px solid; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 16px; FONT-SIZE: 8pt;MARGIN-BOTTOM: -1px; PADDING-BOTTOM: 5px; MARGIN-LEFT: 5px; BORDER-LEFT: #bbbbbb 1px solid; WIDTH: 100%; COLOR: #000000; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; BACKGROUND-COLOR: #f9f9f9}
.filler {BORDER-RIGHT: medium none; BORDER-TOP: medium none; DISPLAY: block; BACKGROUND: none transparent scroll repeat 0% 0%; MARGIN-BOTTOM: -1px; FONT: 100%/8px Tahoma; MARGIN-LEFT: 43px; BORDER-LEFT: medium none; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: medium none; POSITION: relative}
.Solidfiller {BORDER-RIGHT: medium none; BORDER-TOP: medium none; DISPLAY: block; BACKGROUND: none transparent scroll repeat 0% 0%; MARGIN-BOTTOM: -1px; FONT: 100%/8px Tahoma; MARGIN-LEFT: 0px; BORDER-LEFT: medium none; COLOR: #000000; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: medium none; POSITION: relative; BACKGROUND-COLOR: #000000}
td {VERTICAL-ALIGN: TOP; FONT-FAMILY: Tahoma}
th {VERTICAL-ALIGN: TOP; COLOR: #cc0000; TEXT-ALIGN: left}
</STYLE>
<SCRIPT language=vbscript>
strShowHide = 1
strShow = "show"
strHide = "hide"
strShowAll = "show all"
strHideAll = "hide all"
Function window_onload()
If UCase(document.documentElement.getAttribute("ES_auditInitialized")) <> "TRUE" Then
Set objBody = document.body.all
For Each obji in objBody
If IsSectionHeader(obji) Then
If IsSectionExpandedByDefault(obji) Then
ShowSection obji
Else
HideSection obji
End If
End If
Next
objshowhide.innerText = strShowAll
document.documentElement.setAttribute "ES_auditInitialized", "true"
End If
End Function
Function IsSectionExpandedByDefault(objHeader)
IsSectionExpandedByDefault = (Right(objHeader.className, Len("_expanded")) = "_expanded")
End Function
Function document_onclick()
Set strsrc = window.event.srcElement
While (strsrc.className = "sectionTitle" or strsrc.className = "expando")
Set strsrc = strsrc.parentElement
Wend
If Not IsSectionHeader(strsrc) Then Exit Function
ToggleSection strsrc
window.event.returnValue = False
End Function
Sub ToggleSection(objHeader)
SetSectionState objHeader, "toggle"
End Sub
Sub SetSectionState(objHeader, strState)
i = objHeader.sourceIndex
Set all = objHeader.parentElement.document.all
While (all(i).className <> "container")
i = i + 1
Wend
Set objContainer = all(i)
If strState = "toggle" Then
If objContainer.style.display = "none" Then
SetSectionState objHeader, "show"
Else
SetSectionState objHeader, "hide"
End If
Else
Set objExpando = objHeader.children.item(1)
If strState = "show" Then
objContainer.style.display = "block"
objExpando.innerText = strHide
ElseIf strState = "hide" Then
objContainer.style.display = "none"
objExpando.innerText = strShow
End If
End If
End Sub
Function objshowhide_onClick()
Set objBody = document.body.all
Select Case strShowHide
Case 0
strShowHide = 1
objshowhide.innerText = strShowAll
For Each obji In objBody
If IsSectionHeader(obji) Then
HideSection obji
End If
Next
Case 1
strShowHide = 0
objshowhide.innerText = strHideAll
For Each obji In objBody
If IsSectionHeader(obji) Then
ShowSection obji
End If
Next
End Select
End Function
Function IsSectionHeader(obj) : IsSectionHeader = (obj.className = "heading0_expanded") Or (obj.className = "heading1_expanded") Or (obj.className = "heading1") Or (obj.className = "heading2"): End Function
Sub HideSection(objHeader) : SetSectionState objHeader, "hide" : End Sub
Sub ShowSection(objHeader) : SetSectionState objHeader, "show": End Sub
</SCRIPT>
</HEAD>
<BODY>
<p><b><font face="Arial" size="5">$Target Audit<hr size="8" color="#CC0000"></font></b>
<font face="Arial" size="1"><b><i>Version 1.1 by Alan Renouf (Virtu-Al)</i></b></font><br>
<font face="Arial" size="1">Report generated on $Date </font></p>
<TABLE cellSpacing=0 cellPadding=0>
<TBODY>
<TR>
<TD>
<DIV id=objshowhide tabIndex=0><FONT face=Arial></FONT></DIV>
</TD>
</TR>
</TBODY>
</TABLE>
<DIV class=heading0_expanded>
<SPAN class=sectionTitle tabIndex=0>$target Details</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=filler></DIV>
<DIV class=container>
<DIV class=heading1>
<SPAN class=sectionTitle tabIndex=0>General</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
<tr>
<th width='25%'><b>Computer Name</b></font></th>
<td width='75%'>$($ComputerSystem.Name)</font></td>
</tr>
<tr>
<th width='25%'><b>Computer Role</b></font></th>
<td width='75%'> $ComputerRole </font></td>
</tr>
<tr>
<th width='25%'><b>$CompType</b></font></th>
<td width='75%'>$($ComputerSystem.Domain)</font></td>
</tr>
<tr>
<th width='25%'><b>Operating System</b></font></th>
<td width='75%'>$($OperatingSystems.Caption)</font></td>
</tr>
<tr>
<th width='25%'><b>Service Pack</b></font></th>
<td width='75%'>$($OperatingSystems.CSDVersion)</font></td>
</tr>
<tr>
<th width='25%'><b>System Root</b></font></th>
<td width='75%'>$($OperatingSystems.SystemDrive)</font></td>
</tr>
<tr>
<th width='25%'><b>Manufacturer</b></font></th>
<td width='75%'>$($ComputerSystem.Manufacturer)</font></td>
</tr>
<tr>
<th width='25%'><b>Model</b></font></th>
<td width='75%'>$($ComputerSystem.Model)</font></td>
</tr>
<tr>
<th width='25%'><b>Number of Processors</b></font></th>
<td width='75%'>$($ComputerSystem.NumberOfProcessors)</font></td>
</tr>
<tr>
<th width='25%'><b>Memory</b></font></th>
<td width='75%'>$($ComputerSystem.TotalPhysicalMemory)</font></td>
</tr>
<tr>
<th width='25%'><b>Registered User</b></font></th>
<td width='75%'>$($ComputerSystem.PrimaryOwnerName)</font></td>
</tr>
<tr>
<th width='25%'><b>Registered Organisation</b></font></th>
<td width='75%'>$($OperatingSystems.Organization)</font></td>
</tr>
<tr>
<th width='25%'><b>Last System Boot</b></font></th>
<td width='75%'>$LBTime</font></td>
</tr>
</TABLE>
</DIV>
</DIV>
<DIV class=filler></DIV>
<DIV class=container>
<DIV class=heading1>
<SPAN class=sectionTitle tabIndex=0>HotFixes</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
<tr>
<th width='25%'><b>HotFix Number</b></font></th>
<th width='75%'><b>Description</b></font></th>
</tr>
"@
ForEach ($objQuickFix in $colQuickFixes)
{
if ($objQuickFix.HotFixID -ne "File 1")
{
$Report+= " <tr>"
$Report+= " <td width='25%'>$($objQuickFix.HotFixID)</font></td>"
$Report+= " <td width='75%'>$($objQuickFix.Description)</font></td>"
$Report+= " </tr>"
}
}
$Report+= @"
</TABLE>
</DIV>
</DIV>
</DIV>
<DIV class=filler></DIV>
<DIV class=container>
<DIV class=heading1>
<SPAN class=sectionTitle tabIndex=0>Logical Disk Configuration</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
<tr>
<th width='15%'><b>Drive Letter</b></font></th>
<th width='20%'><b>Label</b></font></th>
<th width='20%'><b>File System</b></font></th>
<th width='15%'><b>Disk Size</b></font></th>
<th width='15%'><b>Disk Free Space</b></font></th>
<th width='15%'><b>% Free Space</b></font></th>
</tr>
"@
Foreach ($objDisk in $colDisks)
{
if ($objDisk.DriveType -eq 3)
{
$Report+= " <tr>"
$Report+= " <td width='15%'>$($objDisk.DeviceID)</font></td>"
$Report+= " <td width='20%'>$($objDisk.VolumeName)</font></td>"
$Report+= " <td width='20%'>$($objDisk.FileSystem)</font></td>"
$disksize = [math]::round(($objDisk.size / 1048576))
$Report+= " <td width='15%'>$disksize MB</font></td>"
$freespace = [math]::round(($objDisk.FreeSpace / 1048576))
$Report+= " <td width='15%'>$Freespace MB</font></td>"
$percFreespace=[math]::round(((($objDisk.FreeSpace / 1048576)/($objDisk.Size / 1048676)) * 100),0)
$Report+= " <td width='15%'>$percFreespace%</font></td>"
$Report+= " </tr>"
}
}
$Report+= @"
</TABLE>
</DIV>
</DIV>
</DIV>
<DIV class=filler></DIV>
<DIV class=container>
<DIV class=heading1>
<SPAN class=sectionTitle tabIndex=0>NIC Configuration</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
"@
Foreach ($objAdapter in $colAdapters)
{
if ($objAdapter.IPEnabled -eq "True")
{
$NICCount = $NICCount + 1
If ($NICCount -gt 1)
{
$Report+= " </TABLE>"
$Report+= " <DIV class=Solidfiller></DIV>"
$Report+= " <TABLE>"
}
$Report+= " <tr>"
$Report+= " <th width='25%'><b>Description</b></font></th>"
$Report+= " <td width='75%'>$($objAdapter.Description)</font></td>"
$Report+= " </tr>"
$Report+= " <tr>"
$Report+= " <th width='25%'><b>Physical address</b></font></th>"
$Report+= " <td width='75%'>$($objAdapter.MACaddress)</font></td>"
$Report+= " </tr>"
If ($objAdapter.IPAddress -ne $Null)
{
$Report+= " <tr>"
$Report+= " <th width='25%'><b>IP Address / Subnet Mask</b></font></th>"
$Report+= " <td width='75%'>$($objAdapter.IPAddress)/$($objAdapter.IPSubnet)</font></td>"
$Report+= " </tr>"
$Report+= " </tr>"
$Report+= " <tr>"
$Report+= " <th width='25%'><b>Default Gateway</b></font></th>"
$Report+= " <td width='75%'>$($objAdapter.DefaultIPGateway)</font></td>"
$Report+= " </tr>"
}
$Report+= " <tr>"
$Report+= " <th width='25%'><b>DHCP enabled</b></font></th>"
If ($objAdapter.DHCPEnabled -eq "True")
{
$Report+= " <td width='75%'>Yes</font></td>"
}
Else
{
$Report+= " <td width='75%'>No</font></td>"
}
$Report+= " </tr>"
$Report+= " <tr>"
$Report+= " <th width='25%'><b>DNS Servers</b></font></th>"
$Report+= " <td width='75%'>"
If ($objAdapter.DNSServerSearchOrder -ne $Null)
{
$Report+= " $($objAdapter.DNSServerSearchOrder) "
}
$Report+= " </tr>"
$Report+= " <tr>"
$Report+= " <th width='25%'><b>Primary WINS Server</b></font></th>"
$Report+= " <td width='75%'>$($objAdapter.WINSPrimaryServer)</font></td>"
$Report+= " </tr>"
$Report+= " <tr>"
$Report+= " <th width='25%'><b>Secondary WINS Server</b></font></th>"
$Report+= " <td width='75%'>$($objAdapter.WINSSecondaryServer)</font></td>"
$Report+= " </tr>"
$NICCount = $NICCount + 1
}
}
$Report+= @"
</TABLE>
</DIV>
</DIV>
</DIV>
<DIV class=filler></DIV>
"@
if ((get-wmiobject -namespace "root/cimv2" -list) | ? {$_.name -match "Win32_Product"})
{
Write-Output "..Installed Software"
$colApps = get-wmiobject -ComputerName $Target Win32_Product | select Name,Version,Vendor,InstallDate
$Report+= @"
<DIV class=container>
<DIV class=heading1>
<SPAN class=sectionTitle tabIndex=0>Software</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
<tr>
<th width='25%'><b>Name</b></font></th>
<th width='25%'><b>Version</b></font></th>
<th width='25%'><b>Vendor</b></font></th>
<th width='25%'><b>Install Date</b></font></th>
</tr>
"@
Foreach ($objApps in $colApps)
{
$Report+= " <tr>"
$Report+= " <td width='50%'>$($objApps.Name)</font></td>"
$Report+= " <td width='20%'>$($objApps.Version)</font></td>"
$Report+= " <td width='15%'>$($objApps.Vendor)</font></td>"
$Report+= " <td width='15%'>$($objApps.InstallDate)</font></td>"
$Report+= " </tr>"
}
$Report+= " </TABLE>"
$Report+= " </DIV>"
$Report+= " </DIV>"
$Report+= " </DIV>"
$Report+= " <DIV class=filler></DIV>"
}
$Report+= @"
<DIV class=container>
<DIV class=heading1>
<SPAN class=sectionTitle tabIndex=0>Local Shares</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
<tr>
<th width='25%'><b>Share</b></font></th>
<th width='25%'><b>Path</b></font></th>
<th width='50%'><b>Comment</b></font></th>
</tr>
"@
Foreach ($objShare in $colShares)
{
$Report+= " <tr>"
$Report+= " <td width='25%'>$($objShare.Name)</font></td>"
$Report+= " <td width='25%'>$($objShare.Path)</font></td>"
$Report+= " <td width='50%'>$($objShare.Caption)</font></td>"
$Report+= " </tr>"
}
$Report+= @"
</TABLE>
</DIV>
</DIV>
</DIV>
<DIV class=filler></DIV>
<DIV class=container>
<DIV class=heading1>
<SPAN class=sectionTitle tabIndex=0>Printers</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
<tr>
<th width='25%'><b>Printer</b></font></th>
<th width='25%'><b>Location</b></font></th>
<th width='25%'><b>Default Printer</b></font></th>
<th width='25%'><b>Portname</b></font></th>
</tr>
"@
Foreach ($objPrinter in $colInstalledPrinters)
{
If ($objPrinter.Name -eq "")
{
$Report+= " <tr>"
$Report+= " <td width='100%'>No Printers Installed</font></td>"
}
Else
{
$Report+= " <tr>"
$Report+= " <td width='25%'>$($objPrinter.Name)</font></td>"
$Report+= " <td width='25%'>$($objPrinter.Location)</font></td>"
if ($objPrinter.Default -eq "True")
{
$Report+= " <td width='25%'>Yes</font></td>"
}
Else
{
$Report+= " <td width='25%'>No</font></td>"
}
$Report+= " <td width='25%'>$($objPrinter.Portname)</font></td>"
}
$Report+= " </tr>"
}
$Report+= @"
</TABLE>
</DIV>
</DIV>
</DIV>
<DIV class=filler></DIV>
<DIV class=container>
<DIV class=heading1>
<SPAN class=sectionTitle tabIndex=0>Services</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
<tr>
<th width='20%'><b>Name</b></font></th>
<th width='20%'><b>Account</b></font></th>
<th width='20%'><b>Start Mode</b></font></th>
<th width='20%'><b>State</b></font></th>
<th width='20%'><b>Expected State</b></font></th>
</tr>
"@
Foreach ($objService in $colListOfServices)
{
$Report+= " <tr>"
$Report+= " <td width='20%'>$($objService.Caption)</font></td>"
$Report+= " <td width='20%'>$($objService.Startname)</font></td>"
$Report+= " <td width='20%'>$($objService.StartMode)</font></td>"
If ($objService.StartMode -eq "Auto")
{
if ($objService.State -eq "Stopped")
{
$Report+= " <td width='20%'><font color='#FF0000'>$($objService.State)</font></td>"
$Report+= " <td width='25%'><font face='Wingdings'color='#FF0000'>û</font></td>"
}
}
If ($objService.StartMode -eq "Auto")
{
if ($objService.State -eq "Running")
{
$Report+= " <td width='20%'><font color='#009900'>$($objService.State)</font></td>"
$Report+= " <td width='20%'><font face='Wingdings'color='#009900'>ü</font></td>"
}
}
If ($objService.StartMode -eq "Disabled")
{
If ($objService.State -eq "Running")
{
$Report+= " <td width='20%'><font color='#FF0000'>$($objService.State)</font></td>"
$Report+= " <td width='25%'><font face='Wingdings'color='#FF0000'>û</font></td>"
}
}
If ($objService.StartMode -eq "Disabled")
{
if ($objService.State -eq "Stopped")
{
$Report+= " <td width='20%'><font color='#009900'>$($objService.State)</font></td>"
$Report+= " <td width='20%'><font face='Wingdings'color='#009900'>ü</font></td>"
}
}
If ($objService.StartMode -eq "Manual")
{
$Report+= " <td width='20%'><font color='#009900'>$($objService.State)</font></td>"
$Report+= " <td width='20%'><font face='Wingdings'color='#009900'>ü</font></td>"
}
If ($objService.State -eq "Paused")
{
$Report+= " <td width='20%'><font color='#FF9933'>$($objService.State)</font></td>"
$Report+= " <td width='20%'><font face='Wingdings'color='#009900'>ü</font></td>"
}
$Report+= " </tr>"
}
$Report+= @"
</TABLE>
</DIV>
</DIV>
</DIV>
<DIV class=filler></DIV>
<DIV class=container>
<DIV class=heading1>
<SPAN class=sectionTitle tabIndex=0>Regional Settings</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
<tr>
<th width='25%'><b>Time Zone</b></font></th>
<td width='75%'>$($TimeZone.Description)</font></td>
</tr>
<tr>
<th width='25%'><b>Country Code</b></font></th>
<td width='75%'>$($OperatingSystems.Countrycode)</font></td>
</tr>
<tr>
<th width='25%'><b>Locale</b></font></th>
<td width='75%'>$($OperatingSystems.Locale)</font></td>
</tr>
<tr>
<th width='25%'><b>Operating System Language</b></font></th>
<td width='75%'>$($OperatingSystems.OSLanguage)</font></td>
</tr>
<tr>
<th width='25%'><b>Keyboard Layout</b></font></th>
<td width='75%'>$keyb</font></td>
</tr>
</TABLE>
</div>
</DIV>
</DIV>
<DIV class=filler></DIV>
<DIV class=container>
<DIV class=heading1>
<SPAN class=sectionTitle tabIndex=0>Event Logs</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<DIV class=container>
<DIV class=heading2>
<SPAN class=sectionTitle tabIndex=0>Event Log Settings</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
<tr>
<th width='25%'><b>Log Name</b></font></th>
<th width='25%'><b>Overwrite Outdated Records</b></font></th>
<th width='25%'><b>Maximum Size</b></font></th>
<th width='25%'><b>Current Size</b></font></th>
</tr>
"@
ForEach ($objLogFile in $colLogfiles)
{
$Report+= " <tr>"
$Report+= " <td width='25%'>$($objLogFile.LogFileName)</font></td>"
If ($objLogfile.OverWriteOutdated -lt 0)
{
$Report+= " <td width='25%'>Never</font></td>"
}
if ($objLogFile.OverWriteOutdated -eq 0)
{
$Report+= " <td width='25%'>As needed</font></td>"
}
Else
{
$Report+= " <td width='25%'>After $($objLogFile.OverWriteOutdated) days</font></td>"
}
$MaxFileSize = ($objLogfile.MaxFileSize) / 1024
$FileSize = ($objLogfile.FileSize) / 1024
$Report+= " <td width='25%'>$MaxFileSize KB</font></td>"
$Report+= " <td width='25%'>$FileSize KB</font></td>"
$Report+= " </tr>"
}
$Report+= @"
</TABLE>
</DIV>
</DIV>
</DIV>
<DIV class=filler></DIV>
<DIV class=container>
<DIV class=heading2>
<SPAN class=sectionTitle tabIndex=0>ERROR Entries</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
<tr>
<th width='10%'><b>Event Code</b></font></th>
<th width='10%'><b>Source Name</b></font></th>
<th width='15%'><b>Time</b></font></th>
<th width='10%'><b>Log</b></font></th>
<th width='55%'><b>Message</b></font></th>
</tr>
"@
ForEach ($objEvent in $colLoggedEvents)
{
$dtmEventDate = $ObjEvent.ConvertToDateTime($objEvent.TimeWritten)
$Report+= " <tr>"
$Report+= " <td width='10%'>$($objEvent.EventCode)</font></td>"
$Report+= " <td width='10%'>$($objEvent.SourceName)</font></td>"
$Report+= " <td width='15%'>$dtmEventDate</font></td>"
$Report+= " <td width='10%'>$($objEvent.LogFile)</font></td>"
$Report+= " <td width='55%'>$($objEvent.Message)</font></td>"
$Report+= " </tr>"
}
$Report+= @"
</TABLE>
</DIV>
</DIV>
</DIV>
<DIV class=filler></DIV>
<DIV class=container>
<DIV class=heading2>
<SPAN class=sectionTitle tabIndex=0>WARNING Entries</SPAN>
<A class=expando href='#'></A>
</DIV>
<DIV class=container>
<DIV class=tableDetail>
<TABLE>
<tr>
<th width='10%'><b>Event Code</b></font></th>
<th width='10%'><b>Source Name</b></font></th>
<th width='15%'><b>Time</b></font></th>
<th width='10%'><b>Log</b></font></th>
<th width='55%'><b>Message</b></font></th>
</tr>
"@
ForEach ($objEvent in $colLoggedEvents)
{
$StrWMIDate = $ObjEvent.ConvertToDateTime($objEvent.TimeWritten)
$Report+= " <tr>"
$Report+= " <td width='10%'>$($objEvent.EventCode)</font></td>"
$Report+= " <td width='10%'>$($objEvent.SourceName)</font></td>"
$Report+= " <td width='15%'>$($dtmEventDate)</font></td>"
$Report+= " <td width='10%'>$($objEvent.LogFile)</font></td>"
$Report+= " <td width='55%'>$($objEvent.Message)</font></td>"
$Report+= " </tr>"
}
$Report+= @"
</TABLE>
</DIV>
</DIV>
</DIV>
<DIV class=filler></DIV>
</DIV>
</DIV>
</DIV>
<DIV class=filler></DIV>
</body>
</html>
"@
$Report | out-file -encoding ASCII -filepath $Filename
}
|
PowerShellCorpus/PoshCode/TabExpansion for V2CTP_8.ps1
|
TabExpansion for V2CTP_8.ps1
|
## Tab-Completion
#################
## For V2CTP3.
## This won't work on V1 and V2CTP and V2CTP2.
## Please dot souce this script file.
## In first loading, it may take a several minutes, in order to generate ProgIDs and TypeNames list.
##
## What this can do is:
##
## [datetime]::n<tab>
## [datetime]::now.d<tab>
## $a = New-Object "Int32[,]" 2,3; $b = "PowerShell","PowerShell"
## $c = [ref]$a; $d = [ref]$b,$c
## $d[0].V<tab>[0][0].Get<tab>
## $d[1].V<tab>[0,0].tos<tab>
## $function:a<tab>
## $env:a<tab>
## [System.Type].a<tab>
## [datetime].Assembly.a<tab>
## ).a<tab> # shows System.Type properties and methods...
## #native command name expansion
## fsu<tab>
## #command option name expansion (for fsutil ipconfig net powershell only)
## fsutil <tab>
## ipconfig <tab>
## net <tab>
## powershell <tab>
## #TypeNames and Type accelerators expansion
## [Dec<tab>
## [system.Man<tab>.auto<tab>.p<tab>
## New-Object -TypeName IO.Dir<tab>
## New-Object System.win<tab>.for<tab>.bu<tab>
## #ProgIDs expansion
## New-Object -Com shel<tab>
## #Enum option expansion
## Set-ExecutionPolicy <tab>
## Set-ExecutionPolicy All<tab>
## Set-ExcusionPolisy -ex <tab>
## Get-TraceSource Inte<tab>
## iex -Errora <tab> -wa Sil<tab>
## #WmiClasses expansion
## Get-WmiObject -class Win32_<tab>
## gwmi __Instance<tab>
## #Encoding expansion
## [Out-File | Export-CSV | Select-String | Export-Clixml] -enc <tab>
## [Add-Content | Get-Content | Set-Content} -Encoding Big<tab>
## #PSProvider name expansion
## [Get-Location | Get-PSDrive | Get-PSProvider | New-PSDrive | Remove-PSDrive] -PSProvider <tab>
## Get-PSProvider <tab>
## pwd -psp al<tab>
## #PSDrive name expansion
## [Get-PSDrive | New-PSDrive | Remove-PSDrive] [-Name] <tab>
## Get-PSDrive <tab>
## pwd -psd <tab>
## #PSSnapin name expansion
## [Add-PSSnapin | Get-PSSnapin | Remove-PSSnapin ] [-Name] <tab>
## Get-Command -PSSnapin <tab>
## Remove-PSSnapin <tab>
## Get-PSSnapin M<tab>
## #Eventlog name and expansion
## Get-Eventlog -Log <tab>
## Get-Eventlog w<tab>
## #Eventlog's entrytype expansion
## Get-EventLog -EntryType <tab>
## Get-EventLog -EntryType Er<tab>
## Get-EventLog -Ent <tab>
## #Service name expansion
## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-Name] <tab>
## New-Service -DependsOn <tab>
## New-Service -Dep e<tab>
## Get-Service -n <tab>
## Get-Service <tab>,a<tab>,p<tab>
## gsv <tab>
## #Service display name expansion
## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-DisplayName] <tab>
## Get-Service -Dis <tab>
## gsv -Dis <tab>,w<tab>,b<tab>
## #Cmdlet and Topic name expansion (this also support default help function and man alias)
## Get-Help [-Name] about_<tab>
## Get-Help <tab>
## #Category name expansion (this also support default help function and man alias)
## Get-Help -Category c<tab>,<tab>
## #Command name expansion
## Get-Command [-Name] <tab>
## Get-Command -Name <tab>
## gcm a<tab>,<tab>
## #Scope expansion
## [Clear-Variable | Export-Alias | Get-Alias | Get-PSDrive | Get-Variable | Import-Alias
## New-Alias | New-PSDrive | New-Variable | Remove-Variable | Set-Alias | Set-Variable] -Scope <tab>
## Clear-Variable -Scope G<tab>
## Set-Alias -s <tab>
## #Process name expansion
## [Get-Process | Stop-Process] [-Name] <tab>
## Stop-Process -Name <tab>
## Stop-Process -N pow<tab>
## Get-Process <tab>
## ps power<tab>
## #Trace sources expansion
## [Trace-Command | Get-TraceSource | Set-TraceSource] [-Name] <tab>,a<tab>,p<tab>
## #Trace -ListenerOption expansion
## [Set-TraceSource | Trace-Command] -ListenerOption <tab>
## Set-TraceSource -Lis <tab>,n<tab>
## #Trace -Option expansion
## [Set-TraceSource | Trace-Command] -Option <tab>
## Set-TraceSource -op <tab>,con<tab>
## #ItemType expansion
## New-Item -Item <tab>
## ni -ItemType d<tab>
## #ErrorAction and WarningAction option expansion
## CMDLET [-ErrorAction | -WarningAction] <tab>
## CMDLET -Errora s<tab>
## CMDLET -ea con<tab>
## CMDLET -wa <tab>
## #Continuous expansion with comma when parameter can treat multiple option
## # if there are spaces, occur display bug in the line
## # if strings contains '$' or '-', not work
## Get-Command -CommandType <tab>,<tab><tab>,cm<tab>
## pwd -psp <tab>,f<tab>,va<tab>
## Get-EventLog -EntryType <tab>,i<tab>,s<tab>
## #Enum expansion in method call expression
## # this needs one or more spaces after left parenthesis or comma
## $str = "day night"
## $str.Split( " ",<space>rem<tab>
## >>> $str.Split( " ", "RemoveEmptyEntries" ) <Enter> ERROR
## $str.Split( " ", "RemoveEmptyEntries" -as<space><tab>
## >>> $str.Split( " ", "RemoveEmptyEntries" -as [System.StringSplitOptions] ) <Enter> Success
## $type = [System.Type]
## $type.GetMembers(<space>Def<tab>
## [IO.Directory]::GetFiles( "C:\\", "*",<space>All<tab>
## # this can do continuous enum expansion with comma and no spaces
## $type.GetMembers( "IgnoreCase<comma>Dec<tab><comma>In<tab>"
## [IO.Directory]::GetAccessControl( "C:\\",<space>au<tab><comma>ac<tab><comma>G<tab>
## #Better '$_.' expansion when cmdlet output objects or method return objects
## ls |group { $_.Cr<tab>.Tost<tab>"y")} | tee -var foo| ? { $_.G<tab>.c<tab> -gt 5 } | % { md $_.N<tab> ; copy $_.G<tab> $_.N<tab> }
## [IO.DriveInfo]::GetDrives() | ? { $_.A<tab> -gt 1GB }
## $Host.UI.RawUI.GetBufferContents($rect) | % { $str += $_.c<tab> }
## gcm Add-Content |select -exp Par<tab>| select -ExpandProperty Par<tab> | ? { $_.Par<tab>.N<tab> -eq "string" }
## $data = Get-Process
## $data[2,4,5] | % { $_.<tab>
## #when Get-PipeLineObject failed, '$_.' shows methods and properties name of FileInfo and String and Type
## #Property name expansion by -Property parameter
## [ Format-List | Format-Custom | Format-Table | Format-Wide | Compare-Object |
## ConvertTo-Html | Measure-Object | Select-Object | Group-Object | Sort-Object ] [-Property] <tab>
## Select-Object -ExcludeProperty <tab>
## Select-Object -ExpandProperty <tab>
## gcm Get-Acl|select -exp Par<tab>
## ps |group na<tab>
## ls | ft A<tab>,M<tab>,L<tab>
## #Hashtable key expansion in the variable name and '.<tab>'
## Get-Process | Get-Unique | % { $hash += @{$_.ProcessName=$_} }
## $hash.pow<tab>.pro<tab>
## #Parameter expansion for function, filter and script
## man -f<tab>
## 'param([System.StringSplitOptions]$foo,[System.Management.Automation.ActionPreference]$bar,[System.Management.Automation.CommandTypes]$baz) {}' > foobar.ps1
## .\\foobar.ps1 -<tab> -b<tab>
## #Enum expansion for function, filter and scripts
## # this can do continuous enum expansion with comma and no spaces
## .\\foobar.ps1 -foo rem<tab> -bar <tab><comma>c<tab><comma>sc<tab> -ea silent<tab> -wa con<tab>
## #Enum expansion for assignment expression
## #needs space(s) after '=' and comma
## #strongly-typed with -as operator and space(s)
## $ErrorActionPreference =<space><tab>
## $cmdtypes = New-Object System.Management.Automation.CommandTypes[] 3
## $cmdtypes =<space><tab><comma><space>func<tab><comma><space>cmd<tab> -as<space><tab>
## #Path expansion with variable and '\\' or '/'
## $PWD\\../../<tab>\\<tab>
## "$env:SystemDrive/pro<tab>/<tab>
## #Operator expansion which starts with '-'
## "Power","Shell" -m<tab> "Power" -r<tab> '(Pow)(er)','$1d$2'
## 1..9 -co<tab> 5
## #Keyword expansion
## fu<tab> test { p<tab> $foo, $bar ) b<tab> "foo" } pr<tab> $_ } en<tab> "$bar" } }
## #Variable name expansion (only global scope)
## [Clear-Variable | Get-Variable | New-Variable | Remove-Variable | Set-Variable] [-Name] <tab>
## [Cmdlet | Function | Filter | ExternalScript] -ErrorVariable <tab>
## [Cmdlet | Function | Filter | ExternalScript] -OutVariable <tab>
## Tee-Object -Variable <tab>
## gv pro<tab>,<tab>
## Remove-Variable -Name out<tab>,<tab>,ps<tab>
## ... | ... | tee -v <tab>
## #Alias name expansion
## [Get-Alias | New-Alias | Set-Alias] [-Name] <tab>
## Export-Alias -Name <tab>
## Get-Alias i<tab>,e<tab>,a<tab>
## epal -n for<tab>
## #Property name expansion with -groupBy parameter
## [Format-List | Format-Custom | Format-Table | Format-Wide] -groupBy <tab>
## ps | ft -g <tab>
## gcm | Format-Wide -GroupBy Par<tab>
## #Type accelerators expansion with no characters
## [<tab>
## New-Object -typename <tab>
## New-Object <tab>
## # File glob expansion with '@'
## ls *.txt@<tab>
## ls file.txt, foo1.txt, 'bar``[1``].txt', 'foo bar .txt' # 1 <tab> expanding with comma
## ls * -Filter *.txt # 2 <tab> refactoring
## ls *.txt # 3 <tab> (or 1 <tab> & 1 <shift>+<tab>) return original glob pattern
## This can also use '^'(hat) or '~'(tilde) for Excluding
## ls <hat>*.txt@<tab>
## ls foo.ps1, 'bar``[1``].xml' # 1 <tab> expanding with comma
## ls * -Filter * -Excluding *.txt # 2 <tab> refactoring
## *.txt<tilde>foo*<tilde>bar*@<tab>
## ls file.txt # 1 <tab> expanding with comma
## ls * -Filter *.txt -Excluding foo*, bar* # 2 <tab> refactoring
## # Ported history expansion from V2CTP3 TabExpansion with '#' ( #<pattern> or #<id> )
## ls * -Filter * -Excluding foo*, bar*<Enter>
## #ls<tab>
## #1<tab>
## # Command buffer stack with ';'(semicolon)
## ls * -Filter * -Excluding foo*, bar*<semicolon><tab> # push command1
## echo "PowerShell"<semicolon><tab> # push command2
## get-process<semicolon><tab> # push command3
## {COMMAND}<Enter> # execute another command
## get-process # Auto pop command3 from stack by LIFO
## This can also hand-operated pop with ';,'(semicolon&comma) or ';:'(semicolon&colon)
## get-process; <semicolon><comma><tab>
## get-process; echo "PowerShell" # pop command2 from stack by LIFO
## # Function name expansion after 'function' or 'filter' keywords
## function cl<tab>
## #Switch syntax option expansion
## switch -w<tab> -f<tab>
## #Better powershell.exe option expansion with '-'
## powershell -no<tab> -<tab> -en<tab>
## #A part of PowerShell attributes expansion ( CmdletBinding, Parameter, Alias, Validate*, Allow* )
## [par<tab>
## [cmd<tab>
## #Member expansion for CmdletBinding and Parameter attributes
## [Parameter(man<tab>,<tab>1,val<tab>$true)]
## [CmdletBinding( <tab>"foo", su<tab>$true)]
## #Several current date/time formats with Ctrl+D
## <Ctrl+D><tab><tab><tab><tab><tab>...
## #Hand-operated pop from command buffer with Ctrl+P (this is also available with ';:' or ';,')
## <command>;<tab> # push command
## <Ctrl+D><tab> # pop
## #Paste clipboard with Ctrl+V
## <Ctrl+V><tab>
## # Cut current line with Ctrl+X
## <command><Ctrl+X><tab>
## # Cut words with a character after Ctrl+X until the character
## 1: PS > dir -Filter *.txt<Ctrl+X>-<tab> # Cut words until '-'
## 2: PS > dir -
## 3: PS > dir -<Ctrl+V><tab> # Paste words that were copyed now
## # Cut last word in current line with Ctrl+Z
## 1: PS > Get-ChildItem *.txt<Ctrl+Z><tab> # Cut last word in current line
## 2: PS > Get-ChildItem
## 3: PS > Get-ChildItem -Exclude <Ctrl+V><tab> # Paste last word that was copyed now
## #[ScriptBlock] member expansion for [ScriptBlock] literal
## { 1+1 }.inv<tab>
## #Help document's section name expansion at a line that has only spaces
## .syn<tab>
## .func<tab>
## #A part of history commands expansion with Ctrl+L (using split(";"),split("|"),split(";|") )
## ls -Force -Recurse -Filter *.txt | ? { $_.LastWriteTime -lt [DateTime]::Today } ; echo PowerShell
## ls<Ctrl+L><tab><tab>
## ?<Ctrl+L><tab><tab>
## ec<Ctrl+L><tab>
## # Now command name expansion's priority is,
## alias -> function -> filter -> cmdlet -> script -> external command
## # PSDrive and item name expansion in variable notation
## ${fu<tab>
## ${function:cl<tab>
## ${c:*<tab>\\*<tab>
## ${c:\\win<tab>/sys<tab>/<tab>
## # Using Ctrl+K, characters insertion (bihind space or semi-coron or pipe operator) feature : it encloses tokens with parnthesis by default
## 1 - 1 - 1 - 1<Ctrl+K><tab>
## 1 - 1 - 1 - (1)<tab>
## 1 - 1 - 1 (- 1)<tab>
## 1 - 1 - (1 - 1)<tab><tab><tab>...
## with double Ctrl+K, it encloses tokens with $( )
## for ( $i=0;$j=1<Ctrl+K><Ctrl+K><tab><tab>
## for ( $($i=0;$j=1)
## if there is a character between <Ctrl+K> and <tab>, it is inserted between tokens
## 1+1 | {$_*2}<Ctrl+K>%<tab>
## 1+1 | %{$_*2}
## 1+1 +1+1<Ctrl+K>;<tab>
## 1+1 ;+1+1
## if the character is ( or { or {, tokens are enclosed ( ) or { } or {}
## int<Ctrl+K>[<tab>
## [int]
## with double Ctrl+K, and if there is a character between <Ctrl+K> and <tab>, it is inserted between tokens with '$'
## C:\\WINDOWS\\system32\\notepad.exe<Ctrl+K><Ctrl+K>{<tab>
## ${C:\\WINDOWS\\system32\\notepad.exe}
## % and ? are given special treatment with double Ctrl+K, these enclose tokens with % { } or ? { } behind '|'
## ls | $_.LastWriteTime -gt "2009/5"<Ctrl+K><Ctrl+K>?<tab>
## ls | ? {$_.LastWriteTime -gt "2009/5"}
## ls | $_.FullName<Ctrl+K><Ctrl+K>%<tab>
## ls | % {$_.FullName}
### Generate ProgIDs list...
if ( Test-Path $PSHOME\\ProgIDs.txt )
{
$_ProgID = type $PSHOME\\ProgIDs.txt -ReadCount 0
}
else
{
$_HKCR = [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\")
$_ProgID = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) )
foreach ( $_subkey in $_HKCR.GetSubKeyNames() )
{
foreach ( $_i in [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\$_subkey\\ProgID") )
{
if ($_i -ne $null)
{
$_ProgID.Add($_i.GetValue(""))
}
}
}
'$_ProgID was updated...' | Out-Host
$_ProgID = $_ProgID|sort -Unique
Set-Content -Value $_ProgID -Path $PSHOME\\ProgIDs.txt -Verbose
}
### Generate TypeNames list...
if ( Test-Path $PSHOME\\TypeNames.txt )
{
$_TypeNames = type $PSHOME\\TypeNames.txt -ReadCount 0
}
else
{
$_TypeNames = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) )
foreach ( $_asm in [AppDomain]::CurrentDomain.GetAssemblies() )
{
foreach ( $_type in $_asm.GetTypes() )
{
$_TypeNames.Add($_type.FullName)
}
}
'$_TypeNames was updated...' | Out-Host
$_TypeNames = $_TypeNames | sort -Unique
Set-Content -Value $_TypeNames -Path $PSHOME\\TypeNames.txt -Verbose
}
if ( Test-Path $PSHOME\\TypeNames_System.txt )
{
$_TypeNames_System = type $PSHOME\\TypeNames_System.txt -ReadCount 0
}
else
{
$_TypeNames_System = $_TypeNames -like "System.*" -replace '^System\\.'
'$_TypeNames_System was updated...' | Out-Host
Set-Content -Value $_TypeNames_System -Path $PSHOME\\TypeNames_System.txt -Verbose
}
### Generate WMIClasses list...
if ( Test-Path $PSHOME\\WMIClasses.txt )
{
$_WMIClasses = type $PSHOME\\WMIClasses.txt -ReadCount 0
}
else
{
$_WMIClasses = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) )
foreach ( $_class in gwmi -List )
{
$_WMIClasses.Add($_class.Name)
}
$_WMIClasses = $_WMIClasses | sort -Unique
'$_WMIClasses was updated...' | Out-Host
Set-Content -Value $_WMIClasses -Path $PSHOME\\WMIClasses.txt -Verbose
}
[Reflection.Assembly]::LoadWithPartialName( "System.Windows.Forms" ) | Out-Null
$global:_cmdstack = New-Object Collections.Stack
$global:_snapin = $null
$global:_TypeAccelerators = [type]::gettype("System.Management.Automation.TypeAccelerators")::get.keys | sort
$global:_cmdline = New-Object Collections.ArrayList
iex (@'
function prompt {
h -Count 1 -OutVariable line |
% { $_.CommandLine.Split("|"); $_.CommandLine.Split(";"); $_.CommandLine.Split(";"); $_.CommandLine.Split(";|") } |
Get-Unique | ? { $_ -ne $line.CommandLine -and $_ -notmatch '^\\s*$' } |
% { $_.Trim(" ") } |
? { $global:_cmdline -notcontains $_ } | % { Set-CommandLine $_ | Out-Null }
if ($_cmdstack.Count -gt 0) {
$line = $global:_cmdstack.Pop() -replace '([[\\]\\(\\)+{}?~%])','{$1}'
[System.Windows.Forms.SendKeys]::SendWait($line)
}
'@ + @"
${function:prompt}
}
"@)
function Write-ClassNames ( $data, $i, $prefix='', $sep='.' )
{
$preItem = ""
foreach ( $class in $data -like $_opt )
{
$Item = $class.Split($sep)
if ( $preItem -ne $Item[$i] )
{
if ( $i+1 -eq $Item.Count )
{
if ( $prefix -eq "[" )
{
$suffix = "]"
}
elseif ( $sep -eq "_" )
{
$suffix = ""
}
else
{
$suffix = " "
}
}
else
{
$suffix = ""
}
$prefix + $_opt.Substring(0, $_opt.LastIndexOf($sep)+1) + $Item[$i] + $suffix
$preItem = $Item[$i]
}
}
}
function Get-PipeLineObject {
$i = -2
$property = $null
do {
$str = $line.Split("|")
# extract the command name from the string
# first split the string into statements and pipeline elements
# This doesn't handle strings however.
$_cmdlet = [regex]::Split($str[$i], '[|;=]')[-1]
# take the first space separated token of the remaining string
# as the command to look up. Trim any leading or trailing spaces
# so you don't get leading empty elements.
$_cmdlet = $_cmdlet.Trim().Split()[0]
if ( $_cmdlet -eq "?" )
{
$_cmdlet = "Where-Object"
}
$global:_exp = $_cmdlet
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0]
}
if ( "Select-Object" -eq $_cmdlet )
{
if ( $str[$i] -match '\\s+-Exp\\w*[\\s:]+(\\w+)' )
{
$property = $Matches[1] + ";" + $property
}
}
$i--
} while ( "Get-Unique", "Select-Object", "Sort-Object", "Tee-Object", "Where-Object" -contains $_cmdlet )
if ( $global:_forgci -eq $null )
{
$a = @(ls "Alias:\\")[0]
$e = @(ls "Env:\\")[0]
$f = @(ls "Function:\\")[0]
$h = @(ls "HKCU:\\")[0]
$v = @(ls "Variable:\\")[0]
$c = @(ls "cert:\\")[0]
$global:_forgci = gi $PSHOME\\powershell.exe |
Add-Member -Name CommandType -MemberType 'NoteProperty' -Value $f.CommandType -PassThru |
Add-Member -Name Definition -MemberType 'NoteProperty' -Value $a.Definition -PassThru |
Add-Member -Name Description -MemberType 'NoteProperty' -Value $a.Description -PassThru |
Add-Member -Name Key -MemberType 'NoteProperty' -Value $e.Key -PassThru |
Add-Member -Name Location -MemberType 'NoteProperty' -Value $c.Location -PassThru |
Add-Member -Name LocationName -MemberType 'NoteProperty' -Value $c.LocationName -PassThru |
Add-Member -Name Options -MemberType 'NoteProperty' -Value $a.Options -PassThru |
Add-Member -Name ReferencedCommand -MemberType 'NoteProperty' -Value $a.ReferencedCommand -PassThru |
Add-Member -Name ResolvedCommand -MemberType 'NoteProperty' -Value $a.ResolvedCommand -PassThru |
Add-Member -Name ScriptBlock -MemberType 'NoteProperty' -Value $f.ScriptBlock -PassThru |
Add-Member -Name StoreNames -MemberType 'NoteProperty' -Value $c.StoreNames -PassThru |
Add-Member -Name SubKeyCount -MemberType 'NoteProperty' -Value $h.SubKeyCount -PassThru |
Add-Member -Name Value -MemberType 'NoteProperty' -Value $e.Value -PassThru |
Add-Member -Name ValueCount -MemberType 'NoteProperty' -Value $h.ValueCount -PassThru |
Add-Member -Name Visibility -MemberType 'NoteProperty' -Value $a.Visibility -PassThru |
Add-Member -Name Property -MemberType 'NoteProperty' -Value $h.Property -PassThru |
Add-Member -Name ResolvedCommandName -MemberType 'NoteProperty' -Value $a.ResolvedCommandName -PassThru |
Add-Member -Name Close -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name CreateSubKey -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name DeleteSubKey -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name DeleteSubKeyTree -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name DeleteValue -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Flush -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetSubKeyNames -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetValue -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetValueKind -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetValueNames -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsValidValue -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name OpenSubKey -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name SetValue -MemberType 'ScriptMethod' -Value {} -PassThru
}
if ( $global:_mix -eq $null )
{
$f = gi $PSHOME\\powershell.exe
$t = [type]
$s = ""
$global:_mix = `
Add-Member -InputObject (New-Object PSObject) -Name Mode -MemberType 'NoteProperty' -Value $f.Mode -PassThru |
Add-Member -Name Assembly -MemberType 'NoteProperty' -Value $t.Assembly -PassThru |
Add-Member -Name AssemblyQualifiedName -MemberType 'NoteProperty' -Value $t.AssemblyQualifiedName -PassThru |
Add-Member -Name Attributes -MemberType 'NoteProperty' -Value $f.Attributes -PassThru |
Add-Member -Name BaseType -MemberType 'NoteProperty' -Value $t.BaseType -PassThru |
Add-Member -Name ContainsGenericParameters -MemberType 'NoteProperty' -Value $t.ContainsGenericParameters -PassThru |
Add-Member -Name CreationTime -MemberType 'NoteProperty' -Value $f.CreationTime -PassThru |
Add-Member -Name CreationTimeUtc -MemberType 'NoteProperty' -Value $f.CreationTimeUtc -PassThru |
Add-Member -Name DeclaringMethod -MemberType 'NoteProperty' -Value $t.DeclaringMethod -PassThru |
Add-Member -Name DeclaringType -MemberType 'NoteProperty' -Value $t.DeclaringType -PassThru |
Add-Member -Name Exists -MemberType 'NoteProperty' -Value $f.Exists -PassThru |
Add-Member -Name Extension -MemberType 'NoteProperty' -Value $f.Extension -PassThru |
Add-Member -Name FullName -MemberType 'NoteProperty' -Value $f.FullName -PassThru |
Add-Member -Name GenericParameterAttributes -MemberType 'NoteProperty' -Value $t.GenericParameterAttributes -PassThru |
Add-Member -Name GenericParameterPosition -MemberType 'NoteProperty' -Value $t.GenericParameterPosition -PassThru |
Add-Member -Name GUID -MemberType 'NoteProperty' -Value $t.GUID -PassThru |
Add-Member -Name HasElementType -MemberType 'NoteProperty' -Value $t.HasElementType -PassThru |
Add-Member -Name IsAbstract -MemberType 'NoteProperty' -Value $t.IsAbstract -PassThru |
Add-Member -Name IsAnsiClass -MemberType 'NoteProperty' -Value $t.IsAnsiClass -PassThru |
Add-Member -Name IsArray -MemberType 'NoteProperty' -Value $t.IsArray -PassThru |
Add-Member -Name IsAutoClass -MemberType 'NoteProperty' -Value $t.IsAutoClass -PassThru |
Add-Member -Name IsAutoLayout -MemberType 'NoteProperty' -Value $t.IsAutoLayout -PassThru |
Add-Member -Name IsByRef -MemberType 'NoteProperty' -Value $t.IsByRef -PassThru |
Add-Member -Name IsClass -MemberType 'NoteProperty' -Value $t.IsClass -PassThru |
Add-Member -Name IsCOMObject -MemberType 'NoteProperty' -Value $t.IsCOMObject -PassThru |
Add-Member -Name IsContextful -MemberType 'NoteProperty' -Value $t.IsContextful -PassThru |
Add-Member -Name IsEnum -MemberType 'NoteProperty' -Value $t.IsEnum -PassThru |
Add-Member -Name IsExplicitLayout -MemberType 'NoteProperty' -Value $t.IsExplicitLayout -PassThru |
Add-Member -Name IsGenericParameter -MemberType 'NoteProperty' -Value $t.IsGenericParameter -PassThru |
Add-Member -Name IsGenericType -MemberType 'NoteProperty' -Value $t.IsGenericType -PassThru |
Add-Member -Name IsGenericTypeDefinition -MemberType 'NoteProperty' -Value $t.IsGenericTypeDefinition -PassThru |
Add-Member -Name IsImport -MemberType 'NoteProperty' -Value $t.IsImport -PassThru |
Add-Member -Name IsInterface -MemberType 'NoteProperty' -Value $t.IsInterface -PassThru |
Add-Member -Name IsLayoutSequential -MemberType 'NoteProperty' -Value $t.IsLayoutSequential -PassThru |
Add-Member -Name IsMarshalByRef -MemberType 'NoteProperty' -Value $t.IsMarshalByRef -PassThru |
Add-Member -Name IsNested -MemberType 'NoteProperty' -Value $t.IsNested -PassThru |
Add-Member -Name IsNestedAssembly -MemberType 'NoteProperty' -Value $t.IsNestedAssembly -PassThru |
Add-Member -Name IsNestedFamANDAssem -MemberType 'NoteProperty' -Value $t.IsNestedFamANDAssem -PassThru |
Add-Member -Name IsNestedFamily -MemberType 'NoteProperty' -Value $t.IsNestedFamily -PassThru |
Add-Member -Name IsNestedFamORAssem -MemberType 'NoteProperty' -Value $t.IsNestedFamORAssem -PassThru |
Add-Member -Name IsNestedPrivate -MemberType 'NoteProperty' -Value $t.IsNestedPrivate -PassThru |
Add-Member -Name IsNestedPublic -MemberType 'NoteProperty' -Value $t.IsNestedPublic -PassThru |
Add-Member -Name IsNotPublic -MemberType 'NoteProperty' -Value $t.IsNotPublic -PassThru |
Add-Member -Name IsPointer -MemberType 'NoteProperty' -Value $t.IsPointer -PassThru |
Add-Member -Name IsPrimitive -MemberType 'NoteProperty' -Value $t.IsPrimitive -PassThru |
Add-Member -Name IsPublic -MemberType 'NoteProperty' -Value $t.IsPublic -PassThru |
Add-Member -Name IsSealed -MemberType 'NoteProperty' -Value $t.IsSealed -PassThru |
Add-Member -Name IsSerializable -MemberType 'NoteProperty' -Value $t.IsSerializable -PassThru |
Add-Member -Name IsSpecialName -MemberType 'NoteProperty' -Value $t.IsSpecialName -PassThru |
Add-Member -Name IsUnicodeClass -MemberType 'NoteProperty' -Value $t.IsUnicodeClass -PassThru |
Add-Member -Name IsValueType -MemberType 'NoteProperty' -Value $t.IsValueType -PassThru |
Add-Member -Name IsVisible -MemberType 'NoteProperty' -Value $t.IsVisible -PassThru |
Add-Member -Name LastAccessTime -MemberType 'NoteProperty' -Value $f.LastAccessTime -PassThru |
Add-Member -Name LastAccessTimeUtc -MemberType 'NoteProperty' -Value $f.LastAccessTimeUtc -PassThru |
Add-Member -Name LastWriteTime -MemberType 'NoteProperty' -Value $f.LastWriteTime -PassThru |
Add-Member -Name LastWriteTimeUtc -MemberType 'NoteProperty' -Value $f.LastWriteTimeUtc -PassThru |
Add-Member -Name MemberType -MemberType 'NoteProperty' -Value $t.MemberType -PassThru |
Add-Member -Name MetadataToken -MemberType 'NoteProperty' -Value $t.MetadataToken -PassThru |
Add-Member -Name Module -MemberType 'NoteProperty' -Value $t.Module -PassThru |
Add-Member -Name Name -MemberType 'NoteProperty' -Value $t.Name -PassThru |
Add-Member -Name Namespace -MemberType 'NoteProperty' -Value $t.Namespace -PassThru |
Add-Member -Name Parent -MemberType 'NoteProperty' -Value $f.Parent -PassThru |
Add-Member -Name ReflectedType -MemberType 'NoteProperty' -Value $t.ReflectedType -PassThru |
Add-Member -Name Root -MemberType 'NoteProperty' -Value $f.Root -PassThru |
Add-Member -Name StructLayoutAttribute -MemberType 'NoteProperty' -Value $t.StructLayoutAttribute -PassThru |
Add-Member -Name TypeHandle -MemberType 'NoteProperty' -Value $t.TypeHandle -PassThru |
Add-Member -Name TypeInitializer -MemberType 'NoteProperty' -Value $t.TypeInitializer -PassThru |
Add-Member -Name UnderlyingSystemType -MemberType 'NoteProperty' -Value $t.UnderlyingSystemType -PassThru |
Add-Member -Name PSChildName -MemberType 'NoteProperty' -Value $f.PSChildName -PassThru |
Add-Member -Name PSDrive -MemberType 'NoteProperty' -Value $f.PSDrive -PassThru |
Add-Member -Name PSIsContainer -MemberType 'NoteProperty' -Value $f.PSIsContainer -PassThru |
Add-Member -Name PSParentPath -MemberType 'NoteProperty' -Value $f.PSParentPath -PassThru |
Add-Member -Name PSPath -MemberType 'NoteProperty' -Value $f.PSPath -PassThru |
Add-Member -Name PSProvider -MemberType 'NoteProperty' -Value $f.PSProvider -PassThru |
Add-Member -Name BaseName -MemberType 'NoteProperty' -Value $f.BaseName -PassThru |
Add-Member -Name Clone -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name CompareTo -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Contains -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name CopyTo -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Create -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name CreateObjRef -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name CreateSubdirectory -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Delete -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name EndsWith -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name FindInterfaces -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name FindMembers -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetAccessControl -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetArrayRank -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetConstructor -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetConstructors -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetCustomAttributes -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetDefaultMembers -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetDirectories -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetElementType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetEnumerator -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetEvent -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetEvents -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetField -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetFields -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetFiles -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetFileSystemInfos -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetGenericArguments -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetGenericParameterConstraints -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetGenericTypeDefinition -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetInterface -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetInterfaceMap -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetInterfaces -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetLifetimeService -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetMember -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetMembers -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetMethod -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetMethods -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetNestedType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetNestedTypes -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetObjectData -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetProperties -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetProperty -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetTypeCode -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IndexOf -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IndexOfAny -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name InitializeLifetimeService -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Insert -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name InvokeMember -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsAssignableFrom -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsDefined -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsInstanceOfType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsNormalized -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsSubclassOf -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name LastIndexOf -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name LastIndexOfAny -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name MakeArrayType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name MakeByRefType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name MakeGenericType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name MakePointerType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name MoveTo -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Normalize -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name PadLeft -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name PadRight -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Refresh -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Remove -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Replace -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name SetAccessControl -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Split -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name StartsWith -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Substring -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name ToCharArray -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name ToLower -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name ToLowerInvariant -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name ToUpper -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name ToUpperInvariant -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Trim -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name TrimEnd -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name TrimStart -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Chars -MemberType 'NoteProperty' -Value $s.Chars -PassThru
}
if ( "Add-Member" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Compare-Object" -eq $_cmdlet )
{
$global:_dummy = (Compare-Object 1 2)[0]
}
if ( "ConvertFrom-SecureString" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "ConvertTo-SecureString" -eq $_cmdlet )
{
$global:_dummy = convertto-securestring "P@ssW0rD!" -asplaintext -force
}
if ( "ForEach-Object" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Get-Acl" -eq $_cmdlet )
{
$global:_dummy = Get-Acl
}
if ( "Get-Alias" -eq $_cmdlet )
{
$global:_dummy = (Get-Alias)[0]
}
if ( "Get-AuthenticodeSignature" -eq $_cmdlet )
{
$global:_dummy = Get-AuthenticodeSignature $PSHOME\\powershell.exe
}
if ( "Get-ChildItem" -eq $_cmdlet )
{
$global:_dummy = $global:_forgci
}
if ( "Get-Command" -eq $_cmdlet )
{
$global:_dummy = @(iex $str[$i+1])[0]
}
if ( "Get-Content" -eq $_cmdlet )
{
$global:_dummy = (type $PSHOME\\profile.ps1)[0]
}
if ( "Get-Credential" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Get-Culture" -eq $_cmdlet )
{
$global:_dummy = Get-Culture
}
if ( "Get-Date" -eq $_cmdlet )
{
$global:_dummy = Get-Date
}
if ( "Get-Event" -eq $_cmdlet )
{
$global:_dummy = (Get-Event)[0]
}
if ( "Get-EventLog" -eq $_cmdlet )
{
$global:_dummy = @(iex $str[$i+1])[0]
}
if ( "Get-ExecutionPolicy" -eq $_cmdlet )
{
$global:_dummy = Get-ExecutionPolicy
}
if ( "Get-Help" -eq $_cmdlet )
{
$global:_dummy = Get-Help Add-Content
}
if ( "Get-History" -eq $_cmdlet )
{
$global:_dummy = Get-History -Count 1
}
if ( "Get-Host" -eq $_cmdlet )
{
$global:_dummy = Get-Host
}
if ( "Get-Item" -eq $_cmdlet )
{
$global:_dummy = $global:_forgci
}
if ( "Get-ItemProperty" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Get-Location" -eq $_cmdlet )
{
$global:_dummy = Get-Location
}
if ( "Get-Member" -eq $_cmdlet )
{
$global:_dummy = (1|Get-Member)[0]
}
if ( "Get-Module" -eq $_cmdlet )
{
$global:_dummy = (Get-Module)[0]
}
if ( "Get-PfxCertificate" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Get-Process" -eq $_cmdlet )
{
$global:_dummy = ps powershell
}
if ( "Get-PSBreakpoint" -eq $_cmdlet )
{
$global:_dummy =
Add-Member -InputObject (New-Object PSObject) -Name Action -MemberType 'NoteProperty' -Value '' -PassThru |
Add-Member -Name Command -MemberType 'NoteProperty' -Value '' -PassThru |
Add-Member -Name Enabled -MemberType 'NoteProperty' -Value '' -PassThru |
Add-Member -Name HitCount -MemberType 'NoteProperty' -Value '' -PassThru |
Add-Member -Name Id -MemberType 'NoteProperty' -Value '' -PassThru |
Add-Member -Name Script -MemberType 'NoteProperty' -Value '' -PassThru
}
if ( "Get-PSCallStack" -eq $_cmdlet )
{
$global:_dummy = Get-PSCallStack
}
if ( "Get-PSDrive" -eq $_cmdlet )
{
$global:_dummy = Get-PSDrive Function
}
if ( "Get-PSProvider" -eq $_cmdlet )
{
$global:_dummy = Get-PSProvider FileSystem
}
if ( "Get-PSSnapin" -eq $_cmdlet )
{
$global:_dummy = Get-PSSnapin Microsoft.PowerShell.Core
}
if ( "Get-Service" -eq $_cmdlet )
{
$global:_dummy = (Get-Service)[0]
}
if ( "Get-TraceSource" -eq $_cmdlet )
{
$global:_dummy = Get-TraceSource AddMember
}
if ( "Get-UICulture" -eq $_cmdlet )
{
$global:_dummy = Get-UICulture
}
if ( "Get-Variable" -eq $_cmdlet )
{
$global:_dummy = Get-Variable _
}
if ( "Get-WmiObject" -eq $_cmdlet )
{
$global:_dummy = @(iex $str[$i+1])[0]
}
if ( "Group-Object" -eq $_cmdlet )
{
$global:_dummy = 1 | group
}
if ( "Measure-Command" -eq $_cmdlet )
{
$global:_dummy = Measure-Command {}
}
if ( "Measure-Object" -eq $_cmdlet )
{
$global:_dummy = Measure-Object
}
if ( "New-PSDrive" -eq $_cmdlet )
{
$global:_dummy = Get-PSDrive Alias
}
if ( "New-TimeSpan" -eq $_cmdlet )
{
$global:_dummy = New-TimeSpan
}
if ( "Resolve-Path" -eq $_cmdlet )
{
$global:_dummy = $PWD
}
if ( "Select-String" -eq $_cmdlet )
{
$global:_dummy = " " | Select-String " "
}
if ( "Set-Date" -eq $_cmdlet )
{
$global:_dummy = Get-Date
}
if ( $property -ne $null)
{
foreach ( $name in $property.Split(";", "RemoveEmptyEntries" -as [System.StringSplitOptions]) )
{
$global:_dummy = @($global:_dummy.$name)[0]
}
}
}
function Set-CommandLine ( [string]$script ) { $global:_cmdline.Add($script) }
function Get-CommandLine ( [string]$name ) {
$name = $name -replace '\\?','`?'
$global:_cmdline -like "$name*"
}
function TabExpansion {
# This is the default function to use for tab expansion. It handles simple
# member expansion on variables, variable name expansion and parameter completion
# on commands. It doesn't understand strings so strings containing ; | ( or { may
# cause expansion to fail.
param($line, $lastWord)
& {
# Helper function to write out the matching set of members. It depends
# on dynamic scoping to get $_base, _$expression and $_pat
function Write-Members ($sep='.')
{
# evaluate the expression to get the object to examine...
Invoke-Expression ('$_val=' + $_expression)
if ( $_expression -match '^\\$global:_dummy' )
{
$temp = $_expression -replace '^\\$global:_dummy(.*)','$1'
$_expression = '$_' + $temp
}
$_method = [Management.Automation.PSMemberTypes] `
'Method,CodeMethod,ScriptMethod,ParameterizedProperty'
if ($sep -eq '.')
{
$params = @{view = 'extended','adapted','base'}
}
else
{
$params = @{static=$true}
}
if ( $_val -is [Hashtable] )
{
[Object[]]$_keys = $null
foreach ( $_name in $_val.Keys )
{
$_keys += `
New-Object Microsoft.PowerShell.Commands.MemberDefinition `
[int],$_name,"Property",0
}
}
if ( $_keys -ne $null )
{
$_members = [Object[]](Get-Member @params -InputObject $_val $_pat) + ($_keys | ? {$_.name -like $_pat})
} else {
$_members = (Get-Member @params -InputObject $_val $_pat)
}
foreach ($_m in $_members | Sort-Object membertype,name)
{
if ($_m.MemberType -band $_method)
{
# Return a method...
$_base + $_expression + $sep + $_m.name + '('
}
else {
# Return a property...
$_base + $_expression + $sep + $_m.name
}
}
}
switch ([int]$line[-1])
{
# Ctrl+D several date/time formats
4 {
"[DateTime]::Now"
[DateTime]::Now
[DateTime]::Now.ToString("yyyyMMdd")
[DateTime]::Now.ToString("MMddyyyy")
[DateTime]::Now.ToString("yyyyMMddHHmmss")
[DateTime]::Now.ToString("MMddyyyyHHmmss")
'd f g m o r t u y'.Split(" ") | % { [DateTime]::Now.ToString($_) }
break;
}
# Ctrl+K put parentheses behind space or semi-coron or pipe operator
11 {
if ( $line -ne $( "=" + [Char]11 ) )
{
if ( $line[-2] -eq 11 )
{
$left = '$' + "("
$line = $line.Substring(0,$line.length-2)
}
else
{
$left = "("
$line = $line.Substring(0,$line.length-1)
}
$global:_ctrlk = @()
$l = $line.Length
while ( $l -ge 0 )
{
$i = $line.Substring(0,$l).LastIndexOfAny(" ;|")
$global:_ctrlk += $line.Insert($i+1, $left) + ")"
$l = $i
}
$global:_ctrlk += $line
[Windows.Forms.SendKeys]::SendWait("{Esc}=^K{TAB}")
}
else {
$global:_ctrlk
}
break TabExpansion;
}
# Ctrl+L a part of history commands expansion
12 {
Get-CommandLine $lastWord.SubString(0, $lastword.Length-1)
break;
}
# Ctrl+P hand-operated pop from command buffer stack
16 {
$_base = $lastword.SubString(0, $lastword.Length-1)
$_base + $global:_cmdstack.Pop()
break;
}
# Ctrl+R $Host.UI.RawUI.
18 {
'$Host.UI.RawUI.'
'$Host.UI.RawUI'
break;
}
# Ctrl+V paste clipboard
22 {
$_base = $lastword.SubString(0, $lastword.Length-1)
$_clip = New-Object System.Windows.Forms.TextBox
$_clip.Multiline = $true
$_clip.Paste()
$_base + $_clip.Text
break;
}
# Ctrl+X cut current line
24 {
$_clip = new-object System.Windows.Forms.TextBox;
$_clip.Multiline = $true;
$_clip.Text = $line.SubString(0, $line.Length-1)
$_clip.SelectAll()
$_clip.Copy()
[System.Windows.Forms.SendKeys]::SendWait("{ESC}")
break;
}
# Ctrl+Z cut last word in current line
26 {
$line.SubString(0, $line.Length-1) -match '(^(.*\\s)([^\\s]*)$)|(^[^\\s]*$)' | Out-Null
$_clip = new-object System.Windows.Forms.TextBox;
$_clip.Multiline = $true;
$_clip.Text = $Matches[3]
$_clip.SelectAll()
$_clip.Copy()
[System.Windows.Forms.SendKeys]::SendWait("{ESC}")
$line = $Matches[2] -replace '([[\\]\\(\\)+{}?~%])','{$1}'
[System.Windows.Forms.SendKeys]::SendWait($line)
break;
}
}
switch ( [int]$line[-2] )
{
# Ctrl+K put character behind space or semi-coron or pipe operator
11 {
switch ( $line[-1] )
{
'{' { $right = '}' }
'(' { $right = ')' }
'[' { $right = ']' }
}
$left = $line[-1]
$delimiter = " ;|"
if ( $line[-3] -eq 11 )
{
if ( $line[-1] -eq '%' -or $line[-1] -eq '?' )
{
$left = ' ' + $left + ' {'; $right = '}'
$delimiter = '|'
}
else
{
$left = '$' + $left
}
$line = $line.Substring(0,$line.length-3)
}
else
{
$line = $line.Substring(0,$line.length-2)
}
$global:_ctrlk = @()
$l = $line.Length
while ( $l -ge 0 )
{
$i = $line.Substring(0,$l).LastIndexOfAny($delimiter)
$global:_ctrlk += $line.Insert($i+1, $left) + $right
$l = $i
}
$global:_ctrlk += $line
[Windows.Forms.SendKeys]::SendWait("{Esc}=^K{TAB}")
break TabExpansion;
}
# Ctrl+X cut words with a character after Ctrl+X until the character
24 {
$line.SubString(0, $line.Length-2) -match "(^(.*$($line[-1]))([^$($line[-1])]*)`$)|(^[^\\$($line[-1])]*`$)" | Out-Null
$_clip = new-object System.Windows.Forms.TextBox;
$_clip.Multiline = $true;
$_clip.Text = $Matches[3]
$_clip.SelectAll()
$_clip.Copy()
[System.Windows.Forms.SendKeys]::SendWait("{ESC}")
$line = $Matches[2] -replace '([[\\]\\(\\)+{}?~%])','{$1}'
[System.Windows.Forms.SendKeys]::SendWait($line)
break;
}
}
switch -regex ($lastWord)
{
# Handle property and method expansion at '$_'
'(^.*)(\\$_\\.)(\\w*)$' {
$_base = $matches[1]
$_expression = '$global:_dummy'
$_pat = $matches[3] + '*'
$global:_dummy = $null
Get-PipeLineObject
if ( $global:_dummy -eq $null )
{
if ( $global:_exp -match '^\\$.*\\(.*$' )
{
$type = ( iex $global:_exp.Split("(")[0] ).OverloadDefinitions[0].Split(" ")[0] -replace '\\[[^\\[\\]]*\\]$' -as [type]
if ( $_expression -match '^\\$global:_dummy' )
{
$temp = $_expression -replace '^\\$global:_dummy(.*)','$1'
$_expression = '$_' + $temp
}
foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } )
{
if ($_m.MemberType -eq "Method")
{
$_base + $_expression + '.' + $_m.name + '('
}
else {
$_base + $_expression + '.' + $_m.name
}
}
break;
}
elseif ( $global:_exp -match '^\\[.*\\:\\:.*\\(.*$' )
{
$tname, $mname = $_exp.Split(":(", "RemoveEmptyEntries"-as [System.StringSplitOptions])[0,1]
$type = @(iex ($tname + '.GetMember("' + $mname + '")'))[0].ReturnType.FullName -replace '\\[[^\\[\\]]*\\]$' -as [type]
if ( $_expression -match '^\\$global:_dummy' )
{
$temp = $_expression -replace '^\\$global:_dummy(.*)','$1'
$_expression = '$_' + $temp
}
foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } )
{
if ($_m.MemberType -eq "Method")
{
$_base + $_expression + '.' + $_m.name + '('
}
else {
$_base + $_expression + '.' + $_m.name
}
}
break;
}
elseif ( $global:_exp -match '^(\\$\\w+(\\[[0-9,\\.]+\\])*(\\.\\w+(\\[[0-9,\\.]+\\])*)*)$' )
{
$global:_dummy = @(iex $Matches[1])[0]
}
else
{
$global:_dummy = $global:_mix
}
}
Write-Members
break;
}
# Handle property and method expansion rooted at variables...
# e.g. $a.b.<tab>
'(^.*)(\\$(\\w|\\.)+)\\.(\\w*)$' {
$_base = $matches[1]
$_expression = $matches[2]
$_pat = $matches[4] + '*'
[void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock]
if ( $_expression -match '^\\$_\\.' )
{
$_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1')
}
Write-Members
break;
}
# Handle simple property and method expansion on static members...
# e.g. [datetime]::n<tab>
'(^.*)(\\[(\\w|\\.)+\\])\\:\\:(\\w*)$' {
$_base = $matches[1]
$_expression = $matches[2]
$_pat = $matches[4] + '*'
Write-Members '::'
break;
}
# Handle complex property and method expansion on static members
# where there are intermediate properties...
# e.g. [datetime]::now.d<tab>
'(^.*)(\\[(\\w|\\.)+\\]\\:\\:(\\w+\\.)+)(\\w*)$' {
$_base = $matches[1] # everything before the expression
$_expression = $matches[2].TrimEnd('.') # expression less trailing '.'
$_pat = $matches[5] + '*' # the member to look for...
Write-Members
break;
}
# Handle property and method expansion on [ScriptBlock] members...
# e.g. { 1+1 }.inv<tab>
'(^.*})\\.(\\w*)$' {
$_base = $matches[1]
$_pat = $matches[2] + '*'
foreach ( $_m in {} | Get-Member $_pat | sort membertype,name )
{
if ($_m.MemberType -eq "Method")
{
$_base + '.' + $_m.name + '('
}
else {
$_base + '.' + $_m.name
}
}
break;
}
# Handle variable name expansion...
'(^.*\\$)(\\w+)$' {
$_prefix = $matches[1]
$_varName = $matches[2]
foreach ($_v in Get-ChildItem ('variable:' + $_varName + '*'))
{
$_prefix + $_v.name
}
break;
}
# Handle item name expansion in variable notation...
'(^.*\\${)(((\\w+):([\\\\/]?))[^\\\\/]+([\\\\/][^\\\\/]*)*)$' {
$_prefix = $matches[1]
$_driveName = $matches[3]
$_itemName = $matches[2] + "*"
Get-ChildItem $_itemName |
% {
if ( $matches[5] -and $_.PSProvider.Name -eq "FileSystem" )
{
$output = $_prefix + $_.FullName
}
elseif ( $_.PSProvider.Name -eq "FileSystem" -and $matches[6] )
{
$cd = (Get-Location -PSDrive $matches[4]).Path
$output = $_prefix + $_driveName + $_.FullName.Substring($cd.Length+1)
}
elseif ( $_.PSProvider.Name -eq "FileSystem" )
{
$cd = (Get-Location -PSDrive $matches[4]).Path
$output = $_prefix + $_driveName + $_.FullName.Substring($cd.Length+1)
}
else
{
$output = $_prefix + $_driveName + $_.Name
}
if ( $_.PSIsContainer )
{
$output
}
else
{
$output + "}"
}
}
break;
}
# Handle PSDrive name expansion in variable notation...
'(^.*\\${)(\\w+)$' {
$_prefix = $matches[1]
$_driveName = $matches[2] + "*"
Get-PSDrive $_driveName | % { $_prefix + $_ + ':' }
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+(\\.\\w*)*)\\])*))(\\[(\\w*(\\.\\w*)*))$' {
$_base = $matches[1]
$_opt = $matches[8] + '*'
if ( $_opt -eq "*" )
{
$_TypeAccelerators -replace '^(.*)$', '[$1]' | % { $_base + $_ }
}
else
{
$_TypeAccelerators -like $_opt -replace '^(.*)$', '[$1]' | % { $_base + $_ }
"CmdletBinding", "Parameter", "Alias",
"ValidateArguments", "ValidateCount", "ValidateEnumeratedArguments", "ValidateLength",
"ValidateNotNull", "ValidateNotNullOrEmpty", "ValidatePattern", "ValidateRange",
"ValidateScript", "ValidateSet", "AllowEmptyCollection", "AllowEmptyString", "AllowNull" `
-like $_opt -replace '^(.*)$', '[$1(' | % { $_base + $_ }
Write-ClassNames $_TypeNames_System ($_opt.Spli
|
PowerShellCorpus/PoshCode/Set-Proxy_1.ps1
|
Set-Proxy_1.ps1
|
param(
[Parameter(Position=0,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$true)]
[alias("Name","ComputerName")] $Computer = @($env:computername),
[switch] $ClearProxy
)
begin{
$IEsettingsKey = ".DEFAULT\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"
[array]$ProxyResult = @()
function SetProxySettings($Computer){
Set-RegDWord -ComputerName $Computer -Hive Users -Key $IEsettingsKey -Value ProxyEnable -Data 0 -Force
Set-RegString -ComputerName $Computer -Hive Users -Key $IEsettingsKey -Value ProxyServer -Force
Set-RegString -ComputerName $Computer -Hive Users -Key $IEsettingsKey -Value ProxyOverride -Force
Set-RegBinary -ComputerName $Computer -Hive Users -Key "$IEsettingsKey\\Connections" -Value DefaultConnectionSettings -Force
Set-RegBinary -ComputerName $Computer -Hive Users -Key "$IEsettingsKey\\Connections" -Value SavedLegacySettings -Force
}
function GetProxySettings($Computer){
$Output = @()
$Output += (Get-RegDWord -ComputerName $Computer -Hive Users -Key $IEsettingsKey -Value "ProxyEnable" | Select-Object ComputerName,Value,Data)
$Output += (Get-RegString -ComputerName $Computer -Hive Users -Key $IEsettingsKey -Value "ProxyServer" | Select-Object ComputerName,Value,Data)
$Output += (Get-RegString -ComputerName $Computer -Hive Users -Key $IEsettingsKey -Value "ProxyOverride" | Select-Object ComputerName,Value,Data)
$Output += (Get-RegBinary -ComputerName $Computer -Hive Users -Key "$IEsettingsKey\\Connections" -Value "DefaultConnectionSettings" | Select-Object ComputerName,Value,Data)
$Output += (Get-RegBinary -ComputerName $Computer -Hive Users -Key "$IEsettingsKey\\Connections" -Value "SavedLegacySettings" | Select-Object ComputerName,Value,Data)
return $Output
}
}
process{
if (Test-connection $Computer -quiet -count 1){
Try {
$ProxyResult += GetProxySettings $Computer
if ($ClearProxy){SetProxySettings $Computer; $ProxyResult += GetProxySettings $Computer}
}
Catch {
Write-Warning "$($error[0]) "
Break
}
}
}
end{
$ProxyResult
}
|
PowerShellCorpus/PoshCode/Compare-InstalledHotfix.ps1
|
Compare-InstalledHotfix.ps1
|
Function Compare-InstalledHotfix {
param (
[parameter(Mandatory=$true,Position=0)]
$server1,
[parameter(Mandatory=$true,Position=1)]
$server2,
[parameter(Mandatory=$true,Position=3)]
[Management.Automation.PSCredential]
$credential
)
$server1HotFix = get-hotfix -computer $server1 -Credential $credential | select HotfixId
$server2HotFix = get-hotfix -computer $server2 -Credential $credential | select HotfixId
$comparedHotfixes = compare-object $server2HotFix $server1HotFix -IncludeEqual
$result = @();
foreach ($c in $comparedHotfixes) {
$kbinfo = "" | select KB,$server1,$server2
$kbinfo.KB = $c.InputObject.HotfixId
switch ($c.SideIndicator)
{
"==" {
write-host -ForegroundColor Green "Both servers have $($c.InputObject.HotfixId)"
$kbinfo.($server1) = $true
$kbinfo.($server2) = $true
$result += $kbinfo
}
"=>" {
write-host -ForegroundColor Yellow "$server1 has $($c.InputObject.HotfixId) but $server2 doesn't"
$kbinfo.($server1) = $true
$kbinfo.($server2) = $false
$result += $kbinfo
}
"<=" {
write-host -ForegroundColor Magenta "$server2 has $($c.InputObject.HotfixId) but $server1 doesn't"
$kbinfo.($server1) = $false
$kbinfo.($server2) = $true
$result += $kbinfo
}
} # End Switch
} # End foreach
$result
} # End Function
|
PowerShellCorpus/PoshCode/Test-Hash.ps1
|
Test-Hash.ps1
|
function Test-Hash {
#.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
# C:\\PS>ls .\\Bin\\Release -recurse | Test-Hash -BasePath .\\Bin\\Release -Type SHA256 | Export-CSV ~\\Hashes.csv
# C:\\Program Files\\MyProduct>Import-CSV ~\\Hashes.csv | Test-Hash
#
# This example shows how to take the hash of a collection of files and store them in a csv file, and then later verify that the files in a secondary location match the originals exactly.
#
#.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
[CmdletBinding(DefaultParameterSetName="NoExpectation")]
PARAM(
# The path to the file to hash
[Parameter(Position=0,Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("PSPath")]
[string]$Path,
# When hashing many files in folders, use this to convert to relative paths (so you can compare again in a different location)
[Parameter(Position=2,Mandatory=$false,ParameterSetName="NoExpectation")]
[string]$BasePath,
# Supports hashing against a .md5 or .sha1 file such as frequently found on open source servers or torrent sites
[Parameter(Position=1,Mandatory=$true,ParameterSetName="FromHashFile")]
[string]$HashFileName,
# Supports passing in the expected hash (particularly useful when piping input from a previous run)
[Parameter(Position=2,Mandatory=$true,ParameterSetName="ManualHash", ValueFromPipelineByPropertyName=$true)]
[Parameter(Position=2,Mandatory=$false,ParameterSetName="FromHashFile")]
[ALias("Hash")]
[string]$ExpectedHash = $(if($HashFileName){ ((Get-Content $HashFileName) -match $Path)[0].split(" ")[0] }),
# The algorithm to use when hashing
[Parameter(Position=1,Mandatory=$true,ParameterSetName="ManualHash", ValueFromPipelineByPropertyName=$true)]
[Parameter(Position=1,Mandatory=$false,ParameterSetName="NoExpectation")]
[ValidateSet("MD5","SHA1","SHA256","SHA384","SHA512","RIPEMD160")]
[string[]]$Algorithm = $(if($HashFileName){ [IO.Path]::GetExtension((Convert-Path $HashFileName)).Substring(1) } else { "SHA256" })
)
begin {
$ofs=""
if($BasePath) {
Push-Location $BasePath
}
}
process {
if($BasePath) {
$Path = Resolve-Path $Path -Relative
}
if(Test-Path $Path -Type Container) {
# I'd like to support recursing all the files, but for now, just skip
Write-Warning "Cannot calculate hash for directories: '$Path'"
return
}
$Hashes = @(
foreach($Type in $Algorithm) {
# Take the Hash without storing the bytes (ouch)
[string]$hash = [Security.Cryptography.HashAlgorithm]::Create( $Type ).ComputeHash( [IO.File]::ReadAllBytes( (Convert-Path $Path) ) ) | ForEach { "{0:x2}" -f $_ }
# Output an object with the hash, algorithm and path
New-Object PSObject -Property @{ Path = $Path; Algorithm = $Type; Hash = $Hash }
}
)
if($ExpectedHash) {
# Check all the hashes to see if any of them match
if( $Match = $Hashes | Where { $_.Hash -eq $ExpectedHash } ) {
Write-Verbose "Matched hash:`n$($Match | Out-String)"
# Output an object with the hash, algorithm and path
New-Object PSObject -Property @{ Path = $Match.Path; Algorithm = $Match.Algorithm; Hash = $Match.Hash; Matches = $True }
} else {
Write-Verbose "Failed to match hash:`n$($PSBoundParameters | Out-String)"
# Output an object with the first hash, algorithm and path
New-Object PSObject -Property @{ Path = $Hashes[0].Path; Algorithm = $Hashes[0].Algorith; Hash = $Hashes[0].Hash; Matches = $False }
}
} else {
Write-Output $Hashes
}
}
end {
if($BasePath) {
Pop-Location
}
}
}
|
PowerShellCorpus/PoshCode/Get MOSS User Profile_1.ps1
|
Get MOSS User Profile_1.ps1
|
function Get-UserProfile($accountName)
{
[reflection.assembly]::LoadWithPartialName("Microsoft.SharePoint") | out-null
[reflection.assembly]::LoadWithPartialName("Microsoft.Office.Server") | out-null
$upm =[Microsoft.Office.Server.UserProfiles.UserProfileManager](
[Microsoft.Office.Server.ServerContext]::Default)
$upm.GetUserProfile($accountName)
}
function Get-UserProfileData($profile)
{
$propsToDisplay = $upm.Properties | ? { $_.IsSystem -eq $false -and $_.IsSection -eq $false }
$o = new-object PSObject
$propsToDisplay | foreach {
add-member -inp $o -membertype NoteProperty -name $_.Name -value $profile[$_.Name].Value
}
$o
}
@@
@@
@@#USAGE 1: (update one profile)
@@# $up = Get-UserProfile "spadmin"
@@# $up["YourCustomField"].Value = "new value"
@@# $up.Commit()
@@#
@@#USAGE 2: (export profile data to CSV)
@@#
@@# $upm = [Microsoft.Office.Server.UserProfiles.UserProfileManager](
@@# [Microsoft.Office.Server.ServerContext]::Default)
@@
@@
@@
@@#
# $unrolledProfilesCollection = $upm | foreach { $_ }
# $unrolledProfilesCollection | foreach { Get-UserProfileData $_ } | export-csv -NoTypeInformation "C:\\temp\\profiles.txt"
|
PowerShellCorpus/PoshCode/ACE.psm1.ps1
|
ACE.psm1.ps1
|
#######################
function Get-ACEConnection
{
param($ConnectionString)
$conn = new-object System.Data.OleDb.OleDbConnection($ConnectionString)
$conn.open()
$conn
} #Get-ACEConnection
#######################
function Get-ACETable
{
param($Connection)
$Connection.GetOleDbSchemaTable([System.Data.OleDb.OleDbSchemaGuid]::tables,$null)
} #Get-ACETable
#######################
function Get-ACEConnectionString
{
param($FilePath)
switch -regex ($FilePath)
{
'\\.xls$|\\.xlsx$|\\.xlsb$' {"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=`"$filepath`";Extended Properties=`"Excel 12.0 Xml;HDR=YES`";"}
'\\.mdb$|\\.accdb$' {"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=`"$filepath`";Persist Security Info=False;"}
}
} #Get-ACEConnectionString
#######################
<#
.SYNOPSIS
Queries Excel and Access files.
.DESCRIPTION
Get-ACEData gets data from Microsoft Office Access (*.mdb and *.accdb) files and Microsoft Office Excel (*.xls, *.xlsx, and *.xlsb) files
.INPUTS
None
You cannot pipe objects to Get-ACEData
.OUTPUTS
System.Data.DataSet
.EXAMPLE
Get-ACEData -FilePath ./budget.xlsx -WorkSheet 'FY2010$','FY2011$'
This example gets data for the worksheets FY2010 and FY2011 from the Excel file
.EXAMPLE
Get-ACEData - -FilePath ./budget.xlsx -WorksheetListOnly
This example list the Worksheets for the Excel file
.EXAMPLE
Get-ACEData -FilePath ./projects.xls -Query 'Select * FROM [Sheet1$]'
This example gets data using a query from the Excel file
.NOTES
Imporant!!!
Install ACE 12/26/2010 or higher version from LINK below
If using an x64 host install x64 version and use x64 PowerShell
Version History
v1.0 - Chad Miller - 4/21/2011 - Initial release
.LINK
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=c06b8369-60dd-4b64-a44b-84b371ede16d&displaylang=en
#>
function Get-ACEData
{
[CmdletBinding()]
param(
[Parameter(Position=0, Mandatory=$true)]
[ValidateScript({$_ -match '\\.xls$|\\.xlsx$|\\.xlsb$|\\.mdb$|\\.accdb$'})] [string]$FilePath,
[Parameter(Position=1, Mandatory=$false)]
[alias("Worksheet")] [string[]]$Table,
[Parameter(Position=2, Mandatory=$false)] [string]$Query,
[Parameter(Mandatory=$false)]
[alias("WorksheetListOnly")] [switch]$TableListOnly
)
$FilePath = $(resolve-path $FilePath).path
$conn = Get-ACEConnection -ConnectionString $(Get-ACEConnectionString $FilePath)
#If TableListOnly switch specified list tables/worksheets then exit
if ($TableListOnly)
{
Get-ACETable -Connection $conn
$conn.Close()
}
#Else tablelistonly switch not specified
else
{
$ds = New-Object system.Data.DataSet
$cmd = new-object System.Data.OleDb.OleDbCommand
$cmd.Connection = $conn
$da = new-object System.Data.OleDb.OleDbDataAdapter
if ($Query)
{
$qry = $Query
$cmd.CommandText = $qry
$da.SelectCommand = $cmd
$dt = new-object System.Data.dataTable
$null = $da.fill($dt)
$ds.Tables.Add($dt)
}
#Return one or more specified tables/worksheets
elseif ($Table)
{
$Table |
foreach{ $qry = "select * from [{0}]" -f $_;
$cmd.CommandText = $qry;
$da.SelectCommand = $cmd;
$dt = new-object System.Data.dataTable("$_");
$null = $da.fill($dt);
$ds.Tables.Add($dt)}
}
#Return all tables/worksheets
else
{
Get-ACETable $conn |
where {$_.TABLE_TYPE -eq 'TABLE' } |
foreach{ $qry = "select * from [{0}]" -f $_.TABLE_NAME;
$cmd.CommandText = $qry;
$da.SelectCommand = $cmd;
$dt = new-object System.Data.dataTable("$($_.TABLE_NAME)");
$null = $da.fill($dt);
$ds.Tables.Add($dt)}
}
$conn.Close()
Write-Output ($ds)
}
} #Get-ACEData
Export-ModuleMember -function Get-ACEData
|
PowerShellCorpus/PoshCode/Compare-DataSources.ps1
|
Compare-DataSources.ps1
|
#Define DPMHosts
[CmdletBinding()]
param([string]$PrimaryDPMHost, [string]$SecondaryDPMHost);
Write-Verbose "Compare-DataSources.ps1 written by Shai Perednik sperednik@deloitte.com"
Write-Verbose "Primary DPM Host: $PrimaryDPMHost"
Write-Verbose "Secondary DPM Host: $SecondaryDPMHost"
#Load DPM Snaping
Write-Verbose "Loading DPM PowerShell snapin"
Add-PSSnapin -name Microsoft.DataProtectionManager.PowerShell -ErrorAction SilentlyContinue
Write-Verbose "Finished loading DPM PowerShell snapin"
#*=============================================================================
#* FUNCTION GetDataSourcesFromDPMHost
#*=============================================================================
# Function: GetDataSourcesFromDPMHost
# Created: [05/03/2012]
# Author: Shai Perdnik sperednik@delloite.com
# Arguments:DPMHost
# Version: 0.0.1
# =============================================================================
# Purpose: Gets the DPM Hosts DataSources in a sorted array
#
#
# =============================================================================
Function GetDataSourcesFromDPMHost ($DPMHost){
Write-Verbose "==========================================================================="
Write-Verbose "Starting GetDataSourcesFromDPMHost Function on DPM Host: $DPMHost"
Write-Verbose "==========================================================================="
#Get the ProtectionGroups on the Primary
Write-Verbose "Getting Protection Groups from $DPMHost"
$PG = Get-Protectiongroup -DPMServerName $DPMHost | Sort-Object FriendlyName
#Initialize the variable $DataSourceDetails
$DataSourceDetails = @()
#Loop through the Protection Groups and Get the DataSources
foreach ($pgitem in $PG) {
Write-Verbose "Getting DataSources from $DPMHost"
$DS = Get-Datasource -ProtectionGroup $pgitem | Sort-Object FriendlyName
Write-Verbose "Checking individual datasource items and adding them to the array"
#Check what kind of DataSource it is
foreach ($dsitem in $DS) {
#Write-Host $dsitem.Type.DatasourceType
switch ($dsitem.Type.DatasourceType) {
"Microsoft.Internal.EnterpriseStorage.Dls.UI.ObjectModel.SQL.SQLObjectType" {
Write-Verbose "SQL DataSource: $dsitem.DisplayPath"
$DataSourceDetails += $dsitem.DisplayPath
break
}
"Microsoft.Internal.EnterpriseStorage.Dls.UI.ObjectModel.SystemProtection.SystemProtectionObjectType" {
Write-Verbose "System State DataSource: $dsitem.ProductionServerName\\$dsitem.DataSourceName"
$DataSourceDetails += $dsitem.ProductionServerName + "\\" + $dsitem.DataSourceName
break
}
"Microsoft.Internal.EnterpriseStorage.Dls.UI.ObjectModel.FileSystem.FsObjectType" {
Write-Verbose "Volume DataSource: $dsitem.ProductionServerName\\$dsitem.DataSourceName"
$DataSourceDetails += $dsitem.ProductionServerName + "\\" + $dsitem.DataSourceName
break
}
"Microsoft.Internal.EnterpriseStorage.Dls.UI.ObjectModel.FileSystem.FsDataSource" {
Write-Verbose "Volume DataSource: $dsitem.ProductionServerName\\$dsitem.DataSourceName"
$DataSourceDetails += $dsitem.ProductionServerName + "\\" + $dsitem.DataSourceName
break
}
default {
Write-Verbose "Other/Unknown DataSource: $dsitem"
break
}
}
}
}
#disconnect from DPMhost
Write-Verbose "Disconnecting form $DPMHost"
Disconnect-DPMServer -DPMServerName $DPMHost
#Sort the Array
Write-Verbose "Sorting the Array"
[Array]::Sort([array]$DataSourceDetails)
#Return a value
return $DataSourceDetails
}
#*=============================================================================
#* End of Function
#*=============================================================================
#*=============================================================================
#* SCRIPT BODY
#*=============================================================================
#Get the DataSources of the Primary and Secondary DPM hosts
Write-Verbose "Geting the datasources from the primary host $PrimaryDPMHost using GetDataSourcesFromDPMHost function"
$arPrimaryHost = GetDataSourcesFromDPMHost $PrimaryDPMHost
Write-Verbose "Geting the datasources from the Secondary host $SecondaryDPMHost using GetDataSourcesFromDPMHost function"
$arSecondaryHost = GetDataSourcesFromDPMHost $SecondaryDPMHost
#Now compare the two arrays
#Define container arrays
$PrimaryDataSourcesInSecondaryHost = @()
$PrimaryDataSourcesNotInSecondaryHost = @()
#do the work
Write-Verbose "Comparing the DataSources of the primary DPM host $PrimaryDPMHost againsnt the secodary $SecondaryDPMHost"
Foreach ($PrimaryHostItem in $arPrimaryHost)
{
If ($arSecondaryHost -contains $PrimaryHostItem){
$PrimaryDataSourcesInSecondaryHost += $PrimaryHostItem
}
Else{
$PrimaryDataSourcesNotInSecondaryHost += $PrimaryHostItem
}
}
Write-Verbose "==============================================================================================="
Write-Verbose "Primary, $PrimaryDPMHost, DataSources in secondary host $SecondaryDPMHost"
Write-Verbose "==============================================================================================="
$strOutString = Out-String -InputObject $PrimaryDataSourcesInSecondaryHost
Write-Verbose $strOutString
Write-Verbose "==============================================================================================="
Write-Verbose "==============================================================================================="
Write-Verbose "Primary, $PrimaryDPMHost, DataSources ***NOT*** in secondary host $SecondaryDPMHost"
Write-Verbose "==============================================================================================="
$strOutString = Out-String -InputObject $PrimaryDataSourcesNotInSecondaryHost
Write-Verbose $strOutString
Write-Verbose "==============================================================================================="
#Write the Results to a file on c:\\temp\\logs
Write-Host "Writing the comparisons to log files under c:\\temp\\logs"
New-Item -Path c:\\temp\\logs -ItemType directory -ErrorAction SilentlyContinue
$inpath = "c:\\temp\\logs\\" + $PrimaryDPMHost + "_DataSources_In_" + $SecondaryDPMHost + ".log"
$notinpath = "c:\\temp\\logs\\" + $PrimaryDPMHost + "_DataSources_Not_In_" + $SecondaryDPMHost + ".log"
Out-File -FilePath $inpath -InputObject $PrimaryDataSourcesInSecondaryHost
Write-Host "Wrote $inpath" -ForegroundColor Green -BackgroundColor Black
Out-File -FilePath $notinpath -InputObject $PrimaryDataSourcesNotInSecondaryHost
Write-Host "Wrote $notinpath" -ForegroundColor Green -BackgroundColor Black
Write-Verbose "Script finished"
#*=============================================================================
#* END OF SCRIPT:
#*=============================================================================
|
PowerShellCorpus/PoshCode/Password Generator Form.ps1
|
Password Generator Form.ps1
|
Function Create-Password {
#How many characters in the password
[int]$passwordlength = 14
##Make sure that number of characters below are not greater than $passwordlength!!
#Minimum Upper Case characters in password
[int]$min_upper = 3
#Minimum Lower Case characters in password
[int]$min_lower = 3
#Minimum Numerical characters in password
[int]$min_number = 3
#Minimum Symbol/Puncutation characters in password
[int]$min_symbol = 3
#Misc password characters in password
[int]$min_misc = ($passwordlength - ($min_upper + $min_lower + $min_number + $min_symbol))
#Characters for the password
$upper = @("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")
$lower = @("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")
$number = @(1,2,3,4,5,6,7,8,9,0)
$symbol = @("!","@","#","%","&","(",")","`"",".","<",">","+","=","-","_")
$combine = $upper + $lower + $number + $symbol
$password = @()
#Start adding upper case into password
1..$min_upper | % {$password += Get-Random $upper}
#Add lower case into password
1..$min_lower | % {$password += Get-Random $lower}
#Add numbers into password
1..$min_number | % {$password += Get-Random $number}
#Add symbols into password
1..$min_symbol | % {$password += Get-Random $symbol}
#Fill out the rest of the password length
1..$min_misc | % {$password += Get-Random $combine}
#Randomize password
Get-Random $password -count $passwordlength | % {[string]$randompassword += $_}
Return $randompassword
}
#Generated Form Function
function GenerateForm {
#region Import the Assemblies
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
#endregion
#Show popup if not running in -STA mode
If (((get-host).RunSpace).ApartmentState -ne "STA") {
[System.Windows.Forms.MessageBox]::Show("You are not running Powershell in (Single Threaded Apartment) STA mode! Please restart powershell in STA mode (powershell.exe -STA)","Warning") | Out-Null
Break
}
#region Generated Form Objects
$form1 = New-Object System.Windows.Forms.Form
$textBox1 = New-Object System.Windows.Forms.TextBox
$lbl_summary = New-Object System.Windows.Forms.Label
$lbl_passwordlabel = New-Object System.Windows.Forms.Label
$btn_generate = New-Object System.Windows.Forms.Button
$chk_printreport = New-Object System.Windows.Forms.CheckBox
$lbl_bottomheader = New-Object System.Windows.Forms.Label
$lbl_topheader = New-Object System.Windows.Forms.Label
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects
#----------------------------------------------
#Generated Event Script Blocks
#----------------------------------------------
#Provide Custom Code for events specified in PrimalForms.
$btn_generate_OnClick= {
#Saving password to variable
$password = Create-Password
#Displaying password to screen
$textBox1.Text = $password
Start-Sleep -Seconds 1
If ($($chk_printreport.Checked) -eq $True) {
#Define Printer - Uses Default printer
$code = @'
using System;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Drawing.Imaging;
namespace ScreenShotDemo
{
/// <summary>
/// Provides functions to capture the entire screen, or a particular window, and save it to a file.
/// </summary>
public class ScreenCapture
{
/// <summary>
/// Creates an Image object containing a screen shot of the entire desktop
/// </summary>
/// <returns></returns>
public Image CaptureScreen()
{
return CaptureWindow( User32.GetForegroundWindow() );
}
/// <summary>
/// Creates an Image object containing a screen shot of a specific window
/// </summary>
/// <param name="handle">The handle to the window. (In windows forms, this is obtained by the Handle property)</param>
/// <returns></returns>
public Image CaptureWindow(IntPtr handle)
{
// get te hDC of the target window
IntPtr hdcSrc = User32.GetWindowDC(handle);
// get the size
User32.RECT windowRect = new User32.RECT();
User32.GetWindowRect(handle,ref windowRect);
int width = windowRect.right - windowRect.left;
int height = windowRect.bottom - windowRect.top;
// create a device context we can copy to
IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
// create a bitmap we can copy it to,
// using GetDeviceCaps to get the width/height
IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc,width,height);
// select the bitmap object
IntPtr hOld = GDI32.SelectObject(hdcDest,hBitmap);
// bitblt over
GDI32.BitBlt(hdcDest,0,0,width,height,hdcSrc,0,0,GDI32.SRCCOPY);
// restore selection
GDI32.SelectObject(hdcDest,hOld);
// clean up
GDI32.DeleteDC(hdcDest);
User32.ReleaseDC(handle,hdcSrc);
// get a .NET image object for it
Image img = Image.FromHbitmap(hBitmap);
// free up the Bitmap object
GDI32.DeleteObject(hBitmap);
return img;
}
/// <summary>
/// Captures a screen shot of a specific window, and saves it to a file
/// </summary>
/// <param name="handle"></param>
/// <param name="filename"></param>
/// <param name="format"></param>
public void CaptureWindowToFile(IntPtr handle, string filename, ImageFormat format)
{
Image img = CaptureWindow(handle);
img.Save(filename,format);
}
/// <summary>
/// Captures a screen shot of the entire desktop, and saves it to a file
/// </summary>
/// <param name="filename"></param>
/// <param name="format"></param>
public void CaptureScreenToFile(string filename, ImageFormat format)
{
Image img = CaptureScreen();
img.Save(filename,format);
}
/// <summary>
/// Helper class containing Gdi32 API functions
/// </summary>
private class GDI32
{
public const int SRCCOPY = 0x00CC0020; // BitBlt dwRop parameter
[DllImport("gdi32.dll")]
public static extern bool BitBlt(IntPtr hObject,int nXDest,int nYDest,
int nWidth,int nHeight,IntPtr hObjectSource,
int nXSrc,int nYSrc,int dwRop);
[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC,int nWidth,
int nHeight);
[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
[DllImport("gdi32.dll")]
public static extern bool DeleteDC(IntPtr hDC);
[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
[DllImport("gdi32.dll")]
public static extern IntPtr SelectObject(IntPtr hDC,IntPtr hObject);
}
/// <summary>
/// Helper class containing User32 API functions
/// </summary>
private class User32
{
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[DllImport("user32.dll")]
public static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll")]
public static extern IntPtr GetWindowDC(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDC);
[DllImport("user32.dll")]
public static extern IntPtr GetWindowRect(IntPtr hWnd,ref RECT rect);
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
}
}
}
'@
add-type $code -ReferencedAssemblies 'System.Windows.Forms','System.Drawing'
#Print Form
$form1.FormBorderStyle = 0
$form1.Activate()
$fph = New-Object ScreenShotDemo.ScreenCapture
$img = $fph.CaptureScreen()
$pd = New-Object System.Drawing.Printing.PrintDocument
$pd.Add_PrintPage({$_.Graphics.DrawImage(([System.Drawing.Image]$img), 0, 0)})
$pd.Print()
$form1.FormBorderStyle = 5
}
#Pasting password to clipboard
#This will only work if Powershell is running in Single Threaded Apartment (STA): powershell.exe -sta or run from ISE
#You can check by running the following command: ((get-host).RunSpace).ApartmentState
[Windows.Forms.Clipboard]::SetText($password)
}
$handler_form1_Load=
{
$form1.TopMost = $True
$form1.Activate()
}
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}
#----------------------------------------------
#region Generated Form Code
$form1.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",9.75,1,3,0)
$form1.BackColor = [System.Drawing.Color]::FromArgb(255,255,255,255)
$form1.Text = "Password Generator"
$form1.AllowDrop = $True
$form1.Name = "form1"
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 685
$System_Drawing_Size.Height = 496
$form1.ClientSize = $System_Drawing_Size
$form1.FormBorderStyle = 5
$form1.add_Load($handler_form1_Load)
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 227
$System_Drawing_Size.Height = 19
$textBox1.Size = $System_Drawing_Size
$textBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$textBox1.ReadOnly = $True
$textBox1.BorderStyle = 0
$textBox1.Text = "NOTVALID1"
$textBox1.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",12,1,3,0)
$textBox1.Name = "textBox1"
$textBox1.BackColor = [System.Drawing.Color]::FromArgb(255,255,255,255)
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 304
$System_Drawing_Point.Y = 268
$textBox1.Location = $System_Drawing_Point
$textBox1.TabIndex = 7
$textBox1.add_TextChanged($handler_textBox1_TextChanged)
$form1.Controls.Add($textBox1)
$lbl_summary.TabIndex = 6
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 619
$System_Drawing_Size.Height = 156
$lbl_summary.Size = $System_Drawing_Size
$lbl_summary.Text = "Ensure your password contains at least 3 special characters, 3 numbers, 3 uppercase and 3 lowercase letters for a total of at least 14 characters long. You will be unable to change this password for the next 24 hours."
$lbl_summary.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",12,1,3,0)
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 41
$System_Drawing_Point.Y = 85
$lbl_summary.Location = $System_Drawing_Point
$lbl_summary.DataBindings.DefaultDataSourceUpdateMode = 0
$lbl_summary.Name = "lbl_summary"
$form1.Controls.Add($lbl_summary)
$lbl_passwordlabel.TabIndex = 4
$lbl_passwordlabel.TextAlign = 64
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 111
$System_Drawing_Size.Height = 47
$lbl_passwordlabel.Size = $System_Drawing_Size
$lbl_passwordlabel.Text = "Password:"
$lbl_passwordlabel.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",12,1,3,0)
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 184
$System_Drawing_Point.Y = 254
$lbl_passwordlabel.Location = $System_Drawing_Point
$lbl_passwordlabel.DataBindings.DefaultDataSourceUpdateMode = 0
$lbl_passwordlabel.Name = "lbl_passwordlabel"
$form1.Controls.Add($lbl_passwordlabel)
$btn_generate.TabIndex = 3
$btn_generate.Name = "btn_generate"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 104
$System_Drawing_Size.Height = 39
$btn_generate.Size = $System_Drawing_Size
$btn_generate.UseVisualStyleBackColor = $True
$btn_generate.Text = "Generate"
$btn_generate.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",8.25,1,3,0)
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 304
$System_Drawing_Point.Y = 364
$btn_generate.Location = $System_Drawing_Point
$btn_generate.DataBindings.DefaultDataSourceUpdateMode = 0
$btn_generate.add_Click($btn_generate_OnClick)
$form1.Controls.Add($btn_generate)
$chk_printreport.UseVisualStyleBackColor = $True
$chk_printreport.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",9,1,3,0)
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 104
$System_Drawing_Size.Height = 24
$chk_printreport.Size = $System_Drawing_Size
$chk_printreport.TabIndex = 2
$chk_printreport.Text = "Print Report"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 304
$System_Drawing_Point.Y = 323
$chk_printreport.Location = $System_Drawing_Point
$chk_printreport.DataBindings.DefaultDataSourceUpdateMode = 0
$chk_printreport.Name = "chk_printreport"
$chk_printreport.checked = $True
$form1.Controls.Add($chk_printreport)
$lbl_bottomheader.TabIndex = 1
$lbl_bottomheader.ImageAlign = 512
$lbl_bottomheader.TextAlign = 32
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 662
$System_Drawing_Size.Height = 59
$lbl_bottomheader.Size = $System_Drawing_Size
$lbl_bottomheader.Text = "FOR OFFICIAL USE ONLY"
$lbl_bottomheader.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",20.25,1,3,0)
$lbl_bottomheader.ForeColor = [System.Drawing.Color]::FromKnownColor("Green")
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 11
$System_Drawing_Point.Y = 425
$lbl_bottomheader.Location = $System_Drawing_Point
$lbl_bottomheader.DataBindings.DefaultDataSourceUpdateMode = 0
$lbl_bottomheader.Name = "lbl_bottomheader"
$lbl_bottomheader.add_Click($handler_label2_Click)
$form1.Controls.Add($lbl_bottomheader)
$lbl_topheader.TabIndex = 0
$lbl_topheader.ImageAlign = 512
$lbl_topheader.TextAlign = 32
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 662
$System_Drawing_Size.Height = 59
$lbl_topheader.Size = $System_Drawing_Size
$lbl_topheader.Text = "FOR OFFICIAL USE ONLY"
$lbl_topheader.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",20.25,1,3,0)
$lbl_topheader.ForeColor = [System.Drawing.Color]::FromKnownColor("Green")
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 11
$System_Drawing_Point.Y = 6
$lbl_topheader.Location = $System_Drawing_Point
$lbl_topheader.DataBindings.DefaultDataSourceUpdateMode = 0
$lbl_topheader.Name = "lbl_topheader"
$lbl_topheader.add_Click($handler_label1_Click)
$form1.Controls.Add($lbl_topheader)
#endregion Generated Form Code
#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$form1.ShowDialog()| Out-Null
} #End Function
#Call the Function
GenerateForm
|
PowerShellCorpus/PoshCode/Build-TFSProjects.ps1
|
Build-TFSProjects.ps1
|
#-------------------------------------------------------------------------
# Script that will:
# 1. Create a workspace. Workspacce Name: _Root
# 2. Get the latest code from repository
#-------------------------------------------------------------------------
Param(
[switch]
$CSRWEB,
[switch]
$CSRWS,
[switch]
$CSRServices,
[string]
$LogPath
)
Begin
{
If ($LogPath)
{
IF (-NOT (Test-Path $LogPath))
{
throw "Log Path:$($LogPath) not found!"
}
}
$MSBUILD="c:\\WINDOWS\\Microsoft.NET\\Framework\\v3.5\\MsBuild"
$WEBPROJECTOUTPUTDIR="$OUTDIR\\CSRWeb"
$SCRIPT:Outdir = "C:\\Application\\CSR";
#-------------------------------------------------------------------------
Function SetTFS
{
$SCRIPT:tfsServer = "172.29.4.179"
$script:userName = [system.environment]::UserName;
$script:computerName = [system.environment]::machinename
$script:workspaceName = $computerName + "_" + $userName +"_WS" #Use 'WS' as an acronym for "WorkSpace"
$script:CSRDIR = "C:\\Brassring2\\Application\\";
$script:WEBPROJECTOUTPUTDIR="$Outdir\\CSRWeb"
$script:WEBPROJECTOUTPUTDIR1="$Outdir\\CSRWS"
$script:WEBPROJECTOUTPUTDIR2="$Outdir\\CSRServices"
$script:REFPATH="referenceToAllAssembiesUsedInTheProjectSeperatedbySemiColon"
$script:MSBUILD="c:\\WINDOWS\\Microsoft.NET\\Framework\\v3.5\\MsBuild"
$script:failed = $false
# Set up the TF Alias
# Find where VS is installed.
$key = Get-ItemProperty HKLM:\\SOFTWARE\\Microsoft\\VisualStudio\\9.0
$dir = [string] (Get-ItemProperty $key.InstallDir)
$script:tf = "$dir\\tf.exe"
} # End SetTFS
#-------------------------------------------------------------------------
Function CreateWorkspace
{
Begin {
Function DeleteWorkspace
{
# Delete the workspace if it exists.
echo "Deleting workspace (if exists): $workspaceName" | Tee-Object -Variable Log
&$TF workspace /delete $workspaceName /noprompt | out-null
echo "Done deleting workspace." | Tee-Object -Variable Log
} #END DeleteWorkspace
}
Process {
DeleteWorkspace
# Create the folder
if (! (Test-Path $CSRDIR)) {
echo "Creating folder: $CSRDIR" | Tee-Object -Variable Log
new-item -itemtype directory -path $CSRDIR -force | out-null
echo "Completed Creating folder: $CSRDIR" | Tee-Object -Variable Log
}
# Move to folder
cd $CSRDIR
# Create the workspace
echo "Creating workspace: $workspaceName" | Tee-Object -Variable Log
&$TF workspace /new /computer:$computerName /server:$TFsServer /noprompt $workspaceName
echo "Done Creating workspace: $workspaceName" | Tee-Object -Variable Log
# Get the latest
echo "Getting the latest code from: $TFsServer. This could take awhile..." | Tee-Object -Variable Log
&$TF get $/CSR/CSR /recursive
echo "Done getting latest." | Tee-Object -Variable Log
echo "Tree initialization is complete." | Tee-Object -Variable Log
}
} #END CreateWorkspace
#-------------------------------------------------------------------------
# Get Next Label
#
# Labels are BL{major}.{minor}
# major = 1 - ???
# minor = 001 - 999
#-------------------------------------------------------------------------
Function GetNextLabel()
{
$major = 1
$minor = 1
$list = (&$TF labels /format:brief |? { $_ -notmatch "-.+" -and $_ -notmatch "Label.+Owner.+Date"})
if ($list -ne $null) {
# Split label into major minor
$major,[int]$minor= (($list | Select-Object -last 1).split()).split(".")
# Increment minor label
$minor++
# Remove BL from string, and cast to int
[int]$major = $major.substring(2)
# If minor gt 999 increment major and reset minor
if ($minor -gt 999) {
$major++
$minor = 1
}
}
# return label
$label = "BL{0}.{1:000}" -f $major, $minor
return $label
}
#-------------------------------------------------------------------------
Function MSBuild($outputdir, $webproject, $project, $ref)
{
# I think this can be cleaned up with where-object, but it's too important to play with
$failed = $false
&$MSBUILD /p:Configuration=Release /p:OutDir=$Outputdir /p:WebProjectOutputDir=$webproject $project |% {
if ($_ -match "Build FAILED") { $failed = $true } ; $_
}
if ($failed) { throw (new-object NullReferenceException) }
$failed = $false
&$MSBUILD /p:Configuration=Release /t:ResolveReferences /p:OutDir=$Outputdir\\bin\\ /p:ReferencePath=$ref $project |% {
if ($_ -match "Build FAILED") { $failed = $true } ; $_
}
if ($failed) { throw (new-object NullReferenceException) }
}
#-------------------------------------------------------------------------
# Create the Label
#-------------------------------------------------------------------------
Function ApplyLabel()
{
Write-Host "Create the Label" | Tee-Object -Variable Log
$label = GetNextLabel
&$TF label $label $/CSR/CSR /recursive
&$TF get /version:L$($label)
Write-Host "Applied label $label" | Tee-Object -Variable Log
return $Label
} # END ApplyLabel
} # End Begin
Process
{
trap [Exception]
{
write-host "Build Failed" | Tee-Object -Variable Log
exit 1;
}
. SetTFS
. CreateWorkspace
. ApplyLabel
IF (!$CSRWS -AND !$CSRWEB -AND !$CSRServices)
{
Write-Debug "No Options Found Setting ALL"
$CSRWS = $TRUE
$CSRWEB = $TRUE
$CSRServices = $TRUE
}
Switch ("")
{
{$CSRWEB}
{
Write-Host "Building CSRWEB" | Tee-Object -Variable Log
MsBuild "$Outdir\\CSRWeb\\" $WEBPROJECTOUTPUTDIR " $CSRDIR\\CSR\\CSR\\CSRWeb\\CSRWeb\\CSRWeb.csproj" $REFPATH
# ©-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.ApplicationBlocks.Data.dll $CSRDIR\\CSRWeb\\bin\\ -credential
# ©-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.Practices.EnterpriseLibrary.Caching.dll $CSRDIR\\CSRWeb\\bin\\ -credential
# ©-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.Practices.ObjectBuilder.dll $CSRDIR\\CSRWeb\\bin\\ -credential
rm $Outdir\\CSRWeb\\*.config -recurse
rm $Outdir\\CSRWeb\\*.pdb -recurse
rm $Outdir\\CSRWeb\\*.dll -recurse
rm $Outdir\\CSRWeb\\*.xml -recurse
rm $Outdir\\CSRWeb\\bin\\*.pdb -recurse
rm $Outdir\\CSRWeb\\bin\\*.config -recurse
rm $Outdir\\CSRWeb\\bin\\*.xml -recurse
Write-Host : "Build CSRWEB Successful" | Tee-Object -Variable Log
}
{$CSRWS}
{
Write-Host "Building CSRWS" | Tee-Object -Variable Log
MsBuild "$Outdir\\CSRWS\\" $WEBPROJECTOUTPUTDIR1 "$CSRDIR\\CSR\\CSR\\CSRWS\\CSRWS\\CSRWS.csproj" $REFPATH
# ©-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.ApplicationBlocks.Data.dll $CSRDIR\\CSRWeb\\bin\\ -credential
# ©-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.Practices.EnterpriseLibrary.Caching.dll $CSRDIR\\CSRWeb\\bin\\ -credential
# ©-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.Practices.ObjectBuilder.dll $CSRDIR\\CSRWeb\\bin\\ -credential
rm $Outdir\\CSRWS\\*.config -recurse
rm $Outdir\\CSRWS\\*.pdb -recurse
rm $Outdir\\CSRWS\\*.dll -recurse
rm $Outdir\\CSRWS\\*.xml -recurse
rm $Outdir\\CSRWS\\bin\\*.pdb -recurse
rm $Outdir\\CSRWS\\bin\\*.config -recurse
rm $Outdir\\CSRWS\\bin\\*.xml -recurse
Write-Host : "Build CSRWS Successful" | Tee-Object -Variable Log
}
{$CSRServices}
{
Write-Host "Building CSR Services" | Tee-Object -Variable Log
MsBuild "$Outdir\\CSRSERVICES\\" $WEBPROJECTOUTPUTDIR2 "CSRDIR\\CSR\\CSR\\CSRSERVICES\\CSRSERVICES\\CSRSERVICES.csproj" $REFPATH
# ©-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.ApplicationBlocks.Data.dll $CSRDIR\\CSRWeb\\bin\\ -credential
# ©-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.Practices.EnterpriseLibrary.Caching.dll $CSRDIR\\CSRWeb\\bin\\ -credential
# ©-item C:\\TFSMAIN\\CSR\\bin\\Microsoft.Practices.ObjectBuilder.dll $CSRDIR\\CSRWeb\\bin\\ -credential
rm $Outdir\\CSRSERVICES\\*.config -recurse
rm $Outdir\\CSRSERVICES\\*.pdb -recurse
rm $Outdir\\CSRSERVICES\\*.dll -recurse
rm $Outdir\\CSRSERVICES\\*.xml -recurse
rm $Outdir\\CSRSERVICES\\bin\\*.pdb -recurse
rm $Outdir\\CSRSERVICES\\bin\\*.config -recurse
rm $Outdir\\CSRSERVICES\\bin\\*.xml -recurse
Write-Host : "Build CSR Services Successful" | Tee-Object -Variable Log
}
}
} #End Process
End
{
IF ($LogPath)
{
Out-file -InputObject $Log -Encoding ascii
}
} #END End
|
PowerShellCorpus/PoshCode/Select-Random v2.1.ps1
|
Select-Random v2.1.ps1
|
# ---------------------------------------------------------------------------
### <Script>
### <Author>
### Joel "Jaykul" Bennett
### </Author>
### <Description>
### Selects a random element from the collection either passed as a parameter or input via the pipeline.
### If the collection is passed in as an argument, we simply pick a random number between 0 and count-1
### for each element you want to return, but when processing pipeline input we want to keep memory use
### to a minimum, so we use a "reservoir sampling" algorithm[1].
###
### [1] http://gregable.com/2007/10/reservoir-sampling.html
###
### The script stores $count elements (the eventual result) at all times. It continues processing
### elements until it reaches the end of the input. For each input element $n (the count of the inputs
### so far) there is a $count/$n chance that it becomes part of the result.
### * For each previously selected element, there is a $count/($n-1) chance of it being selected
### * For the ones selected, there's a ($count/$n * 1/$count = 1/$n) chance of it being replaced, so a
### ($n-1)/$n chance of it remaining ... thus, it's cumulative probability of being among the selected
### elements after the nth input is processed is $count/($n-1) * ($n-1)/$n = $count/$n, as it should be.
###
### </Description>
### <Usage>
### $arr = 1..5; Select-Random $arr
### 1..10 | Select-Random -Count 2
### </Usage>
### <Version>2.1.0.0</Version>
### </Script>
# ---------------------------------------------------------------------------
param([int]$count=1, [array]$inputObject=$null)
BEGIN {
if ($args -eq '-?') {
@"
Usage: Select-Random [[-Count] <int>] [-inputObject] <array> (from pipeline) [-?]
Parameters:
-Count : The number of elements to select.
-Collection : The collection from which to select a random element.
-? : Display this usage information and exit
Examples:
PS> $arr = 1..5; Select-Random $arr
PS> 1..10 | Select-Random -Count 2
"@
exit
}
elseif ($inputObject)
{
### If you're accepting $args, you need to pass those in...
# Write-Output $io | &($MyInvocation.InvocationName) $args;
Write-Output $inputObject | &($MyInvocation.InvocationName) -Count $count
break;
}
else
{
$seen = 0
$selected = new-object object[] $count
$rand = new-object Random
}
}
PROCESS {
if($_) {
$seen++
if($seen -lt $count) {
$selected[$seen-1] = $_
} ## For each input element $n there is a $count/$n chance that it becomes part of the result.
elseif($rand.NextDouble() -lt ($count/$seen))
{
## For the ones previously selected, there's a 1/$n chance of it being replaced
$selected[$rand.Next(0,$count)] = $_
}
}
}
END {
if (-not $inputObject)
{ ## DO ONCE: (only on the re-invoke, not when using -inputObject)
Write-Verbose "Selected $count of $seen elements"
Write-Output $selected
# foreach($el in $selected) { Write-Output $el }
}
}
|
PowerShellCorpus/PoshCode/Invoke-SqlCmd_2.ps1
|
Invoke-SqlCmd_2.ps1
|
function Invoke-Sqlcmd2
{
param(
[string]$ServerInstance,
[string]$Database,
[string]$Query,
[Int32]$QueryTimeout=30
)
$conn=new-object System.Data.SqlClient.SQLConnection
$conn.ConnectionString="Server={0};Database={1};Integrated Security=True" -f $ServerInstance,$Database
$conn.Open()
$cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn)
$cmd.CommandTimeout=$QueryTimeout
$ds=New-Object system.Data.DataSet
$da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd)
[void]$da.fill($ds)
$conn.Close()
$ds.Tables[0]
}
|
PowerShellCorpus/PoshCode/Time-Stamp.ps1
|
Time-Stamp.ps1
|
function Time-Stamp
{
return [System.DateTime]::Now.ToString("yyyy.MM.dd hh:mm:ss");
}
New-Alias -Name ts -Value Time-Stamp;
|
PowerShellCorpus/PoshCode/Compare-Property.ps1
|
Compare-Property.ps1
|
##############################################################################\n##\n## Compare-Property\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\nCompare the property you provide against the input supplied to the script.\nThis provides the functionality of simple Where-Object comparisons without\nthe syntax required for that cmdlet.\n\n.EXAMPLE\n\nGet-Process | Compare-Property Handles gt 1000\n\n.EXAMPLE\n\nPS >Set-Alias ?? Compare-Property\nPS >dir | ?? PsIsContainer\n\n#>\n\nparam(\n ## The property to compare\n $Property,\n\n ## The operator to use in the comparison\n $Operator = "eq",\n\n ## The value to compare with\n $MatchText = "$true"\n)\n\nBegin { $expression = "`$_.$property -$operator `"$matchText`"" }\nProcess { if(Invoke-Expression $expression) { $_ } }
|
PowerShellCorpus/PoshCode/test_3.ps1
|
test_3.ps1
|
[CmdletBinding()]
param()
"This file is in the $PSScriptRoot folder."
|
PowerShellCorpus/PoshCode/Get-ADNonExpPass.ps1
|
Get-ADNonExpPass.ps1
|
param ($LDAPPath = "", [switch]$Help)
if ($Help)
{
""
Write-Host "Usage: .\\Get-ADNonExpPass.ps1 <LDAPPath>" -foregroundcolor Yellow
Write-Host "Ex: .\\Get-ADNonExpPass.ps1 'LDAP://ou=users,dc=domain,dc=com'" -foregroundcolor Yellow
""
break
}
#UAC Flag in Hex
#http://support.microsoft.com/kb/305144
$DontExpire = 0x10000
$Root = [ADSI]$LDAPPath
$Category = "user"
$Selector = New-Object DirectoryServices.DirectorySearcher
$Selector.SearchRoot = $Root
$Selector.Filter = ("(objectCategory=$Category)")
#$Selector.pagesize = 2000
# Grab all the user objects for the OU
$Users = $Selector.findall()
foreach ($User in $Users) {
$DN = $User.properties.distinguishedname
$UserProp = [ADSI]"LDAP://$dn"
if (($UserProp.UserAccountControl[0] -band $DontExpire) -eq 65536)
{
$UserProp | Select Name, UserAccountControl
}
}
|
PowerShellCorpus/PoshCode/Get-OLEDBData_2.ps1
|
Get-OLEDBData_2.ps1
|
###########################################################################
# Get-OLEDBData
# --------------------------------------------
# Description: This function is used to retrieve data via an OLEDB data
# connection.
#
# Inputs: $connectstring - Connection String.
# $sql - SQL statement to be executed to retrieve data.
#
# Usage: Get-OLEDBData <connction string> <SQL statement>
#
#Connection String for Excel 2007:
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=`"$filepath`";Extended Properties=`"Excel 12.0 Xml;HDR=YES`";"
#Connection String for Excel 2003:
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=`"$filepath`";Extended Properties=`"Excel 8.0;HDR=Yes;IMEX=1`";"
#Excel query
#'select * from [sheet1$]'
#Informix
#"password=$password;User ID=$userName;Data Source=$dbName@$serverName;Persist Security Info=true;Provider=Ifxoledbc.2"
#Oracle
#"password=$password;User ID=$userName;Data Source=$serverName;Provider=OraOLEDB.Oracle"
#SQL Server
#"Server=$serverName;Trusted_connection=yes;database=$dbname;Provider=SQLNCLI;"
###########################################################################
function Get-OLEDBData ($connectstring, $sql) {
$OLEDBConn = New-Object System.Data.OleDb.OleDbConnection($connectstring)
$OLEDBConn.open()
$readcmd = New-Object system.Data.OleDb.OleDbCommand($sql,$OLEDBConn)
$readcmd.CommandTimeout = '300'
$da = New-Object system.Data.OleDb.OleDbDataAdapter($readcmd)
$dt = New-Object system.Data.datatable
[void]$da.fill($dt)
$OLEDBConn.close()
return $dt
}
|
PowerShellCorpus/PoshCode/ConvertTo-DN_1.ps1
|
ConvertTo-DN_1.ps1
|
#Author: Glenn Sizemore glnsize@get-admin.com
#
#Purpose: Convert a DN to a Canonical name, 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/Get-MacAddressOui.ps1
|
Get-MacAddressOui.ps1
|
function Get-MacAddressOui {
<#
.SYNOPSIS
Gets a MAC address OUI (Organizationally Unique Identifier).
.DESCRIPTION
The Get-MacAddressOui function retrieves the MAC address OUI reference list maintained by the IEEE standards website and
returns the name of the company to which the MAC address OUI is assigned.
.PARAMETER MacAddress
Specifies the MAC address for which the OUI should be retrieved.
.EXAMPLE
Get-MacAddressOui 00:02:B3:FF:FF:FF
Returns the MAC address OUI and the company assigned that idenifier.
.INPUTS
System.String
.OUTPUTS
PSObject
.NOTES
Name: Get-MacAddressOui
Author: Rich Kusak (rkusak@hotmail.com)
Created: 2011-09-01
LastEdit: 2011-09-02 12:51
Version: 1.0.0.0
.LINK
http://standards.ieee.org/develop/regauth/oui/oui.txt
.LINK
about_regular_expressions
#>
[CmdletBinding()]
param (
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[ValidateScript({
$patterns = @(
'^[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}$'
'^[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}-[0-9a-f]{2}$'
'^[0-9a-f]{4}\\.[0-9a-f]{4}\\.[0-9a-f]{4}$'
'^[0-9a-f]{12}$'
)
if ($_ -match ($patterns -join '|')) {$true} else {
throw "The argument '$_' does not match a valid MAC address format."
}
})]
[string]$MacAddress
)
begin {
$uri = 'http://standards.ieee.org/develop/regauth/oui/oui.txt'
$webClient = New-Object System.Net.WebClient
$ouiReference = $webClient.DownloadString($uri)
$properties = 'MacAddress', 'OUI', 'Company'
} # begin
process {
$oui = ($MacAddress -replace '\\W').Remove(6)
New-Object PSObject -Property @{
'MacAddress' = $MacAddress
'OUI' = $oui
'Company' = [regex]::Match($ouiReference, "($oui)\\s*\\(base 16\\)\\s*(.+)").Groups[2].Value
} | Select $properties
} # process
} # function Get-MacAddressOui
|
PowerShellCorpus/PoshCode/chkhash_21.ps1
|
chkhash_21.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
}
# chkhash.ps1 [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #3] [-u] [-h [path of .xml database]]
# -u updates the XML file database and exits
# otherwise, all files are checked against the XML file database.
# -h specifies location of xml hash database
$hashespath=".\\hashes.xml"
del variable:\\args3 -ea 0
del variable:\\args2 -ea 0
del variable:\\xfiles -ea 0
del variable:\\files -ea 0
del variable:\\exclude -ea 0
$args3=@()
$args2=@($args)
$nu = 0
$errs = 0
$fc = 0
$fm = 0
$upd = $false
$create = $false
"ChkHash.ps1 - ChkHash.ps1 can create a .XML database of files and their SHA-512 hashes and check files against the database, "
"in order to detect corrupt or hacked files."
""
".\\chkhash.ps1 -h for usage."
""
for($i=0;$i -lt $args2.count; $i++)
{
if ($args2[$i] -like "-h*") # -help specified?
{
"Usage: .\\chkhash.ps1 [-h] [-u] [-c] [-x <file path of hashes .xml database>] [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #n] [-e <Dirs>]"
"Options: -h - Help display."
" -c - Create hash database. If .xml hash database does not exist, -c will be assumed."
" -u - Update changed files and add new files to existing database."
" -x - specifies .xml database file path to use. Default is .\\hashes.xml"
" -e - exclude dirs. Put this after the files/dirs you want to check with SHA512 and needs to be fullpath (e.g. c:\\users\\bob not ..\\bob)."
""
"Examples: PS>.\\chkhash.ps1 c:\\ d:\\ -c -x c:\\users\\bob\\hashes\\hashes.xml"
" [hash all files on c:\\ and d:\\ and subdirs, create and store hashes in c:\\users\\bob\\hashes\\hashes.xml]"
" PS>.\\chkhash.ps1 c:\\users\\alice\\pictures\\sunset.jpg -u -x c:\\users\\alice\\hashes\\pictureshashes.xml]"
" [hash c:\\users\\alice\\pictures\\sunset.jpg and add or update the hash to c:\\users\\alice\\hashes\\picturehashes.xml"
" PS>.\\chkhash.ps1 c:\\users\\eve\\documents d:\\media\\movies -x c:\\users\\eve\\hashes\\private.xml"
" [hash all files in c:\\users\\eve\\documents and d:\\media\\movies, check against hashes stored in c:\\users\\eve\\hashes\\private.xml"
" or create it and store hashes there if not present]"
" PS>.\\chkhash.ps1 c:\\users\\eve -x c:\\users\\eve\\hashes\\private.xml -e c:\\users\\eve\\hashes"
" [hash all files in c:\\users\\eve and subdirs, check hashes against c:\\users\\eve\\hashes\\private.xml or store if not present, exclude "
" c:\\users\\eve\\hashes directory and subdirs]"
" PS>.\\chkhash.p1s c:\\users\\ted\\documents\\f* d:\\data -x d:\\hashes.xml -e d:\\data\\test d:\\data\\favorites -u"
" [hash all files starting with 'f' in c:\\users\\ted\\documents, and all files in d:\\data, add or update hashes to"
" existing d:\\hashes.xml, exclude d:\\data\\test and d:\\data\\favorites and subdirs]"
" PS>.\\chkhash -x c:\\users\\alice\\hashes\\hashes.xml"
" [Load hashes.xml and check hashes of all files contained within.]"
""
"Note: files in subdirectories of any specified directory are automatically processed."
" if you specify only an -x option, or no option and .\\hash.xml exists, only files in the database will be checked."
exit
}
if ($args2[$i] -like "-u*") {$upd=$true;continue} # Update and Add new files to database?
if ($args2[$i] -like "-c*") {$create=$true;continue} # Create database specified?
if ($args2[$i] -like "-x*")
{
$i++ # Get hashes xml database path
if ($i -ge $args2.count)
{
write-host "-X specified but no file path of .xml database specified. Exiting."
exit
}
$hashespath=$args2[$i]
continue
}
if ($args2[$i] -like "-e*") # Exclude files, dirs
{
while (($i+1) -lt $args2.count)
{
$i++
if ($args2[$i] -like "-*") {break}
$exclude+=@(join-path $args2[$i] "\\") # collect array of excluded directories.
}
continue
}
$args3+=@($args2[$i]) # Add files/dirs
}
if ($args3.count -ne 0)
{
# Get list of files and SHA512 hash them.
"Enumerating files from specified locations..."
$files=@(dir $args3 -recurse -ea 0 | ?{$_.mode -notmatch "d"} | ?{noequal $_.directoryname $exclude}) # Get list of files
if ($files.count -eq 0) {"No files found. Exiting."; exit}
if ($create -eq $true -or !(test-path $hashespath)) # Create database?
{
# Create SHA512 hashes of files and write to new database
$files = $files | %{write-host "SHA-512 Hashing `"$($_.fullname)`" ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
$files |export-clixml $hashespath
"Created $hashespath"
"$($files.count) file hash(es) saved. Exiting."
exit
}
write-host "Loading file hashes from $hashespath..." -nonewline
$xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database
if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit}
}
else
{
if (!(test-path $hashespath)) {"No database found or specified, exiting."; exit}
write-host "Loading file hashes from $hashespath..." -nonewline
$xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database and check it
if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit}
$files=$xfiles
}
"Loaded $($xfiles.count) file hash(es)."
$hash=@{}
for($x=0;$x -lt $xfiles.count; $x++) # Build dictionary (hash) of filenames and indexes into file array
{
if ($hash.contains($xfiles[$x].fullname)) {continue}
$hash.Add($xfiles[$x].fullname,$x)
}
foreach($f in $files)
{
if ((get-item -ea 0 $f.fullname) -eq $null) {continue} # skip if file no longer exists.
$n=($hash.($f.fullname))
if ($n -eq $null)
{
$nu++ # increment needs/needed updating count
if ($upd -eq $false) {"Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue
"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
}
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force}
$fc++ # File checked increment.
if ($xfiles[$n].SHA512 -eq $f.SHA512) # Check SHA512 for mixmatch.
{$fm++;continue} # if matched, increment file matches and continue loop
$errs++ # increment mixmatches
if ($upd -eq $true) { $xfiles[$n]=$f; "Updated `"$($f.fullname)`"";continue}
"Bad SHA-512 found: `"$($f.fullname)`""
}
if ($upd -eq $true) # if database updated
{
$xfiles|export-clixml $hashespath # write xml database
"Updated $hashespath"
"$nu file hash(es) added to database."
"$errs file hash(es) updated in database."
exit
}
"$errs SHA-512 mixmatch(es) found."
"$fm file(s) SHA512 matched."
"$fc file(s) checked total."
if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
|
PowerShellCorpus/PoshCode/CertMgmt pack_3.ps1
|
CertMgmt pack_3.ps1
|
#####################################################################
# CertMgmtPack.ps1
# Version 0.51
#
# Digital certificate management pack
#
# Vadims Podans (c) 2009
# http://www.sysadmins.lv/
#####################################################################
#requires -Version 2.0
function Import-Certificate {
<#
.Synopsis
Imports digital certificates to Certificate Store from files
.Description
Improrts digital certificates to Certificate Store from various types of
certificates files, such .CER, .DER, .PFX (password required), .P7B.
.Parameter Path
Specifies the path to certificate file
.Parameter Password
Specifies password to PFX/PKCS#12 file only. For other certificate types
is not required.
Note: this parameter must be passed as SecureString.
.Parameter Storage
Specifies place in Sertificate Store for certificate. For user certificates
(default) you MAY specify 'User' and importing certificate will be stored
in CurrentUser Certificate Store. For computer certificates you MUST specify
'Computer' and importing certificates will be stored in LocalMachine Certificate
Store.
.Parameter Container
Specifies container within particular Certificate Store location. Container may
be one of AuthRoot/CA/Disallowed/My/REQUEST/Root/SmartCardRoot/Trust/TrustedPeople/
TrustedPublisher/UserDS. These containers represent MMC console containers
as follows:
AddressBook - AddressBook
AuthRoot - Third-Party Root CAs
CA - Intermediate CAs
Disallowed - Untrused Certificates
My - Personal
REQUEST - Certificate Enrollment Requests
Root - Trusted Root CAs
SmartCardRoot - Smart Card Trusted Roots
Trust - Enterprise Trust
TrustedPeople - Trusted People
TrustedPublishers - Trusted Publishers
UserDS - Active Directory User Object
.Parameter Exportable
Marks imported certificates private key as exportable. May be used only for PFX
files only. If this switch is not presented for PFX files, after importing you
will not be able to export this certificate with private key again.
.Parameter StrongProtection
Enables private key strong protection that requires user password each time
when certificate private key is used. Not available for computer certificates,
because computers certificates are used under LocalSystem account and here is
no UI for user to type password.
.Outputs
This command provide a simple message if the export is successful.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
[string]$Path,
[Parameter(Position = 1)]
[System.Security.SecureString]$Password,
[Parameter(Position = 2)]
[string][ValidateSet("CurrentUser", "LocalMachine")]$Storage = "CurrentUser",
[string][ValidateSet("AddressBook", "AuthRoot", "CA", "Disallowed", "My", "REQUEST",
"Root", "SmartCardRoot", "Trust", "TrustedPeople", "TrustedPublisher", "UserDS")]$Container = "My",
[switch]$Exportable,
[switch]$StrongProtection
)
if (!(Resolve-Path $Path)) {throw "Looks like your specified certificate file doesn't exist"}
$file = gi $Path -Force -ErrorAction Stop
$certs = New-Object system.security.cryptography.x509certificates.x509certificate2
switch ($Storage) {
"CurrentUser" {$flags = "UserKeySet"}
"LocalMachine" {$flags = "MachineKeySet"}
}
switch -regex ($file.Extension) {
".CER|.DER" {$certs.Import($file.FullName, $null, $flags)}
".PFX" {
if (!$password) {throw "For PFX files password is required."}
if ($StrongProtection -and $Storage -eq "Computer") {
throw "You cannot use Private Key Strong Protection for computer certificates!"
}
if ($Exportable) {$flags = $flags + ", Exportable"}
if ($StrongProtection) {$flags = $flags + ", UserProtected"}
$certs.Import($file.FullName, $password, $flags)
}
".P7B|.SST" {
$certs = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
$certs.Import([System.IO.File]::ReadAllBytes($file.FullName))
}
default {throw "Looks like your specified file is not a certificate file"}
}
$store = New-Object system.security.cryptography.X509Certificates.X509Store $Container, $Storage
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$certs | %{$store.Add($_)}
if ($?) {Write-Host -ForegroundColor Green Certificate file`: $file.fullname was successfully added to $Container container}
$store.Close()
}
function Export-Certificate {
<#
.Synopsis
Exports digital certificates to file Certificate Store.
.Description
Exports digital certificates from Certificate Store to various types of certificate
file such .CER, .DER, .PFX (password required), .P7B or .SST (serializd store).
.Parameter Path
Specifies the path to certificate storing folder
.Parameter Type
Specifies type of imported certificate. May be one of CERT/PFX/PKCS#12/P7B/PKCS#7.
.Parameter Password
Specifies a password for PFX files and used only if type is specified as PFX/PKCS#12.
Note: password must be supplied as SecureString.
.Parameter Storage
Specifies place in Sertificate Store for certificate. For user certificates
(default) you MAY specify 'User' to export certificates from CurrentUser Certificate Store.
For computer certificates you MUST specify 'Computer' to export certificates from
LocalMachine Certificate Store.
.Parameter Container
Specifies container within particular Certificate Store location. Container may
be one of AuthRoot/CA/Disallowed/My/REQUEST/Root/SmartCardRoot/Trust/TrustedPeople/
TrustedPublisher/UserDS. These containers represent MMC console containers
as follows:
AddressBook - AddressBook
AuthRoot - Third-Party Root CAs
CA - Intermediate CAs
Disallowed - Untrused Certificates
My - Personal
REQUEST - Certificate Enrollment Requests
Root - Trusted Root CAs
SmartCardRoot - Smart Card Trusted Roots
Trust - Enterprise Trust
TrustedPeople - Trusted People
TrustedPublishers - Trusted Publishers
UserDS - Active Directory User Object
.EXAMPLE
.Outputs
This command doesn't provide any output, except errors.
.Link
#>
[CmdletBinding()]
param (
[Parameter(Position = 0)]
[string]$Path,
[Parameter(Mandatory = $true, Position = 1)]
[string][ValidatePattern("Cert|Pfx|pkcs12|pkcs7|SST")]$Type,
[Parameter(Position = 2)]
[System.Security.SecureString]$Password,
[Parameter(Position = 3)]
[string][ValidateSet("CurrentUser", "LocalMachine")]$Storage = "CurrentUser",
[Parameter(ValueFromPipeline = $true, Position = 4)]
[string][ValidateSet("AddressBook", "AuthRoot", "CA", "Disallowed", "My", "REQUEST",
"Root", "SmartCardRoot", "Trust", "TrustedPeople", "TrustedPublisher", "UserDS")]$Container = "My",
[string]$Thumbprint,
[string]$Subject,
[string]$Issuer,
[string]$SerialNumber,
[string]$NotAfter,
[string]$NotBefore,
[switch]$DeleteKey,
[switch]$Recurse
)
if (!(Test-Path $Path)) {
New-Item -ItemType directory -Path $Path -Force -ErrorAction Stop
}
if ((Resolve-Path $Path).Provider.Name -ne "FileSystem") {
throw "Spicifed path is not recognized as filesystem path. Try again"
}
if ($Recurse) {
function dirx ($Storage) {
dir cert:\\$Storage -Recurse | ?{!$_.PsIsContainer}
}
} else {
function dirx ($Storage, $Container) {
dir cert:\\$Storage\\$Container
}
}
if ($Type -eq 'pkcs12') {$Type = "PFX"}
if ($Type -eq 'SST') {$Type = "SerializedStore"}
if ($Type -eq "PFX" -and !$Password) {throw "For PFX files password is required."}
$Type = [System.Security.Cryptography.X509Certificates.X509ContentType]::$Type
if ($NotAfter) {$NotAfter = [datetime]::ParseExact($NotAfter, "dd.MM.yyy", $null)}
if ($NotBefore) {$NotBefore = [datetime]::ParseExact($NotBefore, "dd.MM.yyy", $null)}
if ($Thumbprint) {$certs = @(dirx | ?{$_.Thumbprint -like "*$Thumbprint*"})}
elseif ($Subject) {$certs = @(dirx | ?{$_.Subject -like "*$Subject*"})}
elseif ($Issuer) {$certs = @(dirx | ?{$_.Issuer -like "*$Issuer*"})}
elseif ($SerialNumber) {$certs = @(dirx | ?{$_.SerialNumber -like "*$SerialNumber*"})}
elseif ($NotAfter -and !$NotBefore) {$certs = @(dirx | ?{$_.NotAfter -lt $NotAfter})}
elseif (!$NotAfter -and $NotBefore) {$certs = @(dirx | ?{$_.NotBefore -gt $NotBefore})}
elseif ($NotAfter -and $NotBefore) {$certs = @(dirx | ?{$_.NotAfter -lt $NotAfter `
-and $_.NotBefore -gt $NotBefore})}
else {$certs = @(dirx)}
if ($certs.Count -eq 0) {Write-Warning "Sorry, we unable to find certificates that correspond your filter :("; return}
switch -regex ($Type) {
"Cert" {
foreach ($cert in $certs) {
[void]($cert.Subject -match 'CN=([^,]+)')
$CN = $matches[1] -replace '[\\\\/:\\*?`"<>|]', ''
$bytes = $cert.Export($type)
$base64Data = [System.Convert]::ToBase64String($bytes)
Set-Content -LiteralPath $(Join-Path $Path ($CN + "_" + $cert.Thumbprint + ".cer")) -Value $base64Data
}
}
"PFX" {
foreach ($cert in $certs) {
[void]($cert.Subject -match 'CN=([^,]+)')
$CN = $matches[1] -replace '[\\\\/:\\*?`"<>|]', ''
$bytes = $cert.Export($Type, $Password)
[System.IO.File]::WriteAllBytes($(Join-Path $Path ($CN + "_" + $cert.Thumbprint + ".pfx")), $bytes)
if ($DeleteKey) {
$tempcert = $cert.Export("Cert")
$store = New-Object system.security.cryptography.X509Certificates.X509Store $container, $Storage
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$store.Remove($cert)
$store.Add($tempcert)
$store.Close()
}
}
}
"Pkcs7|SerializedStore" {
$certcol = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
$certs | %{[void]$certcol.Add($_)}
$bytes = $certcol.Export($Type)
if ($Type -eq "Pkcs7") {$ext = ".p7b"} else {$ext = ".sst"}
[System.IO.File]::WriteAllBytes($("ExportedCertificates" + $ext, $bytes))
}
}
}
|
PowerShellCorpus/PoshCode/Aero Glass PowerShell.ps1
|
Aero Glass PowerShell.ps1
|
#requires -version 2
param([switch]$Disable)
add-type -namespace Hacks -name Aero -memberdefinition @"
[StructLayout(LayoutKind.Sequential)]
public struct MARGINS
{
public int left;
public int right;
public int top;
public int bottom;
}
[DllImport("dwmapi.dll", PreserveSig = false)]
public static extern void DwmExtendFrameIntoClientArea(IntPtr hwnd, ref MARGINS margins);
[DllImport("dwmapi.dll", PreserveSig = false)]
public static extern bool DwmIsCompositionEnabled();
"@
if (([Environment]::OSVersion.Version.Major -gt 5) -and
[hacks.aero]::DwmIsCompositionEnabled()) {
$hwnd = (get-process -id $pid).mainwindowhandle
$margin = new-object 'hacks.aero+margins'
$host.ui.RawUI.BackgroundColor = "black"
$host.ui.rawui.foregroundcolor = "white"
if ($Disable) {
$margin.top = 0
$margin.left = 0
} else {
$margin.top = -1
$margin.left = -1
}
[hacks.aero]::DwmExtendFrameIntoClientArea($hwnd, [ref]$margin)
} else {
write-warning "Aero is either not available or not enabled on this workstation."
}
|
PowerShellCorpus/PoshCode/Convert Raw SID to SID_1.ps1
|
Convert Raw SID to SID_1.ps1
|
#For intel concerning how to convert raw hex SID to Standard SID got to
#http://blogs.msdn.com/b/oldnewthing/archive/2004/03/15/89753.aspx
#to convert Hex to Dec
function Convert-HEXtoDEC
{
param($HEX)
ForEach ($value in $HEX)
{
[string][Convert]::ToInt32($value,16)
}
}
#to reassort decimal values to correct hex in order to cenvert them
function Reassort
{
param($chaine)
$a = $chaine.substring(0,2)
$b = $chaine.substring(2,2)
$c = $chaine.substring(4,2)
$d = $chaine.substring(6,2)
$d+$c+$b+$a
}
# this is the main function
# it splits the waxw sid into different parts and then converts the values
# finally it brings the converted SID value.
# you can supply an array of raw sid
function ConvertSID
{
param($chaine32)
foreach($chaine in $chaine32) {
[INT]$SID_Revision = $chaine.substring(0,2)
[INT]$Identifier_Authority = $chaine.substring(2,2)
[INT]$Security_NT_Non_unique = Convert-HEXtoDEC(Reassort($chaine.substring(16,8)))
$chaine1 = $chaine.substring(24,8)
$chaine2 = $chaine.substring(32,8)
$chaine3 = $chaine.substring(40,8)
$chaine4 = $chaine.substring(48,8)
[string]$MachineID_1=Convert-HextoDEC(Reassort($chaine1))
[string]$MachineID_2=Convert-HextoDEC(Reassort($chaine2))
[string]$MachineID_3=Convert-HextoDEC(Reassort($chaine3))
[string]$UID=Convert-HextoDEC(Reassort($chaine4))
#"S-1-5-21-" + $MachineID_1 + "-" + $MachineID_2 + "-" + $MachineID_3 + "-" + $UID
"S-$SID_revision-$Identifier_Authority-$Security_NT_Non_unique-$MachineID_1-$MachineID_2-$MachineID_3-$UID"
}
}
|
PowerShellCorpus/PoshCode/Start-ProcessAsUser.ps1
|
Start-ProcessAsUser.ps1
|
##############################################################################\n##\n## Start-ProcessAsUser\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\nLaunch a process under alternate credentials, providing functionality\nsimilar to runas.exe.\n\n.EXAMPLE\n\nPS >$file = Join-Path ([Environment]::GetFolderPath("System")) certmgr.msc\nPS >Start-ProcessAsUser Administrator mmc $file\n\n#>\n\nparam(\n ## The credential to launch the process under\n $Credential = (Get-Credential),\n\n ## The process to start\n [Parameter(Mandatory = $true)]\n [string] $Process,\n\n ## Any arguments to pass to the process\n [string] $ArgumentList = ""\n)\n\nSet-StrictMode -Version Latest\n\n## Create a real credential if they supplied a username\n$credential = Get-Credential $credential\n\n## Exit if they canceled out of the credential dialog\nif(-not ($credential -is "System.Management.Automation.PsCredential"))\n{\n return\n}\n\n## Prepare the startup information (including username and password)\n$startInfo = New-Object Diagnostics.ProcessStartInfo\n$startInfo.Filename = $process\n$startInfo.Arguments = $argumentList\n\n## If we're launching as ourselves, set the "runas" verb\nif(($credential.Username -eq "$ENV:Username") -or\n ($credential.Username -eq "\\$ENV:Username"))\n{\n $startInfo.Verb = "runas"\n}\nelse\n{\n $startInfo.UserName = $credential.Username\n $startInfo.Password = $credential.Password\n $startInfo.UseShellExecute = $false\n}\n\n## Start the process\n[Diagnostics.Process]::Start($startInfo)
|
PowerShellCorpus/PoshCode/Get-WebSite_7.ps1
|
Get-WebSite_7.ps1
|
function Get-WebSite {
<#
.SYNOPSIS
Retrieves information about a website.
.DESCRIPTION
Retrieves information about a website.
.PARAMETER Url
URL of the website to test access to.
.PARAMETER UseDefaultCredentials
Use the currently authenticated user's credentials
.PARAMETER Proxy
Used to connect via a proxy
.PARAMETER TimeOut
Timeout to connect to site, in milliseconds
.PARAMETER Credential
Provide alternate credentials
.NOTES
Name: Get-WebSite
Author: Boe Prox
DateCreated: 08Feb2011
.EXAMPLE
Get-WebSite -url "http://www.bing.com"
Description
------------
Returns information about Bing.Com to include StatusCode and type of web server being used to host the site.
#>
[cmdletbinding(
DefaultParameterSetName = 'url',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = '',
ValueFromPipeline = $True)]
[string][ValidatePattern("^(http|https)\\://*")]$Url,
[Parameter(
Position = 1,
Mandatory = $False,
ParameterSetName = 'defaultcred')]
[switch]$UseDefaultCredentials,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[string]$Proxy,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[Int]$Timeout,
[Parameter(
Mandatory = $False,
ParameterSetName = 'altcred')]
[switch]$Credential
)
Begin {
$psBoundParameters.GetEnumerator() | % {
Write-Verbose "Parameter: $_"
}
#Create the initial WebRequest object using the given url
Write-Verbose "Creating the web request object"
$webRequest = [net.WebRequest]::Create($url)
#Use Proxy address if specified
If ($PSBoundParameters.ContainsKey('Proxy')) {
#Create Proxy Address for Web Request
Write-Verbose "Creating proxy address and adding into Web Request"
$webRequest.Proxy = New-Object -TypeName Net.WebProxy($proxy,$True)
}
#Set timeout
If ($PSBoundParameters.ContainsKey('TimeOut')) {
#Setting the timeout on web request
Write-Verbose "Setting the timeout on web request"
$webRequest.Timeout = $timeout
}
#Determine if using Default Credentials
If ($UseDefaultCredentials) {
#Set to True, otherwise remains False
Write-Verbose "Using Default Credentials"
$webrequest.UseDefaultCredentials = $True
}
#Determine if using Alternate Credentials
If ($Credential) {
#Prompt for alternate credentals
Write-Verbose "Prompt for alternate credentials"
$wc.Credential = (Get-Credential).GetNetworkCredential()
}
#Set TimeStamp prior to attempting connection
$then = get-date
}
Process {
Try {
#Make connection to gather response from site
$response = $webRequest.GetResponse()
#If successful, get the date for comparison
$now = get-date
#Generate report
Write-Verbose "Generating report from website connection and response"
$report = @{
URL = $url
StatusCode = $response.Statuscode -as [int]
StatusDescription = $response.StatusDescription
ResponseTime = "$(($now - $then).totalseconds)"
WebServer = $response.Server
Size = $response.contentlength
}
}
Catch {
#Get timestamp of failed attempt
$now = get-date
#Put the current error into a variable for later use
$errorstring = "$($error[0])"
#Generate report
$report = @{
URL = $url
StatusCode = ([regex]::Match($errorstring,"\\b\\d{3}\\b")).value
StatusDescription = (($errorstring.split('\\)')[2]).split('.\\')[0]).Trim()
ResponseTime = "$(($now - $then).totalseconds)"
WebServer = $response.Server
Size = $response.contentlength
}
}
}
End {
#Display Report
New-Object PSObject -property $report
}
}
|
PowerShellCorpus/PoshCode/ExecutePowerShell.cmd.ps1
|
ExecutePowerShell.cmd.ps1
|
:: <#
copy %0 %0.ps1
PowerShell.exe -ExecutionPolicy Unrestricted -NoProfile -Command "$ErrorActionPreference = 'SilentlyContinue'; . %0.ps1; Remove-Item %0.ps1"
exit
:: #>
$ErrorActionPreference = 'Continue'
### Your PowerShell script goes below here.
### I've put a couple of lines as an example ...
ls | sort length -desc | select -first 5 | ft
ps | sort ws -desc | select -first 10 | ft
|
PowerShellCorpus/PoshCode/Get-User_4.ps1
|
Get-User_4.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/Set-Domain_2.ps1
|
Set-Domain_2.ps1
|
function Set-Domain {
param( [switch]$help,
[string]$domain=$(read-host "Please specify the domain to join"),
[System.Management.Automation.PSCredential]$credential = $(Get-Crdential)
)
$usage = "`$cred = get-credential `n"
$usage += "Set-AvaDomain -domain corp.avanade.org -credential `$cred`n"
if ($help) {Write-Host $usage;exit}
$username = $credential.GetNetworkCredential().UserName
$password = $credential.GetNetworkCredential().Password
$computer = Get-WmiObject Win32_ComputerSystem
$computer.JoinDomainOrWorkGroup($domain ,$password, $username, $null, 3)
}
|
PowerShellCorpus/PoshCode/Migrate UserFolder_1.ps1
|
Migrate UserFolder_1.ps1
|
param(
$RootFolder = "\\\\domain.local\\users",
$NewRootFolder = "\\\\domain.local\\users2",
$LogFolder = "c:\\Projects\\HomeDirs",
$NewSubFolders = @("Documents","Favorites","Desktop","Links","Contacts","BlaBla"),
[switch]$SetACL
)
$UserFolders = gci -Path $RootFolder | ?{$_.PSIsContainer}
$UserFolders | foreach-object -Process {
#create new homedrive
$NewUserFolder = $NewRootFolder + "\\" + $_.name
if ($SetACL){
#set ACL rules for new homedrive
$acl = Get-Acl $_.FullName
$Owner = New-Object System.Security.Principal.NTAccount("domain.local",$_.name)
$acl.SetOwner($Owner)
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule($_.Name,"Modify", "ContainerInherit, ObjectInherit", "None", "Allow")
$acl.AddAccessRule($rule)
}
#create required subfolders per homedrive
$NewSubFolders | foreach{New-Item -Path $($NewUserFolder + "\\" + $_) -type directory}
#build robocopy job per homedrive
$LogFile = $LogFolder + "\\" + $_.name + ".log"
$JobName = $_.name + "_RCsync"
$CommandString = "robocopy $($_.FullName) $($NewUserFolder + "\\Documents") /COPYALL /MIR /FFT /Z /Log+:$LogFile"
start-job -Scriptblock {invoke-Expression $input} -name $JobName -InputObject $CommandString
}
#Wait for all jobs
Get-Job | Wait-Job
#Get all job results
Get-Job | Receive-Job
|
PowerShellCorpus/PoshCode/Test-WebDAV_2.ps1
|
Test-WebDAV_2.ps1
|
function Test-WebDav ()
{
param ( $Url = "$( throw 'URL parameter is required.')" )
$xhttp = New-Object -ComObject msxml2.xmlhttp
$xhttp.open("OPTIONS", $url, $false)
$xhttp.send()
if ( $xhttp.getResponseHeader("DAV") ) { $true }
else { $false }
}
|
PowerShellCorpus/PoshCode/Get-FileHash.ps1
|
Get-FileHash.ps1
|
##############################################################################\n##\n## Get-FileHash\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\nGet the hash of an input file.\n\n.EXAMPLE\n\nGet-FileHash myFile.txt\nGets the hash of a specific file\n\n.EXAMPLE\n\ndir | Get-FileHash\nGets the hash of files from the pipeline\n\n.EXAMPLE\n\nGet-FileHash myFile.txt -Hash SHA1\nGets the has of myFile.txt, using the SHA1 hashing algorithm\n\n#>\n\nparam(\n ## The path of the file to check\n $Path,\n\n ## The algorithm to use for hash computation\n [ValidateSet("MD5", "SHA1", "SHA256", "SHA384", "SHA512")]\n $HashAlgorithm = "MD5"\n)\n\nSet-StrictMode -Version Latest\n\n## Create the hash object that calculates the hash of our file.\n$hashType = [Type] "System.Security.Cryptography.$HashAlgorithm"\n$hasher = $hashType::Create()\n\n## Create an array to hold the list of files\n$files = @()\n\n## If they specified the file name as a parameter, add that to the list\n## of files to process\nif($path)\n{\n $files += $path\n}\n## Otherwise, take the files that they piped in to the script.\n## For each input file, put its full name into the file list\nelse\n{\n $files += @($input | Foreach-Object { $_.FullName })\n}\n\n## Go through each of the items in the list of input files\nforeach($file in $files)\n{\n ## Skip the item if it is not a file\n if(-not (Test-Path $file -Type Leaf)) { continue }\n\n ## Convert it to a fully-qualified path\n $filename = (Resolve-Path $file).Path\n\n ## Use the ComputeHash method from the hash object to calculate\n ## the hash\n $inputStream = New-Object IO.StreamReader $filename\n $hashBytes = $hasher.ComputeHash($inputStream.BaseStream)\n $inputStream.Close()\n\n ## Convert the result to hexadecimal\n $builder = New-Object System.Text.StringBuilder\n $hashBytes | Foreach-Object { [void] $builder.Append($_.ToString("X2")) }\n\n ## Return a custom object with the important details from the\n ## hashing\n $output = New-Object PsObject -Property @{\n Path = ([IO.Path]::GetFileName($file));\n HashAlgorithm = $hashAlgorithm;\n HashValue = $builder.ToString()\n }\n\n $output\n}
|
PowerShellCorpus/PoshCode/Findup_11.ps1
|
Findup_11.ps1
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.IO;
namespace Findup
{
public class FileInfoExt
{
public FileInfoExt(FileInfo fi)
{
FI = fi;
}
public byte[] SHA512_1st1K;
public byte[] SHA512_All;
public FileInfo FI { get; private set; }
public bool Matched { get; set; }
}
class Recurse // Add FileInfoExt objects of files matching filenames, file specifications (E.G. *.txt), and in directories in pathRec, to returnList
{
private string dirPart;
private string filePart;
public void Recursive(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfoExt> returnList)
{
foreach (string d in pathRec)
{
Recursive(d, searchPattern, recursiveFlag, returnList);
}
return;
}
public void Recursive(string pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfoExt> returnList)
{
if (File.Exists(pathRec))
{
try
{
returnList.Add(new FileInfoExt(new FileInfo(pathRec)));
}
catch (Exception e)
{
Console.WriteLine("Add file error: " + e.Message);
}
}
else if (Directory.Exists(pathRec))
{
try
{
DirectoryInfo Dir = new DirectoryInfo(pathRec);
foreach (FileInfo addf in (Dir.GetFiles(searchPattern)))
{
returnList.Add(new FileInfoExt(addf));
}
}
catch (Exception e)
{
Console.WriteLine("Add files from Directory error: " + e.Message);
}
if (recursiveFlag == true)
{
try
{
Recursive((Directory.GetDirectories(pathRec)), searchPattern, recursiveFlag, returnList);
}
catch (Exception e)
{
Console.WriteLine("Add Directory error: " + e.Message);
}
}
}
else
{
try
{
filePart = Path.GetFileName(pathRec);
dirPart = Path.GetDirectoryName(pathRec);
}
catch (Exception e)
{
Console.WriteLine("Parse error on: " + pathRec);
Console.WriteLine(@"Make sure you don't end a directory with a \\ when using quotes. The console arg parser doesn't accept that.");
Console.WriteLine("Exception: " + e.Message);
return;
}
if (filePart.IndexOfAny(new char[] {'?','*'}) >= 0)
{
if ((dirPart == null) || (dirPart == ""))
dirPart = Directory.GetCurrentDirectory();
if (Directory.Exists(dirPart))
{
Recursive(dirPart, filePart, recursiveFlag, returnList);
return;
}
}
Console.WriteLine("Invalid file path, directory path, file specification, or program option specified: " + pathRec);
}
}
}
class Findup
{
const int HashLen = 512/8; // 64-byte hash for SHA512.
public static void Main(string[] args)
{
Console.WriteLine("Findup.exe v1.0 - use -help for usage information. Created in 2010 by James Gentile.");
Console.WriteLine(" ");
string[] paths = new string[0];
System.Boolean recurse = false;
System.Boolean delete = false;
System.Boolean noprompt = false;
System.Boolean b4b = false;
List<FileInfoExt> fs = new List<FileInfoExt>();
long bytesInDupes = 0; // bytes in all the duplicates
long numOfDupes = 0; // number of duplicate files found.
long bytesRec = 0; // number of bytes recovered.
long delFiles = 0; // number of files deleted.
int c = 0;
int i = 0;
string deleteConfirm;
for (i = 0; i < args.Length; i++)
{
if ((System.String.Compare(args[i], "-help", true) == 0) || (System.String.Compare(args[i], "-h", true) == 0))
{
Console.WriteLine("Usage: findup.exe <file/directory #1> <file/directory #2> ... <file/directory #N> [-recurse] [-delete] [-noprompt] [-b4b]");
Console.WriteLine(" ");
Console.WriteLine("Options: -help - displays this help infomration.");
Console.WriteLine(" -recurse - recurses through subdirectories when directories or file specifications (e.g. *.txt) are specified.");
Console.WriteLine(" -delete - deletes duplicates with confirmation prompt.");
Console.WriteLine(" -noprompt - when used with -delete option, deletes files without confirmation prompt.");
Console.WriteLine(" -b4b - do a byte-for-byte comparison, instead of SHA-512 hashing. Slower in some cases, faster in others, and most secure.");
Console.WriteLine(" ");
Console.WriteLine("Examples: findup.exe c:\\\\finances -recurse");
Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data -recurse -delete -noprompt");
Console.WriteLine(" findup.exe c:\\\\data .\\\\*.txt c:\\\\reports\\\\quarter.doc -recurse -b4b");
Console.WriteLine(" ");
return;
}
if (System.String.Compare(args[i], "-recurse", true) == 0)
{
recurse = true;
continue;
}
if (System.String.Compare(args[i], "-delete", true) == 0)
{
delete = true;
continue;
}
if (System.String.Compare(args[i], "-noprompt", true) == 0)
{
noprompt = true;
continue;
}
if (System.String.Compare(args[i], "-b4b", true) == 0)
{
b4b = true;
continue;
}
Array.Resize(ref paths, paths.Length + 1);
paths[c] = args[i];
c++;
}
if (paths.Length == 0)
{
Console.WriteLine("No files specified, try findup.exe -help");
return;
}
Recurse recurseMe = new Recurse();
recurseMe.Recursive(paths, "*.*", recurse, fs);
if (fs.Count < 2)
{
Console.WriteLine("Findup.exe needs at least 2 files to compare. try findup.exe -help");
return;
}
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(salt); // get 512-bit SHA-512 salt.
for (i = 0; i < fs.Count; i++)
{
if (fs[i].Matched == true) // If file was already matched, then skip to next.
continue;
for (c = i + 1; c < fs.Count; c++)
{
if (fs[c].Matched == true) // skip already matched inner loop files.
continue;
if (fs[i].FI.Length != fs[c].FI.Length) // If file size matches, then check hash.
continue;
if (System.String.Compare(fs[i].FI.FullName, fs[c].FI.FullName, true) == 0) // don't count the same file as a match.
continue;
if (fs[i].SHA512_1st1K == null) // check/hash first 1K first.
if (Compute1KHash(fs[i]) == false)
continue;
if (fs[c].SHA512_1st1K == null)
if (Compute1KHash(fs[c]) == false)
continue;
if (CompareBytes(fs[i].SHA512_1st1K, fs[c].SHA512_1st1K) == false) // if the 1st 1K has the same hash..
continue;
if (b4b == true) // byte for byte comparison specified?
{
if (B4b(fs[i].FI.FullName, fs[c].FI.FullName) == false) // call the byte for byte comparison function
continue;
}
else if (fs[i].FI.Length > 1024) // skip hashing the file again if < 1024 bytes.
{
if (fs[i].SHA512_All == null) // check/hash the rest of the files.
if (ComputeFullHash(fs[i]) == false)
continue;
if (fs[c].SHA512_All == null)
if (ComputeFullHash(fs[c]) == false)
continue;
if (CompareBytes(fs[i].SHA512_All, fs[c].SHA512_All) == false)
continue;
}
Console.WriteLine("Match : " + fs[i].FI.FullName);
Console.WriteLine("with : " + fs[c].FI.FullName);
fs[c].Matched = true; // do not check or match against this file again.
numOfDupes++; // increase count of matches.
bytesInDupes += fs[c].FI.Length; // accumulate number of bytes in duplicates.
if (delete != true) // if delete is specified, try to delete the duplicate file.
continue;
if (noprompt == false)
{
Console.Write("Delete the duplicate file <Y/n>?");
deleteConfirm = Console.ReadLine();
if ((deleteConfirm[0] != 'Y') && (deleteConfirm[0] != 'y')) // if user typed 'Y' then delete the file.
continue;
}
try
{
File.Delete(fs[c].FI.FullName);
Console.WriteLine("Deleted: " + fs[c].FI.FullName);
bytesRec += fs[c].FI.Length; // record bytes recovered.
delFiles++;
}
catch (Exception e)
{
Console.WriteLine("File delete error: " + e.Message);
}
}
}
Console.WriteLine(" ");
Console.WriteLine("Files checked : {0:N0}", fs.Count);
Console.WriteLine("Duplicate files : {0:N0}", numOfDupes);
Console.WriteLine("Duplicate bytes : {0:N0}", bytesInDupes);
Console.WriteLine("Duplicates deleted : {0:N0}", delFiles);
Console.WriteLine("Recovered bytes : {0:N0}", bytesRec);
return; // Exit after displaying statistics.
}
private static Boolean B4b(string path1, string path2)
{
try
{
using (var stream = File.OpenRead(path1))
{
using (var stream2 = File.OpenRead(path2))
{
while (stream.Position != stream.Length)
{
var length = stream.Read(largeBuf, 0, largeBuf.Length);
var length2 = stream2.Read(largeBuf2, 0, largeBuf2.Length);
if (length != length2)
return false;
if (CompareBytes(largeBuf, largeBuf2, length) == false)
return false;
}
}
}
return true;
}
catch (Exception e)
{
Console.WriteLine("Byte for Byte comparison failed: " + e.Message);
return false;
}
}
private static Boolean CompareBytes(byte[] byteArray1, byte[] byteArray2, int Len = HashLen)
{
int i = 0;
while (i < Len)
{
if (byteArray1[i] != byteArray2[i])
return false;
i++;
}
return true ;
}
private static readonly byte[] readBuf = new byte[1024];
private static readonly byte[] largeBuf = new byte[HashLen*200];
private static readonly byte[] largeBuf2 = new byte[HashLen*200];
private static readonly byte[] salt = new byte[HashLen];
private static bool Compute1KHash(FileInfoExt path)
{
try
{
using (var stream = File.OpenRead(path.FI.FullName))
{
var length = stream.Read(readBuf, 0, readBuf.Length);
var _SHA512 = SHA512.Create();
_SHA512.TransformBlock(salt, 0, salt.Length, null, 0);
_SHA512.TransformFinalBlock(readBuf, 0, length);
path.SHA512_1st1K = _SHA512.Hash;
return true;
}
}
catch (Exception e)
{
Console.WriteLine("Hash Error: " + e.Message);
path.Matched = true; // since the file error'ed out, don't check against it again.
return false;
}
}
private static bool ComputeFullHash(FileInfoExt path)
{
try
{
var _SHA512 = SHA512.Create();
_SHA512.TransformBlock(salt, 0, salt.Length, null, 0);
using (var stream = File.OpenRead(path.FI.FullName))
{
while (true)
{
var length = stream.Read(largeBuf, 0, largeBuf.Length);
if (stream.Position < stream.Length) // if not at end of file...
_SHA512.TransformBlock(largeBuf, 0, length, null, 0); // hash the buffer, and loop.
else
{
_SHA512.TransformFinalBlock(largeBuf, 0, length); // if at end of file, hash last time and end looping
break;
}
}
}
path.SHA512_All = _SHA512.Hash;
return true;
}
catch (Exception e)
{
Console.WriteLine("Hash error: " + e.Message);
path.Matched = true;
return false;
}
}
}
}
|
PowerShellCorpus/PoshCode/Get-ProcAddress.ps1
|
Get-ProcAddress.ps1
|
function Get-ProcAddress {
<#
.Synopsis
Returns the address of the desired Windows API function.
.Description
The Get-ProcAddress function returns the address of the desired Windows API
function. The technique used to get the address does not rely upon P/Invoke or
compiling C# code. GetProcAddress can be accessed through internal .NET methods
that are simply wrappers for native functions. The Microsoft.Win32.UnsafeNativeMethods
class exports GetProcAddress. This function indirectly access this internal class.
.Parameter Module
Specifies the module that exports the desired function
.Parameter Procedure
Specifies the name of the function whose address will be returned.
.Example
PS> Get-ProcAddress -Module kernel32.dll -Procedure LoadLibraryA
Description
-----------
Returns the address of LoadLibraryA in kernel32.dll.
.Outputs
System.IntPtr
Get-ProcAddress return the address of the function as an IntPtr. If the module or
function is not found, Get-ProcAddress will return [IntPtr]::Zero.
.Link
http://www.exploit-monday.com/
#>
Param (
[Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true)] [String] $Module,
[Parameter(Position = 1, Mandatory = $true)] [String] $Procedure
)
# Get a reference to System.dll in the GAC
$SystemAssembly = [AppDomain]::CurrentDomain.GetAssemblies() |
Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\\\')[-1].Equals('System.dll') }
$UnsafeNativeMethods = $SystemAssembly.GetType('Microsoft.Win32.UnsafeNativeMethods')
# Get a reference to the GetModuleHandle and GetProcAddress methods
$GetModuleHandle = $UnsafeNativeMethods.GetMethod('GetModuleHandle')
$GetProcAddress = $UnsafeNativeMethods.GetMethod('GetProcAddress')
# Get a handle to the module specified
$Kern32Handle = $GetModuleHandle.Invoke($null, @($Module))
$tmpPtr = New-Object IntPtr
$HandleRef = New-Object System.Runtime.InteropServices.HandleRef($tmpPtr, $Kern32Handle)
# Return the address of the function
return $GetProcAddress.Invoke($null, @([System.Runtime.InteropServices.HandleRef]$HandleRef, $Procedure))
}
|
PowerShellCorpus/PoshCode/Set Logfile length_5.ps1
|
Set Logfile length_5.ps1
|
<#
.SYNOPSIS
Set any text file to a fixed number of lines. Use 'Get-Help .\\SetFileLines
-full' to view Help for this file.
.DESCRIPTION
This script will maintain the PS Transcript file (default setting), or any
text file, at a fixed length, ie matching the number of lines entered.
However, omitting the lines parameter will just remove any blank lines; and
using the -Blanks switch will remove blanks from the desired length. Can be
included in $profile.
.EXAMPLE
Set-FileLines -File c:\\Scripts\\anyfile.txt
Remove all blank lines from the file 'anyfile.txt'.
.EXAMPLE
Set-FileLines 1500 -Blanks
This will set the file length of 'Transcript.txt' to 1500 lines and also
remove all blank lines.
.EXAMPLE
Set-FileLines
Remove any blank lines from the default file 'Transcript.txt'.
.NOTES
The 'Lines' property returned by '(Get-Content $file | Measure-Object -line)'
excludes any blank lines so the resulting calculated totals may not be 100%
accurate.
The author can be contacted via www.SeaStarDevelopment.Bravehost.com
V2.1 Use 'Switch -regex' instead of 'Get-Content | foreach', 22 Dec 2011.
#>
Param ([int] $lines = 0,
[String]$file = "$pwd\\Transcript.txt",
[Switch]$blanks)
if ($file -notlike "*.txt") {
[System.Media.SystemSounds]::Hand.Play()
Write-Warning "This script can only process .txt files"
exit 1
}
if (!(Test-Path $file)) {
[System.Media.SystemSounds]::Hand.Play()
Write-Warning "File $file does not exist - please enter valid filename."
exit 1
}
[int]$count = 0
[int]$blankLines = 0
$encoding = 'Default'
$errorActionPreference = 'SilentlyContinue'
if ($lines -eq 0) { #A value of 0 lines will just remove blanks.
[int]$extra = 1
[int]$count = 1
[switch]$blanks = $true #Otherwise no blanks will be deleted below.
}
else {
$fileLength = (Get-Content $file | Measure-Object -line)
[int]$extra = $fileLength.Lines - $lines #Number of lines to remove.
} #Note: $fileLength.Lines excludes any blank lines, so not 100% accurate.
if ($extra -gt 0) {
$fileLength = $null
$date = "{0:G}" -f [DateTime]::Now
Write-Output "$date Starting maintenance on file <$file>"
$tempfile = [IO.Path]::GetTempFileName()
if ($file -like "*transcript*.txt") {
$encoding = 'Unicode'
Stop-Transcript | Out-Null
$status = $? # $true if we are running transcript.
}
switch -regex -file $file {
{ $count -lt $extra } { $count++; continue}
'^\\s*$' { if ($blanks) {
$blankLines++
continue
}
$_ | Out-File $tempFile -encoding $encoding -Append -Force
} #End blank line.
default { $_ | Out-File $tempFile -encoding $encoding -Append -Force }
} #End switch
Remove-Item $file -Force #File in use by another process.
if (!$?) {
[System.Media.SystemSounds]::Hand.Play()
Write-Warning "$($error[0]) Application terminating."
Remove-Item $tempfile
$ErrorActionPreference = 'Continue'
exit 2
}
Move-Item $tempfile -Destination $file -Force
if ($lines -eq 0) { #Only interested in blank lines here.
$tag = "$blankLines blank lines removed."
}
elseIf ($blanks) {
$tag = "$extra lines removed (+ $blankLines blank)."
}
else {
$tag = "$extra lines removed."
}
if (($file -like "*transcript.txt") -and $status) {
Start-Transcript -append -path $file -force | Out-Null
}
Write-Output "Maintenance of file completed: $tag"
}
else {
Write-Output "[$file] Filesize ($($FileLength.Lines) lines) is below minimum; no lines removed."
}
$ErrorActionPreference = 'Continue'
|
PowerShellCorpus/PoshCode/Powershell iTunes_1.ps1
|
Powershell iTunes_1.ps1
|
#
#*****************************************************************
#
# Powershell iTunes v1 $Rev: 754 $
# (c) 2004-2010 Thomas Maurer. All rights reserved.
# created by Thomas Maurer
#
# http://www.thomasmaurer.ch
# http://www.thomasmaurer.ch/projects
#
# last Update by $Author: tmaurer $ on $Date: 2010-11-24 07:50:06 +0100 (Mi, 24 Nov 2010) $
#
# Version 1.0.1
#
#*****************************************************************
#
# Welcome
Write-Host " " -BackgroundColor Black -ForegroundColor White
Write-Host " ____ __ ____ " -BackgroundColor Black -ForegroundColor White
Write-Host " / __ \\____ _ _____ __________/ /_ ___ / / / " -BackgroundColor Black -ForegroundColor White
Write-Host " / /_/ / __ \\ | /| / / _ \\/ ___/ ___/ __ \\/ _ \\/ / / " -BackgroundColor Black -ForegroundColor White
Write-Host " / ____/ /_/ / |/ |/ / __/ / (__ ) / / / __/ / / " -BackgroundColor Black -ForegroundColor White
Write-Host "/_/ \\____/|__/|__/\\___/_/ /____/_/ /_/\\___/_/_/ " -BackgroundColor Black -ForegroundColor White
Write-Host " " -BackgroundColor Black -ForegroundColor White
Write-Host " _ ______ " -BackgroundColor Black -ForegroundColor White
Write-Host " (_)_ __/_ ______ ___ _____ " -BackgroundColor Black -ForegroundColor White
Write-Host " / / / / / / / / __ \\/ _ \\/ ___/ " -BackgroundColor Black -ForegroundColor White
Write-Host " / / / / / /_/ / / / / __(__ ) " -BackgroundColor Black -ForegroundColor White
Write-Host "/_/ /_/ \\__,_/_/ /_/\\___/____/ " -BackgroundColor Black -ForegroundColor White
Write-Host " " -BackgroundColor Black -ForegroundColor White
Write-Host "******************************************************************" -BackgroundColor Black -ForegroundColor White
Write-Host " " -BackgroundColor Black -ForegroundColor White
Write-Host " Welcome to the Powershell iTunes " -BackgroundColor Black -ForegroundColor White
Write-Host " " -BackgroundColor Black -ForegroundColor White
Write-Host " (c) 2010 Thomas Maurer www.thomasmaurer.ch/projects " -BackgroundColor Black -ForegroundColor White
Write-Host " " -BackgroundColor Black -ForegroundColor White
Write-Host "******************************************************************" -BackgroundColor Black -ForegroundColor White
Write-Host " " -BackgroundColor Black -ForegroundColor White
Write-Host " for Help use the Get-PSiTunesHelp " -BackgroundColor Black -ForegroundColor White
Write-Host " " -BackgroundColor Black -ForegroundColor White
# Add ComObjects to $iTunes
$iTunes = New-Object -ComObject iTunes.Application
# Function to start itunes
function Start-iTunes {
process {
$iTunesRunning = Get-Process | Where-Object {$_.ProcessName -eq "iTunes"}
if(!$iTunesRunning) {
$script:iTunes = New-Object -ComObject iTunes.Application
Write-Host "(PS iTunes): iTunes started" -BackgroundColor Black -ForegroundColor green
}
else {
Write-Host "(PS iTunes): iTunes allready running" -BackgroundColor Black -ForegroundColor red
}
}
}
# Function to close itunes
function Close-iTunes {
process {
$iTunesRunning = Get-Process | Where-Object {$_.ProcessName -eq "iTunes"}
if(!$iTunesRunning) {
Write-Host "(PS iTunes): iTunes not running" -BackgroundColor Black -ForegroundColor red
}
else {
Stop-Process $iTunesRunning.Id
Write-Host "(PS iTunes): iTunes closed" -BackgroundColor Black -ForegroundColor red
}
}
}
# Function to play a song
function Play-Track {
process {
if ($iTunes.Playerstate -eq "0"){
$iTunes.Play()
Write-Host "(PS iTunes): Now playing:" $iTunes.CurrentTrack.Name "from" $iTunes.CurrentTrack.Artist -BackgroundColor Black -ForegroundColor green
}
else {
Write-Host "(PS iTunes): Already playing Track:" $iTunes.CurrentTrack.Name "from" $iTunes.CurrentTrack.Artist -BackgroundColor Black -ForegroundColor red
}
}
}
# Function to stop a song
function Pause-Track {
process {
if ($iTunes.Playerstate -eq "1"){
$iTunes.Pause()
Write-Host "(PS iTunes): iTunes paused" -BackgroundColor Black -ForegroundColor Red
}
else {
Write-Host "(PS iTunes): Not playing any track" -BackgroundColor Black -ForegroundColor red
}
}
}
# Function to resume a song
function Resume-Track {
process {
if ($iTunes.Playerstate -eq "0"){
$iTunes.Play()
Write-Host "(PS iTunes): Now playing:" $iTunes.CurrentTrack.Name "from" $iTunes.CurrentTrack.Artist -BackgroundColor Black -ForegroundColor green
}
else {
Write-Host "(PS iTunes): Already playing Track:" $iTunes.CurrentTrack.Name "from" $iTunes.CurrentTrack.Artist -BackgroundColor Black -ForegroundColor red
}
}
}
# Function to go a song back
function Back-Track {
process {
$iTunes.BackTrack()
Write-Host "(PS iTunes): Now playing:" $iTunes.CurrentTrack.Name "from" $iTunes.CurrentTrack.Artist -BackgroundColor Black -ForegroundColor green
}
}
# Function to go to the next
function Next-Track {
process {
$iTunes.NextTrack()
Write-Host "(PS iTunes): Now playing:" $iTunes.CurrentTrack.Name "from" $iTunes.CurrentTrack.Artist -BackgroundColor Black -ForegroundColor green
}
}
# Function to get infos about the current track
function Get-CurrentTrack {
process {
Write-Host "(PS iTunes): Currently playing:" $iTunes.CurrentTrack.Name "from" $iTunes.CurrentTrack.Artist -BackgroundColor Black -ForegroundColor White
}
}
# Function to mute itunes
function Mute-iTunes {
process {
if($itunes.Mute -eq $false) {
$itunes.Mute = $true
Write-Host "(PS iTunes): iTunes muted" -BackgroundColor Black -ForegroundColor Red
}
else {
Write-Host "(PS iTunes): iTunes already muted" -BackgroundColor Black -ForegroundColor red
}
}
}
# Function to unmute itunes
function Unmute-iTunes {
process {
if($itunes.Mute -eq $true) {
$itunes.Mute = $false
Write-Host "(PS iTunes): iTunes unmuted" -BackgroundColor Black -ForegroundColor green
}
else {
Write-Host "(PS iTunes): iTunes already unmuted" -BackgroundColor Black -ForegroundColor red
}
}
}
# Function to set iTunes volume up
function Set-VolumeUP {
process {
if($iTunes.SoundVolume -lt 100) {
$iTunes.SoundVolume = $iTunes.SoundVolume + 2
Write-Host "(PS iTunes): iTunes Volume" $iTunes.SoundVolume -BackgroundColor Black -ForegroundColor green
}
else {
Write-Host "(PS iTunes): iTunes Volume is already 100%" -BackgroundColor Black -ForegroundColor red
}
}
}
# Function to set iTunes volume down
function Set-VolumeDown {
process {
if($iTunes.SoundVolume -gt 0) {
$iTunes.SoundVolume = $iTunes.SoundVolume - 2
Write-Host "(PS iTunes): iTunes Volume" $iTunes.SoundVolume -BackgroundColor Black -ForegroundColor red
}
else {
Write-Host "(PS iTunes): iTunes Volume is already 0%" -BackgroundColor Black -ForegroundColor red
}
}
}
# Function to set iTunes
function Set-Volume {
param (
[int]$Volume
)
process {
if($Volume -ge 0 -and $Volume -le 100) {
$iTunes.SoundVolume = $Volume
Write-Host "(PS iTunes): iTunes Volume" $iTunes.SoundVolume -BackgroundColor Black -ForegroundColor green
}
else {
Write-Host "(PS iTunes): Volume has to be 0-100" -BackgroundColor Black -ForegroundColor red
}
}
}
# Function to show the Version of iTunes
function Show-iTunesVersion {
process {
Write-Host "(PS iTunes): iTunes Version" $iTunes.version -BackgroundColor Black -ForegroundColor White
}
}
# Function to show the Version of iTunes
function get-PSiTunesHelp {
process {
Write-Host " "
Write-Host " Powershell iTunes Help"
Write-Host " "
Write-Host "********************************************************"
Write-Host " "
Write-Host " Commands"
Write-Host " "
Write-Host " Start-iTunes Starts iTunes"
Write-Host " Close-iTunes Closes iTunes"
Write-Host " Play-Track Plays a iTunes Track"
Write-Host " Pause-Track Pauses a iTunes Track"
Write-Host " Resume-Track Resumes a iTunes Track"
Write-Host " Back-Track Go to the last iTunes Track"
Write-Host " Next-Track Plays next iTunes Track"
Write-Host " Mute-Track Mutes iTunes"
Write-Host " Unmute-Track Unmutes iTunes"
Write-Host " Show-iTunesVersion Shows iTunes Version"
Write-Host " Set-VolumeDown Set Volume Down"
Write-Host " Set-VolumeUp Set Volume Up"
Write-Host " Set-Volume Set iTunes Volume (0-100)"
}
}
|
PowerShellCorpus/PoshCode/Deploy Folder .ps1
|
Deploy Folder .ps1
|
Add-PSSnapin Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue #This is needed to pull computers from AD
Clear-Host
$Skipped = @() #Create Array for Skipped Computers
$Finished = @() #Create Array for Finished Computers
$Offline = @() #Create Array for Offline Computers
$Computers = Get-QADComputer -SearchScope Subtree -SearchRoot "OU=Workstations,DC=ins-lua,dc=com" #Get Computers from AD
FOREACH ($Computer in $Computers) #Process Computers
{
$ObjComputerName = New-Object PSObject
$ObjComputerName = $Computer.name
$System = $ObjComputerName
IF (Test-Connection -ComputerName $System -Quiet -Count 1) #Tests to see if computer is online
{
IF (Test-Path "\\\\$System\\C$\\Users\\Public") #This would indicate Windows 7 OR Vista
{
Copy-Item -Path "C:\\Users\\Public\\Training" -Destination "\\\\$System\\C$\\Users\\Public" -Recurse -Force
Write-Host "Finished Win7 System $System"
$Finished += $System
}
ELSE
{
IF (Test-Path "\\\\$System\\C$\\Documents and Settings\\All Users")
{
Copy-Item -Path "C:\\Users\\Public\\Training" -Destination "\\\\$System\\C$\\Documents and Settings\\All Users" -Recurse -Force
Write-Host "Finished WinXP System $System"
$Finished += $System
}
}
}
ELSE
{
$Skipped += $System
}
}
FOREACH ($System in $Skipped) #Process Skipped Computers
{
IF (Test-Connection -ComputerName $System -Quiet -Count 1)
{
IF (Test-Path "\\\\$System\\C$\\Users\\Public")
{
Copy-Item -Path "C:\\Users\\Public\\Training" -Destination "\\\\$System\\C$\\Users\\Public" -Recurse -Force
Write-Host "Finished Win7 System $System"
$Finished += $System
}
ELSE
{
IF (Test-Path "\\\\$System\\C$\\Documents and Settings\\All Users")
{
Copy-Item -Path "C:\\Users\\Public\\Training" -Destination "\\\\$System\\C$\\Documents and Settings\\All Users" -Recurse -Force
Write-Host "Finished WinXP System $System"
$Finished += $System
}
}
}
ELSE
{
$Offline +=$System
}
}
Write-Host "Offline Systems: $Offline"
Write-Host "Finished Systems: $Finished"
|
PowerShellCorpus/PoshCode/TabExpansion for V2CTP_7.ps1
|
TabExpansion for V2CTP_7.ps1
|
## Tab-Completion
#################
## For V2CTP3.
## This won't work on V1 and V2CTP and V2CTP2.
## Please dot souce this script file.
## In first loading, it may take a several minutes, in order to generate ProgIDs and TypeNames list.
##
## What this can do is:
##
## [datetime]::n<tab>
## [datetime]::now.d<tab>
## $a = New-Object "Int32[,]" 2,3; $b = "PowerShell","PowerShell"
## $c = [ref]$a; $d = [ref]$b,$c
## $d[0].V<tab>[0][0].Get<tab>
## $d[1].V<tab>[0,0].tos<tab>
## $function:a<tab>
## $env:a<tab>
## [System.Type].a<tab>
## [datetime].Assembly.a<tab>
## ).a<tab> # shows System.Type properties and methods...
## #native command name expansion
## fsu<tab>
## #command option name expansion (for fsutil ipconfig net powershell only)
## fsutil <tab>
## ipconfig <tab>
## net <tab>
## powershell <tab>
## #TypeNames and Type accelerators expansion
## [Dec<tab>
## [system.Man<tab>.auto<tab>.p<tab>
## New-Object -TypeName IO.Dir<tab>
## New-Object System.win<tab>.for<tab>.bu<tab>
## #ProgIDs expansion
## New-Object -Com shel<tab>
## #Enum option expansion
## Set-ExecutionPolicy <tab>
## Set-ExecutionPolicy All<tab>
## Set-ExcusionPolisy -ex <tab>
## Get-TraceSource Inte<tab>
## iex -Errora <tab> -wa Sil<tab>
## #WmiClasses expansion
## Get-WmiObject -class Win32_<tab>
## gwmi __Instance<tab>
## #Encoding expansion
## [Out-File | Export-CSV | Select-String | Export-Clixml] -enc <tab>
## [Add-Content | Get-Content | Set-Content} -Encoding Big<tab>
## #PSProvider name expansion
## [Get-Location | Get-PSDrive | Get-PSProvider | New-PSDrive | Remove-PSDrive] -PSProvider <tab>
## Get-PSProvider <tab>
## pwd -psp al<tab>
## #PSDrive name expansion
## [Get-PSDrive | New-PSDrive | Remove-PSDrive] [-Name] <tab>
## Get-PSDrive <tab>
## pwd -psd <tab>
## #PSSnapin name expansion
## [Add-PSSnapin | Get-PSSnapin | Remove-PSSnapin ] [-Name] <tab>
## Get-Command -PSSnapin <tab>
## Remove-PSSnapin <tab>
## Get-PSSnapin M<tab>
## #Eventlog name and expansion
## Get-Eventlog -Log <tab>
## Get-Eventlog w<tab>
## #Eventlog's entrytype expansion
## Get-EventLog -EntryType <tab>
## Get-EventLog -EntryType Er<tab>
## Get-EventLog -Ent <tab>
## #Service name expansion
## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-Name] <tab>
## New-Service -DependsOn <tab>
## New-Service -Dep e<tab>
## Get-Service -n <tab>
## Get-Service <tab>,a<tab>,p<tab>
## gsv <tab>
## #Service display name expansion
## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-DisplayName] <tab>
## Get-Service -Dis <tab>
## gsv -Dis <tab>,w<tab>,b<tab>
## #Cmdlet and Topic name expansion (this also support default help function and man alias)
## Get-Help [-Name] about_<tab>
## Get-Help <tab>
## #Category name expansion (this also support default help function and man alias)
## Get-Help -Category c<tab>,<tab>
## #Command name expansion
## Get-Command [-Name] <tab>
## Get-Command -Name <tab>
## gcm a<tab>,<tab>
## #Scope expansion
## [Clear-Variable | Export-Alias | Get-Alias | Get-PSDrive | Get-Variable | Import-Alias
## New-Alias | New-PSDrive | New-Variable | Remove-Variable | Set-Alias | Set-Variable] -Scope <tab>
## Clear-Variable -Scope G<tab>
## Set-Alias -s <tab>
## #Process name expansion
## [Get-Process | Stop-Process] [-Name] <tab>
## Stop-Process -Name <tab>
## Stop-Process -N pow<tab>
## Get-Process <tab>
## ps power<tab>
## #Trace sources expansion
## [Trace-Command | Get-TraceSource | Set-TraceSource] [-Name] <tab>,a<tab>,p<tab>
## #Trace -ListenerOption expansion
## [Set-TraceSource | Trace-Command] -ListenerOption <tab>
## Set-TraceSource -Lis <tab>,n<tab>
## #Trace -Option expansion
## [Set-TraceSource | Trace-Command] -Option <tab>
## Set-TraceSource -op <tab>,con<tab>
## #ItemType expansion
## New-Item -Item <tab>
## ni -ItemType d<tab>
## #ErrorAction and WarningAction option expansion
## CMDLET [-ErrorAction | -WarningAction] <tab>
## CMDLET -Errora s<tab>
## CMDLET -ea con<tab>
## CMDLET -wa <tab>
## #Continuous expansion with comma when parameter can treat multiple option
## # if there are spaces, occur display bug in the line
## # if strings contains '$' or '-', not work
## Get-Command -CommandType <tab>,<tab><tab>,cm<tab>
## pwd -psp <tab>,f<tab>,va<tab>
## Get-EventLog -EntryType <tab>,i<tab>,s<tab>
## #Enum expansion in method call expression
## # this needs one or more spaces after left parenthesis or comma
## $str = "day night"
## $str.Split( " ",<space>rem<tab>
## >>> $str.Split( " ", "RemoveEmptyEntries" ) <Enter> ERROR
## $str.Split( " ", "RemoveEmptyEntries" -as<space><tab>
## >>> $str.Split( " ", "RemoveEmptyEntries" -as [System.StringSplitOptions] ) <Enter> Success
## $type = [System.Type]
## $type.GetMembers(<space>Def<tab>
## [IO.Directory]::GetFiles( "C:\\", "*",<space>All<tab>
## # this can do continuous enum expansion with comma and no spaces
## $type.GetMembers( "IgnoreCase<comma>Dec<tab><comma>In<tab>"
## [IO.Directory]::GetAccessControl( "C:\\",<space>au<tab><comma>ac<tab><comma>G<tab>
## #Better '$_.' expansion when cmdlet output objects or method return objects
## ls |group { $_.Cr<tab>.Tost<tab>"y")} | tee -var foo| ? { $_.G<tab>.c<tab> -gt 5 } | % { md $_.N<tab> ; copy $_.G<tab> $_.N<tab> }
## [IO.DriveInfo]::GetDrives() | ? { $_.A<tab> -gt 1GB }
## $Host.UI.RawUI.GetBufferContents($rect) | % { $str += $_.c<tab> }
## gcm Add-Content |select -exp Par<tab>| select -ExpandProperty Par<tab> | ? { $_.Par<tab>.N<tab> -eq "string" }
## $data = Get-Process
## $data[2,4,5] | % { $_.<tab>
## #when Get-PipeLineObject failed, '$_.' shows methods and properties name of FileInfo and String and Type
## #Property name expansion by -Property parameter
## [ Format-List | Format-Custom | Format-Table | Format-Wide | Compare-Object |
## ConvertTo-Html | Measure-Object | Select-Object | Group-Object | Sort-Object ] [-Property] <tab>
## Select-Object -ExcludeProperty <tab>
## Select-Object -ExpandProperty <tab>
## gcm Get-Acl|select -exp Par<tab>
## ps |group na<tab>
## ls | ft A<tab>,M<tab>,L<tab>
## #Hashtable key expansion in the variable name and '.<tab>'
## Get-Process | Get-Unique | % { $hash += @{$_.ProcessName=$_} }
## $hash.pow<tab>.pro<tab>
## #Parameter expansion for function, filter and script
## man -f<tab>
## 'param([System.StringSplitOptions]$foo,[System.Management.Automation.ActionPreference]$bar,[System.Management.Automation.CommandTypes]$baz) {}' > foobar.ps1
## .\\foobar.ps1 -<tab> -b<tab>
## #Enum expansion for function, filter and scripts
## # this can do continuous enum expansion with comma and no spaces
## .\\foobar.ps1 -foo rem<tab> -bar <tab><comma>c<tab><comma>sc<tab> -ea silent<tab> -wa con<tab>
## #Enum expansion for assignment expression
## #needs space(s) after '=' and comma
## #strongly-typed with -as operator and space(s)
## $ErrorActionPreference =<space><tab>
## $cmdtypes = New-Object System.Management.Automation.CommandTypes[] 3
## $cmdtypes =<space><tab><comma><space>func<tab><comma><space>cmd<tab> -as<space><tab>
## #Path expansion with variable and '\\' or '/'
## $PWD\\../../<tab>\\<tab>
## "$env:SystemDrive/pro<tab>/<tab>
## #Operator expansion which starts with '-'
## "Power","Shell" -m<tab> "Power" -r<tab> '(Pow)(er)','$1d$2'
## 1..9 -co<tab> 5
## #Keyword expansion
## fu<tab> test { p<tab> $foo, $bar ) b<tab> "foo" } pr<tab> $_ } en<tab> "$bar" } }
## #Variable name expansion (only global scope)
## [Clear-Variable | Get-Variable | New-Variable | Remove-Variable | Set-Variable] [-Name] <tab>
## [Cmdlet | Function | Filter | ExternalScript] -ErrorVariable <tab>
## [Cmdlet | Function | Filter | ExternalScript] -OutVariable <tab>
## Tee-Object -Variable <tab>
## gv pro<tab>,<tab>
## Remove-Variable -Name out<tab>,<tab>,ps<tab>
## ... | ... | tee -v <tab>
## #Alias name expansion
## [Get-Alias | New-Alias | Set-Alias] [-Name] <tab>
## Export-Alias -Name <tab>
## Get-Alias i<tab>,e<tab>,a<tab>
## epal -n for<tab>
## #Property name expansion with -groupBy parameter
## [Format-List | Format-Custom | Format-Table | Format-Wide] -groupBy <tab>
## ps | ft -g <tab>
## gcm | Format-Wide -GroupBy Par<tab>
## #Type accelerators expansion with no charactors
## [<tab>
## New-Object -typename <tab>
## New-Object <tab>
## # File glob expansion with '@'
## ls *.txt@<tab>
## ls file.txt, foo1.txt, 'bar``[1``].txt', 'foo bar .txt' # 1 <tab> expanding with comma
## ls * -Filter *.txt # 2 <tab> refactoring
## ls *.txt # 3 <tab> (or 1 <tab> & 1 <shift>+<tab>) return original glob pattern
## This can also use '^'(hat) or '~'(tilde) for Excluding
## ls <hat>*.txt@<tab>
## ls foo.ps1, 'bar``[1``].xml' # 1 <tab> expanding with comma
## ls * -Filter * -Excluding *.txt # 2 <tab> refactoring
## *.txt<tilde>foo*<tilde>bar*@<tab>
## ls file.txt # 1 <tab> expanding with comma
## ls * -Filter *.txt -Excluding foo*, bar* # 2 <tab> refactoring
## # Ported history expansion from V2CTP3 TabExpansion with '#' ( #<pattern> or #<id> )
## ls * -Filter * -Excluding foo*, bar*<Enter>
## #ls<tab>
## #1<tab>
## # Command buffer stack with ';'(semicolon)
## ls * -Filter * -Excluding foo*, bar*<semicolon><tab> # push command1
## echo "PowerShell"<semicolon><tab> # push command2
## get-process<semicolon><tab> # push command3
## {COMMAND}<Enter> # execute another command
## get-process # Auto pop command3 from stack by LIFO
## This can also hand-operated pop with ';,'(semicolon&comma) or ';:'(semicolon&colon)
## get-process; <semicolon><comma><tab>
## get-process; echo "PowerShell" # pop command2 from stack by LIFO
## # Function name expansion after 'function' or 'filter' keywords
## function cl<tab>
## #Switch syntax option expansion
## switch -w<tab> -f<tab>
## #Better powershell.exe option expansion with '-'
## powershell -no<tab> -<tab> -en<tab>
## #A part of PowerShell attributes expansion ( CmdletBinding, Parameter, Alias, Validate*, Allow* )
## [par<tab>
## [cmd<tab>
## #Member expansion for CmdletBinding and Parameter attributes
## [Parameter(man<tab>,<tab>1,val<tab>$true)]
## [CmdletBinding( <tab>"foo", su<tab>$true)]
## #Several current date/time formats with Ctrl+D
## <Ctrl+D><tab><tab><tab><tab><tab>...
## #Hand-operated pop from command buffer with Ctrl+P (this is also available with ';:' or ';,')
## <command>;<tab> # push command
## <Ctrl+D><tab> # pop
## #Paste clipboard with Ctrl+V
## <Ctrl+V><tab>
## # Cut current line with Ctrl+X
## <command><Ctrl+X><tab>
## # Cut words with a charactor after Ctrl+X until the charactor
## 1: PS > dir -Filter *.txt<Ctrl+X>-<tab> # Cut words until '-'
## 2: PS > dir -
## 3: PS > dir -<Ctrl+V><tab> # Paste words that were copyed now
## # Cut last word in current line with Ctrl+Z
## 1: PS > Get-ChildItem *.txt<Ctrl+Z><tab> # Cut last word in current line
## 2: PS > Get-ChildItem
## 3: PS > Get-ChildItem -Exclude <Ctrl+V><tab> # Paste last word that was copyed now
## #[ScriptBlock] member expansion for [ScriptBlock] literal
## { 1+1 }.inv<tab>
## #Help document's section name expansion at a line that has only spaces
## .syn<tab>
## .func<tab>
## #A part of history commands expansion with Ctrl+L (using split(";"),split("|"),split(";|") )
## ls -Force -Recurse -Filter *.txt | ? { $_.LastWriteTime -lt [DateTime]::Today } ; echo PowerShell
## ls<Ctrl+L><tab><tab>
## ?<Ctrl+L><tab><tab>
## ec<Ctrl+L><tab>
## # Now command name expansion's priority is,
## alias -> function -> filter -> cmdlet -> script -> external command
## # PSDrive and item name expansion in variable notation
## ${fu<tab>
## ${function:cl<tab>
## ${c:*<tab>\\*<tab>
## ${c:\\win<tab>/sys<tab>/<tab>
### Generate ProgIDs list...
if ( Test-Path $PSHOME\\ProgIDs.txt )
{
$_ProgID = type $PSHOME\\ProgIDs.txt -ReadCount 0
}
else
{
$_HKCR = [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\")
$_ProgID = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) )
foreach ( $_subkey in $_HKCR.GetSubKeyNames() )
{
foreach ( $_i in [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\$_subkey\\ProgID") )
{
if ($_i -ne $null)
{
$_ProgID.Add($_i.GetValue(""))
}
}
}
'$_ProgID was updated...' | Out-Host
$_ProgID = $_ProgID|sort -Unique
Set-Content -Value $_ProgID -Path $PSHOME\\ProgIDs.txt -Verbose
}
### Generate TypeNames list...
if ( Test-Path $PSHOME\\TypeNames.txt )
{
$_TypeNames = type $PSHOME\\TypeNames.txt -ReadCount 0
}
else
{
$_TypeNames = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) )
foreach ( $_asm in [AppDomain]::CurrentDomain.GetAssemblies() )
{
foreach ( $_type in $_asm.GetTypes() )
{
$_TypeNames.Add($_type.FullName)
}
}
'$_TypeNames was updated...' | Out-Host
$_TypeNames = $_TypeNames | sort -Unique
Set-Content -Value $_TypeNames -Path $PSHOME\\TypeNames.txt -Verbose
}
if ( Test-Path $PSHOME\\TypeNames_System.txt )
{
$_TypeNames_System = type $PSHOME\\TypeNames_System.txt -ReadCount 0
}
else
{
$_TypeNames_System = $_TypeNames -like "System.*" -replace '^System\\.'
'$_TypeNames_System was updated...' | Out-Host
Set-Content -Value $_TypeNames_System -Path $PSHOME\\TypeNames_System.txt -Verbose
}
### Generate WMIClasses list...
if ( Test-Path $PSHOME\\WMIClasses.txt )
{
$_WMIClasses = type $PSHOME\\WMIClasses.txt -ReadCount 0
}
else
{
$_WMIClasses = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) )
foreach ( $_class in gwmi -List )
{
$_WMIClasses.Add($_class.Name)
}
$_WMIClasses = $_WMIClasses | sort -Unique
'$_WMIClasses was updated...' | Out-Host
Set-Content -Value $_WMIClasses -Path $PSHOME\\WMIClasses.txt -Verbose
}
[Reflection.Assembly]::LoadWithPartialName( "System.Windows.Forms" ) | Out-Null
$global:_cmdstack = New-Object Collections.Stack
$global:_snapin = $null
$global:_TypeAccelerators = [type]::gettype("System.Management.Automation.TypeAccelerators")::get.keys | sort
$global:_cmdline = New-Object Collections.ArrayList
iex (@'
function prompt {
h -Count 1 -OutVariable line |
% { $_.CommandLine.Split("|"); $_.CommandLine.Split(";"); $_.CommandLine.Split(";"); $_.CommandLine.Split(";|") } |
Get-Unique | ? { $_ -ne $line.CommandLine -and $_ -notmatch '^\\s*$' } |
% { $_.Trim(" ") } |
? { $global:_cmdline -notcontains $_ } | % { Set-CommandLine $_ | Out-Null }
if ($_cmdstack.Count -gt 0) {
$line = $global:_cmdstack.Pop() -replace '([[\\]\\(\\)+{}?~%])','{$1}'
[System.Windows.Forms.SendKeys]::SendWait($line)
}
'@ + @"
${function:prompt}
}
"@)
function Write-ClassNames ( $data, $i, $prefix='', $sep='.' )
{
$preItem = ""
foreach ( $class in $data -like $_opt )
{
$Item = $class.Split($sep)
if ( $preItem -ne $Item[$i] )
{
if ( $i+1 -eq $Item.Count )
{
if ( $prefix -eq "[" )
{
$suffix = "]"
}
elseif ( $sep -eq "_" )
{
$suffix = ""
}
else
{
$suffix = " "
}
}
else
{
$suffix = ""
}
$prefix + $_opt.Substring(0, $_opt.LastIndexOf($sep)+1) + $Item[$i] + $suffix
$preItem = $Item[$i]
}
}
}
function Get-PipeLineObject {
$i = -2
$property = $null
do {
$str = $line.Split("|")
# extract the command name from the string
# first split the string into statements and pipeline elements
# This doesn't handle strings however.
$_cmdlet = [regex]::Split($str[$i], '[|;=]')[-1]
# take the first space separated token of the remaining string
# as the command to look up. Trim any leading or trailing spaces
# so you don't get leading empty elements.
$_cmdlet = $_cmdlet.Trim().Split()[0]
if ( $_cmdlet -eq "?" )
{
$_cmdlet = "Where-Object"
}
$global:_exp = $_cmdlet
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0]
}
if ( "Select-Object" -eq $_cmdlet )
{
if ( $str[$i] -match '\\s+-Exp\\w*[\\s:]+(\\w+)' )
{
$property = $Matches[1] + ";" + $property
}
}
$i--
} while ( "Get-Unique", "Select-Object", "Sort-Object", "Tee-Object", "Where-Object" -contains $_cmdlet )
if ( $global:_forgci -eq $null )
{
$a = @(ls "Alias:\\")[0]
$e = @(ls "Env:\\")[0]
$f = @(ls "Function:\\")[0]
$h = @(ls "HKCU:\\")[0]
$v = @(ls "Variable:\\")[0]
$c = @(ls "cert:\\")[0]
$global:_forgci = gi $PSHOME\\powershell.exe |
Add-Member -Name CommandType -MemberType 'NoteProperty' -Value $f.CommandType -PassThru |
Add-Member -Name Definition -MemberType 'NoteProperty' -Value $a.Definition -PassThru |
Add-Member -Name Description -MemberType 'NoteProperty' -Value $a.Description -PassThru |
Add-Member -Name Key -MemberType 'NoteProperty' -Value $e.Key -PassThru |
Add-Member -Name Location -MemberType 'NoteProperty' -Value $c.Location -PassThru |
Add-Member -Name LocationName -MemberType 'NoteProperty' -Value $c.LocationName -PassThru |
Add-Member -Name Options -MemberType 'NoteProperty' -Value $a.Options -PassThru |
Add-Member -Name ReferencedCommand -MemberType 'NoteProperty' -Value $a.ReferencedCommand -PassThru |
Add-Member -Name ResolvedCommand -MemberType 'NoteProperty' -Value $a.ResolvedCommand -PassThru |
Add-Member -Name ScriptBlock -MemberType 'NoteProperty' -Value $f.ScriptBlock -PassThru |
Add-Member -Name StoreNames -MemberType 'NoteProperty' -Value $c.StoreNames -PassThru |
Add-Member -Name SubKeyCount -MemberType 'NoteProperty' -Value $h.SubKeyCount -PassThru |
Add-Member -Name Value -MemberType 'NoteProperty' -Value $e.Value -PassThru |
Add-Member -Name ValueCount -MemberType 'NoteProperty' -Value $h.ValueCount -PassThru |
Add-Member -Name Visibility -MemberType 'NoteProperty' -Value $a.Visibility -PassThru |
Add-Member -Name Property -MemberType 'NoteProperty' -Value $h.Property -PassThru |
Add-Member -Name ResolvedCommandName -MemberType 'NoteProperty' -Value $a.ResolvedCommandName -PassThru |
Add-Member -Name Close -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name CreateSubKey -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name DeleteSubKey -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name DeleteSubKeyTree -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name DeleteValue -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Flush -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetSubKeyNames -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetValue -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetValueKind -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetValueNames -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsValidValue -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name OpenSubKey -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name SetValue -MemberType 'ScriptMethod' -Value {} -PassThru
}
if ( $global:_mix -eq $null )
{
$f = gi $PSHOME\\powershell.exe
$t = [type]
$s = ""
$global:_mix = `
Add-Member -InputObject (New-Object PSObject) -Name Mode -MemberType 'NoteProperty' -Value $f.Mode -PassThru |
Add-Member -Name Assembly -MemberType 'NoteProperty' -Value $t.Assembly -PassThru |
Add-Member -Name AssemblyQualifiedName -MemberType 'NoteProperty' -Value $t.AssemblyQualifiedName -PassThru |
Add-Member -Name Attributes -MemberType 'NoteProperty' -Value $f.Attributes -PassThru |
Add-Member -Name BaseType -MemberType 'NoteProperty' -Value $t.BaseType -PassThru |
Add-Member -Name ContainsGenericParameters -MemberType 'NoteProperty' -Value $t.ContainsGenericParameters -PassThru |
Add-Member -Name CreationTime -MemberType 'NoteProperty' -Value $f.CreationTime -PassThru |
Add-Member -Name CreationTimeUtc -MemberType 'NoteProperty' -Value $f.CreationTimeUtc -PassThru |
Add-Member -Name DeclaringMethod -MemberType 'NoteProperty' -Value $t.DeclaringMethod -PassThru |
Add-Member -Name DeclaringType -MemberType 'NoteProperty' -Value $t.DeclaringType -PassThru |
Add-Member -Name Exists -MemberType 'NoteProperty' -Value $f.Exists -PassThru |
Add-Member -Name Extension -MemberType 'NoteProperty' -Value $f.Extension -PassThru |
Add-Member -Name FullName -MemberType 'NoteProperty' -Value $f.FullName -PassThru |
Add-Member -Name GenericParameterAttributes -MemberType 'NoteProperty' -Value $t.GenericParameterAttributes -PassThru |
Add-Member -Name GenericParameterPosition -MemberType 'NoteProperty' -Value $t.GenericParameterPosition -PassThru |
Add-Member -Name GUID -MemberType 'NoteProperty' -Value $t.GUID -PassThru |
Add-Member -Name HasElementType -MemberType 'NoteProperty' -Value $t.HasElementType -PassThru |
Add-Member -Name IsAbstract -MemberType 'NoteProperty' -Value $t.IsAbstract -PassThru |
Add-Member -Name IsAnsiClass -MemberType 'NoteProperty' -Value $t.IsAnsiClass -PassThru |
Add-Member -Name IsArray -MemberType 'NoteProperty' -Value $t.IsArray -PassThru |
Add-Member -Name IsAutoClass -MemberType 'NoteProperty' -Value $t.IsAutoClass -PassThru |
Add-Member -Name IsAutoLayout -MemberType 'NoteProperty' -Value $t.IsAutoLayout -PassThru |
Add-Member -Name IsByRef -MemberType 'NoteProperty' -Value $t.IsByRef -PassThru |
Add-Member -Name IsClass -MemberType 'NoteProperty' -Value $t.IsClass -PassThru |
Add-Member -Name IsCOMObject -MemberType 'NoteProperty' -Value $t.IsCOMObject -PassThru |
Add-Member -Name IsContextful -MemberType 'NoteProperty' -Value $t.IsContextful -PassThru |
Add-Member -Name IsEnum -MemberType 'NoteProperty' -Value $t.IsEnum -PassThru |
Add-Member -Name IsExplicitLayout -MemberType 'NoteProperty' -Value $t.IsExplicitLayout -PassThru |
Add-Member -Name IsGenericParameter -MemberType 'NoteProperty' -Value $t.IsGenericParameter -PassThru |
Add-Member -Name IsGenericType -MemberType 'NoteProperty' -Value $t.IsGenericType -PassThru |
Add-Member -Name IsGenericTypeDefinition -MemberType 'NoteProperty' -Value $t.IsGenericTypeDefinition -PassThru |
Add-Member -Name IsImport -MemberType 'NoteProperty' -Value $t.IsImport -PassThru |
Add-Member -Name IsInterface -MemberType 'NoteProperty' -Value $t.IsInterface -PassThru |
Add-Member -Name IsLayoutSequential -MemberType 'NoteProperty' -Value $t.IsLayoutSequential -PassThru |
Add-Member -Name IsMarshalByRef -MemberType 'NoteProperty' -Value $t.IsMarshalByRef -PassThru |
Add-Member -Name IsNested -MemberType 'NoteProperty' -Value $t.IsNested -PassThru |
Add-Member -Name IsNestedAssembly -MemberType 'NoteProperty' -Value $t.IsNestedAssembly -PassThru |
Add-Member -Name IsNestedFamANDAssem -MemberType 'NoteProperty' -Value $t.IsNestedFamANDAssem -PassThru |
Add-Member -Name IsNestedFamily -MemberType 'NoteProperty' -Value $t.IsNestedFamily -PassThru |
Add-Member -Name IsNestedFamORAssem -MemberType 'NoteProperty' -Value $t.IsNestedFamORAssem -PassThru |
Add-Member -Name IsNestedPrivate -MemberType 'NoteProperty' -Value $t.IsNestedPrivate -PassThru |
Add-Member -Name IsNestedPublic -MemberType 'NoteProperty' -Value $t.IsNestedPublic -PassThru |
Add-Member -Name IsNotPublic -MemberType 'NoteProperty' -Value $t.IsNotPublic -PassThru |
Add-Member -Name IsPointer -MemberType 'NoteProperty' -Value $t.IsPointer -PassThru |
Add-Member -Name IsPrimitive -MemberType 'NoteProperty' -Value $t.IsPrimitive -PassThru |
Add-Member -Name IsPublic -MemberType 'NoteProperty' -Value $t.IsPublic -PassThru |
Add-Member -Name IsSealed -MemberType 'NoteProperty' -Value $t.IsSealed -PassThru |
Add-Member -Name IsSerializable -MemberType 'NoteProperty' -Value $t.IsSerializable -PassThru |
Add-Member -Name IsSpecialName -MemberType 'NoteProperty' -Value $t.IsSpecialName -PassThru |
Add-Member -Name IsUnicodeClass -MemberType 'NoteProperty' -Value $t.IsUnicodeClass -PassThru |
Add-Member -Name IsValueType -MemberType 'NoteProperty' -Value $t.IsValueType -PassThru |
Add-Member -Name IsVisible -MemberType 'NoteProperty' -Value $t.IsVisible -PassThru |
Add-Member -Name LastAccessTime -MemberType 'NoteProperty' -Value $f.LastAccessTime -PassThru |
Add-Member -Name LastAccessTimeUtc -MemberType 'NoteProperty' -Value $f.LastAccessTimeUtc -PassThru |
Add-Member -Name LastWriteTime -MemberType 'NoteProperty' -Value $f.LastWriteTime -PassThru |
Add-Member -Name LastWriteTimeUtc -MemberType 'NoteProperty' -Value $f.LastWriteTimeUtc -PassThru |
Add-Member -Name MemberType -MemberType 'NoteProperty' -Value $t.MemberType -PassThru |
Add-Member -Name MetadataToken -MemberType 'NoteProperty' -Value $t.MetadataToken -PassThru |
Add-Member -Name Module -MemberType 'NoteProperty' -Value $t.Module -PassThru |
Add-Member -Name Name -MemberType 'NoteProperty' -Value $t.Name -PassThru |
Add-Member -Name Namespace -MemberType 'NoteProperty' -Value $t.Namespace -PassThru |
Add-Member -Name Parent -MemberType 'NoteProperty' -Value $f.Parent -PassThru |
Add-Member -Name ReflectedType -MemberType 'NoteProperty' -Value $t.ReflectedType -PassThru |
Add-Member -Name Root -MemberType 'NoteProperty' -Value $f.Root -PassThru |
Add-Member -Name StructLayoutAttribute -MemberType 'NoteProperty' -Value $t.StructLayoutAttribute -PassThru |
Add-Member -Name TypeHandle -MemberType 'NoteProperty' -Value $t.TypeHandle -PassThru |
Add-Member -Name TypeInitializer -MemberType 'NoteProperty' -Value $t.TypeInitializer -PassThru |
Add-Member -Name UnderlyingSystemType -MemberType 'NoteProperty' -Value $t.UnderlyingSystemType -PassThru |
Add-Member -Name PSChildName -MemberType 'NoteProperty' -Value $f.PSChildName -PassThru |
Add-Member -Name PSDrive -MemberType 'NoteProperty' -Value $f.PSDrive -PassThru |
Add-Member -Name PSIsContainer -MemberType 'NoteProperty' -Value $f.PSIsContainer -PassThru |
Add-Member -Name PSParentPath -MemberType 'NoteProperty' -Value $f.PSParentPath -PassThru |
Add-Member -Name PSPath -MemberType 'NoteProperty' -Value $f.PSPath -PassThru |
Add-Member -Name PSProvider -MemberType 'NoteProperty' -Value $f.PSProvider -PassThru |
Add-Member -Name BaseName -MemberType 'NoteProperty' -Value $f.BaseName -PassThru |
Add-Member -Name Clone -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name CompareTo -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Contains -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name CopyTo -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Create -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name CreateObjRef -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name CreateSubdirectory -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Delete -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name EndsWith -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name FindInterfaces -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name FindMembers -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetAccessControl -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetArrayRank -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetConstructor -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetConstructors -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetCustomAttributes -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetDefaultMembers -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetDirectories -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetElementType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetEnumerator -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetEvent -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetEvents -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetField -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetFields -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetFiles -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetFileSystemInfos -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetGenericArguments -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetGenericParameterConstraints -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetGenericTypeDefinition -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetInterface -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetInterfaceMap -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetInterfaces -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetLifetimeService -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetMember -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetMembers -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetMethod -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetMethods -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetNestedType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetNestedTypes -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetObjectData -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetProperties -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetProperty -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name GetTypeCode -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IndexOf -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IndexOfAny -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name InitializeLifetimeService -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Insert -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name InvokeMember -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsAssignableFrom -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsDefined -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsInstanceOfType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsNormalized -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name IsSubclassOf -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name LastIndexOf -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name LastIndexOfAny -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name MakeArrayType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name MakeByRefType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name MakeGenericType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name MakePointerType -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name MoveTo -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Normalize -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name PadLeft -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name PadRight -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Refresh -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Remove -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Replace -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name SetAccessControl -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Split -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name StartsWith -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Substring -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name ToCharArray -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name ToLower -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name ToLowerInvariant -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name ToUpper -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name ToUpperInvariant -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Trim -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name TrimEnd -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name TrimStart -MemberType 'ScriptMethod' -Value {} -PassThru |
Add-Member -Name Chars -MemberType 'NoteProperty' -Value $s.Chars -PassThru
}
if ( "Add-Member" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Compare-Object" -eq $_cmdlet )
{
$global:_dummy = (Compare-Object 1 2)[0]
}
if ( "ConvertFrom-SecureString" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "ConvertTo-SecureString" -eq $_cmdlet )
{
$global:_dummy = convertto-securestring "P@ssW0rD!" -asplaintext -force
}
if ( "ForEach-Object" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Get-Acl" -eq $_cmdlet )
{
$global:_dummy = Get-Acl
}
if ( "Get-Alias" -eq $_cmdlet )
{
$global:_dummy = (Get-Alias)[0]
}
if ( "Get-AuthenticodeSignature" -eq $_cmdlet )
{
$global:_dummy = Get-AuthenticodeSignature $PSHOME\\powershell.exe
}
if ( "Get-ChildItem" -eq $_cmdlet )
{
$global:_dummy = $global:_forgci
}
if ( "Get-Command" -eq $_cmdlet )
{
$global:_dummy = @(iex $str[$i+1])[0]
}
if ( "Get-Content" -eq $_cmdlet )
{
$global:_dummy = (type $PSHOME\\profile.ps1)[0]
}
if ( "Get-Credential" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Get-Culture" -eq $_cmdlet )
{
$global:_dummy = Get-Culture
}
if ( "Get-Date" -eq $_cmdlet )
{
$global:_dummy = Get-Date
}
if ( "Get-Event" -eq $_cmdlet )
{
$global:_dummy = (Get-Event)[0]
}
if ( "Get-EventLog" -eq $_cmdlet )
{
$global:_dummy = @(iex $str[$i+1])[0]
}
if ( "Get-ExecutionPolicy" -eq $_cmdlet )
{
$global:_dummy = Get-ExecutionPolicy
}
if ( "Get-Help" -eq $_cmdlet )
{
$global:_dummy = Get-Help Add-Content
}
if ( "Get-History" -eq $_cmdlet )
{
$global:_dummy = Get-History -Count 1
}
if ( "Get-Host" -eq $_cmdlet )
{
$global:_dummy = Get-Host
}
if ( "Get-Item" -eq $_cmdlet )
{
$global:_dummy = $global:_forgci
}
if ( "Get-ItemProperty" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Get-Location" -eq $_cmdlet )
{
$global:_dummy = Get-Location
}
if ( "Get-Member" -eq $_cmdlet )
{
$global:_dummy = (1|Get-Member)[0]
}
if ( "Get-Module" -eq $_cmdlet )
{
$global:_dummy = (Get-Module)[0]
}
if ( "Get-PfxCertificate" -eq $_cmdlet )
{
$global:_dummy = $null
}
if ( "Get-Process" -eq $_cmdlet )
{
$global:_dummy = ps powershell
}
if ( "Get-PSBreakpoint" -eq $_cmdlet )
{
$global:_dummy =
Add-Member -InputObject (New-Object PSObject) -Name Action -MemberType 'NoteProperty' -Value '' -PassThru |
Add-Member -Name Command -MemberType 'NoteProperty' -Value '' -PassThru |
Add-Member -Name Enabled -MemberType 'NoteProperty' -Value '' -PassThru |
Add-Member -Name HitCount -MemberType 'NoteProperty' -Value '' -PassThru |
Add-Member -Name Id -MemberType 'NoteProperty' -Value '' -PassThru |
Add-Member -Name Script -MemberType 'NoteProperty' -Value '' -PassThru
}
if ( "Get-PSCallStack" -eq $_cmdlet )
{
$global:_dummy = Get-PSCallStack
}
if ( "Get-PSDrive" -eq $_cmdlet )
{
$global:_dummy = Get-PSDrive Function
}
if ( "Get-PSProvider" -eq $_cmdlet )
{
$global:_dummy = Get-PSProvider FileSystem
}
if ( "Get-PSSnapin" -eq $_cmdlet )
{
$global:_dummy = Get-PSSnapin Microsoft.PowerShell.Core
}
if ( "Get-Service" -eq $_cmdlet )
{
$global:_dummy = (Get-Service)[0]
}
if ( "Get-TraceSource" -eq $_cmdlet )
{
$global:_dummy = Get-TraceSource AddMember
}
if ( "Get-UICulture" -eq $_cmdlet )
{
$global:_dummy = Get-UICulture
}
if ( "Get-Variable" -eq $_cmdlet )
{
$global:_dummy = Get-Variable _
}
if ( "Get-WmiObject" -eq $_cmdlet )
{
$global:_dummy = @(iex $str[$i+1])[0]
}
if ( "Group-Object" -eq $_cmdlet )
{
$global:_dummy = 1 | group
}
if ( "Measure-Command" -eq $_cmdlet )
{
$global:_dummy = Measure-Command {}
}
if ( "Measure-Object" -eq $_cmdlet )
{
$global:_dummy = Measure-Object
}
if ( "New-PSDrive" -eq $_cmdlet )
{
$global:_dummy = Get-PSDrive Alias
}
if ( "New-TimeSpan" -eq $_cmdlet )
{
$global:_dummy = New-TimeSpan
}
if ( "Resolve-Path" -eq $_cmdlet )
{
$global:_dummy = $PWD
}
if ( "Select-String" -eq $_cmdlet )
{
$global:_dummy = " " | Select-String " "
}
if ( "Set-Date" -eq $_cmdlet )
{
$global:_dummy = Get-Date
}
if ( $property -ne $null)
{
foreach ( $name in $property.Split(";", "RemoveEmptyEntries" -as [System.StringSplitOptions]) )
{
$global:_dummy = @($global:_dummy.$name)[0]
}
}
}
function Set-CommandLine ( [string]$script ) { $global:_cmdline.Add($script) }
function Get-CommandLine ( [string]$name ) {
$name = $name -replace '\\?','`?'
$global:_cmdline -like "$name*"
}
function TabExpansion {
# This is the default function to use for tab expansion. It handles simple
# member expansion on variables, variable name expansion and parameter completion
# on commands. It doesn't understand strings so strings containing ; | ( or { may
# cause expansion to fail.
param($line, $lastWord)
& {
# Helper function to write out the matching set of members. It depends
# on dynamic scoping to get $_base, _$expression and $_pat
function Write-Members ($sep='.')
{
# evaluate the expression to get the object to examine...
Invoke-Expression ('$_val=' + $_expression)
if ( $_expression -match '^\\$global:_dummy' )
{
$temp = $_expression -replace '^\\$global:_dummy(.*)','$1'
$_expression = '$_' + $temp
}
$_method = [Management.Automation.PSMemberTypes] `
'Method,CodeMethod,ScriptMethod,ParameterizedProperty'
if ($sep -eq '.')
{
$params = @{view = 'extended','adapted','base'}
}
else
{
$params = @{static=$true}
}
if ( $_val -is [Hashtable] )
{
[Object[]]$_keys = $null
foreach ( $_name in $_val.Keys )
{
$_keys += `
New-Object Microsoft.PowerShell.Commands.MemberDefinition `
[int],$_name,"Property",0
}
}
if ( $_keys -ne $null )
{
$_members = [Object[]](Get-Member @params -InputObject $_val $_pat) + ($_keys | ? {$_.name -like $_pat})
} else {
$_members = (Get-Member @params -InputObject $_val $_pat)
}
foreach ($_m in $_members | Sort-Object membertype,name)
{
if ($_m.MemberType -band $_method)
{
# Return a method...
$_base + $_expression + $sep + $_m.name + '('
}
else {
# Return a property...
$_base + $_expression + $sep + $_m.name
}
}
}
switch ([int]$line[-1])
{
# Ctrl+D several date/time formats
4 {
"[DateTime]::Now"
[DateTime]::Now
[DateTime]::Now.ToString("yyyyMMdd")
[DateTime]::Now.ToString("MMddyyyy")
[DateTime]::Now.ToString("yyyyMMddHHmmss")
[DateTime]::Now.ToString("MMddyyyyHHmmss")
'd f g m o r t u y'.Split(" ") | % { [DateTime]::Now.ToString($_) }
break;
}
# Ctrl+L a part of history commands expansion
12 {
Get-CommandLine $lastWord.SubString(0, $lastword.Length-1)
break;
}
# Ctrl+P hand-operated pop from command buffer stack
16 {
$_base = $lastword.SubString(0, $lastword.Length-1)
$_base + $global:_cmdstack.Pop()
break;
}
# Ctrl+R $Host.UI.RawUI.
18 {
'$Host.UI.RawUI.'
'$Host.UI.RawUI'
break;
}
# Ctrl+V paste clipboard
22 {
$_base = $lastword.SubString(0, $lastword.Length-1)
$_clip = New-Object System.Windows.Forms.TextBox
$_clip.Multiline = $true
$_clip.Paste()
$_base + $_clip.Text
break;
}
# Ctrl+X cut current line
24 {
$_clip = new-object System.Windows.Forms.TextBox;
$_clip.Multiline = $true;
$_clip.Text = $line.SubString(0, $line.Length-1)
$_clip.SelectAll()
$_clip.Copy()
[System.Windows.Forms.SendKeys]::SendWait("{ESC}")
break;
}
# Ctrl+Z cut last word in current line
26 {
$line.SubString(0, $line.Length-1) -match '(^(.*\\s)([^\\s]*)$)|(^[^\\s]*$)' | Out-Null
$_clip = new-object System.Windows.Forms.TextBox;
$_clip.Multiline = $true;
$_clip.Text = $Matches[3]
$_clip.SelectAll()
$_clip.Copy()
[System.Windows.Forms.SendKeys]::SendWait("{ESC}")
$line = $Matches[2] -replace '([[\\]\\(\\)+{}?~%])','{$1}'
[System.Windows.Forms.SendKeys]::SendWait($line)
break;
}
}
switch ( [int]$line[-2] )
{
# Ctrl+X cut words with a charactor after Ctrl+X until the charactor
24 {
$line.SubString(0, $line.Length-2) -match "(^(.*$($line[-1]))([^$($line[-1])]*)`$)|(^[^\\$($line[-1])]*`$)" | Out-Null
$_clip = new-object System.Windows.Forms.TextBox;
$_clip.Multiline = $true;
$_clip.Text = $Matches[3]
$_clip.SelectAll()
$_clip.Copy()
[System.Windows.Forms.SendKeys]::SendWait("{ESC}")
$line = $Matches[2] -replace '([[\\]\\(\\)+{}?~%])','{$1}'
[System.Windows.Forms.SendKeys]::SendWait($line)
break;
}
}
switch -regex ($lastWord)
{
# Handle property and method expansion at '$_'
'(^.*)(\\$_\\.)(\\w*)$' {
$_base = $matches[1]
$_expression = '$global:_dummy'
$_pat = $matches[3] + '*'
$global:_dummy = $null
Get-PipeLineObject
if ( $global:_dummy -eq $null )
{
if ( $global:_exp -match '^\\$.*\\(.*$' )
{
$type = ( iex $global:_exp.Split("(")[0] ).OverloadDefinitions[0].Split(" ")[0] -replace '\\[[^\\[\\]]*\\]$' -as [type]
if ( $_expression -match '^\\$global:_dummy' )
{
$temp = $_expression -replace '^\\$global:_dummy(.*)','$1'
$_expression = '$_' + $temp
}
foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } )
{
if ($_m.MemberType -eq "Method")
{
$_base + $_expression + '.' + $_m.name + '('
}
else {
$_base + $_expression + '.' + $_m.name
}
}
break;
}
elseif ( $global:_exp -match '^\\[.*\\:\\:.*\\(.*$' )
{
$tname, $mname = $_exp.Split(":(", "RemoveEmptyEntries"-as [System.StringSplitOptions])[0,1]
$type = @(iex ($tname + '.GetMember("' + $mname + '")'))[0].ReturnType.FullName -replace '\\[[^\\[\\]]*\\]$' -as [type]
if ( $_expression -match '^\\$global:_dummy' )
{
$temp = $_expression -replace '^\\$global:_dummy(.*)','$1'
$_expression = '$_' + $temp
}
foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } )
{
if ($_m.MemberType -eq "Method")
{
$_base + $_expression + '.' + $_m.name + '('
}
else {
$_base + $_expression + '.' + $_m.name
}
}
break;
}
elseif ( $global:_exp -match '^(\\$\\w+(\\[[0-9,\\.]+\\])*(\\.\\w+(\\[[0-9,\\.]+\\])*)*)$' )
{
$global:_dummy = @(iex $Matches[1])[0]
}
else
{
$global:_dummy = $global:_mix
}
}
Write-Members
break;
}
# Handle property and method expansion rooted at variables...
# e.g. $a.b.<tab>
'(^.*)(\\$(\\w|\\.)+)\\.(\\w*)$' {
$_base = $matches[1]
$_expression = $matches[2]
$_pat = $matches[4] + '*'
[void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock]
if ( $_expression -match '^\\$_\\.' )
{
$_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1')
}
Write-Members
break;
}
# Handle simple property and method expansion on static members...
# e.g. [datetime]::n<tab>
'(^.*)(\\[(\\w|\\.)+\\])\\:\\:(\\w*)$' {
$_base = $matches[1]
$_expression = $matches[2]
$_pat = $matches[4] + '*'
Write-Members '::'
break;
}
# Handle complex property and method expansion on static members
# where there are intermediate properties...
# e.g. [datetime]::now.d<tab>
'(^.*)(\\[(\\w|\\.)+\\]\\:\\:(\\w+\\.)+)(\\w*)$' {
$_base = $matches[1] # everything before the expression
$_expression = $matches[2].TrimEnd('.') # expression less trailing '.'
$_pat = $matches[5] + '*' # the member to look for...
Write-Members
break;
}
# Handle property and method expansion on [ScriptBlock] members...
# e.g. { 1+1 }.inv<tab>
'(^.*})\\.(\\w*)$' {
$_base = $matches[1]
$_pat = $matches[2] + '*'
foreach ( $_m in {} | Get-Member $_pat | sort membertype,name )
{
if ($_m.MemberType -eq "Method")
{
$_base + '.' + $_m.name + '('
}
else {
$_base + '.' + $_m.name
}
}
break;
}
# Handle variable name expansion...
'(^.*\\$)(\\w+)$' {
$_prefix = $matches[1]
$_varName = $matches[2]
foreach ($_v in Get-ChildItem ('variable:' + $_varName + '*'))
{
$_prefix + $_v.name
}
break;
}
# Handle item name expansion in variable notation...
'(^.*\\${)(((\\w+):([\\\\/]?))[^\\\\/]+([\\\\/][^\\\\/]*)*)$' {
$_prefix = $matches[1]
$_driveName = $matches[3]
$_itemName = $matches[2] + "*"
Get-ChildItem $_itemName |
% {
if ( $matches[5] -and $_.PSProvider.Name -eq "FileSystem" )
{
$output = $_prefix + $_.FullName
}
elseif ( $_.PSProvider.Name -eq "FileSystem" -and $matches[6] )
{
$cd = (Get-Location -PSDrive $matches[4]).Path
$output = $_prefix + $_driveName + $_.FullName.Substring($cd.Length+1)
}
elseif ( $_.PSProvider.Name -eq "FileSystem" )
{
$cd = (Get-Location -PSDrive $matches[4]).Path
$output = $_prefix + $_driveName + $_.FullName.Substring($cd.Length+1)
}
else
{
$output = $_prefix + $_driveName + $_.Name
}
if ( $_.PSIsContainer )
{
$output
}
else
{
$output + "}"
}
}
break;
}
# Handle PSDrive name expansion in variable notation...
'(^.*\\${)(\\w+)$' {
$_prefix = $matches[1]
$_driveName = $matches[2] + "*"
Get-PSDrive $_driveName | % { $_prefix + $_ + ':' }
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+(\\.\\w*)*)\\])*))(\\[(\\w*(\\.\\w*)*))$' {
$_base = $matches[1]
$_opt = $matches[8] + '*'
if ( $_opt -eq "*" )
{
$_TypeAccelerators -replace '^(.*)$', '[$1]' | % { $_base + $_ }
}
else
{
$_TypeAccelerators -like $_opt -replace '^(.*)$', '[$1]' | % { $_base + $_ }
"CmdletBinding", "Parameter", "Alias",
"ValidateArguments", "ValidateCount", "ValidateEnumeratedArguments", "ValidateLength",
"ValidateNotNull", "ValidateNotNullOrEmpty", "ValidatePattern", "ValidateRange",
"ValidateScript", "ValidateSet", "AllowEmptyCollection", "AllowEmptyString", "AllowNull" `
-like $_opt -replace '^(.*)$', '[$1(' | % { $_base + $_ }
Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1) '[' | % { $_base + $_ }
Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1) '[' | % { $_base + $_ }
}
break;
}
# Handle file/directory name which contains $env: variable
# e.g. $env:windir\\<tab>
'^\\$(env:)?\\w+([\\\\/][^\\\\/]*)*$' {
$path = iex ('"' + $Matches[0] + '"')
if ( $Matches[2].Length -gt 1 )
{
$parent = Split-Path $path -Parent
$leaf = (Split-Path $path -Leaf) + '*'
}
else
{
$parent = $path
$leaf = '*'
}
if ( Test-Path $parent )
{
$i = $Matches[0].LastIndexOfAny("/\\")
$_base = $Matches[0].Substring(0,$i+1)
[IO.Directory]::GetFileSystemEntries( $parent, $leaf ) | % { $_base + ($_.Split("\\/")[-1] -replace '([\\$\\s&])','`$1' -replace '([[\\]])', '````$1') }
}
}
# Handle file glob expansion ...
# e.g. *.txt~about*@<tab>
'^(\\^?([^~]+))(~(.*))*@$' {
if ( $Matches[1] -notlike "^*" )
{
$include = $Matches[2] -replace '``','`'
if ( $Matches[3] )
{
$exclude = $Matches[3].Split("~", "RemoveEmptyEntries" -as [System.StringSplitOptions]) -replace '``','`'
}
}
else
{
$include = "*"
$exclude = $Matches[2] -replace '``','`'
}
$fse = [IO.Directory]::GetFileSystemEntries($PWD)
$fse = $fse -replace '.*[\\\\/]([^/\\\\]*)$','$1'
% -in ($fse -like $include) { $fse = $_; $exclude | % { $fse = $fse -notlike $_ } }
$fse = $fse -replace '^.*\\s.*$', ("'`$0'")
$fse = $fse -replace '([\\[\\]])', '``$1' -replace '^.*([\\[\\]]).*$', ("'`$0'")
$fse = $fse -replace "''", "'"
$OFS = ", "; "$fse"
$OFS = ", "; "* -Filter $include " + $(if($exclude){"-Exclude $exclude"})
$Matches[0].Substring(0, $Matches[0].Length-1)
break;
}
# Handle command buffer stack...
'(.*);(.?)$' {
$_base = $Matches[1]
if ( $Matches[2] -eq ":" -or $Matches[2] -eq "," )
{
if ( $_cmdstack.Count -gt 0 )
{
$_base + $global:_cmdstack.Pop()
}
else
{
""; break;
}
}
elseif ( $Matches[2] -eq "" )
{
$global:_cmdstack.Push($line.SubString(0,$line.Length-1))
[System.Windows.Forms.SendKeys]::SendWait("{ESC}")
""; break;
}
}
# Do completion on parameters...
'^-([\\w0-9]*)' {
$_pat = $matches[1] + '*'
# extract the command name from the string
# first split the string into statements and pipeline elements
# This doesn't handle strings however.
$_command = [regex]::Split($line, '[|;=]')[-1]
# Extract the trailing unclosed block e.g. ls | foreach { cp
if ($_command -match '\\{([^
|
PowerShellCorpus/PoshCode/Invoke-Generic_2.ps1
|
Invoke-Generic_2.ps1
|
function Invoke-Generic {
#.Synopsis
# Invoke Generic method definitions via reflection:
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[Alias('On')]
$InputObject
,
[Parameter(Position=1,ValueFromPipelineByPropertyName=$true)]
[Alias('Named')]
[string]$MethodName
,
[Parameter(Position=2)]
[Alias("Types")]
[Type[]]$ParameterType
,
[Parameter(Position=4, ValueFromRemainingArguments=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("Args")]
[Object[]]$ArgumentList
,
[Switch]$Static
)
begin {
if($Static) {
$BindingFlags = [System.Reflection.BindingFlags]"IgnoreCase,Public,Static"
} else {
$BindingFlags = [System.Reflection.BindingFlags]"IgnoreCase,Public,Instance"
}
}
process {
$Type = $InputObject -as [Type]
if(!$Type) { $Type = $InputObject.GetType() }
if($WithArgs -and -not $ParameterTypes) {
$ParameterTypes = $withArgs | % { $_.GetType() }
} elseif(!$ParameterTypes) {
$ParameterTypes = [Type]::EmptyTypes
}
trap { continue }
$MemberInfo = $Type.GetMethod($MethodName, $BindingFlags)
if(!$MemberInfo) {
$MemberInfo = $Type.GetMethod($MethodName, $BindingFlags, $null, $NonGenericArgumentTypes, $null)
}
if(!$MemberInfo) {
$MemberInfo = $Type.GetMethods($BindingFlags) | Where-Object {
$MI = $_
[bool]$Accept = $MI.Name -eq $MethodName
if($Accept){
Write-Verbose "$Accept = $($MI.Name) -eq $($MethodName)"
[Array]$GenericTypes = @($MI.GetGenericArguments() | Select -Expand Name)
[Array]$Parameters = @($MI.GetParameters() | Add-Member ScriptProperty -Name IsGeneric -Value {
$GenericTypes -Contains $this.ParameterType
} -Passthru)
$Accept = $ParameterTypes.Count -eq $Parameters.Count
Write-Verbose " $Accept = $($Parameters.Count) Arguments"
if($Accept) {
for($i=0;$i -lt $Parameters.Count;$i++) {
$Accept = $Accept -and ( $Parameters[$i].IsGeneric -or ($ParameterTypes[$i] -eq $Parameters[$i].ParameterType))
Write-Verbose " $Accept =$(if($Parameters[$i].IsGeneric){' GENERIC or'}) $($ParameterTypes[$i]) -eq $($Parameters[$i].ParameterType)"
}
}
}
return $Accept
} | Sort { @($_.GetGenericArguments()).Count } | Select -First 1
}
Write-Verbose "Time to make generic methods."
Write-Verbose $MemberInfo
[Type[]]$GenericParameters = @()
[Array]$ConcreteTypes = @($MemberInfo.GetParameters() | Select -Expand ParameterType)
for($i=0;$i -lt $ParameterTypes.Count;$i++){
Write-Verbose "$($ParameterTypes[$i]) ? $($ConcreteTypes[$i] -eq $ParameterTypes[$i])"
if($ConcreteTypes[$i] -ne $ParameterTypes[$i]) {
$GenericParameters += $ParameterTypes[$i]
}
$ParameterTypes[$i] = Add-Member -in $ParameterTypes[$i] -Type NoteProperty -Name IsGeneric -Value $($ConcreteTypes[$i] -ne $ParameterTypes[$i]) -Passthru
}
$ParameterTypes | Where-Object { $_.IsGeneric }
Write-Verbose "$($GenericParameters -join ', ') generic parameters"
$MemberInfo = $MemberInfo.MakeGenericMethod( $GenericParameters )
Write-Verbose $MemberInfo
if($WithArgs) {
[Object[]]$Arguments = $withArgs | %{ $_.PSObject.BaseObject }
Write-Verbose "Arguments: $(($Arguments | %{ $_.GetType().Name }) -Join ', ')"
$MemberInfo.Invoke( $InputObject, $Arguments )
} else {
$MemberInfo.Invoke( $InputObject )
}
} }
|
PowerShellCorpus/PoshCode/New-StoredProcFunction_1.ps1
|
New-StoredProcFunction_1.ps1
|
# New-StoredProcFunction.ps1
# Steven Murawski
# http://blog.usepowershell.com
# 04/08/2009
# Example: ./New-StoredProcFunction.ps1 'DataSource=MySqlServer;Database=Northwind;User=AnythingButSa;Password=abc123' sp_createnewcustomer
# Example 'sp_createnewcustomer | ./New-StoredProcFunction.ps1 'DataSource=MySqlServer;Database=Northwind;User=AnythingButSa;Password=abc123'
param($ConnectionString, [String[]]$StoredProc= $null)
BEGIN
{
if ($StoredProc.count -gt 0)
{
$StoredProc | ./New-StoredProcFunction.ps1 $ConnectionString
}
function Get-StoredProcText()
{
param ($ProcName, $ConnectionString)
$query = @'
SELECT ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_BODY = 'SQL' AND ROUTINE_NAME LIKE '$_'
'@
$connection = New-Object System.Data.SqlClient.SqlConnection $connectionString
$command = New-Object System.Data.SqlClient.SqlCommand $query,$connection
$connection.Open()
$adapter = New-Object System.Data.SqlClient.SqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
[void] $adapter.Fill($dataSet)
$result = $dataSet.Tables | ForEach-Object {$_.Rows}
$connection.Close()
return $Result.ROUTINE_DEFINITION
}
function Get-FunctionParameter()
{
param ($Text)
[regex]$EndRegex = '\\)\\s+AS'
[regex]$ParamRegex = '@(?<Parameter>\\w+?)\\s+(?<DataType>\\w+(\\(\\d+\\))*)(,|\\s+)*(?<Output>out)*'
$ParamStart = $Text.indexof('(')
$ParamEnd = $EndRegex.Match($text).index
$ParamText = $Text.Substring($ParamStart, ($ParamEnd-$ParamStart))
$RegMatches = $ParamRegex.matches($ParamText)
foreach ($RegMatch in $RegMatches)
{
$Parameter = "" | Select-Object Name, DataType, IsOutput
$Parameter.Name = $RegMatch.Groups[3].value
$Parameter.DataType = $RegMatch.Groups[4].Value
[bool]$Parameter.IsOutput = $RegMatch.Groups[5].Value
$Parameter
}
}
}
PROCESS
{
if ($_ -ne $null)
{
$FunctionName = $_
$StoredProcText = Get-StoredProcText $FunctionName $ConnectionString
$Parameters = Get-FunctionParameter $StoredProcText
[String[]]$InputParamNames = $Parameters | where {-not $_.IsOutput} | ForEach-Object {$_.Name}
[String[]]$OutputParameterNames = $Parameters | Where-Object {$_.IsOutput} | ForEach-Object {$_.Name}
$ScriptText = ' '
if ($InputParamNames.count -gt 0)
{
$OFS = ', $'
$ScriptText += 'param (${0})' -f $InputParamNames
$ScriptText += "`n"
$OFS = ', '
}
$BodyTemplate = @'
$connection = New-Object System.Data.SqlClient.SqlConnection('{0}')
$command = New-Object System.Data.SqlClient.SqlCommand('{1}', $connection)
$command.CommandType = [System.Data.CommandType]::StoredProcedure
'@
$ScriptText += $BodyTemplate -f $ConnectionString, $FunctionName
if ( ($Parameters -ne $null) -or ($Parameters.count -gt 1) )
{
if ($OutputParameterNames.count -gt 0)
{
$ReturnText = ""
$CommandOutput = "" | select $OutputParameterNames
}
#Add the parameters
foreach ($param in $Parameters)
{
if ($param.datatype -match '(?<type>\\w+)\\((?<nbr>\\d+)\\)')
{
$ParamTemplate = '$command.Parameters.Add("@{0}", "{1}", {2}) | out-null '
$ScriptText += "`n"
$ScriptText += $ParamTemplate -f $param.name, $matches.type, $matches.nbr
}
else
{
$ParamTemplate = '$command.Parameters.Add("@{0}", "{1}") | out-null '
$ScriptText += "`n"
$ScriptText += $ParamTemplate -f $param.name, $param.datatype
}
if ($param.IsOutput)
{
$ScriptText += "`n"
$ScriptText += '$command.Parameters["@{0}"].Direction = [System.Data.ParameterDirection]::Output ' -f $param.Name
$ReturnText += "`n"
$ReturnText += '$CommandOutput.{0} = $command.Parameters["@{0}"].Value' -f $param.name
}
else
{
$ScriptText += "`n"
$ScriptText += '$command.Parameters["@{0}"].Value = ${0} ' -f $param.name
}
}
}
$ScriptText += "`n"
$ScriptText += @'
$connection.Open() | out-null
$command.ExecuteNonQuery() | out-null
'@
if ($OutputParameterNames.count -gt 0)
{
$ScriptText += $ReturnText
}
$ScriptText += @'
$connection.Close() | out-null
return $CommandOutput
'@
#$ScriptText
Set-Item -Path function:global:$FunctionName -Value $scripttext
}
}
|
PowerShellCorpus/PoshCode/New-Shortcut_1.ps1
|
New-Shortcut_1.ps1
|
#requires -version 2.0
function New-Shortcut {
<#
.SYNOPSIS
Creates a new shortcut (.lnk file) pointing at the specified file.
.DESCRIPTION
The New-Shortcut script creates a shortcut pointing at the target in the location you specify. You may specify the location as a folder path (which must exist), with a name for the new file (ending in .lnk), or you may specify one of the "SpecialFolder" names like "QuickLaunch" or "CommonDesktop" followed by the name.
If you specify the path for the link file without a .lnk extension, the path is assumed to be a folder.
.EXAMPLE
New-Shortcut C:\\Windows\\Notepad.exe
Will make a shortcut to notepad in the current folder named "Notepad.lnk"
.EXAMPLE
New-Shortcut C:\\Windows\\Notepad.exe QuickLaunch\\Editor.lnk -Description "Run Notepad"
Will make a shortcut to notepad on the QuickLaunch bar with the name "Editor.lnk" and the tooltip "Run Notepad"
.EXAMPLE
New-Shortcut C:\\Windows\\Notepad.exe F:\\User\\
Will make a shortcut to notepad in the F:\\User\\ folder with the name "Notepad.lnk"
.NOTE
Partial dependency on Get-SpecialPath ( http://poshcode.org/858 )
#>
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$true)]
[string]$TargetPath,
## Put the shortcut where you want: "Special Folder" names allowed!
[Parameter(Position=1,Mandatory=$true)]
[string]$LinkPath,
## Extra parameters for the shortcut
[string]$Arguments="",
[string]$WorkingDirectory="",
[string]$WindowStyle="Normal",
[string]$IconLocation="",
[string]$Hotkey="",
[string]$Description="",
[string]$Folder=""
)
# Values for Window Style:
# 1 - Normal -- Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position.
# 3 - Maximized -- Activates the window and displays it as a maximized window.
# 7 - Minimized -- Minimizes the window and activates the next top-level window.
if(!(Test-Path $TargetPath) -and !($TargetPath.Contains("://"))) {
Write-Error "TargetPath must be an existing file for the link to point at (or a URL)"
return
}
function New-ShortCutFile {
param(
[string]$TargetPath=$(throw "Please specify a TargetPath for link to point to"),
[string]$LinkPath=$(throw "must pass a path for the shortcut file"),
[string]$Arguments="",
[string]$WorkingDirectory=$(Split-Path $TargetPath -parent),
[string]$WindowStyle="Normal",
[string]$IconLocation="",
[string]$Hotkey="",
[string]$Description=$(Split-Path $TargetPath -Leaf)
)
if(-not ($TargetPath.Contains("://") -or (Test-Path (Split-Path (Resolve-Path $TargetPath) -parent)))) {
Throw "Cannot create Shortcut: Parent folder does not exist"
}
if(-not (Test-Path variable:\\global:WshShell)) {
$global:WshShell = New-Object -com "WScript.Shell"
}
$Link = $global:WshShell.CreateShortcut($LinkPath)
$Link.TargetPath = $TargetPath
[IO.FileInfo]$LinkInfo = $LinkPath
## Properties for file shortcuts only
## If the $LinkPath ends in .url you can't set the arguments, icon, etc
## if you make the same shortcut with a .lnk extension
## you can still point it at a URL, but you can set hotkeys, icons, etc
if( $LinkInfo.Extension -ne ".url" ) {
$Link.WorkingDirectory = $WorkingDirectory
## Validate $WindowStyle
if($WindowStyle -is [string]) {
if( $WindowStyle -like "Normal" ) { $WindowStyle = 1 }
if( $WindowStyle -like "Maximized" ) { $WindowStyle = 3 }
if( $WindowStyle -like "Minimized" ) { $WindowStyle = 7 }
}
if( $WindowStyle -ne 1 -and $WindowStyle -ne 3 -and $WindowStyle -ne 7) { $WindowStyle = 1 }
$Link.WindowStyle = $WindowStyle
if($Hotkey.Length -gt 0 ) { $Link.HotKey = $Hotkey }
if($Arguments.Length -gt 0 ) { $Link.Arguments = $Arguments }
if($Description.Length -gt 0 ) { $Link.Description = $Description }
if($IconLocation.Length -gt 0 ) { $Link.IconLocation = $IconLocation }
}
$Link.Save()
Write-Output (get-item $LinkPath)
}
## If they didn't explicitly specify a folder
if($Folder.Length -eq 0) {
if($LinkPath.Length -gt 0) {
$path = Split-Path $LinkPath -parent
[IO.FileInfo]$LinkInfo = $LinkPath
if( $LinkInfo.Extension.Length -eq 0 ) {
$Folder = $LinkPath
} else {
# If the LinkPath is just a single word with no \\ or extension...
if($path.Length -eq 0) {
$Folder = $Pwd
} else {
$Folder = $path
}
}
}
else
{ $Folder = $Pwd }
}
## If they specified a link path, check it for an extension
if($LinkPath.Length -gt 0) {
$LinkPath = Split-Path $LinkPath -leaf
[IO.FileInfo]$LinkInfo = $LinkPath
if( $LinkInfo.Extension.Length -eq 0 ) {
# If there's no extension, it must be a folder
$Folder = $LinkPath
$LinkPath = ""
}
}
## If there's no Link name, make one up based on the target
if($LinkPath.Length -eq 0) {
if($TargetPath.Contains("://")) {
$LinkPath = "$($TargetPath.split('/')[2]).url"
} else {
[IO.FileInfo]$LinkInfo = $TargetPath
$LinkPath = "$(([IO.FileInfo]$TargetPath).BaseName).lnk"
}
}
## If the folder doesn't actually exist, maybe it's special...
if( -not (Test-Path $Folder)) {
$morepath = "";
if( $Folder.Contains("\\") ) {
$morepath = $Folder.SubString($Folder.IndexOf("\\"))
$Folder = $Folder.SubString(0,$Folder.IndexOf("\\"))
}
$Folder = Join-Path (Get-SpecialPath $Folder) $morepath
# or maybe they just screwed up
trap { throw new-object ArgumentException "Cannot create shortcut: parent folder does not exist" }
}
$LinkPath = (Join-Path $Folder $LinkPath)
New-ShortCutFile $TargetPath $LinkPath $Arguments $WorkingDirectory $WindowStyle $IconLocation $Hotkey $Description
}
|
PowerShellCorpus/PoshCode/set-localpwd.ps1
|
set-localpwd.ps1
|
# Sets local account passwords on one or more computers
# usage [computerName1,computerName2,... | ] ./set-localpwd.ps1 [-user] <userName> [-password] <password> [[-computers] computerName1,computerName2,...]
param(
[string] $User
, [string] $Password
, [string[]] $ComputerNames = @()
)
$ComputerNames += @($input)
if (! $ComputerNames)
{
$ComputerNames = $env:computername
}
function ChangePassword ([string] $ChangeComputer, [string] $ChangeUser, [string] $ChangePassword) {
"*** Setting password for $ChangeComputer/$ChangeUser"
& {
$ErrorActionPreference="silentlycontinue"
([ADSI] "WinNT://$computer/$user").SetPassword($password)
if ($?) { " Success" }
else { " Failed: $($error[0])" }
}
}
function ShowUsage {
@'
usage [computerName1,computerName2,... | ] ./set-localpwd.ps1 [-user] <userName> [-password] <password> [[-computers] computerName1,computerName2,...]
'@
}
if ($user -match '^$|-\\?|/\\?|-help' -or ! $password) { ShowUsage; break; }
ForEach ($computer in $ComputerNames) {
ChangePassword $computer $user $password
}
|
PowerShellCorpus/PoshCode/convert CSV_s to Excel.ps1
|
convert CSV_s to Excel.ps1
|
Function Release-Ref ($ref)
{
([System.Runtime.InteropServices.Marshal]::ReleaseComObject(
[System.__ComObject]$ref) -gt 0)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}
Function ConvertCSV-ToExcel
{
<#
.SYNOPSIS
Converts one or more CSV files into an excel file.
.DESCRIPTION
Converts one or more CSV files into an excel file. Each CSV file is imported into its own worksheet with the name of the
file being the name of the worksheet.
.PARAMETER inputfile
Name of the CSV file being converted
.PARAMETER output
Name of the converted excel file
.EXAMPLE
Get-ChildItem *.csv | ConvertCSV-ToExcel -output 'report.xlsx'
.EXAMPLE
ConvertCSV-ToExcel -inputfile 'file.csv' -output 'report.xlsx'
.EXAMPLE
ConvertCSV-ToExcel -inputfile @("test1.csv","test2.csv") -output 'report.xlsx'
.NOTES
Author: Boe Prox
Date Created: 01SEPT210
Last Modified:
#>
#Requires -version 2.0
[CmdletBinding(
SupportsShouldProcess = $True,
ConfirmImpact = 'low',
DefaultParameterSetName = 'file'
)]
Param (
[Parameter(
ValueFromPipeline=$True,
Position=0,
Mandatory=$True,
HelpMessage="Name of CSV/s to import")]
[ValidateNotNullOrEmpty()]
[array]$inputfile,
[Parameter(
ValueFromPipeline=$False,
Position=1,
Mandatory=$True,
HelpMessage="Name of excel file output")]
[ValidateNotNullOrEmpty()]
[string]$output
)
Begin {
#Configure regular expression to match full path of each file
[regex]$regex = "^\\w\\:\\\\"
#Find the number of CSVs being imported
$count = ($inputfile.count -1)
#Create Excel Com Object
$excel = new-object -com excel.application
#Disable alerts
$excel.DisplayAlerts = $False
#Show Excel application
$excel.Visible = $False
#Add workbook
$workbook = $excel.workbooks.Add()
#Remove other worksheets
$workbook.worksheets.Item(2).delete()
#After the first worksheet is removed,the next one takes its place
$workbook.worksheets.Item(2).delete()
#Define initial worksheet number
$i = 1
}
Process {
ForEach ($input in $inputfile) {
#If more than one file, create another worksheet for each file
If ($i -gt 1) {
$workbook.worksheets.Add() | Out-Null
}
#Use the first worksheet in the workbook (also the newest created worksheet is always 1)
$worksheet = $workbook.worksheets.Item(1)
#Add name of CSV as worksheet name
$worksheet.name = "$((GCI $input).basename)"
#Open the CSV file in Excel, must be converted into complete path if no already done
If ($regex.ismatch($input)) {
$tempcsv = $excel.Workbooks.Open($input)
}
ElseIf ($regex.ismatch("$($input.fullname)")) {
$tempcsv = $excel.Workbooks.Open("$($input.fullname)")
}
Else {
$tempcsv = $excel.Workbooks.Open("$($pwd)\\$input")
}
$tempsheet = $tempcsv.Worksheets.Item(1)
#Copy contents of the CSV file
$tempSheet.UsedRange.Copy() | Out-Null
#Paste contents of CSV into existing workbook
$worksheet.Paste()
#Close temp workbook
$tempcsv.close()
#Select all used cells
$range = $worksheet.UsedRange
#Autofit the columns
$range.EntireColumn.Autofit() | out-null
$i++
}
}
End {
#Save spreadsheet
$workbook.saveas("$pwd\\$output")
Write-Host -Fore Green "File saved to $pwd\\$output"
#Close Excel
$excel.quit()
#Release processes for Excel
$a = Release-Ref($range)
}
}
|
PowerShellCorpus/PoshCode/finddupe_14.ps1
|
finddupe_14.ps1
|
# new version avoids recalculating MD5s, has delete/noprompt options, and by default checks the current directory.
function Get-MD5([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]'))
{
$stream = $null;
$cryptoServiceProvider = [System.Security.Cryptography.MD5CryptoServiceProvider];
$hashAlgorithm = new-object $cryptoServiceProvider
$stream = $file.OpenRead();
$hashByteArray = $hashAlgorithm.ComputeHash($stream);
$stream.Close();
## We have to be sure that we close the file stream if any exceptions are thrown.
trap
{
if ($stream -ne $null)
{
$stream.Close();
}
break;
}
foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }}
return [string]$result;
}
$starttime=[datetime]::now
write-host "Usage: finddupe.ps1 <directory/file #1> <directory/file #2> ... <directory/file #N> [-delete] [-noprompt]"
$matches = 0 # initialize number of matches for summary.
$filesdeleted = 0 # number of files deleted.
$bytesrec = 0 # Number of bytes recovered.
$files=@()
$del = $false # delete duplicates
$noprompt = $false # delete without prompting toggle
$currentdir = $true # work on current directory by default
if ($args -match "-delete") {$del=$true}
if ($args -match "-noprompt") {$noprompt=$true}
$files=(dir -recurse ($args | ?{$_ -ne "-delete" -and $_ -ne "-noprompt"})|?{$_.psiscontainer -ne $true} )
if ($files -eq $null) {"No files found.`a";exit}
for ($i=0;$i -ne $files.count; $i++) # Cycle thru all files
{
if ($files[$i] -eq $null) {continue}
$filecheck = $files[$i]
$files[$i] = $null
for ($c=0;$c -ne $files.count; $c++)
{
if ($files[$c] -eq $null) {continue}
# write-host "Comparing $filecheck and $($files[$c]) `r" -nonewline
if ($filecheck.length -eq $files[$c].length)
{
#write-host "Comparing MD5 of $($filecheck.fullname) and $($files[$c].fullname) `r" -nonewline
if ($filecheck.md5 -eq $null)
{
$md5 = (get-md5 $filecheck.fullname)
$filecheck = $filecheck | %{add-member -inputobject $_ -name MD5 -membertype noteproperty -value $md5 -passthru}
}
if ($files[$c].md5 -eq $null)
{
$md5 = (get-md5 $files[$c].fullname)
$files[$c] = $files[$c] | %{add-member -inputobject $_ -name MD5 -membertype noteproperty -value $md5 -passthru}
}
if ($filecheck.md5 -eq $files[$c].md5)
{
write-host "Size and MD5 match: " -fore red -nonewline
write-host "`"$($filecheck.fullname)`"" -nonewline
write-host " and " -nonewline
write-host "`"$($files[$c].fullname)`""
$matches++
if ($del -eq $true)
{
if ($noprompt -eq $true)
{
del $files[$c].fullname
write-host "Deleted duplicate: " -f red -nonewline
write-host "$($files[$c].fullname)."
}
else
{
del $files[$c].fullname -confirm
}
if ((get-item -ea 0 $files[$c].fullname) -eq $null)
{
$filesdeleted += 1
$bytesrec += $files[$c].length
}
}
$files[$c] = $null
}
}
}
}
write-host ""
write-host "Number of Files checked: $($files.count)." # Display useful info; files checked and matches found.
write-host "Number of duplicates found: $matches."
Write-host "Number of duplicates deleted: $filesdeleted." # Display number of duplicate files deleted and bytes recovered.
write-host "$bytesrec bytes recovered."
write-host ""
write-host "Time to run: $(([datetime]::now)-$starttime|select hours, minutes, seconds, milliseconds)"
write-host ""
|
PowerShellCorpus/PoshCode/Hack ESXi_5.ps1
|
Hack ESXi_5.ps1
|
$screen = " You see here a virtual switch. ------------ ------
#...........| |....|
--------------- ###------------ |...(|
|..%...........|########## ###-@...|
|...%...........### # ## |....|
+.......<......| ### ### |..!.|
--------------- ### ### ------
---.----- ###
|.......|####
---------
.
Clyde the Sysadmin St:7 Dx:9 Co:10 In:18 Wi:18 Ch:6 Chaotic Evil
Dlvl:3 $:120 HP:39(41) Pw:36(36) AC:6 Exp:5 T:1073
"
Set-VMHostAdvancedConfiguration -name Annotations.WelcomeMessage -value $screen
|
PowerShellCorpus/PoshCode/9cae4b8c-e40a-43f0-8dea-dd78acab16c3.ps1
|
9cae4b8c-e40a-43f0-8dea-dd78acab16c3.ps1
|
[reflection.assembly]::LoadWithPartialName("Microsoft.SharePoint") | out-null
[reflection.assembly]::LoadWithPartialName("Microsoft.Office.Server") | out-null
[reflection.assembly]::LoadWithPartialName("Microsoft.Office.Server.Search") | out-null
@@#NOTE: I've set strict crawl freshness/crawl duration/success ratio threshholds. Reset as desired
@@# to something that more suits your reality.
$crawlFreshnessDayThreshhold = 2
$crawlDurationHourThreshhold = 4
$successRatioThreshhold = 0.9
function Calculate-CrawlDuration(
[Microsoft.Office.Server.Search.Administration.SharePointContentSource]$contentSource)
{
if ($contentSource.CrawlStatus -eq [Microsoft.Office.Server.Search.Administration.CrawlStatus]::Idle) {
return "Green - no current crawl"
}
$timespan = [datetime]::Now - $contentSource.CrawlStarted
$timespanFormatted = "Running for $($timespan.TotalDays.ToString('0.00')) Days ($($timespan.TotalHours.ToString('0.0')) hours)"
if ($timespan.TotalHours -le ($crawlDurationHourThreshhold / 2)) {
return "Green - $timespanFormatted"
} elseif ($timespan.TotalHours -le ($crawlDurationHourThreshhold)) {
return "Yellow - $timespanFormatted"
} else {
return "Red - $timespanFormatted"
}
}
function Calculate-CrawlFreshness(
[Microsoft.Office.Server.Search.Administration.SharePointContentSource]$contentSource)
{
$timespan = [datetime]::Now - $contentSource.CrawlCompleted
$timespanFormatted = "$($timespan.TotalDays.ToString('0.00')) days ago"
if ($timespan.Days -le 0) {
return "Green - $timespanFormatted"
} elseif ($timespan.Days -lt $crawlFreshnessDayThreshhold) {
return "Yellow - $timespanFormatted"
} else {
return "Red - $timespanFormatted"
}
}
function Calculate-IndexHealth(
[Microsoft.Office.Server.Search.Administration.SharePointContentSource]$contentSource,
$successCount, $warningCount, $errorCount)
{
$formatted = "($($successCount)/$($warningCount)/$($errorCount))"
if ($errorCount -eq 1) {
return "Red - exactly 1 error, usually indicates permissions/config error - $formatted"
}
$successRatio = ([double]$successCount)/([double]($warningCount + $errorCount))
$successRatioMidpointToPerfection = (1.0 - ((1.0 - $successRatioThreshhold)/2.0))
if ($successRatio -ge $successRatioMidpointToPerfection) {
return "Green - $formatted"
} elseif ($successRatio -ge $successRatioThreshhold) {
return "Yellow - $formatted"
} else {
return "Red - $formatted"
}
}
function Get-CrawlHealth
{
$serverContext = [Microsoft.Office.Server.ServerContext]::Default
$searchContext = [Microsoft.Office.Server.Search.Administration.SearchContext]::GetContext($serverContext)
$content = [Microsoft.Office.Server.Search.Administration.Content]$searchContext
$history = [Microsoft.Office.Server.Search.Administration.CrawlHistory]$searchContext
$contentSources = $content.ContentSources | foreach { $_ }
$contentSources | foreach {
#unroll DataTable object into more useful DataRow object
$crawlHistory = $history.GetLastCompletedCrawlHistory($_.Id) | % { $_ }
add-member -inputobject $_ -membertype NoteProperty -name "CurrentCrawlDuration" -value (Calculate-CrawlDuration $_)
add-member -inputobject $_ -membertype NoteProperty -name "CompletedCrawlFreshness" -value (Calculate-CrawlFreshness $_)
add-member -inputobject $_ -membertype NoteProperty -name "IndexHealth" -value (Calculate-IndexHealth -contentSource $_ $crawlHistory.SuccessCount $crawlHistory.WarningCount $crawlHistory.ErrorCount)
}
$contentSources | select Name, CurrentCrawlDuration, CompletedCrawlFreshness, IndexHealth | fl
}
@@#USAGE: -Open a PowerShell session on the SharePoint server with elevated credentials
@@# (specifically, with access to the SSP - usually the SharePoint farm account)
@@# -Tweak the threshholds (they may be too ambitious for your environment)
@@# -Paste this text into an open PowerShell window and type (without the # mark)
@@# Get-CrawlHealth
|
PowerShellCorpus/PoshCode/Search-AD.ps1
|
Search-AD.ps1
|
# add enumerations and types required for functions
Add-Type @'
using System;
namespace redtoo {
namespace AD {
public enum Provider : int {
LDAP,
GC,
}
}
public class ADsPathPart {
public string Provider;
public string Server;
public string BaseDN;
public string RDN;
public string DCComponent;
public string Parent;
public string DistinguishedName;
}
}
'@
function Test-ObjectPath {
<#
.SYNOPSIS
Tests if an Object in AD exists.
.DESCRIPTION
Tests if an Object in AD exists. Valid inputs are a DN or a DirectoryEntry object.
With parameter you can force an imput type. Without a parameter the script figures out if an input was a string or directoryEntry object.
.PARAMETER DistinguishedName
The distinguished name of the object to be tested. The DN may be specified using aDSPath or distinguished name.
If an incorrect DN syntax is supplied, it will return $false
.PARAMETER DirectoryEntry
A DirectoryEntry object to be tested.
If a string value is passed, it will be casted to a DirectoryEntry.
.PARAMETER isValid
Verifies that the syntax of the DN is correct.
Returns $true if valid and otherwise $false
.PARAMETER PassThru
Returns the [DirectoryServices.DirectoryEntry] object if object exists, otherwise returns false
.PARAMETER AsDN
Use together with -PassThru. Returns distinguished path as String
.PARAMETER AsADsPath
Use together with -PassThru. Returns ADsPath as String
.PARAMETER $SplitParts
Returns a PowerShell object with the different LDAP URI parts
.EXAMPLE
PS C:\\> Test-ObjectPath "CN=myOU,DC=test,DC=intra"
-------------------------------------------------------
Test if an object with the DN CN=myOU,DC=test,DC=intra exists.
.EXAMPLE
PS C:\\> Test-ObjectPath "CN=myOU,DC=test,DC=intra" -isValid
-------------------------------------------------------
Test if the DN CN=myOU,DC=test,DC=intra is correct.
.EXAMPLE
PS C:\\> Test-ObjectPath -DirectoryEntry ([DirectoryServices.DirectoryEntry]"LDAP://CN=myOU,DC=test,DC=intra"
-------------------------------------------------------
Test if an object represented by the directoryEntry of CN=myOU,DC=test,DC=intra exists
.EXAMPLE
PS C:\\> Test-ObjectPath "LDAP://CN=myOU,DC=test,DC=intra"
-------------------------------------------------------
Test if an object with the DN CN=myOU,DC=test,DC=intra exists.
.EXAMPLE
PS C:\\> Test-ObjectPath ([DirectoryServices.DirectoryEntry]"LDAP://CN=myOU,DC=test,DC=intra"
-------------------------------------------------------
Test if an object represented by the directoryEntry of CN=myOU,DC=test,DC=intra exists
.INPUTS
System.String,DirectoryServices.DirectoryEntry
.OUTPUTS
System.Bool
.Notes
NAME: Test-ObjectPath
AUTHOR: Patrick Sczepanski (patrick@sczepanski.com)
Version: 20120716
#Requires -Version 2.0
#>
[Cmdletbinding(DefaultParameterSetName="String")]
Param(
[Alias('dn')]
[Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$True,Position=0,ParameterSetName="String")]
[string]$DistinguishedName,
[Parameter(ParameterSetName="String")]
[switch]$isValid,
[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$True,Position=0,ParameterSetName="DirectoryEntry")]
[System.DirectoryServices.DirectoryEntry]
$DirectoryEntry,
# A System.DirectoryServices.SearchResult object representing the group to list the members from
# You may use Search-AD to find the group to be listed
[Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$True,Position=0,ParameterSetName="SearchResult")]
[AllowNull()]
[DirectoryServices.SearchResult]
$SearchResult,
[Parameter(ParameterSetName="String")]
[string]
$connection,
[Parameter()]
[switch]
$Passthru,
[Parameter()]
[switch]
$AsDN,
[Parameter()]
[switch]
$AsADsPath,
[Parameter()]
[switch]
$SplitParts
)
Begin {
$ThisFunctionName = $MyInvocation.MyCommand.Name
# the function uses different return points due to multiple decissions taken
# it seemed easier to do it this way than try to collect all variations and evaluate again at the end
if( ( $PSBoundParameters.ContainsKey("AsDN") -or $PSBoundParameters.ContainsKey("AsADsPath") -or $PSBoundParameters.ContainsKey("SplitParts") ) -and (-not $PSBoundParameters.ContainsKey("Passthru") ) ) {
Write-Warning "[$ThisFunctionName] :: You need to specify -Passthru if you want to use -AsDN and -AsADsPath"
}
function Split-ADSPath ( $ADSPath ) {
if ( $ADSPath -match '^(?:(?:(?<Provider>LDAP|GC)://)(?:(?<DC>(?:[\\w\\.-])+)/)*)+(?<Base>(?:(?:URI|CN|OU)=.*?,)*)(?<DCComponent>(?:DC=.*)+)$' ) {
# Removed " else { $null }"
New-Object redtoo.ADsPathPart -Property @{
"Provider" = if ($Matches.Contains("Provider") ) { $Matches.Provider };
"Server" = if ($Matches.Contains("DC") ) { $Matches.DC };
"BaseDN" = if ($Matches.Contains("Base") ) { $Matches.base -replace ",$","" };
"RDN" = if ($Matches.Contains("Base") ) { ($Matches.base.split(","))[0] };
"DCComponent" = if ($Matches.Contains("DCComponent") ) { $Matches.DCComponent };
"Parent" = if ($Matches.Contains("Provider") ) { ($Matches.base.split(",", [StringSplitOptions]::RemoveEmptyEntries) | select -Skip 1) -join "," };
"DistinguishedName" = if ($Matches.Contains("Base") -and `
$Matches.Contains("DCComponent") ) { "{0}{1}" -f $Matches.base, $Matches.DCComponent };
}
} else {
Write-Warning "[$ThisFunctionName] :: Failed to match LDAP Path: '$LDAPPath'"
}
}
}
Process {
switch ($pscmdlet.ParameterSetName) {
"String" {
if ( $connection ) {
$connection = $connection + "/"
} else {
$connection = ""
}
switch -regex ( $DistinguishedName ) {
#'^((?<Provider>(LDAP|GC)://)(?<DC>([\\w\\.-])+/)*)+(?<Base>((URI|CN|OU)=.*?,)*)(?<DCComponent>(DC=.*)+)$'
'^(((LDAP|GC)://)(([\\w\\.-])+/)*)+((UID|CN|OU)=.*?,)*(DC=.*)+$' {
$LDAPpath = $DistinguishedName
break
}
'^(([\\w\\.-])+/)*((UID|CN|OU)=.*?,)*(DC=.*)+$' {
# matching dn without machine or domain.
# Allows adding a machine name using -connection which is otherwise ignored
$LDAPpath = "LDAP://$connection$DistinguishedName"
break
}
'^WinNT://(?<Computer>\\w.*|\\.)/(?<Account>\\w.*)$' {
# match WinNT provider such as "WinNT://mycomputer/jdoe,user"
$LDAPpath = $DistinguishedName
break
}
Default { return $false }
}
if ( $isValid ) {
# only verified syntax
return $true
}
$exists = try { [DirectoryServices.DirectoryEntry]::exists("$LDAPpath") } catch { $false }
if ( $exists ) {
if ( $Passthru ) {
if ( $AsDN ) {
return ([regex]::Match($LDAPpath,".*/(.*)")).Groups[1].Value
} elseif ( $AsADsPath ) {
return $LDAPpath
} elseif ( $SplitParts ) {
Split-ADSPath $LDAPpath
} else {
return [DirectoryServices.DirectoryEntry]"$LDAPpath"
}
} else {
return $true
}
} else {
return $false
}
break
}
"DirectoryEntry" {
if ( [string]::IsNullOrEmpty( ( $DirectoryEntry | Get-Member -MemberType Property ) ) ) {
return $false
} else {
if ( $Passthru ) {
if ( $AsDN ) {
return ([regex]::Match($DirectoryEntry.adspath,".*/(.*)")).Groups[1].Value
} elseif ( $AsADsPath ) {
return $DirectoryEntry.adspath
} elseif ( $SplitParts ) {
Split-ADSPath $DirectoryEntry.adspath
} else {
return $DirectoryEntry
}
} else {
return $true
}
}
break
}
"SearchResult" {
if ( [string]::IsNullOrEmpty( $SearchResult ) ) {
return $false
} else {
$DN = $SearchResult.Properties.adspath
if ( $Passthru ) {
if ( $AsDN ) {
return ([regex]::Match($SearchResult.Properties.adspath[0],".*/(.*)")).Groups[1].Value
} elseif ( $AsADsPath ) {
return $SearchResult.Properties.adspath[0]
} elseif ( $SplitParts ) {
Split-ADSPath ( $SearchResult.Properties.adspath[0] )
} else {
return [DirectoryServices.DirectoryEntry]$SearchResult.Properties.adspath
}
} else {
return $true
}
break
}
}
}
}
End {
}
}
function Search-AD {
<#
.Synopsis
Searching Active Directory
.Description
Searching Active Directory
.Parameter Provider
Provider to use to connect. Allowed are GC and LDAP
Default: LDAP
.Parameter Connection
Optional domain controller name used to connect to execute the search
Default: Any (closest)
.Parameter Forest
Use forest root DN as default searchbase, GC as default provider
and set the default scope to subtree
.Parameter Domain
Use current domain root DN as default searchbase
and set the default scope to subtree
.Parameter Searchbase
Distinguished name of the searchbase to start the search from
Default: Current Domain
.Parameter Filter
LDAP filter
Default: (objectclass=*)
.Parameter Attributes
Attributes to be returned
Default distinguishedname
.Parameter Scope
Search scope. Allowed scopes are base, onelevel, subtree
Default: base
.Parameter PageSize
Number of objects returned per page. In standard AD user a number below 1000 which is the default maximum object returned in one step
Default: 1000
.Parameter SizeLimit
Maximum number of objects returned. Enter 0 for unlimited numer
Default: 1000
.Parameter ChooseItem
Allows to choose a single item out of multiple items returned by the search
.Parameter PropertyNamesOnly
Returns only the property names without values
.Parameter FindOne
Returns the first object matching
.Example
$Group = Search-AD -connection "DC1.mydomain.com" -filter "(&(objectcategory=group)(samaccountname=group51)))" -searchbase "DC=mydomain,DC=com" -scope "subtree"
.OUTPUTS
[System.DirectoryServices.SearchResultCollection]
.INPUTS
NA
.Link
Search-AD
.Notes
NAME: Search-AD
AUTHOR: Patrick Sczepanski (patrick@sczepanski.com)
Version: 20120709
#Requires -Version 2.0
#>
[Cmdletbinding(DefaultParameterSetName="DN")]
Param (
[Parameter(ValueFromPipelineByPropertyName=$true,Position=0)]
[redtoo.AD.Provider]$Provider = [redtoo.AD.Provider]::LDAP,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[string]
$Connection,
[Alias('base','b')]
[Parameter(ValueFromPipelineByPropertyName=$true,Position=0,ParameterSetName="DN")]
[ValidateScript( {Test-ObjectPath $_ -IsValid} )]
[string]
$Searchbase = ([DirectoryServices.DirectoryEntry]"LDAP://RootDSE").DefaultNamingContext,
[Parameter(ValueFromPipelineByPropertyName=$true,ParameterSetName="Domain")]
[switch]
$DomainBase,
[Parameter(ValueFromPipelineByPropertyName=$true,ParameterSetName="Forest")]
[switch]
$ForestBase,
[Alias('f')]
[Parameter(ValueFromPipelineByPropertyName=$true)]
[string]
$Filter = "(objectclass=*)",
[Alias('a','attribute','attrib')]
[Parameter(ValueFromPipelineByPropertyName=$true)]
[string[]]
$Attributes,
[Alias('s')]
[Parameter(ValueFromPipelineByPropertyName=$true)]
[DirectoryServices.SearchScope]
$Scope = "base",
[Parameter(ValueFromPipelineByPropertyName=$true)]
[int32]$PageSize = 1000,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[int32]$SizeLimit = 1000,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[switch]$PropertyNamesOnly,
[Alias('choose','select','c')]
[Parameter(ValueFromPipelineByPropertyName=$true)]
[switch]
$ChooseItem,
[Alias('One')]
[switch]
$FindOne,
[switch]
$CountOnly,
[Alias('Chasing')]
[Parameter(ValueFromPipelineByPropertyName=$true)]
[DirectoryServices.ReferralChasingOption]
$ReferralChasing = [DirectoryServices.ReferralChasingOption]::None,
[DirectoryServices.SecurityMasks]
$SecurityMasks = [DirectoryServices.SecurityMasks]::Dacl
)
Begin {
$ThisFunctionName = $MyInvocation.MyCommand.Name
$RootDSE = [DirectoryServices.DirectoryEntry]"LDAP://RootDSE"
if ( ! $RootDSE ) {
Write-Warning "[$ThisFunctionName] :: You are not connected to AD. This function can only be used within an AD Forest."
Return $null
}
}
Process {
switch ( $psCmdlet.ParameterSetName ) {
"Forest" {
$SearchBase = $RootDSE.rootDomainNamingContext
if ( ! $PSBoundParameters.ContainsKey("Provider") ) {
$Provider = [redtoo.AD.Provider]::GC;
}
if ( ! $PSBoundParameters.ContainsKey("Scope") ) {
$Scope = [DirectoryServices.SearchScope]::Subtree
}
}
"Domain" {
$SearchBase = $RootDSE.defaultNamingContext
if ( ! $PSBoundParameters.ContainsKey("Scope") ) {
$Scope = [DirectoryServices.SearchScope]::Subtree
}
}
}
# Normalize the searchbase
# 1. Split it apart
$SearchBaseParts = Test-ObjectPath $SearchBase -passthru -SplitParts
# 2. Get the DC which could resolve the name to allow cross domain searches
if ( $Connection ) {
$SearchBaseParts.Server = $Connection
} else {
# get a DC of the domain on which the object is located
# Taking the DN of the object, getting its parent domain, replacing DC= to make a DNS name which is then used to get the domain context
$DomainDNS = ( $SearchBaseParts.DCComponent ) -replace "DC=","" -replace ",","."
$SearchBaseParts.Server = ( [adsi]"LDAP://$DomainDNS/RootDSE" ).dnsHostName
}
if ( $Provider ) {
$SearchBaseParts.Provider = $Provider
}
# Finally merge information again
$SearchBase = "{0}://{1}/{2}" -f $SearchBaseParts.Provider, $SearchBaseParts.Server, $SearchBaseParts.DistinguishedName
if ( $attributes -notcontains "distinguishedname" ) {
$attributes += "distinguishedname"
}
if ( $CountOnly ) {
$PropertyNamesOnly = $true
$cacheResults = $false
} else {
$cacheResults = $true
}
[DirectoryServices.DirectoryEntry]$searchbaseURI = $SearchBase
[DirectoryServices.DirectorySearcher]$Searcher = new-object DirectoryServices.DirectorySearcher($searchbaseURI)
if ( $attributes -match "NTSecurityDescriptor" ) {
$Searcher.SecurityMasks = $SecurityMasks
}
$Searcher.filter = $filter
$Searcher.CacheResults = $cacheResults
$Searcher.SearchScope = $scope
$Searcher.PageSize = $PageSize
$Searcher.PropertyNamesOnly = $PropertyNamesOnly
$Searcher.PropertiesToLoad.AddRange($attributes)
$Searcher.ReferralChasing = $ReferralChasing
try {
if ( $FindOne ) {
[System.DirectoryServices.SearchResult]$result = $searcher.FindOne()
} else {
[System.DirectoryServices.SearchResultCollection]$result = $searcher.FindAll()
}
}
catch {
Write-Warning "[$ThisFunctionName] :: $_`nBase: $SearchBase`nFilter: $filter`nSearchScope: $scope`nAttributes: $Attributes "
return $null
}
switch ( @(,$result) ) {
{ ($_ -is [System.DirectoryServices.SearchResultCollection]) -and ($_.count -lt 1) } { Write-Debug "[Search-AD] :: Cannot find an object in $searchbase using filter $filter"
if ( $CountOnly ) {
return 0
} else {
return $null
}
break }
{ ($_ -is [System.DirectoryServices.SearchResult] -or ($_.count -eq 1)) } { Write-Debug "[Search-AD] :: Found 1 Object"
if ( $CountOnly ) {
return 1
} else {
return $result
}
break }
{ ($_ -is [System.DirectoryServices.SearchResultCollection]) -and ($_.count -gt 1) } {
if ( $CountOnly ) {
return $_.count
} else {
if ( $chooseitem ) {
[int]$count = -1
foreach($object in $result) {
$count = $count + 1
Write-Host "[$count]: " $object.Properties.distinguishedname
}
$selection = Read-Host "Please select object"
if ( $($selection -lt 0) -or $($selection -gt $count) -or $($count -isnot [int]) ) { Write-Error "Selection '$selection' out of scope.`r`nPlease enter an integer value between 0 and $count."; exit(0) }
return $result[$selection]
} else {
return $result
}
}
break }
default { Write-Error -message "[$ThisFunctionName] :: Issue with switch statement. Please check code. Unexpected Error."; }
}
}
End {
}
}
|
PowerShellCorpus/PoshCode/Set-WebConfig_2.ps1
|
Set-WebConfig_2.ps1
|
function Set-WebConfigSqlConnectionString {
param( [switch]$help,
[string]$configfile = $(read-host "Please enter a web.config file to read"),
[string]$connectionString = $(read-host "Please enter a connection string"),
[switch]$backup = $TRUE
)
$usage = "`$conString = `"Data Source=MyDBname;Initial Catalog=serverName;Integrated Security=True;User Instance=True`"`n"
$usage += "`"Set-WebConfigSqlConnectionString -configfile `"C:\\Inetpub\\wwwroot\\myapp\\web.config`" -connectionString `$conString"
if ($help) {Write-Host $usage;break}
$webConfigPath = (Resolve-Path $configfile).Path
$backup = $webConfigPath + ".bak"
# Get the content of the config file and cast it to XML and save a backup copy labeled .bak
$xml = [xml](get-content $webConfigPath)
#save a backup copy if requested
if ($backup) {$xml.Save($backup)}
$root = $xml.get_DocumentElement();
$root.connectionStrings.add.connectionString = $connectionString
# Save it
$xml.Save($webConfigPath)
}
|
PowerShellCorpus/PoshCode/Set-WindowTransparent.ps1
|
Set-WindowTransparent.ps1
|
## Set-WindowTransparent.ps1
##
##
Add-Type -Type @"
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace TE
{
public static class Win32Methods
{
internal const int GWL_EXSTYLE = -20;
internal const int WS_EX_LAYERED = 0x80000;
internal const int LWA_ALPHA = 0x2;
internal const int LWA_COLORKEY = 0x1;
[DllImport("user32.dll")]
internal static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);
[DllImport("user32.dll")]
internal static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll")]
internal static extern int GetWindowLong(IntPtr hWnd, int nIndex);
public static void SetWindowTransparent(IntPtr hWnd)
{
SetWindowLong(hWnd, GWL_EXSTYLE, GetWindowLong(hWnd, GWL_EXSTYLE) ^ WS_EX_LAYERED);
SetLayeredWindowAttributes(hWnd, 0, 230, LWA_ALPHA);
}
}
}
"@
$hwnd = (Get-Process -Id $pid).MainWindowHandle
[TE.Win32Methods]::SetWindowTransparent($hwnd)
|
PowerShellCorpus/PoshCode/CreateVDS_2.ps1
|
CreateVDS_2.ps1
|
function CreateVDS(
$vdsName, $datacenter, $vmHost, $physicalNic, $portGroupType = "earlyBinding", `
[array]$portGroupNameList = @(),[array]$uplinkList = @() ) {
# ------- Create vDS ------- #
$vdsCreateSpec = New-Object VMware.Vim.DVSCreateSpec
$vdsCreateSpec.configSpec = New-Object VMware.Vim.DVSConfigSpec
$vdsCreateSpec.configSpec.name = $vdsName
$vdsCreateSpec.configSpec.uplinkPortPolicy =
New-Object VMware.Vim.DVSNameArrayUplinkPortPolicy
if ($uplinkList.Count -eq 0) {
$vdsCreateSpec.configSpec.uplinkPortPolicy.uplinkPortName =
New-Object System.String[] (2)
$vdsCreateSpec.configSpec.uplinkPortPolicy.uplinkPortName[0] = "dvUplink1"
$vdsCreateSpec.configSpec.uplinkPortPolicy.uplinkPortName[1] = "dvUplink2"
} else {
$vdsCreateSpec.configSpec.uplinkPortPolicy.uplinkPortName =
New-Object System.String[] ($uplinkList.Count)
for ($i = 0; $i -lt $uplinkList.Count; $i++){
$vdsCreateSpec.configSpec.uplinkPortPolicy.uplinkPortName[$i] =
$uplinkList[$i]
}
}
$hostIdValue = ($vmHost.Id.Split('-', 2))[1]
$vdsCreateSpec.configSpec.host =
New-Object VMware.Vim.DistributedVirtualSwitchHostMemberConfigSpec[] (1)
$vdsCreateSpec.configSpec.host[0] =
New-Object VMware.Vim.DistributedVirtualSwitchHostMemberConfigSpec
$vdsCreateSpec.configSpec.host[0].operation = "add"
$vdsCreateSpec.configSpec.host[0].host =
New-Object VMware.Vim.ManagedObjectReference
$vdsCreateSpec.configSpec.host[0].host.type = "HostSystem"
$vdsCreateSpec.configSpec.host[0].host.value = $hostIdValue
$vdsCreateSpec.configSpec.host[0].backing =
New-Object VMware.Vim.DistributedVirtualSwitchHostMemberPnicBacking
$vdsCreateSpec.configSpec.host[0].backing =
New-Object VMware.Vim.DistributedVirtualSwitchHostMemberPnicBacking
$vdsCreateSpec.configSpec.host[0].backing.pnicSpec =
New-Object VMware.Vim.DistributedVirtualSwitchHostMemberPnicSpec[] (1)
$vdsCreateSpec.configSpec.host[0].backing.pnicSpec[0] =
New-Object VMware.Vim.DistributedVirtualSwitchHostMemberPnicSpec
$vdsCreateSpec.configSpec.host[0].backing.pnicSpec[0].pnicDevice =
$physicalNic.DeviceName
$networkFolderView = Get-View -Id (($datacenter | Get-View).NetworkFolder)
$vdsMoRef = $networkFolderView.CreateDVS($vdsCreateSpec)
# ------- Add vDPortGroup ------- #
if ($portGroupNameList.Count -eq 0){
$portGroupNameList += "dvPortGroup"
}
$vdProtGroupSpec =
New-Object VMware.Vim.DVPortgroupConfigSpec[] ($portGroupNameList.Length)
for ($i = 0; $i -lt $portGroupNameList.Length; $i++){
$vdProtGroupSpec[$i] = New-Object VMware.Vim.DVPortgroupConfigSpec
$vdProtGroupSpec[$i].name = $portGroupNameList[$i]
$vdProtGroupSpec[$i].numPorts = 128
$vdProtGroupSpec[$i].defaultPortConfig =
New-Object VMware.Vim.VMwareDVSPortSetting
$vdProtGroupSpec[$i].defaultPortConfig.vlan =
New-Object VMware.Vim.VmwareDistributedVirtualSwitchVlanIdSpec
$vdProtGroupSpec[$i].defaultPortConfig.vlan.inherited = $false
$vdProtGroupSpec[$i].defaultPortConfig.vlan.vlanId = 0
$vdProtGroupSpec[$i].type = $portGroupType
}
$vdsView = Get-View -Id $vdsMoRef.ToString()
$vdsView.AddDVPortgroup($vdProtGroupSpec)
return $vdsMoRef
}
|
PowerShellCorpus/PoshCode/get windows product key_6.ps1
|
get windows product key_6.ps1
|
function get-windowsproductkey([string]$computer)
{
$Reg = [WMIClass] ("\\\\" + $computer + "\\root\\default:StdRegProv")
$values = [byte[]]($reg.getbinaryvalue(2147483650,"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion","DigitalProductId").uvalue)
$lookup = [char[]]("B","C","D","F","G","H","J","K","M","P","Q","R","T","V","W","X","Y","2","3","4","6","7","8","9")
$keyStartIndex = [int]52;
$keyEndIndex = [int]($keyStartIndex + 15);
$decodeLength = [int]29
$decodeStringLength = [int]15
$decodedChars = new-object char[] $decodeLength
$hexPid = new-object System.Collections.ArrayList
for ($i = $keyStartIndex; $i -le $keyEndIndex; $i++){ [void]$hexPid.Add($values[$i]) }
for ( $i = $decodeLength - 1; $i -ge 0; $i--)
{
if (($i + 1) % 6 -eq 0){$decodedChars[$i] = '-'}
else
{
$digitMapIndex = [int]0
for ($j = $decodeStringLength - 1; $j -ge 0; $j--)
{
$byteValue = [int](($digitMapIndex * [int]256) -bor [byte]$hexPid[$j]);
$hexPid[$j] = [byte] ([math]::Floor($byteValue / 24));
$digitMapIndex = $byteValue % 24;
$decodedChars[$i] = $lookup[$digitMapIndex];
}
}
}
$STR = ''
$decodedChars | % { $str+=$_}
$STR
}
get-windowsproductkey .
|
PowerShellCorpus/PoshCode/SyntaxHighlighter Brush.ps1
|
SyntaxHighlighter Brush.ps1
|
//
/**
* PowerShell 2.0 Brush for highlighter 2.0
*
* SyntaxHighlighter http://alexgorbatchev.com/wiki/SyntaxHighlighter
*
* @version
* 2.1.0 (April 07 2009)
*
* @copyright
* Copyright (C) 2008-2009 Joel Bennett http://HuddledMasses.org/
*
* @license
* This file is for SyntaxHighlighter.
*
* SyntaxHighlighter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* SyntaxHighlighter is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SyntaxHighlighter. If not, see <http://www.gnu.org/licenses/>.
*/
SyntaxHighlighter.brushes.Powershell = function()
{
var keywords ='while validateset validaterange validatepattern validatelength validatecount ' +
'until trap switch return ref process param parameter in if global: '+
'function foreach for finally filter end elseif else dynamicparam do default ' +
'continue cmdletbinding break begin alias \\\\? % #script #private #local #global '+
'mandatory parametersetname position valuefrompipeline ' +
'valuefrompipelinebypropertyname valuefromremainingarguments helpmessage ';
var operators ='and as band bnot bor bxor casesensitive ccontains ceq cge cgt cle ' +
'clike clt cmatch cne cnotcontains cnotlike cnotmatch contains ' +
'creplace eq exact f file ge gt icontains ieq ige igt ile ilike ilt ' +
'imatch ine inotcontains inotlike inotmatch ireplace is isnot le like ' +
'lt match ne not notcontains notlike notmatch or regex replace wildcard';
var verbs = 'write where wait use update unregister undo trace test tee take suspend ' +
'stop start split sort skip show set send select scroll resume restore ' +
'restart resolve resize reset rename remove register receive read push ' +
'pop ping out new move measure limit join invoke import group get format ' +
'foreach export expand exit enter enable disconnect disable debug cxnew ' +
'copy convertto convertfrom convert connect complete compare clear ' +
'checkpoint aggregate add';
this.regexList = [
{ regex: SyntaxHighlighter.regexLib.singleLinePerlComments, css: 'comments' }, // one line comments
{ regex: new RegExp('@"\\\\n[\\\\s\\\\S]*?\\\\n"@', 'gm'), css: 'string' }, // double quoted here-strings
{ regex: new RegExp("@'\\\\n[\\\\s\\\\S]*?\\\\n'@", 'gm'), css: 'string' }, // single quoted here-strings
{ regex: new RegExp('"(?:\\\\$\\\\([^\\\\)]*\\\\)|[^"]|`"|"")*[^`]"','g'), css: 'string' }, // double quoted strings
{ regex: new RegExp("'(?:[^']|'')*'", 'g'), css: 'string' }, // single quoted strings
{ regex: new RegExp('[\\\\$|@|@@](?:(?:global|script|private|env):)?[A-Z0-9_]+', 'gi'), css: 'variable' }, // $variables
{ regex: new RegExp('(?:'+verbs.replace(/ /g, '\\\\b|\\\\b')+')-[a-zA-Z_][a-zA-Z0-9_]*', 'gmi'), css: 'functions' }, // functions and cmdlets
{ regex: new RegExp(this.getKeywords(keywords), 'gmi'), css: 'keyword' }, // keywords
{ regex: new RegExp('-'+this.getKeywords(operators), 'gmi'), css: 'value bold' }, // operators
{ regex: new RegExp('\\\\s+-[a-zA-Z_][a-zA-Z0-9_]*', 'gmi'), css: 'color1' }, // parameters
{ regex: new RegExp('\\\\[[A-Z_\\\\[][A-Z0-9_. `,\\\\[\\\\]]*\\\\]', 'gi'), css: 'constants' }, // .Net [Type]s
];
}
SyntaxHighlighter.brushes.Powershell.prototype = new SyntaxHighlighter.Highlighter();
SyntaxHighlighter.brushes.Powershell.aliases = ['monad', 'msh', 'powershell', 'PowerShell', 'posh'];
|
PowerShellCorpus/PoshCode/Get-WebSite_4.ps1
|
Get-WebSite_4.ps1
|
function Get-WebPage {
<#
.SYNOPSIS
Downloads web page from site.
.DESCRIPTION
Downloads web page from site and displays source code or displays total bytes of webpage downloaded
.PARAMETER Url
URL of the website to test access to.
.PARAMETER UseDefaultCredentials
Use the currently authenticated user's credentials
.PARAMETER Proxy
Used to connect via a proxy
.PARAMETER Credential
Provide alternate credentials
.PARAMETER ShowSize
Displays the size of the downloaded page in bytes
.NOTES
Name: Get-WebPage
Author: Boe Prox
DateCreated: 08Feb2011
.EXAMPLE
Get-WebPage -url "http://www.bing.com"
Description
------------
Returns the source code from bing.com -showsize
.EXAMPLE
Get-WebPage -url "http://www.bing.com" -ShowSize
Description
------------
Returns the size of the webpage bing.com in bytes.
#>
[cmdletbinding(
DefaultParameterSetName = 'url',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = '',
ValueFromPipeline = $True)]
[string][ValidatePattern("^(http|https)\\://*")]$Url,
[Parameter(
Position = 1,
Mandatory = $False,
ParameterSetName = 'defaultcred')]
[switch]$UseDefaultCredentials,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[string]$Proxy,
[Parameter(
Mandatory = $False,
ParameterSetName = 'altcred')]
[switch]$Credential,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[switch]$ShowSize
)
Begin {
$psBoundParameters.GetEnumerator() | % {
Write-Verbose "Parameter: $_"
}
#Create the initial WebClient object
Write-Verbose "Creating web client object"
$wc = New-Object Net.WebClient
#Use Proxy address if specified
If ($PSBoundParameters.ContainsKey('Proxy')) {
#Create Proxy Address for Web Request
Write-Verbose "Creating proxy address and adding into Web Request"
$wc.Proxy = New-Object -TypeName Net.WebProxy($proxy,$True)
}
#Determine if using Default Credentials
If ($PSBoundParameters.ContainsKey('UseDefaultCredentials')) {
#Set to True, otherwise remains False
Write-Verbose "Using Default Credentials"
$wc.UseDefaultCredentials = $True
}
#Determine if using Alternate Credentials
If ($PSBoundParameters.ContainsKey('Credentials')) {
#Prompt for alternate credentals
Write-Verbose "Prompt for alternate credentials"
$wc.Credential = (Get-Credential).GetNetworkCredential()
}
}
Process {
Try {
If ($ShowSize) {
#Get the size of the webpage
Write-Verbose "Downloading web page and determining size"
"{0:N0}" -f ($wr.DownloadString($url) | Out-String).length -as [INT]
}
Else {
#Get the contents of the webpage
Write-Verbose "Downloading web page and displaying source code"
$wc.DownloadString($url)
}
}
Catch {
Write-Warning "$($Error[0])"
}
}
}
|
PowerShellCorpus/PoshCode/PS2WCF_2.ps1
|
PS2WCF_2.ps1
|
# Call WCF Services With PowerShell V1.0 22.12.2008
#
# by Christian Glessner
# Blog: http://www.iLoveSharePoint.com
# Twitter: http://twitter.com/cglessner
# Codeplex: http://codeplex.com/iLoveSharePoint
#
# requires .NET 3.5
# load WCF assemblies
[void][System.Reflection.Assembly]::LoadWithPartialName("System.ServiceModel")
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Runtime.Serialization")
# get metadata of a service
function global:Get-WsdlImporter($wsdlUrl=$(throw "parameter -wsdlUrl is missing"), $httpGet)
{
if($httpGet -eq $true)
{
$local:mode = [System.ServiceModel.Description.MetadataExchangeClientMode]::HttpGet
}
else
{
$local:mode = [System.ServiceModel.Description.MetadataExchangeClientMode]::MetadataExchange
}
$mexClient = New-Object System.ServiceModel.Description.MetadataExchangeClient((New-Object System.Uri($wsdlUrl)),$mode)
$mexClient.MaximumResolvedReferences = [System.Int32]::MaxValue
$metadataSet = $mexClient.GetMetadata()
$wsdlImporter = New-Object System.ServiceModel.Description.WsdlImporter($metadataSet)
return $wsdlImporter
}
# Generate wcf proxy types
function global:Get-WcfProxy($wsdlImporter=$null, $wsdlUrl, $proxyPath)
{
if($wsdlImporter -eq $null -and $wsdlUrl -eq $null)
{
throw "parameter -wsdlImporter or -wsdlUrl must be specified"
}
else
{
if($wsdlImporter -eq $null)
{
$wsdlImporter = Get-WsdlImporter -wsdlUrl $wsdlUrl
trap [Exception]
{
$script:wsdlImporter = Get-WsdlImporter -wsdlUrl $wsdlUrl -httpGet $true
continue
}
}
}
$generator = new-object System.ServiceModel.Description.ServiceContractGenerator
foreach($contractDescription in $wsdlImporter.ImportAllContracts())
{
[void]$generator.GenerateServiceContractType($contractDescription)
}
$parameters = New-Object System.CodeDom.Compiler.CompilerParameters
if($proxyPath -eq $null)
{
[void]$parameters.GenerateInMemory = $true
}
else
{
$parameters.OutputAssembly = $proxyPath
}
$providerOptions = new-object "System.Collections.Generic.Dictionary``2[System.String,System.String]"
[void]$providerOptions.Add("CompilerVersion","v3.5")
$compiler = New-Object Microsoft.CSharp.CSharpCodeProvider($providerOptions)
$result = $compiler.CompileAssemblyFromDom($parameters, $generator.TargetCompileUnit);
if($result.Errors.Count -gt 0)
{
throw "Proxy generation failed"
}
foreach($type in $result.CompiledAssembly.GetTypes())
{
if($type.BaseType.IsGenericType)
{
if($type.BaseType.GetGenericTypeDefinition().FullName -eq "System.ServiceModel.ClientBase``1" )
{
$type
}
}
}
}
|
PowerShellCorpus/PoshCode/DekiWiki Module 1.0.ps1
|
DekiWiki Module 1.0.ps1
|
## DekiWiki Module -note this is a v2 module, but I think you can dot-source in v1 if you remove the last line ;)
####################################################################################################
## The first of many script cmdlets for working with DekiWiki, based on their REST api sdk "Dream"
## You need log4net.dll mindtouch.core.dll mindtouch.dream.dll and SgmlReaderDll.dll from the SDK
## Download DREAM from http://sourceforge.net/project/showfiles.php?group_id=173074
## Unpack it, and you can find these dlls in the "dist" folder.
####################################################################################################
## More details to come with the next version. Sorry, it's time for bed ;)
## History:
## v 1.0 Set-DekiCredential, Get-DekiContent, Set-DekiContent, New-DekiContent, Get-DekiFile
##
[Reflection.Assembly]::LoadFile( "$PSScriptRoot\\mindtouch.dream.dll" )
$url = "http://powershell.wik.is" #
$api = "$url/@api/deki"
$plug = [MindTouch.Dream.Plug]::New($api);
$cred = $null
function Set-DekiCredential {
param($Credential=$(Get-Credential))
$global:cred = $Credential
}
function Get-DekiCredential {
if(!$global:cred) { Set-DekiCredential $(Get-Credential) }
return $global:cred.GetNetworkCredential();
}
$DreamText = [MindTouch.Dream.MimeType]::TEXT
$DreamXml = [MindTouch.Dream.MimeType]::XML
$DreamHtml = [MindTouch.Dream.MimeType]::HTML
function Get-DekiContent {
param( $pageName = "Test_Page" )
$pageName = [System.Web.HttpUtility]::UrlEncode( [System.Web.HttpUtility]::UrlEncode( $pageName ) )
$plug.At("pages", "=$pageName", "contents").With("mode", "view").Get().AsDocument().AsXmlNode
}
# Get-DekiFile will LIST all files if called with just a PageName
# Otherwise, fileName can be a single fileName, or wildcards
function Get-DekiFile {
param( $pageName = "Test_Page", [string[]]$fileNames, $destinationFolder )
$encodedPageName = Encode-Twice $pageName
$files = $plug.At("pages", "=$encodedPageName", "files").Get().AsDocument().AsXmlNode.file
if(!$fileNames) {
return $files
} else {
foreach($fileName in $fileNames) {
foreach($file in $($files | where { $_.filename -like $fileName } )) {
$encodedFileName = [System.Web.HttpUtility]::UrlEncode( [System.Web.HttpUtility]::UrlEncode( $($file.filename) ) )
Write-Verbose "Fetching $($file.filename) from $pageName"
# Note that you can resize, if it's a picture: .With("size", "bestfit").With("width", 100).With("height", 100).Get();
$message = $plug.At("pages", "=$encodedPageName", "files", "=$encodedFileName").Get()
$fullName = $(Get-FileName $file.filename destinationFolder)
&{
$writer = new-object System.IO.FileStream $fullName, "Create"
$bytes = $message.AsBytes()
$writer.Write($bytes,0,$bytes.Length)
trap {
$writer.Flush()
$writer.Close()
}
$writer.Flush()
$writer.Close()
}
write-output (get-item $fullName)
}
}
}
}
function Set-DekiContent {
param( $pageName = "Test_Page", $content = (throw "You must specify page contents"), $section )
$encodedPageName = Encode-Twice $pageName
# you have to pre-authenticate ...
$null = $plug.At("users", "authenticate").WithCredentials( $(Get-DekiCredential) ).Get()
if( $content -is [System.Xml.XmlDocument]) {
$msg = [MindTouch.Dream.DreamMessage]::Ok( $content )
} else {
$msg = [MindTouch.Dream.DreamMessage]::Ok( $DreamText, $content )
}
Write-Verbose "Updating $pageName at $(UtcNow "yyyyMMddhhmmss"): $($msg.ContentLength) bytes"
Write-Verbose "$($msg.AsText())"
$partway = $plug.At("pages", "=$encodedPageName", "contents").With("edittime",$(UtcNow "yyyyMMddhhmmss"))
if($section) {
$result = $partway.With("Section",0).Post( $msg )
} else {
$result = $partway.Post( $msg )
}
if($result.IsSuccessful) {
return "$url/$pageName"
} else {
return $result.Response
}
trap [MindTouch.Dream.DreamResponseException] {
Write-Error "TRAPPED DreamResponseException`n`n$($_.Exception.Response | Out-String)`n`n`n$($_.Exception.Response.Headers | Out-String)"
break;
}
}
function New-DekiContent {
param( $pageName = "Test_Page", $content = (throw "You must specify page contents") )
$encodedPageName = Encode-Twice $pageName
# you have to pre-authenticate ...
$null = $plug.At("users", "authenticate").WithCredentials( $(Get-DekiCredential) ).Get()
if( $content -is [System.Xml.XmlDocument]) {
$msg = [MindTouch.Dream.DreamMessage]::Ok( $content )
} else {
$msg = [MindTouch.Dream.DreamMessage]::Ok( $DreamText, $content )
}
Write-Verbose "Updating $pageName at $(UtcNow "yyyyMMddhhmmss"): $($msg.ContentLength) bytes"
Write-Verbose "$($msg.AsText())"
$result = $plug.At("pages", "=$encodedPageName", "contents").With("abort", "exists").With("edittime",$(UtcNow "yyyyMMddhhmmss")).Post( $msg )
trap [MindTouch.Dream.DreamResponseException] {
Write-Error "TRAPPED DreamResponseException`n`n$($_.Exception.Response | Out-String)`n`n`n$($_.Exception.Response.Headers | Out-String)"
}
if($result.IsSuccessful) {
return "$url/$pageName"
} else {
return $result.Response
}
}
## Utility Functions
function UtcNow {
Param($Format="")
[DateTime]::Now.ToUniversalTime().ToString($Format)
}
function Encode-Twice {
param([string]$text)
return [System.Web.HttpUtility]::UrlEncode( [System.Web.HttpUtility]::UrlEncode( $text ) )
}
function Get-FileName {
param($fileName=$([IO.Path]::GetRandomFileName()), $path)
$fileName = $fileName.trim("\\/""'")
if($path -and (Test-Path $path)){
$fileName = Split-Path $fileName -leaf
Join-Path $path $fileName
} elseif((Split-Path $fileName) -and (Test-Path (Split-Path $fileName))) {
return $fileName
} else {
Join-Path (Convert-Path (Get-Location -PSProvider "FileSystem")) (Split-Path $fileName -Leaf)
}
}
Export-ModuleMember Set-DekiCredential, Get-DekiContent, Set-DekiContent, New-DekiContent, Get-DekiFile
|
PowerShellCorpus/PoshCode/Format-TablePlus.ps1
|
Format-TablePlus.ps1
|
## Format-Table with wrapping and string trimming.
function Format-TablePlus() {
[CmdletBinding()]
param(
[Switch]
${AutoSize},
[Switch]
${HideTableHeaders},
[Switch]
${Wrap},
[Parameter(Position=0)]
[System.Object[]]
${Property},
[System.Object]
${GroupBy},
[System.String]
${View},
[Switch]
${ShowError},
[Switch]
${DisplayError},
[Switch]
${Force},
[ValidateSet('CoreOnly','EnumOnly','Both')]
[System.String]
${Expand},
[System.Int32]
${Width} = $Host.Ui.RawUI.BufferSize.Width,
[Switch]
${PadEnd},
[Parameter(ValueFromPipeline=$true)]
[System.Management.Automation.PSObject]
${InputObject}
)
begin
{
try {
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
# need to get rid of these before we pass this to the Format-Table cmdlet
$null = $PSBoundParameters.Remove("Width")
$null = $PSBoundParameters.Remove("TrimEnd")
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Format-Table', [System.Management.Automation.CommandTypes]::Cmdlet)
## I made the trimming optional, but defaulted it to on ;)
$scriptCmd = &{
if($PadEnd) {
{& $wrappedCmd @PSBoundParameters | Out-String -Stream -Width $Width }
} else {
{& $wrappedCmd @PSBoundParameters | Out-String -Stream -Width $Width | % { $_.TrimEnd() } }
}
}
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Format-Table
.ForwardHelpCategory Cmdlet
#>
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.