full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PoshCode/ISE-Comments_1.ps1
|
ISE-Comments_1.ps1
|
#requires -version 2.0
## ISE-Comments module v 1.1
##############################################################################################################
## Provides Comment cmdlets for working with ISE
## ConvertTo-BlockComment - Comments out selected text with <# before and #> after
## ConvertTo-BlockUncomment - Removes <# before and #> after selected text
## ConvertTo-Comment - Comments out selected text with a leeding # on every line
## ConvertTo-Uncomment - Removes leeding # on every line of selected text
##
## Usage within ISE or Microsoft.PowershellISE_profile.ps1:
## Import-Module ISE-Comments.psm1
##
## Note: The IsePack, a part of the PowerShellPack, also contains a "Toggle Comments" command,
## but it does not support Block Comments
## http://code.msdn.microsoft.com/PowerShellPack
##
##############################################################################################################
## History:
## 1.1 - Minor alterations to work with PowerShell 2.0 RTM and Documentation updates (Hardwick)
## 1.0 - Initial release (Poetter)
##############################################################################################################
## ConvertTo-BlockComment
##############################################################################################################
## Comments out selected text with <# before and #> after
## This code was originaly designed by Jeffrey Snover and was taken from the Windows PowerShell Blog.
## The original function was named ConvertTo-Comment but as it comments out a block I renamed it.
##############################################################################################################
function ConvertTo-BlockComment
{
$editor = $psISE.CurrentFile.Editor
$CommentedText = "<#`n" + $editor.SelectedText + "#>"
# INSERTING overwrites the SELECTED text
$editor.InsertText($CommentedText)
}
## ConvertTo-BlockUncomment
##############################################################################################################
## Removes <# before and #> after selected text
##############################################################################################################
function ConvertTo-BlockUncomment
{
$editor = $psISE.CurrentFile.Editor
$CommentedText = $editor.SelectedText -replace ("^<#`n", "")
$CommentedText = $CommentedText -replace ("#>$", "")
# INSERTING overwrites the SELECTED text
$editor.InsertText($CommentedText)
}
## ConvertTo-Comment
##############################################################################################################
## Comments out selected text with a leeding # on every line
##############################################################################################################
function ConvertTo-Comment
{
$editor = $psISE.CurrentFile.Editor
$CommentedText = $editor.SelectedText.Split("`n")
# INSERTING overwrites the SELECTED text
$editor.InsertText( "#" + ( [String]::Join("`n#", $CommentedText)))
}
## ConvertTo-Uncomment
##############################################################################################################
## Comments out selected text with <# before and #> after
##############################################################################################################
function ConvertTo-Uncomment
{
$editor = $psISE.CurrentFile.Editor
$CommentedText = $editor.SelectedText.Split("`n") -replace ( "^#", "" )
# INSERTING overwrites the SELECTED text
$editor.InsertText( [String]::Join("`n", $CommentedText))
}
##############################################################################################################
## Inserts a submenu Comments to ISE's Custum Menu
## Inserts command Block Comment Selected to submenu Comments
## Inserts command Block Uncomment Selected to submenu Comments
## Inserts command Comment Selected to submenu Comments
## Inserts command Uncomment Selected to submenu Comments
##############################################################################################################
if (-not( $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus | where { $_.DisplayName -eq "Comments" } ) )
{
$commentsMenu = $psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("_Comments",$null,$null)
$null = $commentsMenu.Submenus.Add("Block Comment Selected", {ConvertTo-BlockComment}, "Ctrl+SHIFT+B")
$null = $commentsMenu.Submenus.Add("Block Uncomment Selected", {ConvertTo-BlockUncomment}, "Ctrl+Alt+B")
$null = $commentsMenu.Submenus.Add("Comment Selected", {ConvertTo-Comment}, "Ctrl+SHIFT+C")
$null = $commentsMenu.Submenus.Add("Uncomment Selected", {ConvertTo-Uncomment}, "Ctrl+Alt+C")
}
# If you are using IsePack (http://code.msdn.microsoft.com/PowerShellPack) and IseCream (http://psisecream.codeplex.com/),
# you can use this code to add your menu items. The added benefits are that you can specify the order of the menu items and
# if the shortcut already exists it will add the menu item without the shortcut instead of failing as the default does.
# Add-IseMenu -Name "Comments" @{
# "Block Comment Selected" = {ConvertTo-BlockComment}| Add-Member NoteProperty order 1 -PassThru | Add-Member NoteProperty ShortcutKey "Ctrl+SHIFT+B" -PassThru
# "Block Uncomment Selected" = {ConvertTo-BlockUncomment}| Add-Member NoteProperty order 2 -PassThru | Add-Member NoteProperty ShortcutKey "Ctrl+Alt+B" -PassThru
# "Comment Selected" = {ConvertTo-Comment}| Add-Member NoteProperty order 3 -PassThru | Add-Member NoteProperty ShortcutKey "Ctrl+SHIFT+C" -PassThru
# "Uncomment Selected" = {ConvertTo-Uncomment}| Add-Member NoteProperty order 4 -PassThru | Add-Member NoteProperty ShortcutKey "Ctrl+Alt+C" -PassThru
# }
|
PowerShellCorpus/PoshCode/Invoke-ComplexDebuggerSc.ps1
|
Invoke-ComplexDebuggerSc.ps1
|
#############################################################################\n##\n## Invoke-ComplexDebuggerScript\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nDemonstrates the functionality of PowerShell's debugging support.\n\n#>\n\nSet-StrictMode -Version Latest\n\nfunction HelperFunction\n{\n $dirCount = 0\n}\n\nWrite-Host "Calculating lots of complex information"\n\n$runningTotal = 0\n$runningTotal += [Math]::Pow(5 * 5 + 10, 2)\n$runningTotal\n\n$dirCount = @(Get-ChildItem $env:WINDIR).Count\n$dirCount\n\nHelperFunction\n\n$dirCount\n\n$runningTotal -= 10\n$runningTotal /= 2\n$runningTotal\n\n$runningTotal *= 3\n$runningTotal /= 2\n$runningTotal
|
PowerShellCorpus/PoshCode/Set-RemoteRegistryKeyPro.ps1
|
Set-RemoteRegistryKeyPro.ps1
|
##############################################################################\n##\n## Set-RemoteRegistryKeyProperty\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\nSet the value of a remote registry key property\n\n.EXAMPLE\n\nPS >$registryPath =\n "HKLM:\\software\\Microsoft\\PowerShell\\1\\ShellIds\\Microsoft.PowerShell"\nPS >Set-RemoteRegistryKeyProperty LEE-DESK $registryPath `\n "ExecutionPolicy" "RemoteSigned"\n\n#>\n\nparam(\n ## The computer to connect to\n [Parameter(Mandatory = $true)]\n $ComputerName,\n\n ## The registry path to modify\n [Parameter(Mandatory = $true)]\n $Path,\n\n ## The property to modify\n [Parameter(Mandatory = $true)]\n $PropertyName,\n\n ## The value to set on the property\n [Parameter(Mandatory = $true)]\n $PropertyValue\n)\n\nSet-StrictMode -Version Latest\n\n## Validate and extract out the registry key\nif($path -match "^HKLM:\\\\(.*)")\n{\n $baseKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey(\n "LocalMachine", $computername)\n}\nelseif($path -match "^HKCU:\\\\(.*)")\n{\n $baseKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey(\n "CurrentUser", $computername)\n}\nelse\n{\n Write-Error ("Please specify a fully-qualified registry path " +\n "(i.e.: HKLM:\\Software) of the registry key to open.")\n return\n}\n\n## Open the key and set its value\n$key = $baseKey.OpenSubKey($matches[1], $true)\n$key.SetValue($propertyName, $propertyValue)\n\n## Close the key and base keys\n$key.Close()\n$baseKey.Close()
|
PowerShellCorpus/PoshCode/ConvertTo-PseudoType_2.ps1
|
ConvertTo-PseudoType_2.ps1
|
#function ConvertTo-PseudoType {
<#
.Synopsis
Convert an object to a custom PSObject wiith robust type information
.Parameter TypeName
The name(s) of the PseudoType(s) to be inserted into the objects for the sake of formatting
.Parameter Mapping
A Hashtable of property names to types (or conversion scripts)
.Parameter InputObject
An object to convert.
.Example
Get-ChildItem | Where { !$_.PsIsContainer } | Export-CSV files.csv
## Given that a CSV file of file information exists,
## And we want to rehydrate it and be able to compare things...
## We need to create a mapping of properties to types
## Optionally, we can provide scriptblocks to convert instances
$Mapping = @{
Attributes = [System.IO.FileAttributes]
CreationTime = [System.DateTime]
CreationTimeUtc = [System.DateTime]
Directory = [System.IO.DirectoryInfo]
DirectoryName = [System.String]
Exists = [System.Boolean]
Extension = [System.String]
FullName = [System.String]
IsReadOnly = [System.Boolean]
LastAccessTime = [System.DateTime]
LastAccessTimeUtc = [System.DateTime]
LastWriteTime = [System.DateTime]
LastWriteTimeUtc = [System.DateTime]
Length = [System.Int64]
Name = [System.String]
PSChildName = [System.String]
PSDrive = [System.Management.Automation.PSDriveInfo]
PSIsContainer = [System.Boolean]
PSParentPath = [System.String]
PSPath = [System.String]
PSProvider = { Get-PSProvider $_ }
ReparsePoint = [System.Management.Automation.PSCustomObject]
VersionInfo = [System.Diagnostics.FileVersionInfo]
}
## Selected.System.IO.FileInfo is what you'd get from | Select *
## But we'll ALSO specify System.IO.FileInfo to get formatted output
Import-CSV | ConvertTo-PseudoType Selected.System.IO.FileInfo, System.IO.FileInfo $Mapping
## That way, the output will look as though you had run:
Get-ChildItem | Where { !$_.PsIsContainer } | Select *
NOTE: Not all types are rehydrateable from CSV output -- the "VersionInfo" will be hydrated as a string...
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0)]
[Alias("Name","Tn")]
[String[]]$TypeName
,
[Parameter(Mandatory=$true, Position=1)]
[Hashtable]$Mapping
,
[Parameter(Mandatory=$true, Position=99, ValueFromPipeline=$true)]
[PSObject[]]$InputObject
)
begin {
$MappingFunction = @{}
foreach($key in $($Mapping.Keys)) {
$MappingFunction.$Key = {$_.$Key -as $Mapping.$Key}
}
[Array]::Reverse($TypeName)
}
process {
foreach($IO in $InputObject) {
$Properties = @{}
foreach($key in $($Mapping.Keys)) {
if($Mapping.$Key -is [ScriptBlock]) {
$Properties.$Key = $IO.$Key | ForEach-Object $Mapping.$Key
} elseif($Mapping.$Key -is [Type]) {
if($Value = $IO.$Key -as $Mapping.$Key) {
$Properties.$Key = $Value
} else {
$Properties.$Key = $IO.$Key
}
} else {
$Properties.$Key = [PSObject]$IO.$Key
}
}
New-Object PSObject -Property $Properties | %{ foreach($type in $TypeName) { $_.PSTypeNames.Insert(0, $type) } $_ }
}
}
#}
|
PowerShellCorpus/PoshCode/Convert-PowerPack2Ps_1.ps1
|
Convert-PowerPack2Ps_1.ps1
|
#######################################################################
# Convert-PowerPack2Ps1
#
# Converts PowerGUI .PowerPack files to ps1 PowerShell script library
# v1 - raw conversion, no name changes, only script elements converted
######################################################################
# Example:
# & .\\Convert-PowerPack2Ps1.ps1 "ActiveDirectory.powerpack" "ActiveDirectory.ps1"
# . .\\ActiveDirectory.ps1
# Get-QADUser 'Dmitry Sotnikov' | MemberofRecursive
######################################################################
#
# (c) Dmitry Sotnikov
# http://dmitrysotnikov.wordpress.com
#
#####################################################################
param(
$PowerPackFile = (throw 'Please supply path to source powerpack file'),
$OutputFilePath = (throw 'Please supply path to output ps1 file')
)
#region Functions
function IterateTree {
# processes all script nodes
param($segment)
if ( $segment.Type -like 'Script*' ) {
$name = $segment.name -replace ' |\\(|\\)', ''
$code = $segment.script.PSBase.InnerText
@"
########################################################################
# Function: $name
# Return type: $($segment.returntype)
########################################################################
function $name {
$code
}
"@ | Out-File $OutputFilePath -Append
}
# recurse folders
if ($segment.items.container -ne $null) {
$segment.items.container | ForEach-Object { IterateTree $_ }
}
}
function Output-Link {
PROCESS {
if ( $_.script -ne $null ) {
$name = $_.name -replace ' |\\(|\\)', ''
$code = $_.script.PSBase.InnerText
@"
########################################################################
# Function: $name
# Input type: $($_.type)
# Return type: $($_.returntype)
########################################################################
function $name {
$code
}
"@ | Out-File $OutputFilePath -Append
}
}
}
#endregion
$sourcefile = Get-ChildItem $PowerPackFile
if ($sourcefile -eq $null) { throw 'File not found' }
@"
########################################################################
# Generated from: $PowerPackFile
# by Convert-PowerPack2Ps1 script
# on $(get-date)
########################################################################
"@ | Out-File $OutputFilePath
$pp = [XML] (Get-Content $sourcefile)
@"
# Scripts generated from script nodes
"@ | Out-File $OutputFilePath -Append
IterateTree $pp.configuration.items.container[0]
@"
# Scripts generated from script links
"@ | Out-File $OutputFilePath -Append
$pp.configuration.items.container[1].items.container |
where { $_.id -eq '481eccc0-43f8-47b8-9660-f100dff38e14' } | ForEach-Object {
$_.items.item, $_.items.container | Output-Link
}
@"
# Scripts generated from script actions
"@ | Out-File $OutputFilePath -Append
$pp.configuration.items.container[1].items.container |
where { $_.id -eq '7826b2ed-8ae4-4ad0-bf29-1ff0a25e0ece' } | ForEach-Object {
$_.items.item, $_.items.container | Output-Link
}
|
PowerShellCorpus/PoshCode/Custom Object Factory Te.ps1
|
Custom Object Factory Te.ps1
|
<#
.SYNOPSIS
A template for a function that creates a PSObject
.DESCRIPTION
If you find yourself creating a lot of custom PSObjects with lots of Properties, this template
may help save you some typing. It discovers the function paramters, and uses them to create a hash
that is splatted against a (new-object psObject)
Any arguments to the function are used as values of the corresponding property when the object is created
Any default values of the function parameters are used as values of the corresponding property
The ParameterSetName defaults to 'All', and is stored as a Property of the object.
If you use ParameterSetName attribute for a function parameter, and call the function specifying one such ParameterSetNamed argument,
the value of the ParamterSetName property identifies which set of Properties are created on the object
Becasue this is a snippet intended to be reused, the first four non-comment lines are the important part
The lines are a bit long, but that makes it easier to cut'n'paste them into a function
.PARAMETER Name
Any Parameter supplied to the function becomes a Property on the PSObject
Any value supplied for a Parameter becomes the value of the Property on the PSObject
.OUTPUTS
As written, a PSOBject is returned, with Properties as defined by the Parameters.
The following is an Example, only the first four non-commented lines are important
#>
function New-CustomDemoObject {
[CmdletBinding(DefaultParametersetName='All')]
Param (
# Replace all of the following parameters with your specific needs
[parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] $Workbook = 'T1.xlsx'
,[parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)][switch] $isVisible
,[parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)][switch] $isKeepOpen
,[parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)][string] $SortDirection = 'Ascending'
,[parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)][string[]] $DatabaseConnectionStrings = @('connecstr1','connectstr2')
,[parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] $ParameterWithDefaultArray = @('connecstr5','connectstr6')
,[parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)][hashtable] $CommandStringsHash = @{cmd1=@{cmdstr='a command';vo=1;so=2};cmd2=@{cmdstr='b command';vo=2;so=1}}
,[parameter(ParameterSetName='PathToDir',ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] $PathToDir = 'C:/Logs'
,[parameter(ParameterSetName='PathToZip',ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] $PathToZip = 'C:/Logs/Backups'
,[parameter(ParameterSetName='PathToZip',ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] $PathInZip = './'
,[parameter(Position=0, ValueFromRemainingArguments=$true)] $RemainingArgs
)
# the following four non-comment lines are the snippet that creates an object from the parameters
# Create a list of the common parameters as a RegExp match string
# Do this by creating a function 'gcp' that has no arguments, then get it's parameters.
# These are the Common Parameters Powershell puts on every function
# List them, Stick ^ at the beginning of each and $ at the end of each,
# and join them using '|' into a single string,
$cp = iex 'function gcp{[CmdletBinding()]Param()$p1=@();((gci Function:$($pscmdlet.MyInvocation.MyCommand)).Parameters).Keys|%{$p1+=$_};$p1|%{"^$_`$"}};[string]::join("|",(gcp))'
# Now operate on "this" function, list it's function's parameters, eliminate the Common Parameters,
# and with the remainder create a hash using the parameter name and parameter type
$p1=@{};((gci Function:$($pscmdlet.MyInvocation.MyCommand)).Parameters).Keys|?{$_ -notmatch $cp}|%{$p1.$_=((gci Function:$($pscmdlet.MyInvocation.MyCommand)).Parameters).$_.ParameterType.Name}
# Iterate over this function's real parameters, turn switches to bools,
# remove ActionPreference (and you can do whatever else you want to in this loop)
# This is a good place to remove any properties, or change them, or add things
$p2=$p1.Clone();$p1.Keys|%{$key=$_;switch ($p1.$_) {'SwitchParameter' {$p2.$key='Bool';break}'ActionPreference' {$p2.Remove($key);break}}}
# Add the ParameterSet as a property and create a new object
# using the hash of argument names and values
# This version of the last line creates strongly-typed Properties,
# but won't handle Parameters/Properties of type arrary or hashtable
# new-object psObject -Property (&(iex $('{@{ParameterSet=[string]'+ "'$($PsCmdlet.ParameterSetName)';" +[string]::join(";",($p2.Keys|%{("{0}="-f $_+'['+$p2.$_+']'+'"$'+$_ +'"')}))+'}}')))
# This version of the last line creates untyped Properties, and does handle hashtables and arrays.
# The keys of $p2 are the properties for the object. the variable (psuedocode) $$key is the value
# Create a statement that can be invoked, then called, which results in a long hash to pass to the -Property operator
# See also this blog https://jamesone111.wordpress.com/2011/01/11/why-it-is-better-not-to-use-powershell-parameter-validation/
new-object psObject -Property (&(iex $('{@{ParameterSet=[string]'+"'$($PsCmdlet.ParameterSetName)';"+[string]::join(";",($p2.Keys|%{("{0}="-f $_+"`$$_")}))+'}}')))
# Now in your own function, you can move properties around, change them, extend them, etc
# I strip out all the comments above, and replace them all with a reference back to this post, to save space.
}
$newobj1 = New-CustomDemoObject # If none of the specific ParamterSet arguments are supplied, the default ParamterSetName 'All' causes all parameters to be created on the PsObject as empty Properties
$newobj2 = New-CustomDemoObject -Workbook 'another.xlsx' -PathToDir 'D:\\Logs'
$newobj3 = New-CustomDemoObject -isVisible -PathToZip 'D:\\Logs\\Backups'
#$newobj4 = New-CustomDemoObject -Workbook 'another.xlsx' -PathToZip 'D:\\Logs\\Backups' -PathToDir 'D:\\Logs' # Uncomment this - you will see an error about paramterset cannot be resolved
# Type $newobj1 ( and $newobj2, and $newobj3) at the command prompt to see the objects that got created
|
PowerShellCorpus/PoshCode/New-Exch2010NlbCluster_1.ps1
|
New-Exch2010NlbCluster_1.ps1
|
###########################################################################
#
# NAME: New-Exch2010NlbCluster.ps1
#
# AUTHOR: Jan Egil Ring
# EMAIL: jer@powershell.no
#
# COMMENT: Script to create a NLB-cluster for the CAS/HUB-roles in Exchange Server 2010.
# For more details, see the following blog-post: http://blog.powershell.no/2010/05/21/script-to-create-a-nlb-cluster-for-the-cas-role-in-exchange-server-2010
#
# You have a royalty-free right to use, modify, reproduce, and
# distribute this script file in any way you find useful, provided that
# you agree that the creator, owner above has no warranty, obligations,
# or liability for such use.
#
# VERSION HISTORY:
# 1.0 20.05.2010 - Initial release
#
###########################################################################
#Importing Microsoft`s PowerShell-module for administering NLB Clusters
Import-Module NetworkLoadBalancingClusters
#Variables for creating the new cluster
$ClusterFqdn = Read-Host "Enter FQDN for the new cluster"
$InterfaceName = Read-Host "Enter interface name for NLB-adapter"
$ClusterPrimaryIP = Read-Host "Enter cluster primary IP"
$ClusterPrimaryIPSubnetMask = Read-Host "Enter subnetmask for cluster primary IP"
Write-Host "Choose cluster operation mode"
Write-Host "1 - Unicast"
Write-Host "2 - Multicast"
Write-Host "3 - IGMP Multicast"
switch (Read-Host "Enter the number for your chosen operation mode")
{
1 {$OperationMode = "unicast"}
2 {$OperationMode = "multicastcast"}
3 {$OperationMode = "igmpmulticast"}
default {Write-Warning "Invalid option, choose '1', '2' or '3'";return}
}
$MSExchangeRPCPort = Read-Host "Enter static port configured for Microsoft Exchange RPC (MAPI)"
$MSExchangeABPort = Read-Host "Enter static port configured for Microsoft Exchange Address book service"
#Creating new cluster
Write-Host "Creating NLB Cluster..." -ForegroundColor yellow
New-NlbCluster -ClusterName $ClusterFqdn -InterfaceName $InterfaceName -ClusterPrimaryIP $ClusterPrimaryIP -SubnetMask $ClusterPrimaryIPSubnetMask -OperationMode $OperationMode
#Removing default port rule for the new cluster
Write-Host "Removing default port rule..." -ForegroundColor yellow
Get-NlbClusterPortRule -HostName . | Remove-NlbClusterPortRule -Force
#Adding port rules for Exchange Server 2010 CAS (SMTP, http, POP3, RPC, IMAP4, https, static port for MSExchangeRPC and MSExchangeAB)
Write-Host "Adding port rules for Exchange Server 2010 CAS" -ForegroundColor yellow
Add-NlbClusterPortRule -Protocol Tcp -Mode Multiple -Affinity Single -StartPort 25 -EndPort 25 -InterfaceName $InterfaceName | Out-Null
Write-Host "Added port rule for SMTP (tcp 25)" -ForegroundColor yellow
Add-NlbClusterPortRule -Protocol Tcp -Mode Multiple -Affinity Single -StartPort 80 -EndPort 80 -InterfaceName $InterfaceName | Out-Null
Write-Host "Added port rule for http (tcp 80)" -ForegroundColor yellow
Add-NlbClusterPortRule -Protocol Tcp -Mode Multiple -Affinity Single -StartPort 110 -EndPort 110 -InterfaceName $InterfaceName | Out-Null
Write-Host "Added port rule for POP3 (tcp 110)" -ForegroundColor yellow
Add-NlbClusterPortRule -Protocol Tcp -Mode Multiple -Affinity Single -StartPort 135 -EndPort 135 -InterfaceName $InterfaceName | Out-Null
Write-Host "Added port rule for RPC (tcp 135)" -ForegroundColor yellow
Add-NlbClusterPortRule -Protocol Tcp -Mode Multiple -Affinity Single -StartPort 143 -EndPort 143 -InterfaceName $InterfaceName | Out-Null
Write-Host "Added port rule for IMAP4 (tcp 143)" -ForegroundColor yellow
Add-NlbClusterPortRule -Protocol Tcp -Mode Multiple -Affinity Single -StartPort 443 -EndPort 443 -InterfaceName $InterfaceName | Out-Null
Write-Host "Added port rule for https (tcp 443)" -ForegroundColor yellow
Add-NlbClusterPortRule -Protocol Tcp -Mode Multiple -Affinity Single -StartPort $MSExchangeRPCPort -EndPort $MSExchangeRPCPort -InterfaceName $InterfaceName | Out-Null
Write-Host "Added port rule for MSExchange RPC (tcp $MSExchangeRPCPort)" -ForegroundColor yellow
Add-NlbClusterPortRule -Protocol Tcp -Mode Multiple -Affinity Single -StartPort $MSExchangeABPort -EndPort $MSExchangeABPort -InterfaceName $InterfaceName | Out-Null
Write-Host "Added port rule for MSExchange Address Book service (tcp $MSExchangeABPort)" -ForegroundColor yellow
#Adding additional cluster nodes based on user input
Write-Warning "Before adding additional nodes, make sure that NLB are installed and the NLB-adapter are configured with a static IP-address on the remote node"
$additionalnodes = Read-Host "Add additional nodes to the cluster? Y/N"
if ($additionalnodes -like "y"){
do {
$NodeFqdn = Read-Host "Enter FQDN for the additional node"
$NewNodeInterface = Read-Host "Enter interface name for NLB-adapter on the additional node"
Write-Host "Adding cluster node $NodeFqdn" -ForegroundColor yellow
Get-NlbCluster -HostName . | Add-NlbClusterNode -NewNodeName $NodeFqdn -NewNodeInterface $NewNodeInterface
$additionalnodes = Read-Host "Add additional nodes to the cluster? Y/N"
} until ($additionalnodes -like "n")
}
|
PowerShellCorpus/PoshCode/default.config.ps1
|
default.config.ps1
|
<!-- An example log4net config (Save as default.config) -->
<log4net>
<appender name="ColoredConsoleAppender" type="log4net.Appender.ColoredConsoleAppender">
<mapping>
<level value="ERROR" />
<foreColor value="Red, HighIntensity" />
<backColor value="White, HighIntensity" />
</mapping>
<mapping>
<level value="DEBUG" />
<foreColor value="Green, HighIntensity" />
</mapping>
<mapping>
<level value="INFO" />
<foreColor value="Cyan, HighIntensity" />
</mapping>
<mapping>
<level value="WARN" />
<foreColor value="Yellow, HighIntensity" />
</mapping>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<file value="example.log" />
<appendToFile value="true" />
<maximumFileSize value="100KB" />
<maxSizeRollBackups value="2" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level %thread %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="ColoredConsoleAppender" />
<appender-ref ref="RollingFile" />
</root>
</log4net>
|
PowerShellCorpus/PoshCode/Join-String.ps1
|
Join-String.ps1
|
#.Synopsis
# Joins array elements together using a specific string separator
#.Example
# $Env:Path = ls | ? {$_.PSIsContainer} | Select -expand FullName | Join ";" -Append $Env:Path
#.Example
# get-process | select -expand name | join ","
#
function Join-String {
param ( [string]$separator, [string]$append, [string]$prepend, [string]$prefix, [string]$postfix, [switch]$unique )
begin { [string[]]$items = @($prepend.split($separator)) }
process { $items += $_ }
end {
$ofs = $separator;
$items += @($append.split($separator));
if($unique) {
$items = $items | Select -Unique
}
return "$prefix$($items -ne '')$postfix"
}
}
|
PowerShellCorpus/PoshCode/Get-Parameter_8.ps1
|
Get-Parameter_8.ps1
|
function Get-Parameter ( $Cmdlet, [switch]$ShowCommon, [switch]$Full ) {
$command = Get-Command $Cmdlet -ea silentlycontinue
# resolve aliases (an alias can point to another alias)
while ($command.CommandType -eq "Alias") {
$command = Get-Command ($command.definition)
}
if (-not $command) { return }
foreach ($paramset in $command.ParameterSets){
$Output = @()
foreach ($param in $paramset.Parameters) {
if ( !$ShowCommon ) {
if ($param.aliases -match "vb|db|ea|wa|ev|wv|ov|ob|wi|cf") { continue }
}
$process = "" | Select-Object Name, Type, ParameterSet, Aliases, Position, IsMandatory,
Pipeline, PipelineByPropertyName
$process.Name = $param.Name
$process.Type = $param.ParameterType.Name
if ( $paramset.name -eq "__AllParameterSets" ) { $process.ParameterSet = "Default" }
else { $process.ParameterSet = $paramset.Name }
$process.Aliases = $param.aliases
if ( $param.Position -lt 0 ) { $process.Position = $null }
else { $process.Position = $param.Position }
$process.IsMandatory = $param.IsMandatory
$process.Pipeline = $param.ValueFromPipeline
$process.PipelineByPropertyName = $param.ValueFromPipelineByPropertyName
$output += $process
}
if ( !$Full ) {
$Output | Select-Object Name, Type, ParameterSet, IsMandatory, Pipeline
}
else { Write-Output $Output }
}
}
|
PowerShellCorpus/PoshCode/Create datastore by LUN .ps1
|
Create datastore by LUN .ps1
|
function New-DatastoreByLun { param( [string]$vmHost, [string]$hbaId, [int]$targetId, [int]$lunId, [string]$dataStoreName )
$view = Get-VMHost $vmHost | get-view
$lun = $view.Config.StorageDevice.ScsiTopology | ForEach-Object { $_.Adapter } | Where-Object {$_.Key -match $hbaId} | ForEach-Object {$_.Target} | Where-Object {$_.Target -eq $targetId} | ForEach-Object {$_.Lun} | Where-Object {$_.Lun -eq $lunId}
$scsiLun = Get-VMHost $vmHost | Get-ScsiLun | Where-Object {$_.Key -eq $lun.ScsiLun}
New-Datastore -VMHost $vmHost -Name $dataStoreName -Path $scsiLun.CanonicalName -Vmfs -BlockSizeMB 8 -FileSystemVersion 3
}
|
PowerShellCorpus/PoshCode/PWD Expiration Email.ps1
|
PWD Expiration Email.ps1
|
#Active Directory Group Name To Be Edited
#Load Active Directory Module
if(@(get-module | where-object {$_.Name -eq "ActiveDirectory"} ).count -eq 0) {import-module ActiveDirectory}
# get domain maximumPasswordAge value
$MaxPassAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge.days
if($MaxPassAge -le 0)
{
throw "Domain 'MaximumPasswordAge' password policy is not configured."
}
#Send Alert to User
$DaysToExpire = 7
$LogPath = "C:\\Scripts\\Logs\\PasswordExpire"
#Create Daily Log File
$a=get-date -format "ddMMyyyy"
echo "Daily Log for $a" | Out-File $LogPath\\$a.txt -append
echo "-----------------------" | Out-File $LogPath\\$a.txt -append
#Check users that have a password expiring in 7 days or less
Get-ADUser -SearchBase (Get-ADRootDSE).defaultNamingContext -Filter {(Enabled -eq "True") -and (PasswordNeverExpires -eq "False") -and (mail -like "*")} -Properties * | Select-Object Name,SamAccountName,mail,@{Name="Expires";Expression={ $MaxPassAge - ((Get-Date) - ($_.PasswordLastSet)).days}} | ForEach-Object {
#Send Email to user that password is going to expire
$SMTPserver = "exchange.yourdomain.com"
$from = "noreply@yourdomain.com"
$to = $_.mail
$subject = "Password reminder: Your Windows password will expire in $($_.Expires) days"
$emailbody = "Your Windows password for the account $($_.SamAccountName) will expire in $($_.Expires) days. For those of you on a Windows machine, please press CTRL-ALT-DEL and click Change Password.
For all others, you can change it with a web browser by using this link: https://yourdomain.com/owa/?ae=Options&t=ChangePassword
Please remember to also update your password everywhere that might use your credentials like your phone or instant messaging application.
If you need help changing your password please contact helpdesk@yourdomain.com"
$mailer = new-object Net.Mail.SMTPclient($SMTPserver)
$msg = new-object Net.Mail.MailMessage($from, $to, $subject, $emailbody)
$mailer.send($msg)
echo $($_.mail) | Out-File $LogPath\\$a.txt -append
}
|
PowerShellCorpus/PoshCode/New-Struct_2.ps1
|
New-Struct_2.ps1
|
## New-Struct
## Creates a Struct class and emits it into memory
## The Struct includes a constructor which takes the parameters in order...
##
## Usage:
## # Assuming you have a csv file with no header and columns: artist,name,length
## New-Struct Song @{
## Artist=[string];
## Name=[string];
## Length=[TimeSpan];
## }
## $songs = gc C:\\Scripts\\songlist.csv | % { new-object Song @($_ -split ",") }
##
function New-Struct {
param([string]$Name,[HashTable]$Properties)
switch($Properties.Keys){{$_ -isnot [String]}{throw "Invalid Syntax"}}
switch($Properties.Values){{$_ -isnot [type]}{throw "Invalid Syntax"}}
# CODE GENERATION MAGIKS!
$code = @"
using System;
public struct $Name {
$($Properties.Keys | % { " public {0} {1};`n" -f $Properties[$_],($_.ToUpper()[0] + $_.SubString(1)) })
public $Name ($( [String]::join(',',($Properties.Keys | % { "{0} {1}" -f $Properties[$_],($_.ToLower()) })) )) {
$($Properties.Keys | % { " {0} = {1};`n" -f ($_.ToUpper()[0] + $_.SubString(1)),($_.ToLower()) })
}
}
"@
## Obtains an ICodeCompiler from a CodeDomProvider class.
$provider = New-Object Microsoft.CSharp.CSharpCodeProvider
## Get the location for System.Management.Automation DLL
$dllName = [PsObject].Assembly.Location
## Configure the compiler parameters
$compilerParameters = New-Object System.CodeDom.Compiler.CompilerParameters
$assemblies = @("System.dll", $dllName)
$compilerParameters.ReferencedAssemblies.AddRange($assemblies)
$compilerParameters.IncludeDebugInformation = $true
$compilerParameters.GenerateInMemory = $true
$compilerResults = $provider.CompileAssemblyFromSource($compilerParameters, $code)
if($compilerResults.Errors.Count -gt 0) {
$compilerResults.Errors | % { Write-Error ("{0} :`t {1}" -F $_.Line,$_.ErrorText) }
}
}
|
PowerShellCorpus/PoshCode/Excel Auto-frontend.ps1
|
Excel Auto-frontend.ps1
|
Function New-DummyVM {
param(
[Parameter(Mandatory=$true,HelpMessage="Target Host")]
[VMware.VimAutomation.Types.VMHost]
$TargetHost,
[Parameter(Mandatory=$true,HelpMessage="Target Host")]
[VMware.VimAutomation.Types.ResourcePool]
$ResourcePool,
[Parameter(Mandatory=$true,HelpMessage="New VM Name")]
[String]
$NewName
)
Get-VMHost $TargetHost | New-VM -ResourcePool $ResourcePool -Name $NewName -DiskMB 1
}
Function Add-BulkHosts {
param(
[Parameter(Mandatory=$true,HelpMessage="Host name or IP address")]
[String]
$HostName,
[Parameter(HelpMessage="Target Datacenter")]
[VMware.VimAutomation.Types.Datacenter]
$Datacenter,
[Parameter(HelpMessage="Target Folder")]
[VMware.VimAutomation.Types.Folder]
$Folder,
[Parameter(HelpMessage="Target Cluster")]
[VMware.VimAutomation.Types.Cluster]
$Cluster,
[Parameter(HelpMessage="Target Resource Pool")]
[VMware.VimAutomation.Types.ResourcePool]
$ResourcePool,
[Parameter(HelpMessage="Target Port")]
[Int32]
$Port=443,
[Parameter(HelpMessage="User")]
[String]
$User = "",
[Parameter(HelpMessage="Password")]
[String]
$Password
)
Process {
if ($Datacenter) {
$location = $Datacenter
} elseif ($Folder) {
$location = $Folder
} elseif ($Cluster) {
$location = $Cluster
} elseif ($ResourcePool) {
$location = $ResourcePool
}
if (!$location) {
Write-Warning "One of Datacenter, Folder, Cluster or ResourcePool must be specified."
return
}
if ($User -ne "") {
Add-VMHost -Name $HostName -Location $location -Port $Port -User $User -Password $Password -Force
} else {
Add-VMHost -Name $HostName -Location $location -Port $Port -Force
}
}
}
Function Get-ExcelFrontEnd {
param($cmdlet)
# Load in some Excel interop stuff.
[reflection.assembly]::loadwithpartialname("microsoft.office.interop.excel") | Out-Null
$xlDvType = "Microsoft.Office.Interop.Excel.XlDVType" -as [type]
$xlDvAlertStyle = "Microsoft.Office.Interop.Excel.XlDvAlertStyle" -as [type]
$xlFormatConditionOperator = "Microsoft.Office.Interop.Excel.XlFormatConditionOperator" -as [type]
$myDocuments = (Get-Itemproperty "hkcu:\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders").Personal
$csvFile = $myDocuments + "\\parameters.csv"
# We watch this file for writes.
$startWriteTime = (Get-ChildItem $csvFile -ea SilentlyContinue).LastWriteTime
# Define what commands will get us various types of data.
$findObjects = @{
[VMware.VimAutomation.Types.Cluster] = { Get-Cluster } ;
[VMware.VimAutomation.Types.Datacenter] = { Get-Datacenter } ;
[Datastore] = { Get-Datastore } ;
[VMware.VimAutomation.Types.Folder] = { Get-Folder } ;
[VMware.VimAutomation.Types.OSCustomizationSpec] = { Get-OSCustomizationSpec } ;
[VMware.VimAutomation.Types.ResourcePool] = { Get-ResourcePool } ;
[VMware.VimAutomation.Types.Template] = { Get-Template } ;
[VMware.VimAutomation.Types.VirtualMachine] = { Get-VM } ;
[VMware.VimAutomation.Types.VMHost] = { Get-VMHost }
}
# Parameters to ignore.
$ignore = @("Verbose", "Debug", "ErrorAction", "WarningAction", "ErrorVariable",
"WarningVariable", "OutVariable", "OutBuffer")
# Determine the names and types of all parameters in the first signature.
$parameters = (Get-Command $cmdlet).Parameters
# Locate the cmdlet template.
$cmdletTemplate = $myDocuments + "\\CmdletFrontend.xlsm"
$ifOffset = 11
# Launch Excel and initialize things.
$xl = New-Object -ComObject Excel.Application
$wb = $xl.Workbooks.Open($cmdletTemplate)
#$wb = $xl.Workbooks.Add()
$ifSheet = $wb.worksheets.item(1)
#$ifSheet.Name = "Interface"
$ifSheet.StandardWidth = 20
$dataSheet = $wb.worksheets.item(2)
#$dataSheet.Name = "Data"
#$wb.worksheets.item(3).Delete()
# Populate the easy stuff.
$ifSheet.Cells.Item(4, 1) = $cmdlet
#$ifSheet.Cells.Item(7, 5) = $defaultVIServer.Name
#$ifSheet.Cells.Item(8, 5) = $defaultVIServer.SessionId
$xl.visible = $true
# Based on the types, start populating stuff under the Data sheet.
$i = 0
foreach ($key in $parameters.keys) {
if ($ignore -contains $key) {
continue
}
$i++
$parameter = $parameters[$key]
$type = $parameter.ParameterType
# If the type is an array, figure out the real type.
# XXX
# Create the column in the Interface sheet.
$ifSheet.Cells.Item($ifOffset, $i) = $key
# If we know how to load instances of this type, load the data in now.
if ($findObjects[$type]) {
$values = . $findObjects[$type]
# Put this data in the Data sheet.
$j = 1
foreach ($value in $values) {
$dataSheet.Cells.Item($j++, $i) = $value.Name
}
# Turn this into a named data range.
$rangeName = $key
Write-Debug $rangeName
# Convert the range to R1C1 notation.
$dataRange = "=Data!R1C{0}:R{1}C{2}" -f $i, ($j-1), $i
Write-Debug $dataRange
$name = $wb.names.add($rangename, $null, $true, $null, $null, $null, $null, $null, $null, $dataRange, $null)
$column = [char]([byte][char]"A" + $i - 1)
$ifRange = "{0}{1}:{2}{3}" -f $column, $ifOffset, $column, 250
Write-Debug $ifRange
# Constrain input in the interface sheet based on this data.
$range = $ifSheet.Range($ifRange).Select()
$validation = $xl.Selection.Validation.Add($xlDvType::xlValidateList, $xlDvAlertStyle::xlValidAlertStop,
$xlFormatConditionOperator::xlBetween, "=$rangename", $null)
}
}
$range = $ifSheet.Range("A1").Select()
# Wait for the file to get updated.
do {
Write-Debug "Waiting"
Start-Sleep 1
$thisWriteTime = (Get-ChildItem $csvFile -ea silentlycontinue).LastWriteTime
} while ($thisWriteTime -le $startWriteTime)
# Run the cmdlet with the data specified.
$xl.Visible = $false
$wb.Close($false)
$xl.Quit()
foreach ($f in (import-csv $csvFile)) {
$properties = $f | Get-Member -type NoteProperty
$argString = ""
$objects = @()
$i = 0
foreach ($property in $properties) {
$pName = $property.Name
#Write-Host ("Property name is " + $pName)
if ($f.$pName -ne "") {
#Write-Host ("Property value is " + $f.$pName)
# Resolve the object.
$parameter = $parameters[$pName]
$type = $parameter.ParameterType
$getter = $findObjects[$type]
$object = $null
if ($getter) {
$lookupExpression = ($getter.ToString() + " -name '" + $f.$pName + "' | Select -first 1")
#Write-Host ("Looking up using " + $lookupExpression)
$object = Invoke-Expression $lookupExpression
} else {
$object = $f.$pName
}
$objects += $object
#Write-Host $objects
$argString += (" -" + $pName + " `$objects[$i]")
#Write-Host ("Set " + $pName + " to " + $objects[$i])
$i++
}
}
$command = $cmdlet + $argString
#Write-Host $command
Invoke-Expression $command
}
}
#Get-ExcelFrontEnd Add-BulkHosts
#Get-ExcelFrontEnd New-DummyVM
|
PowerShellCorpus/PoshCode/MailChimp GetDistributio.ps1
|
MailChimp GetDistributio.ps1
|
#Author: Tozzi June 2012
#OriginalAuthor: Ant B 2012
#Purpose: Batch feed recipients to MailChimp
$ie = new-object -com "InternetExplorer.Application"
# Vars for building the URL
$apikey = "api-key-from-mailchimp"
$listid = "list-id-from-mailchimp"
# Important is to use correct MailChimp data centre. In this case us5, yours might be different
$URL = "https://us5.api.mailchimp.com/1.3/?output=xml&method=listBatchSubscribe&apikey=$apikey"
$URLOpts = "&id=$($listid)&double_optin=False&Update_existing=True"
$Header = "FirstName","Lastname","PrimarySmtpAddress"
$GroupName = "distribution-group-name"
# Get members of the group
$DGMembers = Get-DistributionGroupMember $GroupName | select FirstName, Lastname, PrimarySmtpAddress
# Copy the array contents to a CSV for comparison on the next run, we'll use it to look for removals
if (test-path "C:\\submitted.csv") {
Clear-Content submitted.csv
}
$DGMembers | select PrimarySmtpAddress | export-csv C:\\submitted.csv
# Check for the CSV created above and dump it to an array for comparison
if (test-path "C:\\submitted.csv") {
$list = Import-CSV -delimiter "," -Path C:\\submitted.csv -Header $Header
}
$Removals = compare-object $DGMembers $list | Where {$_.SideIndicator -eq "=>"}
# Loop through the array of group members and submit to the MailChimp API
ForEach ($ObjItem in $DGMembers)
{
$batch = "&batch[0][EMAIL]=$($ObjItem.PrimarySmtpAddress)&batch[0][FNAME]=$($ObjItem.FirstName)&batch[0][LNAME]=$($ObjItem.Lastname)"
$MailOpts = "&batch[0][EMAIL_TYPE]html"
$FURL = $URL + $batch + $MailOpts + $URLOpts
Write-Host $FURL
$ie.navigate($FURL)
Start-Sleep -MilliSeconds 300
}
|
PowerShellCorpus/PoshCode/get windows product key_1.ps1
|
get windows product key_1.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/Unlock & Password Reset.ps1
|
Unlock & Password Reset.ps1
|
<#
Author: Matt Schmitt
Date: 11/28/12
Version: 1.0
From: USA
Email: ithink2020@gmail.com
Website: http://about.me/schmittmatt
Twitter: @MatthewASchmitt
Description
A script for forwarding and unforwarding email for users in Office 365.
#>
Import-Module ActiveDirectory
Write-Host ""
Write-Host "PowerShell AD Password Tool"
Write-Host ""
Write-Host "This tool displays the Exparation Date of a user's Password and thier Lockedout"
Write-Host "Status. It will then allow you to unlock and/or reset the password."
Write-Host ""
Write-Host ""
#Counts how many locked account there are on the local DC and sets it to $count
$count = Search-ADAccount –LockedOut | where { $_.Name -ne "Administrator" -and $_.Name -ne "Guest" } | Measure-Object | Select-Object -expand Count
#If there are locked accounts (other than Administrator and Guest), then this will display who is locked out.
If ( $count -gt 0 ) {
Write-Host "Current Locked Out Accounts on your LOCAL Domain Controller:"
Search-ADAccount –LockedOut | where { $_.Name -ne "Administrator" -and $_.Name -ne "Guest" } | Select-Object SamAccountName, LastLogonDate | Format-Table -AutoSize
}else{
# Write-Host "There are no locked out accounts on your local Domain Controller."
}
Write-Host ""
#Asks for the username
$user = Read-Host "Enter username of the employee you would like to check or [ Ctrl+c ] to exit"
Write-Host ""
Write-Host ""
[datetime]$today = (get-date)
#Get pwdlastset date from AD and set it to $passdate
$searcher=New-Object DirectoryServices.DirectorySearcher
$searcher.Filter="(&(samaccountname=$user))"
$results=$searcher.findone()
$passdate = [datetime]::fromfiletime($results.properties.pwdlastset[0])
#Set password Age to $PwdAge
$PwdAge = ($today - $passdate).Days
If ($PwdAge -gt 90){
Write-Host "Password for $user is EXPIRED!"
Write-Host "Password for $user is $PwdAge days old."
}else{
Write-Host "Password for $user is $PwdAge days old."
}
Write-Host ""
Write-Host ""
Write-Host "Checking LockedOut Status on defined Domain Controllers:"
#Get Lockedout status and display
# ---> IMPORTANT: You need to change DC01.your.domain.com & DC02.your.domain.com to the FQDN of your Domian Controlls
switch (Get-ADUser -server DC01.your.domain.com -Filter {samAccountName -eq $user } -Properties * | Select-Object -expand lockedout) { "False" {"DC01: Not Locked"} "True" {"DC01: LOCKED"}}
switch (Get-ADUser -server DC02.your.domain.com -Filter {samAccountName -eq $user } -Properties * | Select-Object -expand lockedout) { "False" {"DC02: Not Locked"} "True" {"DC02: LOCKED"}}
# ---> You can add more domain controllers to list, by copying one of the lines, then Modifying the text to reflect your DCs.
Write-Host ""
Write-Host ""
[int]$y = 0
$option = Read-Host "Would you like to (1) Unlock user, (2) Reset user's password, (3) Unlock and reset user's password or (4) Exit?"
cls
While ($y -eq 0) {
switch ($option)
{
"1" {
# ---> IMPORTANT: You need to change DC01.your.domain.com & DC02.your.domain.com to the FQDN of your Domian Controlls
Write-Host "Unlocking account on DC01"
Unlock-ADAccount -Identity $user -server DC01.your.domain.com
Write-Host "Unlocking account on DC02"
Unlock-ADAccount -Identity $user -server DC02.your.domain.com
# ---> You can add more domain controllers to list, by copying one of the lines, then Modifying the text to reflect your DCs.
#Get Lockedout status and set it to $Lock
$Lock = (Get-ADUser -Filter {samAccountName -eq $user } -Properties * | Select-Object -expand lockedout)
Write-Host ""
#Depending on Status, tell user if the account is locked or not.
switch ($Lock)
{
"False" { Write-Host "$user is unlocked." }
"True" { Write-Host "$user is LOCKED Out." }
}
Write-Host ""
Write-Host "Press any key to Exit."
$y += 1
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
"2" {
$newpass = (Read-Host -AsSecureString "Enter user's New Password")
Write-Host ""
Write-Host "Resetting Password on local DC..."
Write-Host ""
Set-ADAccountPassword -Identity $user -NewPassword $newpass
Write-Host ""
Write-Host "Resetting Password on DC02"
Write-Host ""
# ---> IMPORTANT: You need to change DC01.your.domain.com & DC02.your.domain.com to the FQDN of your Domian Controlls
Set-ADAccountPassword -Server DC02.your.domain.com -Identity $user -NewPassword $newpass
# ---> You can add more domain controllers to list, by copying one of the lines, then Modifying the text to reflect your DCs.
Write-Host ""
Write-Host "Press any key to Exit."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
$y += 1
}
"3" {
$newpass = (Read-Host -AsSecureString "Enter user's New Password")
Write-Host ""
Write-Host "Resetting Password on Local DC..."
Write-Host ""
Set-ADAccountPassword -Identity $user -NewPassword $newpass
Write-Host ""
Write-Host "Resetting Password on DC02"
Write-Host ""
# ---> IMPORTANT: You need to change DC01.your.domain.com & DC02.your.domain.com to the FQDN of your Domian Controlls
Set-ADAccountPassword -Server DC02.your.domain.com -Identity $user -NewPassword $newpass
# ---> You can add more domain controllers to list, by copying one of the lines, then Modifying the text to reflect your DCs.
Write-Host ""
Write-Host "Password for $user has been reset."
Write-Host ""
# ---> IMPORTANT: You need to change DC01.your.domain.com & DC02.your.domain.com to the FQDN of your Domian Controlls
Write-Host "Unlocking account on DC01"
Unlock-ADAccount -Identity $user -server DC01.your.domain.com
Write-Host "Unlocking account on DC02"
Unlock-ADAccount -Identity $user -server DC02.your.domain.com
# ---> You can add more domain controllers to list, by copying one of the lines, then Modifying the text to reflect your DCs.
#Get Lockedout status and set it to $Lock
$Lock = (Get-ADUser -Filter {samAccountName -eq $user } -Properties * | Select-Object -expand lockedout)
Write-Host ""
#Depending on Status, tell user if the account is locked or not.
switch ($Lock)
{
"False" { Write-Host "$user is unlocked." }
"True" { Write-Host "$user is LOCKED Out." }
}
Write-Host ""
Write-Host "Press any key to Exit."
$y += 1
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
"4" {
#exit code
$y += 1
}
default {
Write-Host "You have entered and incorrect number."
Write-Host ""
$option = Read-Host "Would you like to (1) Unlock user, (2) Reset user's password, (3) Unlock and reset user's password or (4) Exit?"
}
}
}
|
PowerShellCorpus/PoshCode/Start-Timer_1.ps1
|
Start-Timer_1.ps1
|
A syntax error on your $Status array definition - you forgot the braces around the elements;
[string[]]$status=("Cooking","Burning")
cheers, yeatsie
## Start-Timer.ps1
## A kitchen timer script with visible countdown and customizable audio alert and messages
####################################################################################################
param( $seconds=0, $reason="The Timer", $SoundFile="$env:SystemRoot\\Media\\notify.wav",
@@ $minutes=0, $hours=0, $timeout=0, [switch]$novoice, [string[]]$status="Cooking","Burning"
)
$start = [DateTime]::Now
write-progress -activity $reason -status "Running"
$seconds = [Math]::Abs($seconds) + [Math]::Abs($minutes*60) + [Math]::Abs($hours*60*60)
$end = $start.AddSeconds( $seconds )
## Take care of as much overhead as we can BEFORE we start counting
## So the sounds can play as cloase to the end as possible
$Voice = new-object -com SAPI.SpVoice
$Sound = new-Object System.Media.SoundPlayer
if(Test-Path $soundFile) {
$Sound.SoundLocation=$SoundFile
} else {
$soundFile = $Null
}
## The actual timing loop ...
do {
$remain = ($end - [DateTime]::Now).TotalSeconds
$percent = [Math]::Min(100, ((($seconds - $remain)/$seconds) * 100))
$sec = [Math]::Max(000, $remain)
write-progress -activity $reason -status $status[0] -percent $percent -seconds $sec
start-sleep -milli 100
} while( $remain -gt 0 )
## And a loop for beeping
$Host.UI.RawUI.FlushInputBuffer()
do {
if($SoundFile) {
$Sound.PlaySync()
} else {
[System.Media.SystemSounds]::Exclamation.Play()
}
if(!$novoice -and !$Host.UI.RawUI.KeyAvailable){
$null = $Voice.Speak( "$reason is $($status[1])!!", 0 )
}
write-progress -activity $reason -status $status[1] -percent ([Math]::Min(100,((($seconds - $remain)/$seconds) * 100))) -seconds ([Math]::Max(0,$remain))
$remain = ($end - [DateTime]::Now).TotalSeconds
} while( !$Host.UI.RawUI.KeyAvailable -and ($timeout -eq 0 -or $remain -gt -$timeout))
if($SoundFile) {
$Sound.Stop()
}
|
PowerShellCorpus/PoshCode/Start-IRCJabberBridge_1.ps1
|
Start-IRCJabberBridge_1.ps1
|
@@## Depends on the PoshXmpp.dll from http://CodePlex.com/PoshXmpp
@@#requires -pssnapin PoshXmpp
##########################################################################################
# @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 (eg: 'mybot@im.flosoft.biz') ")
,$Password = $(Read-Host "Jabber Password")
,$IRC = $(Read-Host "First Jabber conference address (IRC) (eg: powershell%irc.freenode.net@irc.im.flosoft.biz )")
,$JabberConf = $(Read-Host "Second Jabber conference address (eg: powershell@conference.im.flosoft.biz) ")
,$ChatNick = $(Read-Host "The nickname you want to use")
,$IRCPassword= $(Read-Host "IRC Password")
,[string[]]$AtomFeeds = @("http://groups.google.com/group/microsoft.public.windows.powershell/feed/atom_v1_0_topics.xml")
)
## Requires System.Web for the RSS-feed option
[Reflection.Assembly]::LoadWithPartialName("System.Web") | Out-Null
function Start-PowerBot([switch]$announce) {
$global:LastNewsCheck = [DateTime]::Now
$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
$global:PoshXmppClient.SendMyPresence()
if($announce) {
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))"
}
if($IRCPassword) {
Send-PrivMsg "nickserv" "id $IRCPassword"
}
}
function Send-PrivMsg($to,$msg) {
PoshXmpp\\Send-Message $IRC "/msg $to :$msg"
}
function Process-Command($Chat, $Message) {
$split = $message.Body.Split(" |;")
$from = $Message.From.Bare.ToLower()
switch -regex ( $split[0] ) {
"!list" {
Write-Host "!LIST COMMAND. Send users of [$Chat] to [$($Message.From.Bare)]" -fore Magenta
$users = @($PoshXmppClient.ChatManager.GetUsers( $Chat ).Values)
PoshXmpp\\Send-Message $from ("There are $($users.Count) on $($Chat):")
PoshXmpp\\Send-Message $from [string].join(', ',$users)
}
"!gh|!get-help|!man" {
$help = get-help $split[1] | Select Name,Synopsis,Syntax
if($?) {
if($help -is [array]) {
PoshXmpp\\Send-Message $from ("You're going to need to be more specific, I know all about $((($help | % { $_.Name })[0..($help.Length-2)] -join ', ') + ' and even ' + $help[-1].Name)")
} else {
PoshXmpp\\Send-Message $from $help.Synopsis;
PoshXmpp\\Send-Message $from ($help.Syntax | Out-String -w 1000).Split("`n",4,[StringSplitOptions]::RemoveEmptyEntries)[1]
}
} else {
PoshXmpp\\Send-Message $from "I couldn't find the help file for that, sorry. Jaykul probably didn't get the cmdlet installed right."
}
}
}
}
# 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
}
[regex]$anagram = "^Unscramble ... (.*)$"
function Bridge {
foreach( $msg in (PoshXmpp\\Receive-Message -All) )
{
$Chat = $Null;
if( $msg.Type -eq "Error" )
{
Write-Error $msg.Error
}
elseif( $msg.From.Resource -ne $ChatNick )
{
switch($msg.From.Bare) {
$IRC { $Chat = $JabberConf }
$JabberConf { $Chat = $IRC; }
default { Write-Debug $msg }
}
}
if($Chat) {
switch($msg) {
{ ![String]::IsNullOrEmpty($_.Body) -and ($_.Body[0] -eq '!') }{
PoshXmpp\\Send-Message $Chat ("<{0}> {1}" -f $_.From.Resource, $_.Body)
Process-Command $Chat $_
}
{ ($_.From.Resource -eq "GeoBot") -and $_.Body.StartsWith("Unscramble ... ") }{
Write-Verbose "KILL ANAGRAM! $($anagram.Match($_.Body).Groups[1].value)"
$answers = Solve-Anagram $($anagram.Match($_.Body).Groups[1].value)
foreach($ans in $answers) {
Write-Verbose "ANAGRAM: $($_.From.Bare) $ans"
PoshXmpp\\Send-Message "$($_.From.Bare.ToLower())" "$ans (PowerShell Scripting FTW!)"
}
}
{ ![String]::IsNullOrEmpty($_.Subject) }{
$_.To = $Chat
# Send it directly using a method on the PoshXmppClient
$PoshXmppClient.Send($_)
}
{ $_.From.Resource }{
PoshXmpp\\Send-Message $Chat ("<{0}> {1}" -f $_.From.Resource, $_.Body)
}
}
}
}
}
function Start-Bridge {
"PRESS ANY KEY TO STOP"
while(!$Host.UI.RawUI.KeyAvailable) {
$Host.UI.RawUI.WindowTitle = "PowerBot"
$global:PoshXmppClient.SendMyPresence()
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();
}
##
## Silly anagram spoiler
##
function Solve-Anagram($anagram) {
((Post-HTTP "http://www.easypeasy.com/anagrams/results.php" "name=$anagram").Split("`n") |
select-string "res 1" ) -replace ".*res 1.*value=""\\s*([^""]*)\\s*"".*",'$1'
}
function Post-HTTP($url,$bytes) {
$request = [System.Net.WebRequest]::Create($url)
# $bytes = [Text.Encoding]::UTF8.GetBytes( $bytes )
$request.ContentType = "application/x-www-form-urlencoded"
$request.ContentLength = $bytes.Length
$request.Method = "POST"
$rq = new-object IO.StreamWriter $request.GetRequestStream()
$rq.Write($bytes)#,0,$bytes.Length)
$rq.Flush()
$rq.Close()
$response = $request.GetResponse()
$reader = new-object IO.StreamReader $response.GetResponseStream(),[Text.Encoding]::UTF8
return $reader.ReadToEnd()
}
|
PowerShellCorpus/PoshCode/get-DiskVolumeInfo_1.ps1
|
get-DiskVolumeInfo_1.ps1
|
function get-DiskVolumeInfo
{
<#
.SYNOPSIS
Returns information about disk volumes including freespace
.DESCRIPTION
Returns information about disk volumes including freespace
.EXAMPLE
show-InnerException ExceptionObject
Shows the inner exception object of the error object that is passed to the
function.
.Notes
ChangeLog :
Date Initials Short Description
02/18/2009 RLV New
.Link
http://msdn.microsoft.com/en-us/library/aa394239(v=VS.85).aspx
.Link
http://msdn.microsoft.com/en-us/library/aa394515(VS.85).aspx
.Link
http://msdn.microsoft.com/en-us/library/windows/desktop/aa394173(v=vs.85).aspx
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory=$true)][string]$ComputerName,
[Parameter(Mandatory=$false)][switch]$Raw
)
trap
{
show-InnerException -ex $_
continue
}
write-verbose "$($MyInvocation.InvocationName) - Begin function"
foreach($Key in $PSBoundParameters.Keys){ write-verbose "$($MyInvocation.InvocationName) PARAM: -$Key - $($PSBoundParameters[$Key])" }
# Create an empty array to hold the property bags that will be created later
$VolArray = @()
# Windows 2003 supports mount points
if($(gwmi win32_operatingSystem -comp $ComputerName).version -ge '5.2')
{
# #region Persistent fold region
$VolArray = gwmi win32_volume -Computer $ComputerName | Select-Object `
@{Name='Computer';Expression={$ComputerName}}, `
@{Name='VolumeName';Expression={if($_.Name -like "\\\\?\\Volume*"){'\\\\?\\Volume'}else{$_.Name}}}, `
@{Name='Capacity_GB';Expression={[math]::Round($_.Capacity/1GB)}}, `
@{Name='FreeSpace_GB';Expression={[math]::Round($_.FreeSpace/1GB)}}, `
@{Name='Pct_Free';Expression={if($_.Capacity -gt 0){[math]::Round(($_.FreeSpace/$_.Capacity)*100)}else{0}}}, `
@{Name='BlockSize_KB';Expression={[math]::Round($_.Blocksize/1KB)}}
# #endregion
}
else
# Windows 2000 and Windows XP no mount point support
{
# #region Persistent fold region
$VolArray = gwmi win32_LogicalDisk -Computer $ComputerName | Select-Object `
@{Name='Computer';Expression={$ComputerName}}, `
@{Name='VolumeName';Expression={$_.Name}}, `
@{Name='Capacity_GB';Expression={[math]::Round($_.Size/1GB)}}, `
@{Name='FreeSpace_GB';Expression={[math]::Round($_.FreeSpace/1GB)}}, `
@{Name='Pct_Free';Expression={if($_.Size -gt 0){[math]::Round(($_.FreeSpace/$_.Size)*100)}else{0}}}
# #endregion
}
if($Raw){ $VolArray }
else{ $VolArray | ft -auto }
write-verbose "$($MyInvocation.InvocationName) - End function"
}
|
PowerShellCorpus/PoshCode/Snippet Compiler_4.ps1
|
Snippet Compiler_4.ps1
|
$def = $(if ((gi .).FullName -eq (gi .).Root) {
([string](gi .).Root).TrimEnd("\\")
}
else { (gi .).FullName }
)
##################################################################################################
function Get-CursorPoint {
$x = $rtbEdit.SelectionStart - $rtbEdit.GetFirstCharIndexOfCurrentLine()
$y = $rtbEdit.GetLineFromCharIndex($rtbEdit.SelectionStart) + 1
return (New-Object Drawing.Point($x, $y))
}
function Get-Image([string]$img) {
[Drawing.Image]::FromStream((New-Object IO.MemoryStream(($$ = `
[Convert]::FromBase64String($img)), 0, $$.Length)))
}
function Invoke-Builder {
$lstBugs.Items.Clear()
if ($rtbEdit.Text -ne "") {
switch ($tsCom_1.SelectedIndex) {
"0" {$cscp = New-Object Microsoft.CSharp.CSharpCodeProvider; break}
"1" {$cscp = New-Object Microsoft.CSharp.CSharpCodeProvider($dict); break}
}
switch ($tsCom_2.SelectedIndex) {
"0" {$cdcp.GenerateExecutable = $true; break}
"1" {$cdcp.GenerateExecutable = $false; break}
"2" {
$cdcp.GenerateExecutable = $true
$cdcp.CompilerOptions = "/t:winexe"
break
}
}
$cdcp.IncludeDebugInformation = $chkIDbg.Checked
$cdcp.GenerateInMemory = $chkIMem.Checked
if ($lboRefs.Items.Count -ne 0) {
for ($i = 0; $i -lt $lboRefs.Items.Count; $i++) {
$cdcp.ReferencedAssemblies.Add($lboRefs.Items[$i].ToString())
}
}
$cdcp.WarningLevel = 3
$cdcp.OutputAssembly = $txtName.Text
$script:make = $cscp.CompileAssemblyFromSource($cdcp, $rtbEdit.Text)
$make.Errors | % {
if ($_.Line -ne 0 -and $_.Column -ne 0) {
$err = $_.Line.ToString() + '.' + ($_.Column - 1).ToString()
}
elseif ($_.Line -ne 0 -and $_.Column -eq 0) {
$err = $_.Line.ToString() + ', 0'
}
elseif ($_.Line -eq 0 -and $_.Column -eq 0) {
$err = '*'
}
if (!($_.IsWarning)) {
$lstBugs.ForeColor = [Drawing.Color]::Crimson
$itm = $lstBugs.Items.Add($err, 14)
}
else {
$lstBugs.ForeColor = [Drawing.Color]::Gray
$itm = $lstBugs.Items.Add($err, 15)
}
$itm.SubItems.Add($_.ErrorNumber)
$itm.SubItems.Add($_.ErrorText)
}
}#if
}
function Open-Document {
Watch-UnsavedData
(New-Object Windows.Forms.OpenFileDialog) | % {
$_.FileName = "source"
$_.Filter = "C# (*.cs)|*.cs"
$_.InitialDirectory = $def
if ($_.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) {
$sr = New-Object IO.StreamReader $_.FileName
$rtbEdit.Text = $sr.ReadToEnd()
$sr.Close()
$tpBasic.Text = $_.FileName
$tpBasic.ImageIndex = 2
$script:uns = $false
}
}
}
function Save-Document {
if ($rtbEdit.Text -ne "") {
Save-WorkspaceData
}
}
function Save-DocumentQuickly {
if ($script:uns) {
if ($src -ne $null) {
Out-File $src -enc UTF8 -inp $rtbEdit.Text
$tpBasic.ImageIndex = 2
$script:uns = $false
}
else { Save-WorkspaceData }
}
}
function Save-WorkspaceData {
(New-Object Windows.Forms.SaveFileDialog) | % {
$_.Filter = "C# (*.cs)|*.cs"
$_.InitialDirectory = $def
if ($_.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) {
$script:src = $_.FileName
Out-File $src -enc UTF8 -inp $rtbEdit.Text
$tpBasic.Text = $src
$tpBasic.ImageIndex = 2
$script:uns = $false
}
}
}
function Set-Opacity([object]$obj) {
$ops.Checked = $false
$frmMain.Opacity = [float]('.' + $($obj.Text)[0])
$obj.Checked = $true
}
function Start-AfterBuilding {
Invoke-Builder
if ($script:make.Errors.Count -eq 0) {Invoke-Item $txtName.Text}
}
function Watch-UnsavedData {
if ($script:uns) {
$res = [Windows.Forms.MessageBox]::Show(
" Workspace has been modified.`nDo you want to save changes before?",
$frmMain.Text, [Windows.Forms.MessageBoxButtons]::YesNoCancel,
[Windows.Forms.MessageBoxIcon]::Question
)
switch ($res) {
'Yes' { Save-WorkspaceData; $rtbEdit.Clear(); $tpBasic.Text = "Untitled"; break }
'No' { $rtbEdit.Clear(); $tpBasic.Text = "Untitled"; break }
'Cancel' { return }
}
}
else { $rtbEdit.Clear(); $tpBasic.Text = "Untitled" }
}
function Write-CursorPoint {
$sbPnl_2.Text = 'Str: ' + (Get-CursorPoint).Y.ToString() + ', Col: ' + `
(Get-CursorPoint).X.ToString()
}
##################################################################################################
$mnuITag_Click= {
$tag = "//Author: " + [Security.Principal.WindowsIdentity]::GetCurrent().Name + "`n" + `
"//Date: " + (Get-Date -f 'HH:mm:ss') + "`n`n"
if ($rtbEdit.Text -eq "") {
$rtbEdit.Text = $tag
}
else {
$rtbEdit.Text = $tag + $rtbEdit.Text
}
}
$mnuFont_Click= {
(New-Object Windows.Forms.FontDialog) | % {
$_.Font = "Lucida Console"
$_.MinSize = 10
$_.MaxSize = 12
$_.ShowEffects = $false
if ($_.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) {
$rtbEdit.Font = $_.Font
}
}
}
$mnuOpaF_Click= {
$frmMain.Opacity = 1
$ops.Checked = $false
$mnuOpaF.Checked = $true
$ops = $mnuOpaF
}
$mnuWrap_Click= {
$toggle =! $mnuWrap.Checked
$mnuWrap.Checked = $toggle
$rtbEdit.WordWrap = $toggle
}
$mnuPane_Click= {
switch ($mnuPane.Checked) {
$true { $mnuPane.Checked = $false; $scSplit.Panel2Collapsed = $true; break }
$false { $mnuPane.Checked = $true; $scSplit.Panel2Collapsed = $false; break }
}
}
$mnuSBar_Click= {
$toggle =! $mnuSBar.Checked
$mnuSBar.Checked = $toggle
$sbPanel.Visible = $toggle
}
$tsCom_1_SelectedIndexChanged= {
switch ($tsCom_1.SelectedIndex) {
"0" {$lboRefs.Items.Remove("`"System.Core.dll`""); break}
"1" {$lboRefs.Items.Add("`"System.Core.dll`""); break}
}
}
$tsCom_2_SelectedIndexChanged= {
switch ($tsCom_2.SelectedIndex) {
"0" {
$txtName.Text = $def + '\\app.exe'
$chkIMem.Enabled = $false
$mnuBnRA.Enabled = $true
$tsBut11.Enabled = $true
break
}
"1" {
$txtName.Text = $def + '\\lib.dll'
$chkIMem.Enabled = $true
$mnuBnRA.Enabled = $false
$tsBut11.Enabled = $false
$lboRefs.Items.Remove("`"System.Windows.Forms.dll`"")
$lboRefs.Items.Remove("`"System.Drawing.dll`"")
break
}
"2" {
$txtName.Text = $def + '\\app.exe'
$chkIMem.Enabled = $false
$mnuBnRA.Enabled = $true
$tsBut11.Enabled = $true
$lboRefs.Items.AddRange(@("`"System.Drawing.dll`"", "`"System.Windows.Forms.dll`""))
break
}
}
}
$rtbEdit_TextChanged= {
if ($rtbEdit.Text -ne "") {
$tpBasic.ImageIndex = 1
Write-CursorPoint
$script:uns = $true
}
else {
$tpBasic.Text = "Untitled"
$tpBasic.ImageIndex = 0
$script:uns = $false
$script:src = $null
}
}
$chkIMem_Click= {
switch ($chkIMem.Checked) {
$true {
$txtName.Text = [String]::Empty
$lblName.Enabled = $false
$txtName.Enabled = $false
$chkIDbg.Checked = $false
$chkIDbg.Enabled = $false
$tsCom_2.Enabled = $false
}
$false {
$txtName.Text = $def + '\\lib.dll'
$lblName.Enabled = $true
$txtName.Enabled = $true
$chkIDbg.Checked = $true
$chkIDbg.Enabled = $true
$tsCom_2.Enabled = $true
}
}
}
$mnuICnM_Click= {
$script:buf = $lboRefs.SelectedItem
$lboRefs.Items.Remove($lboRefs.SelectedItem)
}
$mnuIIns_Click= {
(New-Object Windows.Forms.OpenFileDialog) | % {
$_.Filter = "PE File (*.dll)|*.dll"
$_.InitialDirectory = [Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()
if ($_.ShowDialog() -eq [Windows.Forms.DialogResult]::OK) {
$lboRefs.Items.Add('"' + (Split-Path -leaf $_.FileName) + '"')
}
}
}
$frmMain_Load= {
$rtbEdit.Select()
$txtName.Text = $def + '\\app.exe'
$sbPnl_2.Text = "Str: 1, Col: 0"
$lboRefs.Items.Add("`"System.dll`"")
}
##################################################################################################
#
#this is resource section (DO NOT MODIFY THIS!)
#
$i_1 = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + `
"AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAQRJREFUOE+Vkr0OQ1AYhk8ns7" + `
"gR9+MnEbGJhQswGSsxGCxCJHSSGI1GsbF1dAUmMbWvnv6qavskQo73Od/5fHZRFA3D0Pf9OI7TNJE1GIZhWZb" + `
"neY7jiOu6xwunTZqmcRwnyzJimibSSZLQPFZXRQhA13WCC0IYhtsCAm3bKopCNE37UaiqakX41Ijv+2VZSpI0" + `
"V+i6DhVxesr+xn0FDxCKongR4CxA6JmHgG7e01hZCHmei6I4Hwnf6+v2kNM0fRG2B4e+4ji+CnVd0zkcPoBXE" + `
"JBZCmhmFSoEQfBHBfplBUEghmFghGC7B6Q9z1NVleBm2zb+KIwdYDQUVH8Ge8uybFnWGWKTD130GLf2AAAAAE" + `
"lFTkSuQmCC"
$i_2 = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + `
"AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAQ9JREFUOE9jvFlZyfbqFdOZMy" + `
"xv3rB8+sSADfzh4/spL/85MfG9qirDw8jI/8ePgxB+sHbtR0fH683NDI9VVUGqk5Mh6oGi2DWuXft/7dqn0tI" + `
"MQEyUhuTkP7t2PWRlZXjJy0ukhl+zZmHRgNMjwcF/+/thGvbvB/oB6HoIeu/tDUFwESDje3Dwl7Y2FA0gf6Oh" + `
"4GCgOjhCaAD6BotqoGZUDd+rq69xcIA9DQwyDOORzYaw3xcXo2rAG3E/PT2RNCxdCom4587OWBFQChgGz7OzY" + `
"TbANLzcvBkrwqkBjw3AkL2fnHyGiwuUloBRCET40x5QNRBdERJiAFK3XV2BKQoYKcgI6FxkBDQbqPq0qSkAg2" + `
"nz+rHom20AAAAASUVORK5CYII="
$i_3 = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + `
"AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAQhJREFUOE+Nki9TxDAQxRfHSQ" + `
"bDDJ/gZGUt8nB8hcjIyNiTkZGxkZGVsSsri6utDK43GO7lWsr9CYXM67Szfb/dzSZ3xnNK9D6MHwcaD1Rcm3t" + `
"6eqDX7eb58ZOU5bYfoa/VFdskTGsD005HuHUYJj+iRRAA9KIi4cmA/wOAgbtUyYZq+V8g8FAAftuIcr2PQyVO" + `
"FbjLLaH7SdLOWiL4UK5zTX8BgLkSssK36BxIt25ErgCbK4TcEuZVSv+TeypiQncBrB+ctJ3x30BzqgDAsCgKv" + `
"zCJvW/nCgvAfSxqBtwNsFIBk9WOK+FppyKOEFrfA9zaci0D4SX2ETcKx54lFgV0fCZfi/CmwxH35x1B2WVBxw" + `
"AAAABJRU5ErkJggg=="
$i_4 = "iVBORw0KGgoAAAANSUhEUgAAAA4AAAAPCAIAAABbdmkjAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + `
"AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAZhJREFUKFN9kN8rQ2EYxx8u3L" + `
"p244Yb/wB/ADcKV25FaCEs5kcyJLtxs7TFBeXC2hDpkEhIETXLafmxzTBtMsx2Zud4OUMez/bmtKi9fXou3vN" + `
"5v8+3kyO79XmFxQDwsGksqDRBblHy3jd1XkM3/EQ9ntaOKkQA9WXjebVMlayyq5qma7FElSyMsURCjsRe3P4n" + `
"w8iaY/fOH/kG+pyC+elNakoW4hvx7QOVJJ4GGam18zHb5g3c2vNFZwV5yU9GU3SWP6+Wci/CUAy8ksr5TaXIj" + `
"FTuhRUMSCh6URCwe0hIdU31ixrSXS3H6a6adxXDs0cUw9g1uAKJC3O6n5X2pntb6Ibnad7RHXYOLMNJ6IswzR" + `
"wnWDJzb6a3H8T2vgVwBb+I0cmDuKL+30t55G3fYJvBDofXH8SweSccf/+/l3vrl9iin4M9n0oYxzdCUfann+Y" + `
"JXtS1z8LW2RsxMCZcPbz+6cfzyFs8x+bWaVgTFaJ/ZMl7r/D/ovXTPNspNuqmYNkpE72Djn0Rs1DfZAXHYZzo" + `
"6bdlp65h4gfkvOeqbYKaEwAAAABJRU5ErkJggg=="
$i_5 = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAPCAIAAABiEdh4AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + `
"AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAjxJREFUKFNjvP36HwMO8O/Lve" + `
"UbjzD8YGAQELDWllDQMAMpvPnyHxq68eIvRCShYsKOA6eBjPfvXjVMWHD28jWgCMPuU3fXLOlHRkCR6y/+oaE" + `
"z564FZEwAIgag0luXFnz/sBqIfr5b9vv1/FULe3eevHP1+V9kBFEN0rB6Ud+3d8vhqv++mPH7SuHyeZ2LZ7bN" + `
"n9I0a0Ld9J6qyR3ll5/+hSCGFQu6v71aADH734sZ/29V/b+SjoaAGi4+/QtBDEvndHx+NguieueabiDavqpr8" + `
"7KO9YvbVs1vXjarceHU+rkTa2b2VU3trgTqZFg8q+3Tw0lAl9w70rBhed/fe43/H7Qg0P3G/3er/98o+X8t++" + `
"LKsCWz+xnmT23+eKfz/6OejSt6j+/qAcnBnXQh/v/ZkD9Hvb/vdry9SK8kPXDehqMMcyY2vL/e+OBo7YZlPf/" + `
"uNvy/nAHScDHp/9mIP8f9vu9z+7TN+s0aw8ZM1YVTq47e+cUwo6/2zaXKtUu6zx3q/H+j8P/l1P/nYv6dDPx1" + `
"0PPrTvt3G0xertA82yoQ7a2UlFe3/8YPhqldVZf31a1b0vX/Tt3/8/H/T4f+OuLzdY/jh83mr1fpPV2gcqVHu" + `
"CFdOTczbuflb0DEMKm9fPXCziubss72M0DQ8R6WfR0cW5r4V9aIzi+XnlYkH+OtFJ1Zs+ncZyBi6G8p7W9Ia6" + `
"9MqM4Lz0/ySwxzCfKwdLbSM9VT1VSSlpMUERPikxDmW3PyEwQxLDv6niQEAAw6z50R4Nz2AAAAAElFTkSuQmCC"
$i_6 = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAPCAIAAABiEdh4AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + `
"AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAASxJREFUKFOVj8tKw0AUho/PVO" + `
"gDdNFdkbxE3yB9BEHovgSyFgOC1JRKV5OLYWq8BClao91URqx00aAo0mjwDwNxKs0ih7Oa833nn7PzuMyoUsW" + `
"vmb43arWMbpedlRRGAKbiAzBNF7nQbl/idV1SGAHInUVGty8/qsAYcxzH8zzf95EXBAGWFAJgmjxvCFszCgEw" + `
"3WwKrutiNwq7UZxzNQEwRaJCAmC6evqWN8i7t7ac4mjAdDH/E+SgrCEApmC2LhLwNB7Per2w3w8ty7JtO4rua" + `
"jWjXjdlAmBi91+qwPm80TjsdHI6juM0TSGgpQCYRpNPVRgOI007xSWSTpJEFQDTyfW7Kpjmsa57g8GDpIUQqg" + `
"CYjs7f7HC5q+0jsdk08JN/JQVM0YDpIFhV6l80oM4zNkn6agAAAABJRU5ErkJggg=="
$i_7 = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + `
"AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAARZJREFUOE9jvP36HwMMzJq9+8" + `
"bxB/b2ahYWrHBBOOPEid8HD95iuPnyHxyVtu1MSzvT07P/FzYAFAfKMlx/8Q+IgEp9fWcChY5gA0BxoOzMmYd" + `
"AGq4+/wtExJgN1APSQLzZCA0E3Q1RikXD/v37Dxw4cOjQIaBHjh49CvQ5xKM4NWCGDQENBw8ePAwGQOOPHz9O" + `
"VRsg/sZEQHHsfoBI4EJwTwMZoHiAG3PixJ3p009t3Hhq8+bN589fMzaeaWY2B9mGTec+o2g4fvyhk9OKsrKVN" + `
"2/e/P37N1ADEEE0QNCak59QNMyZs7609NCWLbc+fPjw5MkTZA3Ljr6HIIaVR557ejYBdbu5zQS6BBlANEDMXn" + `
"DwLQQBAA5O4fpSVOxBAAAAAElFTkSuQmCC"
$i_8 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAOCAIAAAB/6NG4AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + `
"AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAcRJREFUKFNjXLzr0dWHn0IcFX" + `
"h5uRjAgJGB4dKN54Ur7z/+z83AxMTw9m2aCW9hlD4TMwuDTdWZhJ3/C2Zcuf7iHxBde/rLPG8/Q+1jhqbnDFU" + `
"PGIpvMuRcYkg+KRO87uaLfwwqRWdMV//Pmn3j6vO/By9/kMk4zNDykqHuMUPo7qo5l+duuScTuQWoGoh6Vt5k" + `
"4Mk6wzXnf+rMGwcufWAI2MbQ8JQh95J/3dFLj39efvoXiIAMBt/NDGlnZGK2MzCknmaY8E0mfjdIac1Dhszzl" + `
"bMuXn729+JTBErpPwdUDdLDEH+UofU1iFN2B0h2rbh5/slfNISkOmo/Q9V9kG9ST8v4rli27wkEnX/86+yjP0" + `
"B0/vEfBs/1MJcE72TIv8qQfhZkPBwln0zuOnX64R8gWrr3CUPCMaAvO5bfZGBwX8sQuR8dhe1pW3rj6J1fx+9" + `
"8hxgMdPSJuz8Z9t/4gQsduvnDJG0HSGnCsZbF14HKGHZe/oYV7bn63at4Dyik084Yp+4AcoHKGDad+4wVeRbt" + `
"YYg5BFQqFb1t+4WPEDUMa05+wopyJ5wFqXZbs/zAS7gChmVH32NFq098iGo4svLwK2RZAH0Sgt0BWzw0AAAAA" + `
"ElFTkSuQmCC"
$i_9 = "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAOCAIAAAB/6NG4AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + `
"AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAbRJREFUKFN1kE8oQwEcx3+Ui4" + `
"OLOOCipNyJlCs5LMrFDCn/DoqlTIqkXNiBHGTcdljkT1gbCz02Yxtmsz+2mv/mz9Cebe2fvT2/19teQ16fw/d" + `
"93+f7/qU5X+MAEKdiS9tO6wd98xauKMxsrCrIzcnCnjs8b75gKAqXL3G1lSzpJlq36cpVOk9Kp8/TMHxf3kvY" + `
"3VG8imCAeiU0q9GmSvs01Rt00cx7kdBQLjoGoR0mvDD2BDz5gYW0PVOm2xDwCeg6BYXOUyzxZUsiQwsXtifK4" + `
"qaMN6G6UR10n0GPGRpU+xckNgm7Y8qYsUBDv8P8EDG7KQ7xohNV5n4NKrHMnrTnLmEmDB168+PX+SOVyiRKyQ" + `
"Hz0riUbF7D+Cv0WndN3rP7WILbiMEVRAZnjYkBqojOFYQWDdplPXsndzGEaXhy5tEsbUeMx6J1Rcs6FUziE9K" + `
"dBzw9dAR+2NwMA+EIEzY/8ztxwJNjZpp/AJUliEyvXbHfkS9Q7lkDbPkX2DT6EaUpUDtAQLseB3kC5Zbpk+1/" + `
"ASt6H8v6ib9GpMYB2vJTkutTA8i0Xo5lHdk0ol7SeFLL1PwNGc+R5HRDfbAAAAAASUVORK5CYII="
$i10 = "iVBORw0KGgoAAAANSUhEUgAAAA4AAAAQCAIAAACp9tltAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + `
"AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAXhJREFUKFNtkGtLwlAch2d9uj" + `
"5J0Msu2G1oF5PMoCAQAstMtJUmrSIsKBR8oYmXOW9QiKbNSHGmw6nTf2duzpEdHthhPPx4OJqDe6bd4jDVqab" + `
"Ts3Mzmqlp9U/xvk9+AIAgCDzPcxxXZxsLOtLyXE6X+NzXQA1m9rx3BSSLRxhAgwekSmQqAzXYrivb7Iy9Whsy" + `
"THfvpo7UFNNXg+3YqW8OJMzXeSPx9gdxnukly31s2xopsuCkRExErtuXY9CnIwA77DG486nPHrZhCeaqIGF00" + `
"K1hjOIxzXE6pjt8SVTgghYxnERRhtorsEAV4DEA8+teDDf7wiWQ2DoOFRswiayuGe+CRXAlRfRHAZQhdauR1Z" + `
"VN72sWJJCKYiaRVS1+ubTqlMBND+EyXKWAQOlJcdhBwVl81EpGmwqrBhLFTCKvukM/Cst6j9SNxuwJsMXhNAb" + `
"W6GjVGawraHEiQIvRoQygi5+Gpzj4YnAbGT6WzV9TQLmL2vN/QeovzxcByOFi9/gAAAAASUVORK5CYII="
$i11 = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + `
"AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAahJREFUOE+VkdtKAkEYgKc36Q" + `
"V6hx6l2wgi6qKIgkpCkCiIDmwHEUvR6EBFhRTZubTcdHW3RE07bEes2Mx2t82/f3ZEZLtq+C5mdr9vZtitSb2" + `
"UyL9G8qlUjW3QPcTNMcKibHmLS3LxWEIyJ823sQYn1xYIhgUpwxgbtQcn6wRvbVaWmYYQ8eEnuVoPP8+ZXKx3" + `
"wGVhyWfXlMgZRzUGictmYFwBCMo9Z0FT1vE5BqgxSIwF31GAAKJo+wOLWbs/XU1r1xJqDHJ+Zwb6DoCL4fAnA" + `
"cAwDF3XVVV9LWgYbEXzaCIkcmPQQF0G4Bj22URBx4QOnLx+AQYMlMnptRl8zYA6zOh38rIC1ZxJ4PHRDGVymN" + `
"ZpUByHdwfDNhFCe/kSFi9gQYI5EfwJOBJogDIJXqo0+ByCxz5Gz8ie5QRcHks0QJkE4sVykOsEExawjb0CeAR" + `
"wR+FApAHKZIX/KAdSC5h0Ozb+nrBtXgllMh9S1vh3/DXKVZOSakQ6+1f+BpsxGqBMvIdvSCByiw2jo2ehchNX" + `
"FKZ5mOJhnacBmsS1m7fQ3u2vfHjLBM1f7Ns42ve2ZLkAAAAASUVORK5CYII="
$i12 = "iVBORw0KGgoAAAANSUhEUgAAAAsAAAAPCAIAAAC9X6JnAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + `
"AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAX9JREFUKFN9i0tLAnEUR2+bIC" + `
"hatK2PEhQRJkK0CmlRu1ZBSC9aSVkhQWAFmpqZPZymDJ3UStORKCnthZjmlCWWQ0aEkVhhM9UdBqRVw+Fy/uf" + `
"HlDFP38WPPACUV1ThLX0/3Eeh8F5ZXQNX2e94pqBQ6pgsj16if9SAHZ8Qe8SB6+5T+8NJdBH0rh4VdnSIsjxC" + `
"uo+0Znuc/ULHu7LpM5E+cYIIyyPHiedNp89IeNFnLe6VdTcWcYKLDC8yqVvTmQgjSc8YbePTqxGWEzuc3XMin" + `
"uOk3kINqebGNcvopQ4naa6EYsTg2DkYHDP9jRBMFhE6+ra091Ar0XcOLNS1GLSOWyziBIHE56zjDlpd0O4DGR" + `
"WI5UFqBzkNbdvYcQU6XoAmcn47PWq+BLnfE32HRkJjuxGeUruwus9y0GDdOs9PkddSZQhF2uvVu1K7kTx2YXW" + `
"evkLzhmT4EH/VUilb6A0v1C8LRUYJqzWYUxNMx0RYbU2gi6ALhWDQYXH/5X9+AaM1WpeblNK7AAAAAElFTkSu" + `
"QmCC"
$i13 = "iVBORw0KGgoAAAANSUhEUgAAABEAAAAPCAIAAACN07NGAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + `
"AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAZNJREFUOE+VkNlOwkAUhsfn8Q" + `
"F4Gx/C5c5o3KiBqFEjCFHiCu4IGCIhaqopLqAoBGVpUISqoEjYsZ1pPWMTLrxowuTLn5kz/5k/Z7oSeRl1up4" + `
"+ZEDn1KmbNhoVFHsnnYKiAgHg1QHG6rnk1aN2BT0IBICefsYKqu41Kq5LHoVz1KTSx1gPA7x2BW7R7SsGoKFX" + `
"bzngUupRu4KCGTzrLTp8Hzv+wro7u3n0tubKWBwx80bEshoy265NSwFg3sQaZ73G6WPwI44XbQGlvbCi1LHyW" + `
"VeEMnkpkmQBfhXfC9JNBnNpyTDlBT86i7fMp03o6e65qIug7FdNBs2WCGg8j0FDWarnvMgYPOBHvmhjxpOHnp" + `
"Yk137kUkMuVGWhLD9/QwimITkczEhcGrO8NM44wY/cd9XJ3WdRom9XmlTfK1TTXzQn8kYTrl4k0JOkOKbfBz/" + `
"au64w23wTQlp/ITVCJ/kmKToJCeewOgmbkvzxn6GRbfAjO1eCnuX9BGDdelRZtEf//dvcwtnohHNw2AF+tMIW" + `
"O+UX9FIdqJLevT8AAAAASUVORK5CYII="
$i14 = "iVBORw0KGgoAAAANSUhEUgAAABEAAAAQCAIAAAB/UwMIAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + `
"AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAbhJREFUOE+VjWtLInEYxf99nj" + `
"5A36aX3YiKdoPYV1GWBEEUkTpQtBBdyO5EVHQZzDXJrkOlNlZWZppmXrP5X6YzDAzRLmw9HH4cDufwVFw+CfL" + `
"dCyUEVDVfZZqveHLxKCxh+V+PAjmLcwht03zFEyXGPwrjNru07FNhzNxKrBo5iXHHZgk0hcZPu7ToU/+Z/HL+" + `
"QU6O7rkkMxBtkz/skuU/Jc19K0jIwS1zbL2CEKqmWntcc97Lv5MG2yxCsh9lzh0N1HUdxKCl25XIcXj1iVnJb" + `
"oTC19tmQOJVtaH1LAYwJU2AqSIHb9IGlQeDvmsKriqFBpsbhmwHy/3LCWwqq+XCmwCTeQ5GUgZPYgz0XlFw5T" + `
"hf1zmNPllTSr0z10zor1TkyiJdFPGsiD7zcJKdxdnhHdu7oZ4I3QzThYNMTcck+mTpMG+fVjVm/MmWjD+xF4P" + `
"BpPEhcGtQVvFnx+1P13ZOoU/c/hw2ZaoXyuK5KBJ5fpfhaoqfx9nxPfNHqeeKbofp2oU2H8g1Ng2gTya8GWxG" + `
"ZkOQNHVuyjmhOMZPXb8DwyN7Q5Jn0Cn3D250dLnb2kfRJ2Ny+rt6BzW7RZLF6CiHAAAAAElFTkSuQmCC"
$i15 = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAA" + `
"AAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAsZJREFUOE9FkmtIk1EYx9/nvH" + `
"u3V+dUyltIIaI5DAsiyy5SlphmCprpirnp8MWaoEikXwzayrQgzTLtQ0hN0UIssyQv1AcnQnMaXlIzTDOsvG7" + `
"OnG7qTmdq+vBwLpzf/znP4fwBY0z9D6O+k6qpdlha5lOwsri4zDI2eSqz/4DQyWmLoYiAhNlg+JsQjzkOFxXh" + `
"ykpcUYELCnBGBo6Onj1xfH5iYgOzV9+gLafDcGoqVqlwYSHOzcUKBU5JsWd8PA4NnQvY211fty2Yi47CERE2i" + `
"eRDerotONjm7W1xdV11d1/192+NicFBQSaxWO/jM/Fz3H7DtE5nDgzEISHNKtXIzExTVtYUwC+A3wBPpFL96K" + `
"g2O9vg5TXg6VkadtIuGEpKMPj62vz8Rjhu1mIxLi015+aOATy7cvWP0UiIaaXyh0jU6eKicXXt7+ulevcFjnl" + `
"4kBqTLNsnkxms1sWVlX6t1mQ2E3qc477weH1CYZujY4ODw7VMJdW+c0ePs/N3F5dhgaAfoFuWvGyzEXQN428K" + `
"hQ5AzzA6gaCVz28QCKRxsVSrl6eWZT+zbA+f3wVQl5NjXSMwJqI2tbodoJ2mP/J4r2i6imEuno+img4famSYN" + `
"ob5hFCJXD41P0/oSY1mBeMFq/VldnYLQANCGoTu03RSQhzVVVJcw+O9BXisVE6uv7KP494BdHCcaXXVZLHU5+" + `
"VVkVOaTqbp/PyblMlorBYKNQCNEgmp2p2W9hrgDUJkbJHLib41MfEBwD2EgtzchgYH7D/dUV5WjlAZQK1Y/By" + `
"gmiRClQBPAaoCAu4C5CMUSdPy5Eub1iDTe7W6mHQJUAJQShoAeAhAtvkAKoBYhI4dPTK/3vCm+ciq/lHJDZHo" + `
"DkK3AW6tcyQzETrIspFnw41Gw7aXtpw4/HXwuuyyNFB8YZfXOU+PkD27w8+cqq19sbBg2mL+AY/qjcgixtNMA" + `
"AAAAElFTkSuQmCC"
$i16 = "iVBORw0KGgoAAAANSUhEUgAAABEAAAAQCAIAAAB/UwMIAAAABGdBTUEAALGPC/xhBQAAAiVJREFUOE+Fkl1oU" + `
"nEYxn3POR71THexsRzdNeoiggiSYIOii1XU7vqgLptRV8bqJtwownBhJMJgFH3c72aJsaSty7wpL4yam1qp6d" + `
"xRdzx6znHnWPnx5tlcK1305+HPw/Py4+GFV4MdT5YlUZisVLjO0Wai6RwUCrfqNWO5bJiZebUj1s4oCs/lANH" + `
"SqJlcrqFIJNGJtTN51i4LNCKD9X6Bo2226f8wilIspIm1bPdNGzk/b8Yqfc9xLJVabcP+6smnxxVO63AwBth3" + `
"YMCC9d7CN73b7f0no8iltQiF301PH9Em4sjI4CHEnoZI37EPl0rSn9h2Ty5xu5zUosSkojDQf/6Jaz9KFFbM7" + `
"CLj8fh2YBRZyIa01XwXsgSKMHTwcsDfiyyg0ldbJe03TgrCdlWrJx93CGESOSOmAItw4cxgMUaqPqtv8D3pYN" + `
"fU1MvfVSqjbhLU1VZMmKQwDpgG/zMzZkD1XwHXd9cT1MTYKXGrSmVykbtSiMKMCaOAn0GKko4J3TufQQVigEk" + `
"9crsyAcazVaWRZTH3Vl+NMhghcQkwAg/GaaNu74nDp3EF1CQMmOurhckx64goqltpeDaQeQM/QuTPD0RT1Y/E" + `
"4pxu2HI06L1aDUMr/ETJ78mF53umH79WGWWd/zLXvTRLLM/CpmJeYBcg7oPlF62kGab9hP3a8bPn7rfuWhKls" + `
"etu66jzyuikKmvTODf+pt9IVDkvXnrI80KT+QXPeV0lXl4PIgAAAABJRU5ErkJggg=="
##################################################################################################
function frmMain_Show {
Add-Type -AssemblyName System.Windows.Forms
[Windows.Forms.Application]::EnableVisualStyles()
$ico = [Drawing.Icon]::ExtractAssociatedIcon(($PSHome + '\\powershell_ise.exe'))
$cdcp = New-Object CodeDom.Compiler.CompilerParameters
$dict = New-Object "Collections.Generic.Dictionary[String, String]"
$dict.Add("CompilerVersion", "v3.5")
$frmMain = New-Object Windows.Forms.Form
$mnuMain = New-Object Windows.Forms.MenuStrip
$mnuFile = New-Object Windows.Forms.ToolStripMenuItem
$mnuNDoc = New-Object Windows.Forms.ToolStripMenuItem
$mnuOpen = New-Object Windows.Forms.ToolStripMenuItem
$mnuSave = New-Object Windows.Forms.ToolStripMenuItem
$mnuQSav = New-Object Windows.Forms.ToolStripMenuItem
$mnuEmp1 = New-Object Windows.Forms.ToolStripSeparator
$mnuExit = New-Object Windows.Forms.ToolStripMenuItem
$mnuEdit = New-Object Windows.Forms.ToolStripMenuItem
$mnuUndo = New-Object Windows.Forms.ToolStripMenuItem
$mnuRedo = New-Object Windows.Forms.ToolStripMenuItem
$mnuEmp2 = New-Object Windows.Forms.ToolStripSeparator
$mnuCopy = New-Object Windows.Forms.ToolStripMenuItem
$mnuPast = New-Object Windows.Forms.ToolStripMenuItem
$mnuICut = New-Object Windows.Forms.ToolStripMenuItem
$mnuEmp3 = New-Object Windows.Forms.ToolStripSeparator
$mnuSAll = New-Object Windows.Forms.ToolStripMenuItem
$mnuITag = New-Object Windows.Forms.ToolStripMenuItem
$mnuView = New-Object Windows.Forms.ToolStripMenuItem
$mnuFont = New-Object Windows.Forms.ToolStripMenuItem
$mnuEmp4 = New-Object Windows.Forms.ToolStripSeparator
$mnuOpac = New-Object Windows.Forms.ToolStripMenuItem
$mnuOp50 = New-Object Windows.Forms.ToolStripMenuItem
$mnuOp60 = New-Object Windows.Forms.ToolStripMenuItem
$mnuOp70 = New-Object Windows.Forms.ToolStripMenuItem
$mnuOp80 = New-Object Windows.Forms.ToolStripMenuItem
$mnuOp90 = New-Object Windows.Forms.ToolStripMenuItem
$mnuOpaF = New-Object Windows.Forms.ToolStripMenuItem
$mnuTgls = New-Object Windows.Forms.ToolStripMenuItem
$mnuWrap = New-Object Windows.Forms.ToolStripMenuItem
$mnuPane = New-Object Windows.Forms.ToolStripMenuItem
$mnuSBar = New-Object Windows.Forms.ToolStripMenuItem
$mnuMake = New-Object Windows.Forms.ToolStripMenuItem
$mnuBAsm = New-Object Windows.Forms.ToolStripMenuItem
$mnuBnRA = New-Object Windows.Forms.ToolStripMenuItem
$mnuHelp = New-Object Windows.Forms.ToolStripMenuItem
$mnuInfo = New-Object Windows.Forms.ToolStripMenuItem
$tsTools = New-Object Windows.Forms.ToolStrip
$tsBut_1 = New-Object Windows.Forms.ToolStripButton
$tsBut_2 = New-Object Windows.Forms.ToolStripButton
$tsBut_3 = New-Object Windows.Forms.ToolStripButton
$tsBut_4 = New-Object Windows.Forms.ToolStripButton
$tsSep_1 = New-Object Windows.Forms.ToolStripSeparator
$tsBut_5 = New-Object Windows.Forms.ToolStripButton
$tsBut_6 = New-Object Windows.Forms.ToolStripButton
$tsSep_2 = New-Object Windows.Forms.ToolStripSeparator
$tsBut_7 = New-Object Windows.Forms.ToolStripButton
$tsBut_8 = New-Object Windows.Forms.ToolStripButton
$tsBut_9 = New-Object Windows.Forms.ToolStripButton
$tsSep_3 = New-Object Windows.Forms.ToolStripSeparator
$tsBut10 = New-Object Windows.Forms.ToolStripButton
$tsBut11 = New-Object Windows.Forms.ToolStripButton
$tsSep_4 = New-Object Windows.Forms.ToolStripSeparator
$tsLab_1 = New-Object Windows.Forms.ToolStripLabel
$tsCom_1 = New-Object Windows.Forms.ToolStripComboBox
$tsLab_2 = New-Object Windows.Forms.ToolStripLabel
$tsCom_2 = New-Object Windows.Forms.ToolStripComboBox
$scSplit = New-Object Windows.Forms.SplitContainer
$tcSpace = New-Object Windows.Forms.TabControl
$tpBasic = New-Object Windows.Forms.TabPage
$rtbEdit = New-Object Windows.Forms.RichTextBox
$tcBuild = New-Object Windows.Forms.TabControl
$tpError = New-Object Windows.Forms.TabPage
$lstBugs = New-Object Windows.Forms.ListView
$chPoint = New-Object Windows.Forms.ColumnHeader
$chError = New-Object Windows.Forms.ColumnHeader
$chCause = New-Object Windows.Forms.ColumnHeader
$tpBuild = New-Object Windows.Forms.TabPage
$lblName = New-Object Windows.Forms.Label
$txtName = New-Object Windows.Forms.TextBox
$chkIDbg = New-Object Windows.Forms.CheckBox
$chkIMem = New-Object Windows.Forms.CheckBox
$tpRefer = New-Object Windows.Forms.TabPage
$lboRefs = New-Object Windows.Forms.ListBox
$mnuRefs = New-Object Windows.Forms.ContextMenuStrip
$mnuIMov = New-Object Windows.Forms.ToolStripMenuItem
$mnuICnM = New-Object Windows.Forms.ToolStripMenuItem
$mnuIBuf = New-Object Windows.Forms.ToolStripMenuItem
$mnuIIns = New-Object Windows.Forms.ToolStripMenuItem
$imgList = New-Object Windows.Forms.ImageList
$sbPanel = New-Object Windows.Forms.StatusBar
$sbPnl_1 = New-Object Windows.Forms.StatusBarPanel
$sbPnl_2 = New-Object Windows.Forms.StatusBarPanel
$sbPnl_3 = New-Object Windows.Forms.StatusBarPanel
#
#mnuMain
#
$mnuMain.Items.AddRange(@($mnuFile, $mnuEdit, $mnuView, $mnuMake, $mnuHelp))
#
#mnuFile
#
$mnuFile.DropDownItems.AddRange(@($mnuNDoc, $mnuOpen, $mnuSave, $mnuQSav, $mnuEmp1, $mnuExit))
$mnuFile.Text = "&File"
#
#mnuNDoc
#
$mnuNDoc.ShortcutKeys = "Control", "N"
$mnuNDoc.Text = "&New"
$mnuNDoc.Add_Click({Watch-UnsavedData; $script:src = $null})
#
#mnuOpen
#
$mnuOpen.ShortcutKeys = "Control", "O"
$mnuOpen.Text = "&Open..."
$mnuOpen.Add_Click({Open-Document})
#
#mnuSave
#
$mnuSave.ShortcutKeys = "Control", "S"
$mnuSave.Text = "&Save"
$mnuSave.Add_Click({Save-Document})
#
#mnuQSav
#
$mnuQSav.ShortcutKeys = "F2"
$mnuQSav.Text = "&Quick Save"
$mnuQSav.Add_Click({Save-DocumentQuickly})
#
#mnuExit
#
$mnuExit.ShortcutKeys = "Control", "X"
$mnuExit.Text = "E&xit"
$mnuExit.Add_Click({$frmMain.Close()})
#
#mnuEdit
#
$mnuEdit.DropDownItems.AddRange(@($mnuUndo, $mnuRedo, $mnuEmp2, $mnuCopy, $mnuPast, $mnuICut, `
$mnuEmp3, $mnuSAll, $mnuITag))
$mnuEdit.Text = "&Edit"
#
#mnuUndo
#
$mnuUndo.ShortcutKeys = "Control", "Z"
$mnuUndo.Text = "&Undo"
$mnuUndo.Add_Click({$rtbEdit.Undo()})
#
#mnuRedo
#
$mnuRedo.ShortcutKeys = "Control", "D"
$mnuRedo.Text = "&Redo"
$mnuRedo.Add_Click({$rtbEdit.Redo()})
#
#mnuCopy
#
$mnuCopy.ShortcutKeys = "Control", "C"
$mnuCopy.Text = "&Copy"
$mnuCopy.Add_Click({if ($rtbEdit.SelectionLength -ge 0) {$rtbEdit.Copy()}})
#
#mnuPast
#
$mnuPast.ShortcutKeys = "Control", "V"
$mnuPast.Text = "&Paste"
$mnuPast.Add_Click({$rtbEdit.Paste()})
#
#mnuICut
#
$mnuICut.ShortcutKeys = "Del"
$mnuICut.Text = "Cut &Item"
$mnuICut.Add_Click({if ($rtbEdit.SelectionLength -ge 0) {$rtbEdit.Cut()}})
#
#mnuSAll
#
$mnuSAll.ShortcutKeys = "Control", "A"
$mnuSAll.Text = "Select &All"
$mnuSAll.Add_Click({$rtbEdit.SelectAll()})
#
#mnuITag
#
$mnuITag.ShortcutKeys = "F3"
$mnuITag.Text = "Insert &Tag"
$mnuITag.Add_Click($mnuITag_Click)
#
#mnuView
#
$mnuView.DropDownItems.AddRange(@($mnuFont, $mnuEmp4, $mnuOpac, $mnuTgls))
$mnuView.Text = "&View"
#
#mnuFont
#
$mnuFont.Text = "&Font..."
$mnuFont.Add_Click($mnuFont_Click)
#
#mnuOpac
#
$mnuOpac.DropDownItems.AddRange(@($mnuOp50, $mnuOp60, $mnuOp70, $mnuOp80, $mnuOp90, $mnuOpaF))
$mnuOpac.Text = "&Opacity"
#
#mnuOp50
#
$mnuOp50.Text = "50%"
$mnuOp50.Add_Click({Set-Opacity $mnuOp50; $ops = $mnuOp50})
#
#mnuOp60
#
$mnuOp60.Text = "60%"
$mnuOp60.Add_Click({Set-Opacity $mnuOp60; $ops = $mnuOp60})
#
#mnuOp70
#
$mnuOp70.Text = "70%"
$mnuOp70.Add_Click({Set-Opacity $mnuOp70; $ops = $mnuOp70})
#
#mnuOp80
#
$mnuOp80.Text = "80%"
$mnuOp80.Add_Click({Set-Opacity $mnuOp80; $ops = $mnuOp80})
#
#mnuOp90
#
$mnuOp90.Text = "90%"
$mnuOp90.Add_Click({Set-Opacity $mnuOp90; $ops = $mnuOp90})
#
#mnuOpaF
#
$ops = $mnuOpaF
$mnuOpaF.Checked = $true
$mnuOpaF.Text = "Opaque"
$mnuOpaF.Add_Click($mnuOpaF_Click)
#
#mnuTgls
#
$mnuTgls.DropDownItems.AddRange(@($mnuWrap, $mnuPane, $mnuSBar))
$mnuTgls.Text = "&Toggles"
#
#mnuWrap
#
$mnuWrap.Checked = $true
$mnuWrap.ShortcutKeys = "Control", "W"
$mnuWrap.Text = "&Wrap Mode"
$mnuWrap.Add_Click($mnuWrap_Click)
#
#mnuPane
#
$mnuPane.Checked = $true
$mnuPane.ShortcutKeys = "Control", "L"
$mnuPane.Text = "&Lower Pane"
$mnuPane.Add_Click($mnuPane_Click)
#
#mnuSBar
#
$mnuSBar.Checked = $true
$mnuSBar.ShortcutKeys = "Control", "B"
$mnuSBar.Text = "Status &Bar"
$mnuSBar.Add_Click($mnuSBar_Click)
#
#mnuMake
#
$mnuMake.DropDownItems.AddRange(@($mnuBAsm, $mnuBnRA))
$mnuMake.Text = "&Build"
#
#mnuBAsm
#
$mnuBAsm.ShortcutKeys = "F5"
$mnuBAsm.Text = "&Compile"
$mnuBAsm.Add_Click({Invoke-Builder})
#
#mnuBnRA
#
$mnuBnRA.ShortcutKeys = "F9"
$mnuBnRA.Text = "Compile And &Run"
$mnuBnRA.Add_Click({Start-AfterBuilding})
#
#mnuHelp
#
$mnuHelp.DropDownItems.AddRange(@($mnuInfo))
$mnuHelp.Text = "&Help"
#
#mnuInfo
#
$mnuInfo.Text = "About..."
$mnuInfo.Add_Click({frmInfo_Show})
#
#tsTools
#
$tsTools.ImageList = $imgList
$tsTools.Items.AddRange(@($tsBut_1, $tsBut_2, $tsBut_3, $tsBut_4, $tsSep_1, $tsBut_5, `
$tsBut_6, $tsSep_2, $tsBut_7, $tsBut_8, $tsBut_9, $tsSep_3, $tsBut10, $tsBut11, `
$tsSep_4, $tsLab_1, $tsCom_1, $tsLab_2, $tsCom_2))
#
#tsBut_1
#
$tsBut_1.ImageIndex = 3
$tsBut_1.ToolTipText = "New"
$tsBut_1.Add_Click({Watch-UnsavedData; $script:src = $null})
#
#tsBut_2
#
$tsBut_2.ImageIndex = 4
$tsBut_2.ToolTipText = "Open"
$tsBut_2.Add_Click({Open-Document})
#
#tsBtn_3
#
$tsBut_3.ImageIndex = 5
$tsBut_3.ToolTipText = "Save"
$tsBut_3.Add_Click({Save-Document})
#
#tsBut_4
#
$tsBut_4.ImageIndex = 6
$tsBut_4.ToolTipText = "Quick Save"
$tsBut_4.Add_Click({Save-DocumentQuickly})
#
#tsBut_5
#
$tsBut_5.ImageIndex = 7
$tsBut_5.ToolTipText = "Undo"
$tsBut_5.Add_Click({$rtbEdit.Undo()})
#
#tsBut_6
#
$tsBut_6.ImageIndex = 8
$tsBut_6.ToolTipText = "Redo"
$tsBut_6.Add_Click({$rtbEdit.Redo()})
#
#tsBut_7
#
$tsBut_7.ImageIndex = 9
$tsBut_7.ToolTipText = "Copy"
$tsBut_7.Add_Click({if ($rtbEdit.SelectionLength -ge 0) {$rtbEdit.Copy()}})
#
#tsBut_8
#
$tsBut_8.ImageIndex = 10
$tsBut_8.ToolTipText = "Paste"
$tsBut_8.Add_Click({$rtbEdit.Paste()})
#
#tsBtn_9
#
$tsBut_9.ImageIndex = 11
$tsBut_9.ToolTipText = "Cut Item"
$tsBut_9.Add_Click({if ($rtbEdit.SelectionLength -ge 0) {$rtbEdit.Cut()}})
#
#tsBut10
#
$tsBut10.ImageIndex = 12
$tsBut10.ToolTipText = "Build"
$tsBut10.Add_Click({Invoke-Builder})
#
#tsBut11
#
$tsBut11.ImageIndex = 13
$tsBut11.ToolTipText = "Build And Run"
$tsBut11.Add_Click({Start-AfterBuilding})
#
#tsLab_1
#
$tsLab_1.Text = ".NET:"
#
#tsCom_1
#
$tsCom_1.Items.AddRange(@("v2.0", "v3.5"))
$tsCom_1.SelectedItem = "v2.0"
$tsCom_1.Add_SelectedIndexChanged($tsCom_1_SelectedIndexChanged)
#
#tsLab_2
#
$tsLab_2.Text = "Type:"
#
#tsCom_2
#
$tsCom_2.Items.AddRange(@("Console", "Library", "WinForms"))
$tsCom_2.SelectedItem = "Console"
$tsCom_2.Add_SelectedIndexChanged($tsCom_2_SelectedIndexChanged)
#
#scSplit
#
$scSplit.Dock = "Fill"
$scSplit.Panel1.Controls.Add($tcSpace)
$scSplit.Panel2.Controls.Add($tcBuild)
$scSplit.Panel2MinSize = 17
$scSplit.Orientation = "Horizontal"
$scSplit.SplitterDistance = 330
#
#tcSpace
#
$tcSpace.Controls.Add($tpBasic)
$tcSpace.Dock = "Fill"
$tcSpace.ImageList = $imgList
#
#tpBasic
#
$tpBasic.Controls.Add($rtbEdit)
$tpBasic.ImageIndex = 0
$tpBasic.Text = "Untitled"
$tpBasic.UseVisualStyleBackColor = $true
#
#rtbEdit
#
$rtbEdit.AcceptsTab = $true
$rtbEdit.Dock = "Fill"
$rtbEdit.Font = New-Object Drawing.Font("Courier New", 10)
$rtbEdit.ScrollBars = "Both"
$rtbEdit.Add_Click({Write-CursorPoint})
$rtbEdit.Add_KeyUp({Write-CursorPoint})
$rtbEdit.Add_TextChanged($rtbEdit_TextChanged)
#
#tcBuild
#
$tcBuild.Controls.AddRange(@($tpError, $tpBuild, $tpRefer))
$tcBuild.Dock = "Fill"
#
#tpError
#
$tpError.Controls.Add($lstBugs)
$tpError.Text = "Errors"
$tpError.UseVisualStyleBackColor = $true
#
#lstBugs
#
$lstBugs.Columns.AddRange(@($chPoint, $chError, $chCause))
$lstBugs.Dock = "Fill"
$lstBugs.FullRowSelect = $true
$lstBugs.GridLines = $true
$lstBugs.MultiSelect = $false
$lstBugs.ShowItemToolTips = $true
$lstBugs.SmallImageList = $imgList
$lstBugs.View = "Details"
#
#chPoint
#
$chPoint.Text = "Line"
$chPoint.Width = 50
#
#chError
#
$chError.Text = "Error"
$chError.TextAlign = "Right"
$chError.Width = 65
#
#chCause
#
$chCause.Text = "Description"
$chCause.Width = 648
#
#tpBuild
#
$tpBuild.Controls.AddRange(@($lblName, $txtName, $chkIDbg, $chkIMem))
$tpBuild.Text = "Output"
$tpBuild.UseVisualStyleBackColor = $true
#
#lblName
#
$lblName.Location = New-Object Drawing.Point(8, 8)
$lblName.Size = New-Object Drawing.Size(57, 17)
$lblName.Text = "Assembly:"
#
#txtName
#
$txtName.Anchor = "Left, Top, Right"
$txtName.Location = New-Object Drawing.Point(73, 7)
$txtName.Width = 113
#
#chkIDbg
#
$chkIDbg.Checked = $true
$chkIDbg.Location = New-Object Drawing.Point(23, 29)
$chkIDbg.Text = "Include Debug Info"
$chkIDbg.Width = 120
#
#chkIMem
#
$chkIMem.Enabled = $false
$chkIMem.Location = New-Object Drawing.Point(23, 53)
$chkIMem.Text = "Build In Memory"
$chkIMem.Width = 130
$chkIMem.Add_Click($chkIMem_Click)
#
#tpRefer
#
$tpRefer.Controls.Add($lboRefs)
$tpRefer.Text = "References"
$tpRefer.UseVisualStyleBackColor = $true
#
#lboRefs
#
$lboRefs.ContextMenuStrip = $mnuRefs
$lboRefs.Dock = "Fill"
$lboRefs.SelectionMode = "One"
#
#mnuRefs
#
$mnuRefs.Items.AddRange(@($mnuIMov, $mnuICnM, $mnuIBuf, $mnuIIns))
#
#mnuIMov
#
$mnuIMov.ShortcutKeys = "Del"
$mnuIMov.Text = "Remove Item"
$mnuIMov.Add_Click({$lboRefs.Items.Remove($lboRefs.SelectedItem)})
#
#mnuICnM
#
$mnuICnM.ShortcutKeys = "Control", "M"
$mnuICnM.Text = "Copy And Move"
$mnuICnM.Add_Click($mnuICnM_Click)
#
#mnuIBuf
#
$mnuIBuf.Text = "Insert Copied..."
$mnuIBuf.Add_Click({if ($script:buf -ne $null) {$lboRefs.Items.Add($script:buf)}})
#
#mnuIIns
#
$mnuIIns.Text = "Add Reference"
$mnuIIns.Add_Click($mnuIIns_Click)
#
#imgList
#
$i_1, $i_2, $i_3, $i_4, $i_5, $i_6, $i_7, $i_8, $i_9, $i10, $i11, $i12, $i13, `
$i14, $i15, $i16 | % {$imgList.Images.Add((Get-Image $_))}
#
#sbPanel
#
$sbPanel.Panels.AddRange(@($sbPnl_1, $sbPnl_2, $sbPnl_3))
$sbPanel.ShowPanels = $true
$sbPanel.SizingGrip = $false
#
#sbPnl_1
#
$sbPnl_1.AutoSize = "Spring"
#
#sbPnl_2
#
$sbPnl_2.Alignment = "Center"
$sbPnl_2.AutoSize = "Contents"
#
#sbPnl_3
#
$sbPnl_3.Width = 73
#
#frmMain
#
$frmMain.ClientSize = New-Object Drawing.Size(790, 590)
$frmMain.Controls.AddRange(@($scSplit, $sbPanel, $tsTools, $mnuMain))
$frmMain.FormBorderStyle = "FixedSingle"
$frmMain.Icon = $ico
$frmMain.MainMenuStrip = $mnuMain
$frmMain.StartPosition = "CenterScreen"
$frmMain.Text = "Snippet Compiler"
$frmMain.Add_Load($frmMain_Load)
[void]$frmMain.ShowDialog()
}
##################################################################################################
function frmInfo_Show {
$frmInfo = New-Object Windows.Forms.Form
$pbImage = New-Object Windows.Forms.PictureBox
$lblName = New-Object Windows.Forms.Label
$lblCopy = New-Object Windows.Forms.Label
$btnExit = New-Object Windows.Forms.Button
#
#pbImage
#
$pbImage.Location = New-Object Drawing.Point(16, 16)
$pbImage.Size = New-Object Drawing.Size(32, 32)
$pbImage.SizeMode = "StretchImage"
#
#lblName
#
$lblName.Font = New-Object Drawing.Font("Microsoft Sans Serif", 8, [Drawing.FontStyle]::Bold)
$lblName.Location = New-Object Drawing.Point(53, 19)
$lblName.Size = New-Object Drawing.Size(360, 18)
$lblName.Text = "Snippet Compiler v3.00"
#
#lblCopy
#
$lblCopy.Location = New-Object Drawing.Point(67, 37)
$lblCopy.Size = New-Object Drawing.Size(360, 23)
$lblCopy.Text = "(C) 2012-2013 greg zakharov gregzakh@gmail.com"
#
#btnExit
#
$btnExit.Location = New-Object Drawing.Point(135, 67)
$btnExit.Text = "OK"
#
#frmInfo
#
$frmInfo.AcceptButton = $btnExit
$frmInfo.CancelButton = $btnExit
$frmInfo.ClientSize = New-Object Drawing.Size(350, 110)
$frmInfo.ControlBox = $false
$frmInfo.Controls.AddRange(@($pbImage, $lblName, $lblCopy, $btnExit))
$frmInfo.ShowInTaskBar = $false
$frmInfo.StartPosition = "CenterScreen"
$frmInfo.Text = "About..."
$frmInfo.Add_Load({$pbImage.Image = $ico.ToBitmap()})
[void]$frmInfo.ShowDialog()
}
##################################################################################################
frmMain_Show
|
PowerShellCorpus/PoshCode/finddupe_22.ps1
|
finddupe_22.ps1
|
function Get-SHA512([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]'))
{
$stream = $null
$cryptoServiceProvider = [System.Security.Cryptography.SHA512CryptoServiceProvider]
$hashAlgorithm = new-object $cryptoServiceProvider
try
{
$stream = $file.OpenRead()
}
catch { return $null }
$hashByteArray = $hashAlgorithm.ComputeHash($stream)
$stream.Close()
trap
{
if ($stream -ne $null)
{
$stream.Close()
}
return $null
}
foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += ō0{0:X}ö -f $byte } else { $result += ō{0:X}ö -f $byte }}
return [string]$result
}
$starttime=[datetime]::now
write-host "FindDupe.ps1 - find and optionally delete duplicate files. FindDupe.ps1 -help or FindDupe.ps1 -h for usage options."
$m = 0
$args3=$args
$args2=$args3|?{$_ -ne "-delete" -and $_ -ne "-recurse" -and $_ -ne "-hidden" -and $_ -ne "-h" -and $_ -ne "-help"}
if ($args3 -eq "-help" -or $args3 -eq "-h")
{
""
"Usage:"
" PS>.\\FindDupe.ps1 <directory/file #1> <directory/file #2> ... <directory/file #N> [-delete] [-noprompt] [-recurse] [-help]"
"Options:"
" -recurse recurses through all subdirectories of any specified directories."
" -delete prompts to delete duplicates (but not originals.)"
" -hidden checks hidden files, default is to ignore hidden files."
" -help displays this usage option data, and ignores all other arguments."
""
"Examples:"
" PS>.\\finddupe.ps1 c:\\data d:\\finance -recurse"
" PS>.\\finddupe.ps1 d: -recurse -delete"
" PS>.\\finddupe.ps1 c:\\users\\alice\\pictures\\ -recurse -delete"
exit
}
$files=@(dir -ea 0 $args2 -recurse:$([bool]($args3 -eq "-recurse")) -force:$([bool]($args3 -eq "-hidden")) |?{$_.psiscontainer -eq $false}|sort length)
if ($files.count -lt 2) {exit}
$global:sizenamehash=@{}
for ($i=0;$i -lt ($files.count-1); $i++)
{
if ($files[$i].length -ne $files[$i+1].length) {continue}
$breakout=$false
while($true)
{
$sha512 = (get-SHA512 $files[$i].fullname)
if ($sha512 -ne $null)
{
if (($sizenamehash.$($files[$i].length)) -ne $null)
{
if ($sizenamehash.$($files[$i].length).$($files[$i].fullname) -eq $null)
{
$sizenamehash.$($files[$i].length)+=@{$($files[$i].fullname)=$sha512}
}
}
else
{
$sizenamehash+=@{$($files[$i].length)=@{$($files[$i].fullname)=$sha512}}
}
}
if ($breakout -eq $true) {break}
$i++
if ($i -eq ($files.count-1)) {$breakout=$true; continue}
$breakout=(($files[$i].length -ne $files[$i+1].length))
}
}
($sizenamehash.getenumerator()|%{$sizenamehash.$($_.name).getenumerator()}|group value|?{$_.count -gt 1})|%{write-host "Duplicates:" -fore green;$m+=$_.group.count;$_.group}|%{$_.name}
""
write-host "Number of Files checked: $($files.count)."
write-host "Number of duplicate files: $m."
""
write-host "Time to run: $(([datetime]::now)-$starttime|select hours, minutes, seconds, milliseconds)"
""
|
PowerShellCorpus/PoshCode/Check-ClusterPatches.ps1
|
Check-ClusterPatches.ps1
|
## Check-ClusterPatches.ps1
param($ClusterNode=$Env:ComputerName)
$Patches = @{}
$PatchList = $Null
$PatchListComplete = $Null
$Results = @()
Write-Host "Getting Nodes via WMI..." -foregroundcolor Green
$Nodes = Get-WmiObject -computerName $ClusterNode -namespace ROOT\\MSCluster -class MSCluster_Node | Select Name | foreach {$_.Name}
foreach ( $Node in $Nodes )
{
Write-Host "Getting the Patches on:" $Node -foregroundcolor Green
$Patchlist = Get-WmiObject -computerName $Node -namespace ROOT\\CimV2 -class Win32_QuickFixEngineering | select HotFixID
foreach ($Patch in $PatchList)
{
[array]$PatchListComplete = $PatchListComplete + $Patch.HotFixID
}
Write-Host "Adding Patches to Hashtable For:" $Node -foregroundcolor Green
foreach($Patch in $PatchListComplete)
{
# Check to see if the Patch is in the hashtable, if not, add it.
if(!$Patches.$Patch)
{
$Patches.Add($Patch,"Added")
}
}
}
Write-Host "Comparing Patch Levels across Cluster Nodes...This can take several minutes..." -foregroundcolor Yellow
foreach ($Patch in $Patches.Keys)
{
$PatchObj = New-Object System.Object
$PatchObj | Add-Member -memberType NoteProperty -name HotFixID -Value $Patch
foreach ($Node in $Nodes)
{
if (Get-WmiObject -computerName $Node -namespace ROOT\\CimV2 -class Win32_QuickFixEngineering | Where-Object {$_.HotFixID -eq $Patch})
{
$PatchObj | Add-Member -memberType NoteProperty -name $Node -value "Installed"
}
else
{
$PatchObj | Add-Member -memberType NoteProperty -name $Node -value "Missing"
}
}
$Results += $PatchObj
}
Write-Host "Displaying Results..." -foregroundcolor Green
""
foreach ($Result in $Results)
{
$Match = $true
$Servers = $Result | Get-Member -memberType NoteProperty | Where-Object {$_.Name -ne "HotFixID"} | foreach {$_.Name}
foreach($Server in $Servers)
{
foreach($Srv in $Servers)
{
if($Srv -ne $Server)
{
# If the the value is different we set $Match to $false
if($Result."$Srv" -ne $Result."$Server"){$Match = $false}
}
}
}
$Result | add-Member -MemberType NoteProperty -Name Match -value $Match
$Result
}
|
PowerShellCorpus/PoshCode/Convert-ToCHexString.ps1
|
Convert-ToCHexString.ps1
|
function Convert-ToCHexString {
param([String] $input
$ans = ''
[System.Text.Encoding]::ASCII.GetBytes($str) | % { $ans += "0x{0:X2}, " -f $_ }
return $ans.Trim(',',' ')
}
|
PowerShellCorpus/PoshCode/Hash Checker_2.ps1
|
Hash Checker_2.ps1
|
#.Synopsis
# Test the HMAC hash(es) of a file
#.Description
# Takes the HMAC hash of a file using specified algorithm, and optionally, compare it to a baseline hash
#.Example
# Test-Hash npp.5.3.1.Installer.exe -HashFile npp.5.3.1.release.md5
#
# Searches the provided hash file for a line matching the "npp.5.3.1.Installer.exe" file name
# and take the hash of the file (using the extension of the HashFile as the Type of Hash).
#
#.Example
# Test-Hash npp.5.3.1.Installer.exe 360293affe09ffc229a3f75411ffa9a1 MD5
#
# Takes the MD5 hash and compares it to the provided hash
#
#.Example
# Test-Hash npp.5.3.1.Installer.exe 5e6c2045f4ddffd459e6282f3ff1bd32b7f67517
#
# Tests all of the hashes against the provided (Sha1) hash
#
function Test-Hash {
#[CmdletBinding(DefaultParameterSetName="NoExpectation")]
PARAM(
#[Parameter(Position=0,Mandatory=$true)]
[string]$FileName
,
#[Parameter(Position=2,Mandatory=$true,ParameterSetName="ManualHash")]
[string]$ExpectedHash = $(if($HashFileName){ ((Get-Content $HashFileName) -match $FileName)[0].split(" ")[0] })
,
#[Parameter(Position=1,Mandatory=$true,ParameterSetName="FromHashFile")]
[string]$HashFileName
,
#[Parameter(Position=1,Mandatory=$true,ParameterSetName="ManualHash")]
[string[]]$TypeOfHash = $(if($HashFileName){
[IO.Path]::GetExtension((Convert-Path $HashFileName)).Substring(1)
} else { "MD5","SHA1","SHA256","SHA384","SHA512","RIPEMD160" })
)
$ofs=""
$hashes = @{}
foreach($Type in $TypeOfHash) {
[string]$hash = [Security.Cryptography.HashAlgorithm]::Create(
$Type
).ComputeHash(
[IO.File]::ReadAllBytes( (Convert-Path $FileName) )
) | ForEach { "{0:x2}" -f $_ }
$hashes.$Type = $hash
}
if($ExpectedHash) {
($hashes.Values -eq $hash).Count -ge 1
} else {
foreach($hash in $hashes.GetEnumerator()) {
"{0,-8}{1}" -f $hash.Name, $hash.Value
}
}
}
|
PowerShellCorpus/PoshCode/Page-Output 1.1.ps1
|
Page-Output 1.1.ps1
|
## Page (aka More, aka Page-Output)
###################################################################################################
## This is like a (very simple) "more" script for PowerShell ...
## The problem with it is that you're paging by a count of objects, not by how many lines of text
## they'll output ... so the paging doesn't really work except for format-table output ...
## unless you specify it manually.
##
## However, this script provides you with "an option" if you want to have paging and still be able
## to do something like using a script to color the output based on context or syntax:
##
## Simple example:
## ls | Page | % { $_ ; switch( $i++ % 2 ) { 0 { $Host.UI.RawUI.BackgroundColor = "Black" } 1 { $Host.UI.RawUI.BackgroundColor = "DarkGray" } } }
###################################################################################################
## Revision History
## 1.1 - Clean up output (overwrite the prompt)
## - Add option to stop paging (and also to abort)
## 1.0 - Demo script
###################################################################################################
# function Page {
Param( [int]$count=($Host.UI.RawUI.WindowSize.Height-5) )
BEGIN {
$x = 1
$bg = $Host.UI.RawUI.BackgroundColor;
$fg = $Host.UI.RawUI.ForegroundColor;
$page = $true
}
PROCESS {
if($page -and (($x++ % $count) -eq 0)) {
Write-Host "Press a key to continue (or 'A' for all, or 'Q' to quit)..." -NoNew;
$Host.UI.RawUI.FlushInputBuffer();
$ch = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp");
switch -regex ($ch.Character){
"a|A" { $page = $false }
"q|Q" { exit }
}
$pos = $Host.UI.RawUI.CursorPosition;
$pos.X = 0;
$Host.UI.RawUI.CursorPosition = $pos;
}
$_
}
END {
# Don't forget to set the colors back...
$Host.UI.RawUI.BackgroundColor = $bg;
$Host.UI.RawUI.ForegroundColor = $fg;
}
#}
|
PowerShellCorpus/PoshCode/Edit-File in Notepad++_1.ps1
|
Edit-File in Notepad++_1.ps1
|
<#
.Synopsis
Open a file for editing in notepad++
.Description
Opens one or more files in Notepad++, passing all the switches each time. Accepts filenames on the pipeline
.Notes
I took the "no" off the parameters, because in PowerShell you only need to enter just enough of the parameter name to differentiate ... this way each one is differentiatable by the first letter.
.Link
http://notepad-plus.sourceforge.net/uk/cmdLine-HOWTO.php
.Link
http://notepad-plus.sourceforge.net/
.Link
http://poshcode.org/notepad++lexer/
.Example
Edit-File $Profile -MultiInstance -SessionOff -TabBarOff -PluginsOff
Open your Profile in a new Notepad++ window in a "notepad" like mode: multi-session, no tab bars, no previous files, no plugins.
.Example
ls *.ps1 | Edit-File -SessionOff
Open all the ps1 scripts in Notepad++ without restoring previous files.
.Example
Edit-File -language xml ~\\Projects\\Project1\\Project1.csproj
Open the file Project1.csproj as a xml file, even though its extension is not recognized as xml...
.Parameter File
The absolute or relative path of file(s) you want to open, accepts wildcards
.Parameter MultiInstance
Notepad++ is unique instance by default. This option allows you to launch several instances of Notepad++.
.Parameter PluginsOff
Use this parameter to launch Notepad++ without loading the plugins. This parameter is useful when you want to determinate where the bad behaviour or crash come from (from the plugins or from Notepad++ itself).
.Parameter Language
This option applies the specified Language to the filesToOpen to open, allowing you to specify XML for csproj files, for example.
Valid Languages are : c, cpp, java, cs, objc, rc, html, javascript, php, vb, sql, xml, asp, perl, pascal, python, css, lua, batch, ini, nfo, tex, fortran, bash, actionscript and nsis.
.Parameter Number
Cause Notepad++ to go to the LineNumber you want after opening the file
.Parameter SessionOff
Launch Notepad++ without loading the previous session (the files opened in Notepad++ last time).
.Parameter ReadOnly
Open files in read only mode. (Alias: RO)
.Parameter TabBarOff
Turn off the tab interface. Useful if you want a minimalist session ...
#>
[CmdletBinding()]
Param(
[Parameter(ValueFromPipelineByPropertyName=$true,Position=1)]
[Alias("FullName","LiteralPath","Path")]
[string[]]
$File
,
[Parameter()]
[switch]$MultiInstance
,
[Parameter()]
[switch]$PluginsOff
,
[Parameter()]
[string]$Language
,
[Parameter(Position=2)]
[int]$Number
,
[Parameter()]
[switch]$SessionOff
,
[Parameter()]
[Alias("RO")]
[Switch]$ReadOnly
,
[Parameter()]
[Switch]$TabBarOff
)
BEGIN {
$npp = "C:\\Programs\\DevTools\\Notepad++\\notepad++.exe"
$param = @(
if($MultiInstance) { "-multiInst" }
if($PluginsOff) { "-noPlugin" }
if($Language) { "-l$Language" }
if($Number) { "-n$Number" }
if($SessionOff) { "-nosession" }
if($ReadOnly) { "-ro" }
if($TabBarOff) { "-notabbar" }
" "
) -join " "
}
PROCESS {
foreach($path in $File) {
foreach($f in Convert-Path (Resolve-Path $path)) {
$parameters = $param + """" + $f + """"
write-verbose "$npp $parameters"
[Diagnostics.Process]::Start($npp,$parameters).WaitForInputIdle(500)
}
}
}
|
PowerShellCorpus/PoshCode/Speech Recognition.ps1
|
Speech Recognition.ps1
|
$null = [Reflection.Assembly]::LoadWithPartialName("System.Speech")
## Create the two main objects we need for speech recognition and synthesis
if(!$Global:SpeechModuleListener){ ## For XP's sake, don't create them twice...
$Global:SpeechModuleSpeaker = new-object System.Speech.Synthesis.SpeechSynthesizer
$Global:SpeechModuleListener = new-object System.Speech.Recognition.SpeechRecognizer
}
$Script:SpeechModuleMacros = @{}
## Add a way to turn it off
$Script:SpeechModuleMacros.Add("Stop Listening", { $script:listen = $false; Suspend-Listening })
$Script:SpeechModuleComputerName = ${Env:ComputerName}
function Update-SpeechCommands {
#.Synopsis
# Recreate the speech recognition grammar
#.Description
# This parses out the speech module macros, and recreates the speech recognition grammar and semantic results, and then updates the SpeechRecognizer with the new grammar, and makes sure that the ObjectEvent is registered.
$choices = new-object System.Speech.Recognition.Choices
foreach($choice in $Script:SpeechModuleMacros.GetEnumerator()) {
New-Object System.Speech.Recognition.SemanticResultValue $choice.Key, $choice.Value.ToString() |
ForEach-Object{ $choices.Add( $_.ToGrammarBuilder() ) }
}
if($VerbosePreference -ne "SilentlyContinue") { $Script:SpeechModuleMacros.Keys | % { Write-Host "$Computer, $_" -Fore Cyan }}
$builder = New-Object System.Speech.Recognition.GrammarBuilder "$Computer, "
$builder.Append((New-Object System.Speech.Recognition.SemanticResultKey "Commands", $choices.ToGrammarBuilder()))
$grammar = new-object System.Speech.Recognition.Grammar $builder
$grammar.Name = "Power VoiceMacros"
## Take note of the events, but only once (make sure to remove the old one)
Unregister-Event "SpeechModuleCommandRecognized" -ErrorAction SilentlyContinue
$null = Register-ObjectEvent $grammar SpeechRecognized -SourceIdentifier "SpeechModuleCommandRecognized" -Action { iex $event.SourceEventArgs.Result.Semantics.Item("Commands").Value }
$Global:SpeechModuleListener.UnloadAllGrammars()
$Global:SpeechModuleListener.LoadGrammarAsync( $grammar )
}
function Add-SpeechCommands {
#.Synopsis
# Add one or more commands to the speech-recognition macros, and update the recognition
#.Parameter CommandText
# The string key for the command to remove
[CmdletBinding()]
Param([hashtable]$VoiceMacros,[string]$Computer=$Script:SpeechModuleComputerName)
$Script:SpeechModuleMacros += $VoiceMacros ## Add the new macros
$Script:SpeechModuleComputerName = $Computer ## Update the default if they change it, so they only have to do that once.
Update-SpeechCommands
}
function Remove-SpeechCommands {
#.Synopsis
# Remove one or more command from the speech-recognition macros, and update the recognition
#.Parameter CommandText
# The string key for the command to remove
Param([string[]]$CommandText)
foreach($command in $CommandText) { $Script:SpeechModuleMacros.Remove($Command) }
Update-SpeechCommands
}
function Clear-SpeechCommands {
#.Synopsis
# Removes all commands from the speech-recognition macros, and update the recognition
#.Parameter CommandText
# The string key for the command to remove
$Script:SpeechModuleMacros = @{}
## Default value: A way to turn it off
$Script:SpeechModuleMacros.Add("Stop Listening", { Suspend-Listening })
Update-SpeechCommands
}
function Start-Listening {
#.Synopsis
# Sets the SpeechRecognizer to Enabled
$Global:SpeechModuleListener.Enabled = $true
Say "Speech Macros are $($Global:SpeechModuleListener.State)"
Write-Host "Speech Macros are $($Global:SpeechModuleListener.State)"
}
function Suspend-Listening {
#.Synopsis
# Sets the SpeechRecognizer to Disabled
$Global:SpeechModuleListener.Enabled = $false
Say "Speech Macros are disabled"
Write-Host "Speech Macros are disabled"
}
function Out-Speech {
#.Synopsis
# Speaks the input object
#.Description
# Uses the default SpeechSynthesizer settings to speak the string representation of the InputObject
#.Parameter InputObject
# The object to speak
# NOTE: this should almost always be a pre-formatted string, because most things don't render to very speakable text.
Param( [Parameter(ValueFromPipeline=$true)][Alias("IO")]$InputObject )
$null = $Global:SpeechModuleSpeaker.SpeakAsync(($InputObject|Out-String))
}
function Remove-SpeechXP {
#.Synopis
# Dispose of the SpeechModuleListener and SpeechModuleSpeaker
$Global:SpeechModuleListener.Dispose(); $Global:SpeechModuleListener = $null
$Global:SpeechModuleSpeaker.Dispose(); $Global:SpeechModuleSpeaker = $null
}
set-alias asc Add-SpeechCommands
set-alias rsc Remove-SpeechCommands
set-alias csc Clear-SpeechCommands
set-alias say Out-Speech
set-alias listen Start-Listener
Export-ModuleMember -Function * -Alias * -Variable SpeachModuleListener, SpeechModuleSpeaker
###################################################################################################
## USAGE EXAMPLES:
###################################################################################################
# Add-SpeechCommands @{
# "What time is it?" = { Say "It is $(Get-Date -f "h:mm tt")" }
# "What day is it?" = { Say $(Get-Date -f "dddd, MMMM dd") }
# "What's running?" = {
# $proc = ps | sort ws -desc
# Say $("$($proc.Count) processes, including $($proc[0].name), which is using " +
# "$([int]($proc[0].ws/1mb)) megabytes of memory")
# }
# "Run Notepad" = { & "C:\\Programs\\DevTools\\Notepad++\\notepad++.exe" }
# } -Computer "Laptop" -Verbose
#
# Add-SpeechCommands @{ "Check Inbox" = { Say "Checking for email" } }
|
PowerShellCorpus/PoshCode/Send mail to BCC using P.ps1
|
Send mail to BCC using P.ps1
|
<#
.SYNOPSIS
Send mail to BCC using PowerShell
.DESCRIPTION
This script is a re-developed MSDN Sample using PowerShell. It creates
an email message then sends it with a BCC.
.NOTES
File Name : Send-BCCMail.ps1
Author : Thomas Lee - tfl@psp.co.uk
Requires : PowerShell V2 CTP3
.LINK
Original Sample Posted to
http://pshscripts.blogspot.com/2009/01/send-bccmailps1.html
MSDN Sample and details at:
http://msdn.microsoft.com/en-us/library/system.net.mail.mailaddresscollection.aspx
.EXAMPLE
PS C:\\foo> .\\Send-BCCMail.ps1
Sending an e-mail message to The PowerShell Doctor and "Thomas Lee" <tfl@reskit.net>
#>
###
# Start Script
###
# Create from, to, bcc and the message strucures
$From = New-Object system.net.Mail.MailAddress "tfl@cookham.net", "Thomas Lee"
$To = new-object system.net.mail.mailaddress "doctordns@gmail.com", "The PowerShell Doctor"
$Bcc = New-Object system.Net.Mail.mailaddress "tfl@reskit.net", "Thomas Lee"
$Message = New-Object system.Net.Mail.MailMessage $From, $To
# Populate message
$Message.Subject = "Using the SmtpClient class and PowerShell."
$Message.Body = "Using this feature, you can send an e-mail message from an"
$Message.Body += "application very easily. `nEven better, you do it with PowerShell!"
# Add BCC
$Message.Bcc.Add($bcc);
# Create SMTP Client
$Server = "localhost"
$Client = New-Object System.Net.Mail.SmtpClient $server
$Client.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
"Sending an e-mail message to {0} and {1}" -f $to.DisplayName, $Message.Bcc.ToString()
# send the message
try {
$client.Send($message);
}
catch {
"Exception caught in CreateBccTestMessage(): {0}" -f $Error[0]
}
|
PowerShellCorpus/PoshCode/Invoke-NamedParameters.ps1
|
Invoke-NamedParameters.ps1
|
Function Invoke-NamedParameters {
<#
.SYNOPSIS
Invokes a method using named parameters.
.DESCRIPTION
A function that simplifies calling methods with named parameters to make it easier to deal with long signatures and optional parameters. This is particularly helpful for COM objects.
.PARAMETER Object
The object that has the method.
.PARAMETER Method
The name of the method.
.PARAMETER Parameter
A hashtable with the names and values of parameters to use in the method call.
.PARAMETER Argument
An array of arguments without names to use in the method call.
.NOTES
Name: Invoke-NamedParameters
Author: Jason Archer
DateCreated: 2011-04-06
1.0 - 2011-04-06 - Jason Archer
Initial release.
.EXAMPLE
$shell = New-Object -ComObject Shell.Application
Invoke-NamedParameters $Shell "Explore" @{"vDir"="$pwd"}
Description
-----------
Invokes a method named "Explore" with the named parameter "vDir."
#>
[CmdletBinding(DefaultParameterSetName = "Named")]
param(
[Parameter(ParameterSetName = "Named", Position = 0, Mandatory = $true)]
[Parameter(ParameterSetName = "Positional", Position = 0, Mandatory = $true)]
[ValidateNotNull()]
[System.Object]$Object
,
[Parameter(ParameterSetName = "Named", Position = 1, Mandatory = $true)]
[Parameter(ParameterSetName = "Positional", Position = 1, Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]$Method
,
[Parameter(ParameterSetName = "Named", Position = 2, Mandatory = $true)]
[ValidateNotNull()]
[Hashtable]$Parameter
,
[Parameter(ParameterSetName = "Positional")]
[Object[]]$Argument
)
end { ## Just being explicit that this does not support pipelines
if ($PSCmdlet.ParameterSetName -eq "Named") {
## Invoke method with parameter names
## Note: It is ok to use a hashtable here because the keys (parameter names) and values (args)
## will be output in the same order. We don't need to worry about the order so long as
## all parameters have names
$Object.GetType().InvokeMember($Method, [System.Reflection.BindingFlags]::InvokeMethod,
$null, ## Binder
$Object, ## Target
([Object[]]($Parameter.Values)), ## Args
$null, ## Modifiers
$null, ## Culture
([String[]]($Parameter.Keys)) ## NamedParameters
)
} else {
## Invoke method without parameter names
$Object.GetType().InvokeMember($Method, [System.Reflection.BindingFlags]::InvokeMethod,
$null, ## Binder
$Object, ## Target
$Argument, ## Args
$null, ## Modifiers
$null, ## Culture
$null ## NamedParameters
)
}
}
}
<#
Examples
Calling a method with named parameters.
$shell = New-Object -ComObject Shell.Application
Invoke-NamedParameters $Shell "Explore" @{"vDir"="$pwd"}
The syntax for more than one would be @{"First"="foo";"Second"="bar"}
Calling a method that takes no parameters (you can also use -Argument with $null).
$shell = New-Object -ComObject Shell.Application
Invoke-NamedParameters $Shell "MinimizeAll" @{}
#>
|
PowerShellCorpus/PoshCode/MWE_UsageSample.psm1.ps1
|
MWE_UsageSample.psm1.ps1
|
# ModuleWriteErrorUsageExample.psm1
# To use this you need to have the ModuleWriteError module loaded.
#Import-Module c:\\scripts\\ModuleWriteError
# Also:: Using $ErrorView = "CategoryView" is useful too.
function Get-Foo {
[CmdletBinding()]
param(
[string]$name,
[switch]$interrupt
)
Process {
# Just imagine you did some parsing of a file and the foo object wasn't found.
$MyErrorRecord = (
New-ModuleError -ErrorCategory ObjectNotFound `
-message "Cannot get `'$Name`' because it does not exist." `
-identifierText FooObjectNotFound -targetObject $($Name)
)
$PSCmdlet.WriteError( $MyErrorRecord )
}
}
function Set-Foo {
[CmdletBinding()]
param(
[string]$name,
[switch]$interrupt
)
Process {
# we need to get Foo to make sure we can set it.
# Play with the -ea value to see how that changes the ev_errors values.
get-foo $Name -ev ev_errors -ea "SilentlyContinue"
## Trap this module's non-terminating written errors, similar to a catch.
$ev_errors | sort -Unique | foreach { $_ |
where { ($_.exception.getType().Name -eq `
"$($MyInvocation.MyCommand.ModuleName)ModuleException") -and
($_.CategoryInfo.Category.ToString() -eq "ObjectNotFound") } |
%{
# Do whatever processing would be done to handle the error, or
# alter the record and rethrow from this function to present the
# user with an error that matches the function they called.
# Keep the first part of the FQEid since WriteError will append
# the current command name.
$new_FQI = $([regex]::match($_.FullyQualifiedErrorId,
"(.*?,){2}").Groups[0].value).ToString().TrimEnd(",")
# This allows WriteError to correctly apply function naming.
$MyErrorRecord = (
new-object System.Management.Automation.ErrorRecord $_.Exception,
"$($new_FQI)",
$_.CategoryInfo.Category,
$_.CategoryInfo.TargetName)
# Modify the message presented to the user so that instead of
# reporting that we can not 'get' the object when the user called 'set'
$MyErrorRecord.ErrorDetails = (
New-Object System.Management.Automation.ErrorDetails `
"Cannot set `'$Name`' because it was not found." )
# Not sure which is better here... The activity should present
# what action caused the error, but should it be the action of
# this command, or the action of what this command was doing.
# Neither of these are _really_ needed.
#$MyErrorRecord.CategoryInfo.Activity = "$($MyPrefixedCommandName)"
#$MyErrorRecord.CategoryInfo.Activity = $curr_error.CategoryInfo.Activity
# Finally re-write it from here.
$PSCmdlet.WriteError( $MyErrorRecord )
}
}
}
}
function Test-foo {
[CmdletBinding()]
param()
Write-Host "`n********************************************************************************" -ForegroundColor Cyan
$Error.Clear()
Write-Host "Sample output from Get-Foo call:" -ForegroundColor Gray
Get-Foo bar -ev ev_errors
Write-Host "`nDump of what is in `$ev_errors after calling Get-Foo:" -ForegroundColor Gray
foreach ($err in $ev_errors) {Write-Warning ($err|Out-String)}
#Write-Host "`nDump of what is in `$Local:Error after calling Get-Foo:" -ForegroundColor Gray
#Write-Output -InputObject $Local:Error
Write-Host "`nDump of what is in `$Global:Error after calling Get-Foo:" -ForegroundColor Gray
Write-Output -InputObject $Global:Error
Write-Host "`nPlease enter the following command: `'`$Global:Error.clear(); exit`'" -ForegroundColor Blue
$Host.EnterNestedPrompt()
Write-Host "`n`n********************************************************************************" -ForegroundColor Cyan
Write-Host "`nSample output from Set-Foo call:" -ForegroundColor Gray
Set-Foo bar -ev ev_errors
Write-Host "`nDump of what is in `$ev_errors after calling Set-Foo:" -ForegroundColor Gray
foreach ($err in $ev_errors) {Write-Warning ($err|Out-String)}
#Write-Host "`nDump of what is in `$Local:Error after calling Set-Foo:" -ForegroundColor Gray
#Write-Output -InputObject $Local:Error
Write-Host "`nDump of what is in `$Global:Error after calling Set-Foo:" -ForegroundColor Gray
Write-Output -InputObject $Global:Error
}
|
PowerShellCorpus/PoshCode/Log4Net_1.xslt.ps1
|
Log4Net_1.xslt.ps1
|
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://logging.apache.org/log4net/schemas/log4net-events-1.2"
version="1.0">
<xsl:output method="html" indent="yes" encoding="UTF-8"/>
<xsl:template match="events">
<html><head>
<!-- refresh every minute (60 seconds)-->
<meta http-equiv="refresh" content="60" />
<style>
th { vertical-align: top; }
td { padding: 0 6px; border-right: 1px solid black; }
table.data { width: 100% }
td.name, td.value { padding: 0px; border: none; }
td.value { text-align: right }
.FATAL { color: white; background: #ff0000;}
.ERROR { background: #cc6666; }
.WARN { background: #cc9933; }
.DEBUG { background: #66cc66; }
.INFO { background: #eeffee; }
</style>
<!-- You gotta love this: http :// en.hasheminezhad.com/scrollsaver -->
<script type="text/javascript">
<xsl:text disable-output-escaping="yes"><![CDATA[(function(){function ls(){var c=document.cookie.split(';');for(var i=0;i<c.length;i++){var p=c[i].split('=');if(p[0]=='scrollPosition'){p=unescape(p[1]).split('/');for(var j=0;j<p.length;j++){var e=p[j].split(',');try{if(e[0]=='window'){window.scrollTo(e[1],e[2]);}else if(e[0]){var o=document.getElementById(e[0]);o.scrollLeft=e[1];o.scrollTop=e[2];}}catch(ex){}}return;}}}function ss(){var s='scrollPosition=';var l,t;if(window.pageXOffset!==undefined){l=window.pageXOffset;t=window.pageYOffset;}else if(document.documentElement&&document.documentElement.scrollLeft!==undefined){l=document.documentElement.scrollLeft;t=document.documentElement.scrollTop;}else{l=document.body.scrollLeft;t=document.body.scrollTop;}if(l||t){s+='window,'+l+','+t+'/';}var es=(document.all)?document.all:document.getElementsByTagName('*');for(var i=0;i<es.length;i++){var e=es[i];if(e.id&&(e.scrollLeft||e.scrollTop)){s+=e.id+','+e.scrollLeft+','+e.scrollTop+'/';}}document.cookie=s+';';}var a,p;if(window.attachEvent){a=window.attachEvent;p='on';}else{a=window.addEventListener;p='';}a(p+'load',function(){ls();if(typeof Sys!='undefined'&&typeof Sys.WebForms!='undefined'){Sys.WebForms.PageRequestManager.getInstance().add_endRequest(ls);Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(ss);}},false);a(p+'unload',ss,false);})();]]></xsl:text>
</script>
</head><body id="body">
<h2><xsl:value-of select="logname"/>.xml Log</h2>
<table cellspacing="0">
<tr><th rowspan="2">Logger</th><th rowspan="2">Timestamp</th><th rowspan="2">Level</th><th rowspan="2">Thread</th><th rowspan="2">Message</th><th rowspan="2">NDC</th><th colspan="2">Properties</th><th rowspan="2">Location</th></tr>
<tr><th>Name</th><th>Value</th></tr>
<xsl:apply-templates select="event"/>
</table>
</body></html>
</xsl:template>
<xsl:template match="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>
<td class="message"><xsl:apply-templates select="message"/></td>
<td class="NDC"><xsl:apply-templates select="NDC"/><xsl:text disable-output-escaping="yes"><![CDATA[ ]]></xsl:text></td>
<td class="properties" colspan="2"><table class="data"><xsl:apply-templates select="properties/data"/></table></td>
<td class="locationInfo"><xsl:apply-templates select="locationInfo"/></td>
</tr>
</xsl:template>
<xsl:template match="locationInfo">
<xsl:value-of select="@class"/> <xsl:value-of select="@method"/> <xsl:value-of select="@file"/> <xsl:value-of select="@line"/>
</xsl:template>
<xsl:template match="data">
<tr><td class="name"><xsl:value-of select="substring-after(@name,'log4net:')"/><xsl:text disable-output-escaping="yes"><![CDATA[: ]]></xsl:text></td><td class="value"><xsl:value-of select="@value"/></td></tr>
</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/26d9a40a-d77f-4500-a0b2-5d0d79606685.ps1
|
26d9a40a-d77f-4500-a0b2-5d0d79606685.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/Backup-ModifiedGPOs_1.ps1
|
Backup-ModifiedGPOs_1.ps1
|
###########################################################################"
#
# NAME: Backup-ModifiedGPOs.ps1
#
# AUTHOR: Jan Egil Ring
# EMAIL: jan.egil.ring@powershell.no
#
# COMMENT: All Group Policy Objects modified in the specified timespan are backup up to the specified backup path.
# For more details, see the following blog-post:
# http://blog.powershell.no/2010/06/15/backing-up-group-policy-objects-using-windows-powershell
#
# You have a royalty-free right to use, modify, reproduce, and
# distribute this script file in any way you find useful, provided that
# you agree that the creator, owner above has no warranty, obligations,
# or liability for such use.
#
# VERSION HISTORY:
# 1.0 15.06.2010 - Initial release
#
# 1.1 17.11.2010 - Andy Helsby - Added check to create backup directory and report directory if it does not exist.
# - Added optional parameter to allow backups of gpo's modified in last X days (defaults to 1 otherwise)
# - Note if no group policies were modified in the previous X days, the script does throw an error about Name not being provided.
#
# 1.2 24.11.2010 - Added the -FirstRun switch parameter to backup all GPO`s. Added additional logic.
###########################################################################"
#Requires -Version 2.0
Param([switch]$FirstRun)
Import-Module grouppolicy
$BackupPath = "C:\\GPO Backup"
$ReportPath = "C:\\GPO Backup\\Reports\\"
if (!(Test-Path -path $BackupPath)) {New-Item $BackupPath -type directory}
if (!(Test-Path -path $ReportPath)) {New-Item $ReportPath -type directory}
if ($FirstRun) {
$Timespan = (Get-Date).AddDays(-5000)
}
else {
$Timespan = (Get-Date).AddDays(-1)
}
$ModifiedGPOs = Get-GPO -all | Where-Object {$_.ModificationTime -gt $Timespan}
if ($ModifiedGPOs) {
Write-Host "The following "$ModifiedGPOs.count" GPOs were successfully backed up:" -ForegroundColor yellow
Foreach ($GPO in $ModifiedGPOs) {
$GPOBackup = Backup-GPO $GPO.DisplayName -Path $BackupPath
$Path = $ReportPath + $GPO.ModificationTime.Month + "-"+ $GPO.ModificationTime.Day + "-" + $GPO.ModificationTime.Year + "_" +
$GPO.Displayname + "_" + $GPOBackup.Id + ".html"
Get-GPOReport -Name $GPO.DisplayName -path $Path -ReportType HTML
Write-Host $GPO.DisplayName
}
}
else {
Write-Host "No GPO`s modified since $Timespan. If this is your initial backup, run the script with the -FirstRun switch parameter to backup all GPO`s" -ForegroundColor yellow
}
|
PowerShellCorpus/PoshCode/Convert-ToMP_1.ps1
|
Convert-ToMP_1.ps1
|
param([String] $inputPath, [String] $wildcard, [String] $outputPath = $inputPath)
gci -path $inputPath\\$wildcard | % {
$outputFile = Join-Path $outputPath ($_.Name.Replace($_.Extension, '.mp3'))
vlc -I dummy $_.FullName ":sout=#transcode{acodec=mp3,ab=128,channels=6}:standard{access=file,mux=asf,dst=$outputFile}" vlc://quit
Get-Process vlc | % { $_.WaitForExit() }
}
|
PowerShellCorpus/PoshCode/e61c6c2a-be74-4a09-8b96-80d2469d4644.ps1
|
e61c6c2a-be74-4a09-8b96-80d2469d4644.ps1
|
CREATE LOGIN [vCenter_Owner] WITH PASSWORD=N'KVx$!|mhQ^', CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
GO
--Modify Drive and size to match your environment
CREATE DATABASE [vCenter] ON PRIMARY
( NAME = N'vCenter', FILENAME = N'S:\\Data\\vCenter.mdf' , SIZE = 100MB , MAXSIZE = UNLIMITED, FILEGROWTH = 10%)
LOG ON
( NAME = N'vCenter_log', FILENAME = N'T:\\Logs\\vCenter.ldf' , SIZE = 10MB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
GO
use vCenter
GO
CREATE USER [vCenter_Owner] FOR LOGIN [vCenter_Owner] WITH DEFAULT_SCHEMA=[dbo]
GO
sp_addrolemember db_owner, [vCenter_Owner]
GO
use msdb
CREATE USER [vCenter_Owner] FOR LOGIN [vCenter_Owner] WITH DEFAULT_SCHEMA=[dbo]
GO
sp_addrolemember db_owner, [vCenter_Owner]
GO
--After vCenter installation completes, remove the vCenter login from msdb.
use msdb
drop user [vCenter_Owner]
|
PowerShellCorpus/PoshCode/Get-mDatastoreList.ps1
|
Get-mDatastoreList.ps1
|
Function Get-mDatastoreList {
#Parameter- Name of the VMware cluster to choose a datastore from.
param($Cluster)
#get alphabetically last ESX host in the VMware cluster (it's likely the last host added to the cluster, so this might smoke out any problems)
$VMH = get-vmhost -Location $cluster | Where-Object { ($_.ConnectionState -eq "Connected") -and ($_.PowerState -eq "PoweredOn") } | Select-Object -Property Name | Sort-Object Name | Select -Last 1 -Property Name
# Get all the datastores, filtered for exclusions
$DSTs = Get-Datastore -VMHost $VMH.Name | Where-Object { ($_.Type -eq "VMFS") -and ($_.Name -notmatch "local") -and ($_.Name -notmatch "iso") -and ($_.Name -notmatch "template") -and ($_.Name -notmatch "datastore") -and ($_.Name -notmatch "temp") -and ($_.Name -notmatch "decom") -and ($_.Name -notmatch "_BED-PR") -and ($_.Name -notmatch "VMAX") -and ($_.Name -notmatch "NEW") -and ($_.Name -notmatch "MAY-PR-LEG") -and ($_.Name -notmatch "BED-QA-LEG") }
Write-Output $DSTs
}
#20110617 cmonahan- removed filters for "CLD" and "TRX"
#20110629 cmonahan- filtering out BED-PR-31 and BED-PR-32, reserved for mongodb VMs
|
PowerShellCorpus/PoshCode/Run-Defrag_2.ps1
|
Run-Defrag_2.ps1
|
# Run-Defrag
# Defragments the targeted hard drives.
#
# Args:
# $server: A target Server 2003 or 2008 system
# $drive: An optional drive letter. If this is blank then all
# drives are defragmented
# $force: If this switch is set then a defrag will be forced
# even if the drive is low on space
#
# Returns:
# The result description for each drive.
function Run-Defrag {
param([string]$server, [string]$drive, [switch]$force)
[string]$query = 'Select * from Win32_Volume where DriveType = 3'
if ($drive) {
$query += " And DriveLetter LIKE '$drive%'"
}
$volumes = Get-WmiObject -Query $query -ComputerName $server
foreach ($volume in $volumes) {
Write-Host "Defragmenting $($volume.DriveLetter)..." -noNewLine
$result = $volume.Defrag($force)
switch ($result) {
0 {Write-Host 'Success'}
1 {Write-Host 'Access Denied'}
2 {Write-Host 'Not Supported'}
3 {Write-Host 'Volume Dirty Bit Set'}
4 {Write-Host 'Not Enough Free Space'}
5 {Write-Host 'Corrupt MFT Detected'}
6 {Write-Host 'Call Cancelled'}
7 {Write-Host 'Cancellation Request Requested Too Late'}
8 {Write-Host 'Defrag In Progress'}
9 {Write-Host 'Defrag Engine Unavailable'}
10 {Write-Host 'Defrag Engine Error'}
11 {Write-Host 'Unknown Error'}
}
}
}
|
PowerShellCorpus/PoshCode/Set-IPAddress_7.ps1
|
Set-IPAddress_7.ps1
|
# corrected version - $mask variable corrected to match in both places
function Set-IPAddress {
param( [string]$networkinterface =$(read-host "Enter the name of the NIC (ie Local Area Connection)"),
[string]$ip = $(read-host "Enter an IP Address (ie 10.10.10.10)"),
[string]$mask = $(read-host "Enter the subnet mask (ie 255.255.255.0)"),
[string]$gateway = $(read-host "Enter the current name of the NIC you want to rename"),
[string]$dns1 = $(read-host "Enter the first DNS Server (ie 10.2.0.28)"),
[string]$dns2,
[string]$registerDns = "TRUE"
)
$dns = $dns1
if($dns2){$dns ="$dns1,$dns2"}
$index = (gwmi Win32_NetworkAdapter | where {$_.netconnectionid -eq $networkinterface}).InterfaceIndex
$NetInterface = Get-WmiObject Win32_NetworkAdapterConfiguration | where {$_.InterfaceIndex -eq $index}
$NetInterface.EnableStatic($ip, $mask)
$NetInterface.SetGateways($gateway)
$NetInterface.SetDNSServerSearchOrder($dns)
$NetInterface.SetDynamicDNSRegistration($registerDns)
}
|
PowerShellCorpus/PoshCode/Add-Namespace v1.1.ps1
|
Add-Namespace v1.1.ps1
|
trap [System.Management.Automation.RuntimeException]
{
$entryException = $_
if ($_.CategoryInfo.Category -eq [System.Management.Automation.ErrorCategory]::InvalidOperation)
{
if ($_.FullyQualifiedErrorId -eq "TypeNotFound")
{
$targetName = $_.CategoryInfo.TargetName
try
{
$isAmbiguous = $global:__ambiguousTypeNames.Contains($targetName)
}
catch
{
throw $entryException
}
if ($isAmbiguous)
{
$message = New-Object System.Text.StringBuilder
$message.AppendFormat("The type [{0}] is ambiguous. Specify one of the following: ", $targetName).AppendLine() | Out-Null
[System.Type]::GetType("System.Management.Automation.TypeAccelerators")::Get.GetEnumerator() | ForEach-Object {
if (($_.Key.Split('.'))[-1] -eq $targetName)
{
$message.Append($_.Key).AppendLine() | Out-Null
}
}
$message.AppendLine() | Out-Null
$message.AppendFormat("At {0}:{1} char:{2}", $_.InvocationInfo.ScriptName, $_.InvocationInfo.ScriptLineNumber, $_.InvocationInfo.OffsetInLine).AppendLine() | Out-Null
$erroneousToken = $_.InvocationInfo.Line.Substring(0, $_.InvocationInfo.OffsetInLine - 1)
$remainder = $_.InvocationInfo.Line.Substring($_.InvocationInfo.OffsetInLine - 1)
$message.AppendFormat("+ {0} <<<< {1}", $erroneousToken, $remainder).AppendLine() | Out-Null
$message.AppendFormat("`t+ CategoryInfo : {0} : ({1}:{2}) [], {3}", $_.CategoryInfo.Category, $targetName, $_.TargetObject.GetType().Name, $_.Exception.GetType().Name).AppendLine() | Out-Null
$message.AppendFormat("`t+ FullyQualifiedErrorId : {0}", $_.FullyQualifiedErrorId).AppendLine() | Out-Null
Write-Host $message.ToString() -ForegroundColor Red
continue
}
}
}
}
<#
.SYNOPSIS
Imports the types in the specified namespaces in the specified assemblies.
.DESCRIPTION
The Add-Namespace function adds a type accelerator for each type found in the specified namespaces in the specified assemblies that satisfy a set of conditions. For more information see the NOTES section.
.PARAMETER Assembly
Specifies one or more assemblies to import the specified namespaces from.
.PARAMETER Namespace
Specifies one or more namespaces to import.
.INPUTS
System.Reflection.Assembly
You can pipe an assembly to Add-Namespace.
.OUTPUTS
None
This function does not return any output.
.NOTES
The type accelerator for the type is added if the type:
- Has a base type which is not System.Attribute, System.Delegate or System.MulticastDelegate
- Is not abstract
- Is not an interface
- Is not nested
- Is public
- Is visible
- Is qualified by the namespace specified in the Namespace parameter
This function also comes with an exception handler in the form of a trap block. Type name collisions occur when a type has the same name of another type which is in a different namespace. When this happens, the function adds or replaces the type accelerator for that type using its fully-qualified type name. If a type resolution occurs during runtime, the trap block will determine if the type was unresolved during any of the calls made to Add-Namespace and throw an exception listing valid replacements.
Be aware that namspaces can span multiple assemblies, in which case you would have to import the namespace for each assembly that it exists in.
This function will not attempt to add or replace types which already exist under the same name.
This function assumes that the variable $global:__ambiguousTypeNames is exclusively available for use.
The type accelerators added by this function exist only in the current session. To use the type accelerators in all sessions, add them to your Windows PowerShell profile. For more information about the profile, see about_profiles.
.EXAMPLE
C:\\PS> [System.Reflection.Assembly]::LoadWithPartialName("mscorlib") | Add-Namespace System.Reflection
C:\\PS> [Assembly]::LoadWithPartialName("System.Windows.Forms")
This example shows how to import namespaces from an assembly. The assembly must be loaded non-reflectively into the current application domain.
.EXAMPLE
C:\\PS> $assemblies = Get-ExecutingAssemblies -Filter mscorlib, System, System.Windows.Forms, System.Xml
C:\\PS> $assemblies | Add-Namespace System, System.Collections, System.Collections.Generic, System.Net, System.Net.NetworkInformation, System.Reflection, System.Windows.Forms, System.Xml
This example shows how to import multiple namespaces from multiple assemblies using the Get-ExecutingAssemblies function to filter the required assemblies.
.LINK
about_trap
#>
function Add-Namespace
{
[CmdletBinding(SupportsShouldProcess = $true)]
param (
[Parameter(ValueFromPipeline = $true)]
[System.Reflection.Assembly]$Assembly,
[Parameter(Mandatory = $true, Position = 0)]
[ValidateNotNullOrEmpty()]
[String[]]$Namespace
)
begin
{
if ($global:__ambiguousTypeNames -eq $null)
{
$global:__ambiguousTypeNames = New-Object 'System.Collections.Generic.List[System.String]'
}
$genericRegex = [Regex]'(?<Name>.*)`\\d+'
$typeAccelerators = [System.Type]::GetType("System.Management.Automation.TypeAccelerators")
$typeDictionary = $typeAccelerators::Get
}
process
{
$_.GetTypes() | Where-Object {
($_.BaseType -ne [System.Attribute]) -and
($_.BaseType -ne [System.Delegate]) -and
($_.BaseType -ne [System.MulticastDelegate]) -and
!$_.IsAbstract -and
!$_.IsInterface -and
!$_.IsNested -and
$_.IsPublic -and
$_.IsVisible -and
($_.Namespace -ne $null) -and
($Namespace -contains $_.Namespace)
} | ForEach-Object {
$name = $_.Name
$fullName = $_.FullName
if ($_.IsGenericType)
{
if ($_.FullName -match $genericRegex)
{
$fullName = $Matches["Name"]
$name = $fullName.Split('.')[-1]
}
}
if ($typeDictionary.ContainsKey($name))
{
if ($typeDictionary[$name] -eq $_)
{
return
}
}
if ($typeDictionary.ContainsKey($fullName))
{
if ($typeDictionary[$fullName] -eq $_)
{
return
}
}
if ($global:__ambiguousTypeNames.Contains($name))
{
$typeAccelerators::Add($fullName, $_)
return
}
if ($typeDictionary.ContainsKey($name))
{
$type = $typeDictionary[$name]
if ($_ -ne $type)
{
$global:__ambiguousTypeNames.Add($name)
$newName = $type.FullName
if ($type.IsGenericType)
{
if ($newName -match $genericRegex)
{
$newName = $Matches["Name"]
}
}
$typeAccelerators::Remove($name)
$typeAccelerators::Add($newName, $type)
$typeAccelerators::Add($fullName, $_)
}
return
}
$typeAccelerators::Add($name, $_)
} | Out-Null
}
end { }
}
<#
.SYNOPSIS
Gets assemblies that are currently executing in the current application domain.
.DESCRIPTION
The Get-Assemblies function retrieves Assembly objects from assemblies that are executing in the current application domain.
.PARAMETER Filter
Specifies one or more Assembly objects to retrieve.
.INPUTS
None
You cannot pipe objects to Get-ExecutingAssemblies.
.OUTPUTS
System.Reflection.Assembly
A collection of Assembly objects.
.NOTES
You can get a list of currently executing assemblies by calling this function. Sometimes, it is not necessary to load some assemblies as they are loaded into the current application domain by default.
.EXAMPLE
C:\\PS> $assemblies = Get-ExecutingAssemblies -Filter mscorlib, System, System.Windows.Forms
C:\\PS> $assemblies | Add-Namespace System, System.Collections, System.Collections.Generic, System.Net, System.Net.NetworkInformation, System.Reflection, System.Windows.Forms
This example shows how Get-ExecutingAssemblies can be used in conjunction with Add-Namespace.
.LINK
#>
function Get-ExecutingAssemblies
{
param (
[Parameter(Mandatory = $false, Position = 0)]
[String[]]$Filter
)
if (($Filter -eq $null) -or ($Filter.Length -eq 0))
{
return [System.AppDomain]::CurrentDomain.GetAssemblies()
}
return [System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $Filter -contains [System.IO.Path]::GetFileNameWithoutExtension($_.Location) }
}
# Sample usage
# You can do this as an initialization task for your script
Get-ExecutingAssemblies -Filter mscorlib, System, System.Windows.Forms, System.Xml | Add-Namespace -Namespace `
System,
System.Collections,
System.Collections.Generic,
System.Net,
System.Net.NetworkInformation,
System.Reflection,
System.Windows.Forms,
System.Xml
|
PowerShellCorpus/PoshCode/Get-OUComputerNames.ps1
|
Get-OUComputerNames.ps1
|
param(
[switch]$Help,
[string] $OU
)
$usage = @'
Get-OUComputerNames
usage : .\\Get-OUComputerNames.ps1 "OU=TESTOU,dc=domain,dc=com"
returns : the names of computers in Active Directory (AD) that
recursively match a given LDAP query
author : Nathan Hartley
'@
if ($help) {Write-Host $usage;break}
if (!$OU) {$OU = $(read-host "Please specify an LDAP search string")}
if (!$OU -match "^LDAP://") { $OU = "LDAP://" + $OU }
$strCategory = "computer"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$OU")
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher($objDomain,"(objectCategory=$strCategory)",@('name'))
$objSearcher.FindAll() | %{$_.properties.name}
|
PowerShellCorpus/PoshCode/TreeView Sample.ps1
|
TreeView Sample.ps1
|
Add-Type -AssemblyName presentationframework
function view-TextFiles ($dir = '.') {
# Create WPF Form from XAML file and bind Controls to variables
$path = Resolve-Path $dir
$Form=[Windows.Markup.XamlReader]::Load([IO.File]::OpenText('c:\\scripts\\window.xaml').basestream)
$ListBox = $form.FindName('listBox')
$RichTextBox = $form.FindName('richTextBox1')
# Fill ListBox
ls *.ps1 |% {
$li = new-Object Windows.Controls.ListBoxItem
$li.Content = $_.name
$li.Tag= $_.fullname
$listbox.Items.Add($LI)
}
# Add Handler to Read File
$ListBox.add_MouseDoubleClick({
$RichTextBox.SelectAll()
$RichTextBox.Selection.Text = gc $this.Selecteditem.Tag
})
# Invoke Form
$Form.ShowDialog() | out-null
}
|
PowerShellCorpus/PoshCode/hex2dec_1.ps1
|
hex2dec_1.ps1
|
@echo off
::unequal symbols
for %%i in ("!", "x") do if "%1" equ "%%~i" goto:error
::display help information args
for %%i in ("-h", "/h", "-help", "/help") do (
if "%1" equ "%%~i" goto:help
)
if "%1" equ "-?" goto:help
if "%1" equ "/?" goto:help
::interactive mode
if "%1" equ "" (
if not defined run goto:interactive
goto:error
)
::parsing input data
setlocal enabledelayedexpansion
::checking is arg hex or dec
2>nul set /a "res=%1"
if "%1" equ "%res%" goto:dec2hex
::patterns
echo "%1" | findstr /r \\x > nul
set e1=%errorlevel%
echo "%1" | findstr /r [0-9a-f] > nul
set e2=%errorlevel%
echo "%1" | findstr /r [g-wyz] > nul
set e3=%errorlevel%
::parsing error codes
if %e1% equ 0 if %e2% equ 0 if %e3% equ 1 set "k=%1" & goto:hex2dec
if %e1% equ 1 if %e2% equ 0 if %e3% equ 1 set "k=0x%1" & goto:hex2dec
goto:error
:dec2hex
2>nul set /a "num=%1"
set "map=0123456789ABCDEF"
for /l %%i in (1, 1, 8) do (
set /a "res=num & 15, num >>=4"
for %%j in (!res!) do set "hex=!map:~%%j,1!!hex!"
)
for /f "tokens=* delims=0" %%i in ("!hex!") do set "hex=0x%%i"
echo %1 = !hex! & goto:eof
:hex2dec
set "num=%k%"
if "%num:~0,1%" equ "x" goto:error
2>nul set /a "res=%k%"
for /f "tokens=2,3" %%i in ('findstr "# " "%~dpnx0"') do set "num=!num:%%i=%%j!"
if "%res%" neq "" (echo !num! = !res!) else goto:error
endlocal
exit /b
:error
if defined run echo =^>err & goto:eof
echo Invalid data.
exit /b 1
:help
::Hex2dec v1.10 - converts hex to decimal and vice versa
::Copyright (C) 2012 Greg Zakharov
::forum.script-coding.com
::
::Usage: hex2dec [decimal | hexadecimal]
::
::Example 1:
:: C:\\>hex2dec 0x017a
:: 0x017A = 378
::
::Example 2:
:: C:\\>hex2dec 13550
:: 13550 = 0x34EE
::
::Example 3:
:: C:\\>hex2dec 23f
:: 0x23F = 575
for /f "tokens=* delims=:" %%i in ('findstr "^::" "%~dpnx0"') do echo.%%i
exit /b 0
rem :: Upper case chart ::
# a A
# b B
# c C
# d D
# e E
# f F
rem :: End of chart ::
:interactive
::interactive mode on
echo Hex2dec v1.10 - converts hex to decimal and vice versa
echo.
setlocal
::marker - already launched
set run=true
:begin
set /p "ask=>>> "
cmd /c "%~dpnx0" %ask%
if "%ask%" equ "clear" cls
if "%ask%" equ "exit" cls & goto:eof
echo.
goto:begin
endlocal
exit /b
|
PowerShellCorpus/PoshCode/All Exchange 2003 Server.ps1
|
All Exchange 2003 Server.ps1
|
[Array]$ExchSrvs = @("")
[String]$StrFilter = “(objectCategory=msExchExchangeServer)”
$objRootDSE = [ADSI]“LDAP://RootDSE”
[String]$strContainer = $objRootDSE.configurationNamingContext
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = New-object `
System.DirectoryServices.DirectoryEntry(”LDAP://$strContainer”)
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = “Subtree”
$colResults = $objSearcher.FindAll()
ForEach($objResult in $colResults)
{
[String]$Server = $objResult.Properties.name
$ExchSrvs += $Server
}
$ExchSrvs.Count
|
PowerShellCorpus/PoshCode/Get-MyPublicIPAddress.ps1
|
Get-MyPublicIPAddress.ps1
|
<#
.SYNOPSIS
Gets the public IP address that represents your computer on the internet.
.DESCRIPTION
The Get-MyPublicIPAddress script uses DNS-O-Matic, an OpenDNS resource, to retreive the public IP address that represents your computer on the internet.
.EXAMPLE
Get-MyPublicIPAddress
1.1.1.1
Description
-----------
This command returns the public IP address that represents your computer on the internet.
.INPUTS
None
.OUTPUTS
System.String
.NOTES
Name: Get-MyPublicIPAddress
Author: Rich Kusak
Created: 2010-08-30
LastEdit: 2010-08-30 11:05
Version: 1.0.0.0
.LINK
http://myip.dnsomatic.com
.LINK
http://www.opendns.com
#>
[CmdletBinding()]
param ()
# Create a web client object
$webClient = New-Object System.Net.WebClient
# Returns the public IP address
$webClient.DownloadString('http://myip.dnsomatic.com/')
|
PowerShellCorpus/PoshCode/Get-OwnerReport_1.ps1
|
Get-OwnerReport_1.ps1
|
##############################################################################
##
## Get-OwnerReport
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
##############################################################################
<#
.SYNOPSIS
Gets a list of files in the current directory, but with their owner added
to the resulting objects.
.EXAMPLE
Get-OwnerReport | Format-Table Name,LastWriteTime,Owner
Retrieves all files in the current directory, and displays the
Name, LastWriteTime, and Owner
#>
Set-StrictMode -Version Latest
$files = Get-ChildItem
foreach($file in $files)
{
$owner = (Get-Acl $file).Owner
$file | Add-Member NoteProperty Owner $owner
$file
}
|
PowerShellCorpus/PoshCode/Test-UserCredential_5.ps1
|
Test-UserCredential_5.ps1
|
function Test-UserCredential {
[CmdletBinding(DefaultParameterSetName = "set1")]
[OutputType("set1", [System.Boolean])]
[OutputType("PSCredential", [System.Boolean])]
param(
[Parameter(Mandatory=$true, ParameterSetName="set1", position=0)]
[ValidateNotNullOrEmpty()]
[String] $Username,
[Parameter(Mandatory=$true, ParameterSetName="set1", position=1)]
[ValidateNotNullOrEmpty()]
[System.Security.SecureString] $Password,
[Parameter(Mandatory=$true, ParameterSetName="PSCredential", ValueFromPipeline=$true, position=0)]
[ValidateNotNullOrEmpty()]
[Management.Automation.PSCredential] $Credential,
[Parameter(position=2)]
[Switch] $Domain,
[Parameter(position=3)]
[Switch] $UseKerberos
)
Begin {
try { $assem = [system.reflection.assembly]::LoadWithPartialName('System.DirectoryServices.AccountManagement') }
catch { throw 'Failed to load assembly "System.DirectoryServices.AccountManagement". The error was: "{0}".' -f $_ }
$system = Get-WmiObject -Class Win32_ComputerSystem
if (0, 2 -contains $system.DomainRole -and $Domain) {
throw 'This computer is not a member of a domain.'
}
}
Process {
try {
switch ($PSCmdlet.ParameterSetName) {
'PSCredential' {
if ($Domain) {
$Username = $Credential.UserName.TrimStart('\\')
} else {
$Username = $Credential.GetNetworkCredential().UserName
}
$PasswordText = $Credential.GetNetworkCredential().Password
}
'set1' {
# Decrypt secure string.
$PasswordText = [Runtime.InteropServices.Marshal]::PtrToStringAuto(
[Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password)
)
}
}
if ($Domain) {
$pc = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext 'Domain', $system.Domain
} else {
$pc = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext 'Machine', $env:COMPUTERNAME
}
if ($Domain -and $UseKerberos) {
return $pc.ValidateCredentials($Username, $PasswordText)
} else {
return $pc.ValidateCredentials($Username, $PasswordText, [DirectoryServices.AccountManagement.ContextOptions]::Negotiate)
}
} catch {
throw 'Failed to test user credentials. The error was: "{0}".' -f $_
} finally {
Remove-Variable -Name Username -ErrorAction SilentlyContinue
Remove-Variable -Name Password -ErrorAction SilentlyContinue
}
}
<#
.SYNOPSIS
Validates credentials for local or domain user.
.PARAMETER Username
The user's username.
.PARAMETER Password
The user's password.
.PARAMETER Credential
A PSCredential object created by Get-Credential. This can be pipelined to Test-UserCredential.
.PARAMETER Domain
If this flag is set the user credentials should be a domain user account.
.PARAMETER UseKerberos
By default NTLM is used. Specify this switch to attempt kerberos authentication.
This is only used with the 'Domain' parameter.
You may need to specify domain\\user.
.EXAMPLE
PS C:\\> Test-UserCredential -Username andy -password (Read-Host -AsSecureString)
.EXAMPLE
PS C:\\> Test-UserCredential -Username 'mydomain\\andy' -password (Read-Host -AsSecureString) -domain -UseKerberos
.EXAMPLE
PS C:\\> Test-UserCredential -Username 'andy' -password (Read-Host -AsSecureString) -domain
.EXAMPLE
PS C:\\> Get-Credential | Test-UserCredential
.INPUTS
None.
.OUTPUTS
System.Boolean.
.LINK
http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.principalcontext.aspx
.NOTES
Revision History
2011-08-21: Andy Arismendi - Created.
2011-08-22: Andy Arismendi - Add pipelining support for Get-Credential.
2011-08-22: Andy Arismendi - Add support for NTLM/kerberos switch.
#>
}
Test-UserCredential -user andy -password (Read-Host -AsSecureString)
|
PowerShellCorpus/PoshCode/POC csharp expressions_2.ps1
|
POC csharp expressions_2.ps1
|
function run-csharpexpression([string] $expression )
{
$global:ccounter = [int]$ccounter + 1
$local:name = [system.guid]::NewGuid().tostring().replace('-','_').insert(0,"csharpexpr")
$local:ns = "ShellTools.DynamicCSharpExpression.N${ccounter}"
$local:template = @"
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace $ns
{
public static class Runner
{
public static object RunExpression()
{
return [[EXPRESSION]];
}
}
}
"@
$local:source = $local:template.replace("[[EXPRESSION]]",$expression)
add-Type $local:source -Language CsharpVersion3 | out-Null
invoke-Expression ('[' + $local:ns + '.Runner]::RunExpression()')
}
set-alias c run-csharpexpression
c DateTime.Now
c "new{a=1,b=2,c=3}"
c 'from x in Directory.GetFiles(@"c:\\downloads") where x.Contains("win") select x'
|
PowerShellCorpus/PoshCode/Add _ Get-Help -Full_1.ps1
|
Add _ Get-Help -Full_1.ps1
|
$executionContext.SessionState.InvokeCommand.PreCommandLookupAction = {
param($CommandName, $CommandLookupEventArgs)
if($CommandName.StartsWith("?")) {
$RealCommandName = $CommandName.TrimStart("?")
$CommandLookupEventArgs.CommandScriptBlock = {
Get-Help $RealCommandName -Full
## Wrap it in a closure because we need $CommandName
}.GetNewClosure()
}
}
Write-Warning "DO NOT USE THIS POSTCOMMANDLOOKUPACTION EXCEPT FOR DEMONSTRATION"
$executionContext.SessionState.InvokeCommand.PostCommandLookupAction = {
param($CommandName, $CommandLookupEventArgs)
# Only for interactive commands (and that doesn't include "prompt")
# I should exclude out-default so we don't handle it on every pipeline, but ...
if($CommandLookupEventArgs.CommandOrigin -eq "Runspace" -and $CommandName -ne "prompt" ) {
## Create a new script block that checks for the "-??" argument
## And if -?? exists, calls Get-Help -Full instead
## Otherwise calls the expected command
$CommandLookupEventArgs.CommandScriptBlock = {
if($Args.Length -eq 1 -and $Args[0] -eq "-??") {
Get-Help $CommandName -Full
} else {
& $CommandName @args
}
## Wrap it in a closure because we need $CommandName
}.GetNewClosure()
}
}
|
PowerShellCorpus/PoshCode/Send-Growl _1.1.ps1
|
Send-Growl _1.1.ps1
|
## This is the first version of a Growl module (just dot-source to use in PowerShell 1.0)
## v 1.0 supports a very simple notice, and no callbacks
## v 2.0 supports registering multiple message types
## supports callbacks
## v 2.1 redesigned to be a module used from apps, rather than it's own "PowerGrowler" app
## v 3.0 Make it a v2-only PowerShell module
## v 3.1 fixes for PowerShell 2 RTM
## TODO:
## * Test sending notices to other PCs directly
Set-StrictMode -Version 2
## this is just a default now, you'll have opportunities to override it...
$script:appName = "PowerGrowler"
[Reflection.Assembly]::LoadFrom("$(Split-Path (gp HKCU:\\Software\\Growl).'(default)')\\Growl.Connector.dll") | Out-Null
if(!(Test-Path Variable:Global:PowerGrowlerNotices)) {
$global:PowerGrowlerNotices = @{}
}
## We can safely recreate this, it doesn't store much
$script:PowerGrowler = New-Object "Growl.Connector.GrowlConnector"
function Register-GrowlType {
#.Synopsis
# Register a new Type name for growl notices from PowerGrowl
#.Description
# Creates a new type name that can be used for sending growl notices
#.Parameter AppName
# The name of the application you want to register as
#.Parameter Name
# The type name to be used sending growls
#.Parameter DisplayName
# The test to use for display (defaults to use the same value as the type name)
#.Parameter Icon
# Overrides the default icon of the message (accepts .ico, .png, .bmp, .jpg, .gif etc)
#.Parameter MachineName
# The name of a remote machine to register remotely instead of locally.
#.Parameter Priority
# Overrides the default priority of the message (use sparingly)
#.Example
# Register-GrowlType "PoshTwitter" "Command Completed"
#
# Registers the type "Command Completed," using the default icon, for sending notifications to the local PC
#
PARAM(
[Parameter(Mandatory=$true,Position=0)]
[String]$AppName
,
[Parameter(Mandatory=$true,Position=1)]
[ValidateScript( {!$global:PowerGrowlerNotices.Contains($AppName) -OR !$global:PowerGrowlerNotices.$AppName.Notices.ContainsKey($_)} )]
[String]$Name
,
[Parameter(Mandatory=$false,Position=5)]
[String]$Icon = "$PSScriptRoot\\default.ico"
,
[Parameter(Mandatory=$false,Position=6)]
[String]$DisplayName = $Name
,
[Parameter(Mandatory=$false,Position=7)]
[String]$MachineName
,
[Parameter(Mandatory=$false)]
[String]$AppIcon
)
[Growl.Connector.NotificationType]$Notice = $Name
$Notice.DisplayName = $DisplayName
$Notice.Icon = Convert-Path (Resolve-Path $Icon)
if($MachineName) {
$Notice.MachineName = $MachineName
}
if(!$global:PowerGrowlerNotices.Contains($AppName)) {
$global:PowerGrowlerNotices.Add( $AppName, ([Growl.Connector.Application]$AppName) )
$global:PowerGrowlerNotices.$AppName = Add-Member -input $global:PowerGrowlerNotices.$AppName -Name Notices -Type NoteProperty -Value (New-Object hashtable) -Passthru
if($AppIcon) {
$global:PowerGrowlerNotices.$AppName.Icon = Convert-Path (Resolve-Path $AppIcon)
}
}
$global:PowerGrowlerNotices.$AppName.Notices.Add( $Name, $Notice )
$script:PowerGrowler.Register( $global:PowerGrowlerNotices.$AppName , [Growl.Connector.NotificationType[]]@($global:PowerGrowlerNotices.$AppName.Notices.Values) )
}
function Set-GrowlPassword {
#.Synopsis
# Set the Growl password
#.Description
# Set the password and optionally, the encryption algorithm, for communicating with Growl
#.Parameter Password
# The password for Growl
#.Parameter Encryption
# The algorithm to be used for encryption (defaults to AES)
#.Parameter KeyHash
# The algorithm to be used for key hashing (defaults to SHA1)
PARAM(
[Parameter(Mandatory=$true,Position=0)]
[String]$Password
,
[Parameter(Mandatory=$false,Position=1)]
[ValidateSet( "AES", "DES", "RC2", "TripleDES", "PlainText" )]
[String]$Encryption = "AES"
,
[Parameter(Mandatory=$false,Position=2)]
[ValidateSet( "MD5", "SHA1", "SHA256", "SHA384", "SHA512" )]
[String]$KeyHash = "SHA1"
)
$script:PowerGrowler.EncryptionAlgorithm = [Growl.Connector.Cryptography+SymmetricAlgorithmType]::"$Encryption"
$script:PowerGrowler.KeyHashAlgorithm = [Growl.Connector.Cryptography+SymmetricAlgorithmType]::"$KeyHash"
$script:PowerGrowler.Password = $Password
}
## Register the "PowerGrowler" "Default" notice so everything works out of the box
Register-GrowlType $script:AppName "Default" -appIcon "$PsScriptRoot\\default.ico"
function Register-GrowlCallback {
#.Synopsis
# Register a script to be called when each notice is finished.
#.Description
# Registers a scriptblock as a handler for the NotificationCallback event. You should accept two parameters, a Growl.Connector.Response and a Growl.Connector.CallbackData object.
#
# The NotificationCallback only happens when a callback is requested, which in this Growl library only happens if you pass both CallbackData and CallbackType to the Send-Growl function.
#.Example
# Register-GrowlCallback { PARAM( $response, $context )
# Write-Host "Response $($response|out-string)" -fore Cyan
# Write-Host "Context $($context|fl|out-string)" -fore Green
# Write-Host $("Response Type: {0}`nNotification ID: {1}`nCallback Data: {2}`nCallback Data Type: {3}`n" -f $context.Result, $context.NotificationID, $context.Data, $context.Type) -fore Yellow
# }
#
# Registers an informational debugging-style handler.
#
PARAM(
[Parameter(Mandatory=$true)]
[Scriptblock]$Handler
)
Register-ObjectEvent $script:PowerGrowler NotificationCallback -Action $Handler
}
function Send-Growl {
[CmdletBinding(DefaultParameterSetName="NoCallback")]
#.Synopsis
# Send a growl notice
#.Description
# Send a growl notice with the scpecified values
#.Parameter Caption
# The short caption to display
#.Parameter Message
# The message to send (most displays will resize to accomodate)
#.Parameter NoticeType
# The type of notice to send. This MUST be the name of one of the registered types, and senders should bear in mind that each registered type has user-specified settings, so you should not abuse the types, but create your own for messages that will recur.
# For example, the user settings allow certain messages to be disabled, set to a different "Display", or to have their Duration and Stickyness changed, as well as have them be Forwarded to another device, have Sounds play, and set different priorities.
#.Parameter Icon
# Overrides the default icon of the message (accepts .ico, .png, .bmp, .jpg, .gif etc)
#.Parameter Priority
# Overrides the default priority of the message (use sparingly)
#.Example
# Send-Growl "Greetings" "Hello World!"
#
# The Hello World of Growl.
#.Example
# Send-Growl "You've got Mail!" "Message for you sir!" -icon ~\\Icons\\mail.png
#
# Displays a message with a couple of movie quotes and a mail icon.
#
PARAM (
[Parameter(Mandatory=$true, Position=0)]
[ValidateScript( {$global:PowerGrowlerNotices.Contains($AppName)} )]
[string]$AppName
,
[Parameter(Mandatory=$true, Position=1)][Alias("Type")]
[ValidateScript( {$global:PowerGrowlerNotices.$AppName.Notices.ContainsKey($_)} )]
[string]$NoticeType
,
[Parameter(Mandatory=$true, Position=2)]
[string]$Caption
,
[Parameter(Mandatory=$true, Position=3)]
[string]$Message
,
[Parameter(Mandatory=$true, Position=4, ParameterSetName="UrlCallback")]
[Uri]$Url
,
[Parameter(Mandatory=$true, Position=4, ParameterSetName="DataCallback")]
[string]$CallbackData
,
[Parameter(Mandatory=$true, Position=5, ParameterSetName="DataCallback")]
[string]$CallbackType
,
[string]$Icon
,
[Growl.Connector.Priority]$Priority = "Normal"
)
$notice = New-Object Growl.Connector.Notification $appName, $NoticeType, (Get-Date).Ticks.ToString(), $caption, $Message
if($Icon) { $notice.Icon = Convert-Path (Resolve-Path $Icon) }
if($Priority) { $notice.Priority = $Priority }
if($DebugPreference -gt "SilentlyContinue") { Write-Output $notice }
switch( $PSCmdlet.ParameterSetName ) {
"UrlCallback" {
$context = new-object Growl.Connector.CallbackContext $Url
# $urlCb = new-object Growl.Connector.UrlCallbackTarget
# $urlCb.Url = $Url
# $context.SetUrlCallbackTarget($urlcb)
$script:PowerGrowler.Notify($notice, $context)
break;
}
"DataCallback" {
$context = new-object Growl.Connector.CallbackContext $CallbackData, $CallbackType
$script:PowerGrowler.Notify($notice, $context)
break;
}
"NoCallback" {
$script:PowerGrowler.Notify($notice)
break;
}
}
}
Export-ModuleMember -Function Send-Growl, Set-GrowlPassword, Register-GrowlCallback, Register-GrowlType
|
PowerShellCorpus/PoshCode/Get-ADGroupModifications.ps1
|
Get-ADGroupModifications.ps1
|
###########################################################################"
#
# NAME: Get-ADGroupModificationsReport.ps1
#
# AUTHOR: Jan Egil Ring
# EMAIL: jan.egil.ring@powershell.no
#
# COMMENT: Generates a HTML-report of Active Directory group membership modifications (addings and deletions).
# Specify a valid path on line 211 to store the report.
# For more details, see the following blog-post:
# http://janegilring.wordpress.com/2009/10/11/active-directory-group-membership-modifications-report
#
# You have a royalty-free right to use, modify, reproduce, and
# distribute this script file in any way you find useful, provided that
# you agree that the creator, owner above has no warranty, obligations,
# or liability for such use.
#
# VERSION HISTORY:
# 1.0 11.10.2009 - Initial release
#
###########################################################################"
#Requires -Version 2.0
Function Get-CustomHTML ($Header){
$Report = @"
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http`://www.w3.org/TR/html4/frameset.dtd">
<html><head><title>$($Header)</title>
<META http-equiv=Content-Type content='text/html; charset=windows-1252'>
<meta name="save" content="history">
<style type="text/css">
DIV .expando {DISPLAY: block; FONT-WEIGHT: normal; FONT-SIZE: 10pt; RIGHT: 8px; COLOR: #ffffff; FONT-FAMILY: Tahoma; POSITION: absolute; TEXT-DECORATION: underline}
TABLE {TABLE-LAYOUT: fixed; FONT-SIZE: 100%; WIDTH: 100%}
*{margin:0}
.dspcont { BORDER-RIGHT: #bbbbbb 1px solid; BORDER-TOP: #bbbbbb 1px solid; PADDING-LEFT: 16px; FONT-SIZE: 8pt;MARGIN-BOTTOM: -1px; PADDING-BOTTOM: 5px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; WIDTH: 95%; 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}
.save{behavior:url(#default#savehistory);}
.dspcont1{ display:none}
a.dsphead0 {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 5px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; CURSOR: hand; COLOR: #FFFFFF; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; WIDTH: 95%; BACKGROUND-COLOR: #cc0000}
a.dsphead1 {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 5px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; CURSOR: hand; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; WIDTH: 95%; BACKGROUND-COLOR: #7BA7C7}
a.dsphead2 {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 5px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; CURSOR: hand; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; WIDTH: 95%; BACKGROUND-COLOR: #A5A5A5}
a.dsphead1 span.dspchar{font-family:monospace;font-weight:normal;}
td {VERTICAL-ALIGN: TOP; FONT-FAMILY: Tahoma}
th {VERTICAL-ALIGN: TOP; COLOR: #cc0000; TEXT-ALIGN: left}
BODY {margin-left: 4pt}
BODY {margin-right: 4pt}
BODY {margin-top: 6pt}
</style>
</head>
<body>
<b><font face="Arial" size="5">$($Header)</font></b><hr size="8" color="#cc0000">
<font face="Arial" size="1"><b>Generated on $($ENV:Computername)</b></font><br>
<font face="Arial" size="1">Report created on $(Get-Date)</font>
<div class="filler"></div>
<div class="filler"></div>
<div class="filler"></div>
<div class="save">
"@
Return $Report
}
Function Get-CustomHeader0 ($Title){
$Report = @"
<h1><a class="dsphead0">$($Title)</a></h1>
<div class="filler"></div>
"@
Return $Report
}
Function Get-CustomHeader ($Num, $Title){
$Report = @"
<h2><a class="dsphead$($Num)">
$($Title)</a></h2>
<div class="dspcont">
"@
Return $Report
}
Function Get-CustomHeaderClose{
$Report = @"
</DIV>
<div class="filler"></div>
"@
Return $Report
}
Function Get-CustomHeader0Close{
$Report = @"
</DIV>
"@
Return $Report
}
Function Get-CustomHTMLClose{
$Report = @"
</div>
</body>
</html>
"@
Return $Report
}
Function Get-HTMLTable {
param([array]$Content)
$HTMLTable = $Content | ConvertTo-Html
$HTMLTable = $HTMLTable -replace "<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Strict//EN"" ""http`://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"">", ""
$HTMLTable = $HTMLTable -replace "<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01//EN"" ""http`://www.w3.org/TR/html4/strict.dtd"">", ""
$HTMLTable = $HTMLTable -replace "<html xmlns=""http`://www.w3.org/1999/xhtml"">", ""
$HTMLTable = $HTMLTable -replace '<html>', ""
$HTMLTable = $HTMLTable -replace '<head>', ""
$HTMLTable = $HTMLTable -replace '<title>HTML TABLE</title>', ""
$HTMLTable = $HTMLTable -replace '</head><body>', ""
$HTMLTable = $HTMLTable -replace '</body></html>', ""
Return $HTMLTable
}
Function Get-HTMLDetail ($Heading, $Detail){
$Report = @"
<TABLE>
<tr>
<th width='25%'><b>$Heading</b></font></th>
<td width='75%'>$($Detail)</td>
</tr>
</TABLE>
"@
Return $Report
}
function isWithin([int]$days, [datetime]$Date)
{
[DateTime]::Now.AddDays($days).Date -le $Date.Date
}
#Initialize array for domain controllers in the current domain
$domaincontrollers = @()
#Get current domain
$dom = [System.DirectoryServices.ActiveDirectory.Domain]::getcurrentdomain()
#Get domain controllers in the current domain and add them to the $domain controllers array
$dom.DomainControllers | select Name | ForEach-Object {$domaincontrollers += $_.name}
$MyReport = Get-CustomHTML "Active Directory Group Modifications - Daily Report"
$MyReport += Get-CustomHeader0 ("$domaincontroller")
# ---- General Summary Info ----
$MyReport += Get-CustomHeader "1" "General Details"
$MyReport += Get-HTMLDetail "Domain name:" $dom
$MyReport += Get-HTMLDetail "Number of Domain Controllers:" $domaincontrollers.count
$MyReport += Get-CustomHeaderClose
foreach ($domaincontroller in $domaincontrollers){
# ---- Members added to Domain Local Groups ----
$MyReport += Get-CustomHeader "1" "Members added to Domain Local Groups on domaincontroller $domaincontroller"
$MyReport += Get-HTMLTable (Get-EventLog -LogName 'Security' -ComputerName $domaincontroller | Where-Object {(isWithin -1 $_.TimeWritten) -and $_.EventID -eq "636" -or $_.EventID -eq "4732"} | select TimeGenerated,Message )
$MyReport += Get-CustomHeaderClose
$MyReport += Get-CustomHeader0Close
$MyReport += Get-CustomHTMLClose
# ---- Members removed from Domain Local Groups ----
$MyReport += Get-CustomHeader "1" "Members removed from Domain Local Groups on domaincontroller $domaincontroller"
$MyReport += Get-HTMLTable (Get-EventLog -LogName 'Security' -ComputerName $domaincontroller | Where-Object {(isWithin -1 $_.TimeWritten) -and $_.EventID -eq "637" -or $_.EventID -eq "4733"} | select TimeGenerated,Message )
$MyReport += Get-CustomHeaderClose
$MyReport += Get-CustomHeader0Close
$MyReport += Get-CustomHTMLClose
# ---- Members added to Global Groups ----
$MyReport += Get-CustomHeader "1" "Members added to Global Groups on domaincontroller $domaincontroller"
$MyReport += Get-HTMLTable (Get-EventLog -LogName 'Security' -ComputerName $domaincontroller | Where-Object {(isWithin -1 $_.TimeWritten) -and $_.EventID -eq "632" -or $_.EventID -eq "4728"} | select TimeGenerated,Message )
$MyReport += Get-CustomHeaderClose
$MyReport += Get-CustomHeader0Close
$MyReport += Get-CustomHTMLClose
# ---- Members removed from Global Groups ----
$MyReport += Get-CustomHeader "1" "Members removed from Global Groups on domaincontroller $domaincontroller"
$MyReport += Get-HTMLTable (Get-EventLog -LogName 'Security' -ComputerName $domaincontroller | Where-Object {(isWithin -1 $_.TimeWritten) -and $_.EventID -eq "633" -or $_.EventID -eq "4729"} | select TimeGenerated,Message )
$MyReport += Get-CustomHeaderClose
$MyReport += Get-CustomHeader0Close
$MyReport += Get-CustomHTMLClose
# ---- Members added to Universal Groups ----
$MyReport += Get-CustomHeader "1" "Members added to Universal Groups on domaincontroller $domaincontroller"
$MyReport += Get-HTMLTable (Get-EventLog -LogName 'Security' -ComputerName $domaincontroller | Where-Object {(isWithin -1 $_.TimeWritten) -and $_.EventID -eq "660" -or $_.EventID -eq "4756"} | select TimeGenerated,Message )
$MyReport += Get-CustomHeaderClose
$MyReport += Get-CustomHeader0Close
$MyReport += Get-CustomHTMLClose
# ---- Members removed from Universal Groups ----
$MyReport += Get-CustomHeader "1" "Members removed from Universal Groups on domaincontroller $domaincontroller"
$MyReport += Get-HTMLTable (Get-EventLog -LogName 'Security' -ComputerName $domaincontroller | Where-Object {(isWithin -1 $_.TimeWritten) -and $_.EventID -eq "661" -or $_.EventID -eq "4757"} | select TimeGenerated,Message )
$MyReport += Get-CustomHeaderClose
$MyReport += Get-CustomHeader0Close
$MyReport += Get-CustomHTMLClose
}
$Date = Get-Date
$Filename = "C:\\Temp\\" + "DailyReport" + "_" + $Date.Day + "-" + $Date.Month + "-" + $Date.Year + ".htm"
$MyReport | out-file -encoding ASCII -filepath $Filename
|
PowerShellCorpus/PoshCode/Find-Command.ps1
|
Find-Command.ps1
|
function Find-Command{
param([Parameter($Mandatory=$true)]$question)
Get-Command -Verb ($question.Split() | Where {Get-Verb $_ }) -Noun $question.Split()
}
|
PowerShellCorpus/PoshCode/Import-Delimited 2.3.ps1
|
Import-Delimited 2.3.ps1
|
################################################################################
## Convert-Delimiter - A function to convert between different delimiters.
## E.g.: commas to tabs, tabs to spaces, spaces to commas, etc.
################################################################################
## Written primarily as a way of enabling the use of Import-CSV when
## the source file was a columnar text file with data like services.txt:
## ip service port
## 13.13.13.1 http 8000
## 13.13.13.2 https 8001
## 13.13.13.1 irc 6665-6669
##
## Sample Use:
## Get-Content services.txt | Convert-Delimiter " +" "," | Set-Content services.csv
## would convert the file above into something that could passed to:
## Import-Csv services.csv
##
## Get-Content Delimited.csv | Convert-Delimiter "," "`t" | Set-Content Delimited.tab
## would convert a simple comma-separated-values file to a tab-delimited file
################################################################################
## Version History
## Version 1.0
## First working version
## Version 2.0
## Fixed the quoting so it adds quotes in case they're neeeded
## Version 2.1
## Remove quotes which aren't needed
## Version 2.2
## Trim spaces off the ends, they confuse things
## Version 2.3
## Allow empty columns: as in: there,are,six,"comma, delimited",,columns
Function Convert-Delimiter([regex]$from,[string]$to)
{
begin
{
$z = [char](222)
}
process
{
$_ = $_.Trim()
$_ = $_ -replace "(?:`"((?:(?:[^`"]|`"`"))+)(?:`"$from|`"`$))|(?:$from)|(?:((?:.(?!$from))*.)(?:$from|`$))","$z`$1`$2$z$to"
$_ = $_ -replace "$z(?:$to|$z)?`$","$z"
$_ = $_ -replace "`"`"","`"" -replace "`"","`"`""
$_ = $_ -replace "$z((?:[^$z`"](?!$to))+)$z($to|`$)","`$1`$2"
$_ = $_ -replace "$z","`"" -replace "$z","`""
$_
}
}
################################################################################
## Import-Delimited - A replacement function for Import-Csv that can handle other
## delimiters, and can import text (and collect it together) from the pipeline!!
## Dependends on the Convert-Delimiter function.
################################################################################
## NOTICE that this means you can use this to import multitple CSV files as one:
## Sample Use:
## ls ..\\*.txt | export-csv textfiles.csv
## ls *.doc | export-csv docs.csv
## ls C:\\Windows\\System32\\*.hlp | export-csv helpfiles.csv
##
## $files = ls *.csv | Import-Delimited
## OR
## Import-Delimited " +" services1.txt
## OR
## gc *.txt | Import-Delimited " +"
################################################################################
## Version History
## Version 1.0
## First working version
## Version 2.0
## Filter #TYPE lines
## Remove dependency on Convert-Delimiter if the files are already CSV
## Change to use my Template-Pipeline format (removing the nested Import-String function)
## Version 2.1
## Fix a stupid bug ...
## Add filtering for lines starting with "--", hopefully that's not a problem for other people...
## Added Write-DEBUG output for filtered lines...
Function Import-Delimited([regex]$delimiter=",", [string]$PsPath="")
{
BEGIN {
if ($PsPath.Length -gt 0) {
write-output ($PsPath | &($MyInvocation.InvocationName) $delimiter);
} else {
$script:tmp = [IO.Path]::GetTempFileName()
write-debug "Using tempfile $($script:tmp)"
}
}
PROCESS {
if($_ -and $_.Length -gt 0 ) {
if(Test-Path $_) {
if($delimiter -eq ",") {
Get-Content $_ | Where-Object {if($_.StartsWith("#TYPE") -or $_.StartsWith("--")){ write-debug "SKIPPING: $_"; $false;} else { $true }} | Add-Content $script:tmp
} else {
Get-Content $_ | Convert-Delimiter $delimiter "," | Where-Object { if( $_.StartsWith("--") ) { write-debug "SKIPPING: $_"; $false;} else { $true }} | Add-Content $script:tmp
}
}
else {
if($delimiter -eq ",") {
$_ | Where-Object {-not $_.StartsWith("#TYPE")} | Add-Content $script:tmp
} else {
$_ | Convert-Delimiter $delimiter "," | Add-Content $script:tmp
}
}
}
}
END {
# Need to guard against running this twice when you pass PsPath
if ($PsPath.Length -eq 0) {
Import-Csv $script:tmp
}
}
}
|
PowerShellCorpus/PoshCode/Delete-LocalAccount.ps1
|
Delete-LocalAccount.ps1
|
<#
.SYNOPSIS
A script that removes a local user account
.DESCRIPTION
This script searches ActiveDirectory for computer accounts, for each
computer account it removes the specified user account.
.PARAMETER ADSPath
The ActiveDirectory namespace to search for computers
.PARAMETER UserName
The username to remove from each computer
.EXAMPLE
.\\Delete-LocalAccount.ps1 -ADSPath "LDAP://OU=workstations,DC=company,DC=com" -LocalUser delete `
| Export-Csv .\\sample.csv -NoTypeInformation
Description
-----------
This example shows all parameters and piping the output to export-csv
.NOTES
This script requires the ComputerManagement and ActiveDirectoryManagement libraries
The script registers it's name as an event-source on the source computer and writes
events to the application log.
This script assumes the includes folder is a subfolder of the current directory, if that
is not the case you may receive a FullyQualifiedErrorId : CommandNotFoundException when
attempting to dot-source in the libraries.
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/Production/DeleteLocalAccount
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/ComputerManagemenet
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/ActiveDirectoryManagement
#>
Param
(
[Parameter(Mandatory=$true)]
[string]$ADSPath,
[Parameter(Mandatory=$true)]
[string]$LocalUser
)
Begin
{
$ScriptName = $MyInvocation.MyCommand.ToString()
$LogName = "Application"
$ScriptPath = $MyInvocation.MyCommand.Path
$Username = $env:USERDOMAIN + "\\" + $env:USERNAME
New-EventLog -Source $ScriptName -LogName $LogName -ErrorAction SilentlyContinue
$Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nStarted: " + (Get-Date).toString()
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message
. .\\includes\\ComputerManagement.ps1
. .\\includes\\ActiveDirectoryManagement.ps1
}
Process
{
$Workstations = Get-ADObjects -ADSPath $ADSPath
$Jobs = @()
foreach ($Workstation in $Workstations)
{
[string]$ThisWorkstation = $Workstation.Properties.name
[string]$RetVal = Remove-LocalUser -ComputerName $Workstation.Properties.name -UserName $LocalUser
$ThisJob = New-Object PSobject
Add-Member -InputObject $ThisJob -MemberType NoteProperty -Name "ComputerName" -Value $ThisWorkstation
Add-Member -InputObject $ThisJob -MemberType NoteProperty -Name "UserName" -Value $LocalUser
Add-Member -InputObject $ThisJob -MemberType NoteProperty -Name "Status" -Value $RetVal.Trim()
$Jobs += $ThisJob
$ThisJob
}
$Message = [system.string]::Join("`n",($Jobs))
Write-EventLog -LogName $LogName -Source $ScriptName -EventId "101" -EntryType "Information" -Message $Message
}
End
{
$Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nFinished: " + (Get-Date).toString()
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message
}
|
PowerShellCorpus/PoshCode/Import-NmapXML_1.ps1
|
Import-NmapXML_1.ps1
|
#Requires -Version 2.0
function Import-NmapXML
{
####################################################################################
#.Synopsis
# Parse XML output files of the nmap port scanner (www.nmap.org).
#
#.Description
# Parse XML output files of the nmap port scanner (www.nmap.org) and
# emit custom objects with properties containing the scan data. The
# script can accept either piped or parameter input. The script can be
# safely dot-sourced without error as is.
#
#.Parameter Path
# Either 1) a string with or without wildcards to one or more XML output
# files, or 2) one or more FileInfo objects representing XML output files.
#
#.Parameter OutputDelimiter
# The delimiter for the strings in the OS, Ports and Services properties.
# Default is a newline. Change it when you want single-line output.
#
#.Parameter RunStatsOnly
# Only displays general scan information from each XML output file, such
# as scan start/stop time, elapsed time, command-line arguments, etc.
#
#.Parameter ShowProgress
# Prints progress information to StdErr while processing host entries.
#
#.Example
# dir *.xml | Import-NMAPXML
#
#.Example
# Import-NmapXML -path onefile.xml
# Import-NmapXML -path *files.xml
#
#.Example
# $files = dir *some.xml,others*.xml
# Import-NmapXML -path $files
#
#.Example
# Import-NmapXML -path scanfile.xml -runstatsonly
#
#.Example
# Import-NmapXML scanfile.xml -OutputDelimiter " "
#
#Requires -Version 2.0
#
#.Notes
# Author: Jason Fossen (http://blogs.sans.org/windows-security/)
# Edited: Justin Grote <justin+powershell NOSPAMAT grote NOSPAMDOT name>
# Version: 3.6.1-JWG1
# Updated: 02.Feb.2011
# LEGAL: PUBLIC DOMAIN. SCRIPT PROVIDED "AS IS" WITH NO WARRANTIES OR GUARANTEES OF
# ANY KIND, INCLUDING BUT NOT LIMITED TO MERCHANTABILITY AND/OR FITNESS FOR
# A PARTICULAR PURPOSE. ALL RISKS OF DAMAGE REMAINS WITH THE USER, EVEN IF
# THE AUTHOR, SUPPLIER OR DISTRIBUTOR HAS BEEN ADVISED OF THE POSSIBILITY OF
# ANY SUCH DAMAGE. IF YOUR STATE DOES NOT PERMIT THE COMPLETE LIMITATION OF
# LIABILITY, THEN DELETE THIS FILE SINCE YOU ARE NOW PROHIBITED TO HAVE IT.
####################################################################################
[CmdletBinding()]
param (
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]$Path,
[String] $OutputDelimiter = "`n",
[Switch] $RunStatsOnly,
[Switch] $ShowProgress
)
if ($Path -match "/\\?|/help|-h|-help|--h|--help")
{
"`nPurpose: Process nmap XML output files (www.nmap.org).`n"
"Example: Import-NmapXML scanfile.xml"
"Example: Import-NmapXML *.xml -runstatsonly `n"
exit
}
if ($Path -eq $null) {$Path = @(); $input | foreach { $Path += $_ } }
if (($Path -ne $null) -and ($Path.gettype().name -eq "String")) {$Path = dir $path} #To support wildcards in $path.
$1970 = [DateTime] "01 Jan 1970 01:00:00 GMT"
if ($RunStatsOnly)
{
ForEach ($file in $Path)
{
$xmldoc = new-object System.XML.XMLdocument
$xmldoc.Load($file)
$stat = ($stat = " " | select-object FilePath,FileName,Scanner,Profile,ProfileName,Hint,ScanName,Arguments,Options,NmapVersion,XmlOutputVersion,StartTime,FinishedTime,ElapsedSeconds,ScanTypes,TcpPorts,UdpPorts,IpProtocols,SctpPorts,VerboseLevel,DebuggingLevel,HostsUp,HostsDown,HostsTotal)
$stat.FilePath = $file.fullname
$stat.FileName = $file.name
$stat.Scanner = $xmldoc.nmaprun.scanner
$stat.Profile = $xmldoc.nmaprun.profile
$stat.ProfileName = $xmldoc.nmaprun.profile_name
$stat.Hint = $xmldoc.nmaprun.hint
$stat.ScanName = $xmldoc.nmaprun.scan_name
$stat.Arguments = $xmldoc.nmaprun.args
$stat.Options = $xmldoc.nmaprun.options
$stat.NmapVersion = $xmldoc.nmaprun.version
$stat.XmlOutputVersion = $xmldoc.nmaprun.xmloutputversion
$stat.StartTime = $1970.AddSeconds($xmldoc.nmaprun.start)
$stat.FinishedTime = $1970.AddSeconds($xmldoc.nmaprun.runstats.finished.time)
$stat.ElapsedSeconds = $xmldoc.nmaprun.runstats.finished.elapsed
$xmldoc.nmaprun.scaninfo | foreach {
$stat.ScanTypes += $_.type + " "
$services = $_.services #Seems unnecessary, but solves a problem.
if ($services.contains("-"))
{
#In the original XML, ranges of ports are summarized, e.g., "500-522",
#but the script will list each port separately for easier searching.
$array = $($services.replace("-","..")).Split(",")
$temp = @($array | where { $_ -notlike "*..*" })
$array | where { $_ -like "*..*" } | foreach { invoke-expression "$_" } | foreach { $temp += $_ }
$temp = [Int32[]] $temp | sort
$services = [String]::Join(",",$temp)
}
switch ($_.protocol)
{
"tcp" { $stat.TcpPorts = $services ; break }
"udp" { $stat.UdpPorts = $services ; break }
"ip" { $stat.IpProtocols = $services ; break }
"sctp" { $stat.SctpPorts = $services ; break }
}
}
$stat.ScanTypes = $($stat.ScanTypes).Trim()
$stat.VerboseLevel = $xmldoc.nmaprun.verbose.level
$stat.DebuggingLevel = $xmldoc.nmaprun.debugging.level
$stat.HostsUp = $xmldoc.nmaprun.runstats.hosts.up
$stat.HostsDown = $xmldoc.nmaprun.runstats.hosts.down
$stat.HostsTotal = $xmldoc.nmaprun.runstats.hosts.total
$stat
}
return #Don't process hosts.
}
ForEach ($file in $Path) {
If ($ShowProgress) { [Console]::Error.WriteLine("[" + (get-date).ToLongTimeString() + "] Starting $file" ) }
$xmldoc = new-object System.XML.XMLdocument
$xmldoc.Load($file)
# Process each of the <host> nodes from the nmap report.
$i = 0 #Counter for <host> nodes processed.
$xmldoc.nmaprun.host | foreach-object {
$hostnode = $_ # $hostnode is a <host> node in the XML.
# Init variables, with $entry being the custom object for each <host>.
$service = " " #service needs to be a single space.
$entry = ($entry = " " | select-object FQDN, HostName, Status, IPv4, IPv6, MAC, Ports, Services, OS, Script)
# Extract state element of status:
$entry.Status = $hostnode.status.state.Trim()
if ($entry.Status.length -lt 2) { $entry.Status = "<no-status>" }
# Extract fully-qualified domain name(s), removing any duplicates.
$hostnode.hostnames.hostname | foreach-object { $entry.FQDN += $_.name + " " }
$entry.FQDN = [System.String]::Join(" ",@($entry.FQDN.Trim().Split(" ") | sort-object -unique)) #Avoid -Join and -Split for now
if ($entry.FQDN.Length -eq 0) { $entry.FQDN = "<no-fullname>" }
# Note that this code cheats, it only gets the hostname of the first FQDN if there are multiple FQDNs.
if ($entry.FQDN.Contains(".")) { $entry.HostName = $entry.FQDN.Substring(0,$entry.FQDN.IndexOf(".")) }
elseif ($entry.FQDN -eq "<no-fullname>") { $entry.HostName = "<no-hostname>" }
else { $entry.HostName = $entry.FQDN }
# Process each of the <address> nodes, extracting by type.
$hostnode.address | foreach-object {
if ($_.addrtype -eq "ipv4") { $entry.IPv4 += $_.addr + " "}
if ($_.addrtype -eq "ipv6") { $entry.IPv6 += $_.addr + " "}
if ($_.addrtype -eq "mac") { $entry.MAC += $_.addr + " "}
}
if ($entry.IPv4 -eq $null) { $entry.IPv4 = "<no-ipv4>" } else { $entry.IPv4 = $entry.IPv4.Trim()}
if ($entry.IPv6 -eq $null) { $entry.IPv6 = "<no-ipv6>" } else { $entry.IPv6 = $entry.IPv6.Trim()}
if ($entry.MAC -eq $null) { $entry.MAC = "<no-mac>" } else { $entry.MAC = $entry.MAC.Trim() }
# Process all ports from <ports><port>, and note that <port> does not contain an array if it only has one item in it.
if ($hostnode.ports.port -eq $null) { $entry.Ports = "<no-ports>" ; $entry.Services = "<no-services>" }
else
{
$hostnode.ports.port | foreach-object {
if ($_.service.name -eq $null) { $service = "unknown" } else { $service = $_.service.name }
$entry.Ports += $_.state.state + ":" + $_.protocol + ":" + $_.portid + ":" + $service + $OutputDelimiter
# Build Services property. What a mess...but exclude non-open/non-open|filtered ports and blank service info, and exclude servicefp too for the sake of tidiness.
if ($_.state.state -like "open*" -and ($_.service.tunnel.length -gt 2 -or $_.service.product.length -gt 2 -or $_.service.proto.length -gt 2)) { $entry.Services += $_.protocol + ":" + $_.portid + ":" + $service + ":" + ($_.service.product + " " + $_.service.version + " " + $_.service.tunnel + " " + $_.service.proto + " " + $_.service.rpcnum).Trim() + " <" + ([Int] $_.service.conf * 10) + "%-confidence>$OutputDelimiter" }
}
$entry.Ports = $entry.Ports.Trim()
if ($entry.Services -eq $null) { $entry.Services = "<no-services>" } else { $entry.Services = $entry.Services.Trim() }
}
# Extract fingerprinted OS type and percent of accuracy.
$hostnode.os.osmatch | foreach-object {$entry.OS += $_.name + " <" + ([String] $_.accuracy) + "%-accuracy>$OutputDelimiter"}
$hostnode.os.osclass | foreach-object {$entry.OS += $_.type + " " + $_.vendor + " " + $_.osfamily + " " + $_.osgen + " <" + ([String] $_.accuracy) + "%-accuracy>$OutputDelimiter"}
$entry.OS = $entry.OS.Replace(" "," ")
$entry.OS = $entry.OS.Replace("<%-accuracy>","") #Sometimes no osmatch.
$entry.OS = $entry.OS.Trim()
if ($entry.OS.length -lt 16) { $entry.OS = "<no-os>" }
# Extract script output, first for port scripts, then for host scripts.
$hostnode.ports.port | foreach-object {
if ($_.script -ne $null) {
$entry.Script += "<PortScript id=""" + $_.script.id + """>$OutputDelimiter" + ($_.script.output -replace "`n","$OutputDelimiter") + "$OutputDelimiter</PortScript> $OutputDelimiter $OutputDelimiter"
}
}
if ($hostnode.hostscript -ne $null) {
$hostnode.hostscript.script | foreach-object {
$entry.Script += '<HostScript id="' + $_.id + '">' + $OutputDelimiter + ($_.output.replace("`n","$OutputDelimiter")) + "$OutputDelimiter</HostScript> $OutputDelimiter $OutputDelimiter"
}
}
if ($entry.Script -eq $null) { $entry.Script = "<no-script>" }
# Emit custom object from script.
$i++ #Progress counter...
$entry
}
If ($ShowProgress) { [Console]::Error.WriteLine("[" + (get-date).ToLongTimeString() + "] Finished $file, processed $i entries." ) }
}
}
|
PowerShellCorpus/PoshCode/Get-UcsServerVlan_1.ps1
|
Get-UcsServerVlan_1.ps1
|
function Get-UcsServerVlan {
Get-UcsServiceProfile | Foreach-Object {
$sp = $_
$sp | Get-UcsVnic | Foreach-Object {
$vn = $_
$vn | Get-UcsVnicInterface | Foreach-Object {
$output = New-Object psobject –property @{
Server = $sp.Name
Vnic = $vn.name
Vlan = $_.name
}
Write-Output $output
}
}
}
}
|
PowerShellCorpus/PoshCode/IsoDates.psm1.ps1
|
IsoDates.psm1.ps1
|
#requires -version 1.0
# or version 2.0, obviously
## ISO 8601 Dates
########################################################################
## Copyright (c) Joel Bennett, 2009
## Free for use under GPL, MS-RL, MS-PL, or BSD license. Your choice.
function Get-ISODate {
#.Synopsis
# Get the components of an ISO 8601 date: year, week number, day of week
#.Description
# For any given date you get an array of year, week, day that you can use
# as part of a string format....
#.Parameter Date
# The date you want to analyze. Accepts dates on the pipeline
Param([DateTime]$date=$(Get-Date))
Process {
if($_){$date=$_}
## Get Jan 1st of that year
$startYear = Get-Date -Date $date -Month 1 -Day 1
## Get Dec 31st of that year
$endYear = Get-Date -Date $date -Month 12 -Day 31
## ISO 8601 weeks are Monday-Sunday, with days marked 1-7
## But .Net's DayOfWeek enum is 0 for Sunday through 6 for saturday
$dayOfWeek = @(7,1,2,3,4,5,6)[$date.DayOfWeek]
$lastofWeek = @(7,1,2,3,4,5,6)[$endYear.DayOfWeek]
## By definition: the first week of a year is the one which
## includes the first Thursday, and thus, January 4th
$adjust = @(6,7,8,9,10,4,5)[$startYear.DayOfWeek]
switch([Math]::Floor((($date.Subtract($startYear).Days + $adjust)/7)))
{
0 {
## Return weeknumber of dec 31st of the previous year
## But return THIS dayOfWeek
Write-Output @(
@(Get-ISODate $startYear.AddDays(-1))[0,1] + @(,$dayOfWeek))
}
53 {
## If dec 31st falls before thursday it is week 01 of next year
if ($lastofWeek -lt 4) {
Write-Output @(($date.Year + 1), 1, $dayOfWeek)
} else {
Write-Output @($date.Year, $_, $dayOfWeek)
}
}
default {
Write-Output @($date.Year, $_, $dayOfWeek)
}
}
}
}
function Get-ISOWeekOfYear {
#.Synopsis
# Get the correct (according to ISO 8601) week number
#.Description
# For any given date you get the week of the year, according to ISO8610
#.Parameter Date
# The date you want to analyze. Accepts dates on the pipeline
Param([DateTime]$date=$(Get-Date))
Process {
if($_){$date=$_}
@(Get-ISODate $date)[1]
}
}
function Get-ISOYear {
#.Synopsis
# Get the correct (according to ISO 8601) year number
#.Description
# For any given date you get the year number, according to ISO8610 ...
# for some days at the begining or end of year, it reports the previous
# or the next year (because ISO defines those days as part of the first
# or last week of the adjacent year).
#.Parameter Date
# The date you want to analyze. Accepts dates on the pipeline
Param([DateTime]$date=$(Get-Date))
Process {
if($_){$date=$_}
@(Get-ISODate $date)[0]
}
}
function Get-ISODayOfWeek {
#.Synopsis
# Get the correct (according to ISO 8601) day of the week
#.Description
# For any given date you get the day of the week, according to ISO8610
#.Parameter Date
# The date you want to analyze. Accepts dates on the pipeline
Param([DateTime]$date=$(Get-Date))
Process {
if($_){$date=$_}
@(7,1,2,3,4,5,6)[$date.DayOfWeek]
}
}
function Get-ISODateString {
#.Synopsis
# Get the correctly formatted (according to ISO 8601) date string
#.Description
# For any given date you get the date string, according to ISO8610,
# like: 2009-W12-4 for Thursday, March 19th, 2009
#.Parameter Date
# The date you want to analyze. Accepts dates on the pipeline
Param([DateTime]$date=$(Get-Date))
Process {
if($_){$date=$_}
"{0}-W{1:00}-{2}" -f @(Get-ISODate $date)
}
}
function ConvertFrom-ISODateString {
#.Synopsis
# Parses ISO 8601 Date strings in the format: 2009-W12-4 to DateTime
#.Description
# Allows converting ISO-formated date strings back into actual objects
#.Parameter Date
# An ISO8601 date, like:
# 2009-W12-4 for Thursday, March 19th, 2009
# 1999-W52-6 for Saturday, January 1st, 2000
# 2000-W01-1 for Monday, January 3rd, 2000
Param([string]$date)
Process {
if($_){$date=$_}
if($date -notmatch "\\d{4}-W\\d{2}-\\d") {
Write-Error "The string is not an ISO 8601 formatted date string"
}
$ofs = ""
$year = [int]"$($date[0..3])"
$week = [int]"$($date[6..7])"
$day = [int]"$($date[9])"
$firstOfYear = Get-Date -year $year -day 1 -month 1
$days = 7*$week - ((Get-ISODayOfWeek $firstOfYear) - $day)
$result = $firstOfYear.AddDays( $days )
if(($result.Year -ge $year) -and ((Get-ISODayOfWeek $firstOfYear) -le 4) ) {
return $firstOfYear.AddDays( ($days - 7) )
} else {
return $result
}
}
}
|
PowerShellCorpus/PoshCode/Set-LocalPassword_1.ps1
|
Set-LocalPassword_1.ps1
|
param(
[switch]$Help
, [string] $User
, [string] $Password
, [string[]] $ComputerNames = @()
)
$usage = @'
Get-OUComputerNames
usage : [computerName1,computerName2,... | ] ./Set-LocalPassword.ps1 [-user] <userName> [-password] <password> [[-computers] computerName1,computerName2,...]
returns : Sets local account passwords on one or more computers
author : Nathan Hartley
'@
if ($help) {Write-Host $usage;break}
$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])" }
}
}
ForEach ($computer in $ComputerNames) {
ChangePassword $computer $user $password
}
|
PowerShellCorpus/PoshCode/EnvStacks Module 1.0.ps1
|
EnvStacks Module 1.0.ps1
|
## EnvStacks.psm1 module
## NOTE: If you "download" this, make sure it's a psm1 extension before you Add-Module
## NOTE: this will work as a regular v1.0 script if you dot-source it, but it *will* pollute your variable space a bit
## you'll need to comment out the Export-ModuleMember line at the bottom ...
########################################################################################################################
## EnvStacks gives you the ability to set and change your environment variables in a stack-like way so you can easily
## roll back to the previous value whenever you want -- particularly it includes a couple of very useful functions
## for working with Path variables so that you can add or remove specific items easily.
##
## Push-EnvVariable - set the value of an environment variable while stashing the current value in the stack
## Pop-EnvVariable - recall the previous value of an environment variable from the stack
## Add-EnvPathItem - Add an item to the front or end of a path variable (a semi-colon delimited string)
## Remove-EnvPathItem - Remove items from path variables easily -- including by pattern matching or by index
##
## (c) Joel 'Jaykul' Bennett, 2008 -- Freely licensed under GPL/MPL/New BSD/MIT
########################################################################################################################
## Usage Example:
##
## [213]: add-module EnvStacks
@@## VERBOSE: Loading module from path 'Scripts:\\Modules\\EnvStacks\\EnvStacks.psm1'.
@@## VERBOSE: Importing function 'Pop-EnvVariable'.
@@## VERBOSE: Importing function 'Add-EnvPathItem'.
@@## VERBOSE: Importing function 'Remove-EnvPathItem'.
@@## VERBOSE: Importing function 'Push-EnvVariable'.
## [214]: $Env:SessionName
## Console
## [215]: Push-EnvVariable SessionName Graphical
## [216]: $Env:SessionName
## Graphical
## [217]: Pop-EnvVariable SessionName
## [218]: $Env:SessionName
## Console
## [219]: $ENV:PSPACKAGEPATH
## Scripts:\\Modules;C:\\Users\\JBennett\\Documents\\WindowsPowerShell\\Packages
## [220]: Push-EnvVariable PSPackagePath C:\\Users\\JBennett\\Documents\\WindowsPowerShell\\Packages
## [221]: $ENV:PSPACKAGEPATH
## C:\\Users\\JBennett\\Documents\\WindowsPowerShell\\Packages
## [222]: Pop-EnvVariable PSPackagePath
## [223]: $ENV:PSPACKAGEPATH
## Scripts:\\Modules;Scripts:\\AutoModules;C:\\Users\\JBennett\\Documents\\WindowsPowerShell\\Packages
## [224]: Add-EnvPathItem PSPackagePath "$($PSHOME)Packages"
## [225]: $ENV:PSPACKAGEPATH
## Scripts:\\Modules;Scripts:\\AutoModules;C:\\Users\\JBennett\\Documents\\WindowsPowerShell\\Packages;C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Packages
## [226]: Remove-EnvPathItem PSPackagePath -Pop
## [227]: $ENV:PSPACKAGEPATH
## Scripts:\\Modules;Scripts:\\AutoModules;C:\\Users\\JBennett\\Documents\\WindowsPowerShell\\Packages
## [228]: Add-EnvPathItem PSPackagePath "$($PSHOME)Packages" -First
## [229]: Pop-EnvVariable PSPackagePath
## [230]: $ENV:PSPACKAGEPATH
## Scripts:\\Modules;Scripts:\\AutoModules;C:\\Users\\JBennett\\Documents\\WindowsPowerShell\\Packages
## [231]: Add-EnvPathItem PSPackagePath "$($PSHOME)Packages" -First
## [232]: $ENV:PSPACKAGEPATH
## C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Packages;Scripts:\\Modules;Scripts:\\AutoModules;C:\\Users\\JBennett\\Documents\\WindowsPowerShell\\Packages
## [233]: Remove-EnvPathItem PSPackagePath -First
@@## VERBOSE: Removing First Item C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Packages
## [234]: $ENV:PSPACKAGEPATH
## Scripts:\\Modules;Scripts:\\AutoModules;C:\\Users\\JBennett\\Documents\\WindowsPowerShell\\Packages
## [235]: Pop-EnvVariable PSPackagePath
## [236]: $ENV:PSPACKAGEPATH
## C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Packages;Scripts:\\Modules;Scripts:\\AutoModules;C:\\Users\\JBennett\\Documents\\WindowsPowerShell\\Packages
## [237]: Pop-EnvVariable PSPackagePath
## [238]: $ENV:PSPACKAGEPATH
## Scripts:\\Modules;Scripts:\\AutoModules;C:\\Users\\JBennett\\Documents\\WindowsPowerShell\\Packages
## [239]: Pop-EnvVariable PSPackagePath
@@## Can't pop 'PSPackagePath', there's nothing in the stack
@@## At Scripts:\\AutoModules\\EnvStacks\\EnvStacks.psm1:28 char:12
## [240]: Remove-EnvPathItem Path *PowerShell* -Return
@@## VERBOSE: Removing Items like '*PowerShell*'...
## C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\
## C:\\Program Files\\PowerShell Community Extensions
## C:\\Program Files\\PowerShell Community Extensions\\Scripts
## C:\\Users\\JBennett\\Documents\\WindowsPowerShell
## C:\\Users\\JBennett\\Documents\\WindowsPowerShell\\Scripts
## C:\\Users\\JBennett\\Documents\\WindowsPowerShell\\Scripts\\Demo
########################################################################################################################
## This is slightly silly stuff, but we have to use the full name for the stack because it's in a different assembly
## PowerShell support for generics is *HORRIBLE*
$dictionaryType = [System.Collections.Generic.Dictionary``2].AssemblyQualifiedName
$stackType = [System.Collections.Generic.Stack``1].AssemblyQualifiedName
$stringType = [System.String].AssemblyQualifiedName
$stringStackType = "$stackType" -replace "``1", "``1[[$stringType]]"
# Note that this is a dictionary of string to stringstacktype ...
$stringStringStackDictionaryType = "$dictionaryType" -replace "``2", "``2[[$stringType],[$stringStackType]]"
$EnvStackStacks = new-object $stringStringStackDictionaryType
function Split-EnvPathVariable {
PARAM([string]$Variable= $(Throw "Parameter '-Variable' (position 1) is required"), $char=";")
$paths = @()
if (test-path "Env:\\$Variable") {
$paths = (get-content "Env:\\$Variable").Split($char) | Select -Unique
}
return $paths
}
function Pop-EnvVariable {
PARAM([string]$Variable= $(Throw "Parameter '-Variable' (position 1) is required"))
if($EnvStackStacks.ContainsKey($Variable.ToLower()) -and ($EnvStackStacks[$Variable.ToLower()].Count -gt 0)) {
Set-Content "Env:\\$Variable" $EnvStackStacks[$Variable.ToLower()].Pop()
} else {
throw "Can't pop '$Variable', there's nothing in the stack"
}
}
function Add-EnvPathItem {
param([string]$Variable = $(throw "Parameter '-Variable' (position 1) is required"),
$Value = $(throw "Parameter '-Value' (position 2) is required"),
[Switch]$First, [Switch]$NoStack, [Switch]$ReturnOld
)
if(!$NoStack) {
if(!$EnvStackStacks.ContainsKey($Variable.ToLower())) {
$EnvStackStacks.Add( $Variable.ToLower(), (new-object $stringStackType))
}
$EnvStackStacks[$Variable.ToLower()].Push( (get-content "Env:\\$Variable") )
}
if($ReturnOld) {
Get-Content "Env:\\$Variable"
}
$paths = Split-EnvPathVariable $Variable
if($First) {
$newvar = @([string[]]$Value + $paths) | Select-Object -Unique | Where-Object {$_}
} else {
$newvar = @($paths + $Value) | Select-Object -Unique | Where-Object {$_}
}
$ofs = ';'
Set-Content "Env:\\$Variable" "$newvar"
}
function Remove-EnvPathItem {
param([string]$Variable = $(throw "Parameter '-Variable' (position 1) is required"),
$Value, [int[]]$Index, [Switch]$First, [Switch]$Last, [Switch]$Pop, [Switch]$NoStack, [Switch]$ReturnRemoved
)
## You need to pick just one of these, so if you passed two ...
if( ($Value -and ($First -or $Last -or $Pop -or $Index)) -or
($First -and ($Last -or $Pop -or $Index)) -or
($Last -and ($Pop -or $Index)) -or
($Pop -and $Index)) {
throw "Can't resolve parameter set: you must specify only one of: -Value or -Index or -First or -Last or -Pop"
}
if($Pop) {
Pop-EnvVariable $Variable
} elseif(!$NoStack) {
if(!$EnvStackStacks.ContainsKey($Variable.ToLower())) {
$EnvStackStacks.Add( $Variable.ToLower(), (new-object $stringStackType))
}
$EnvStackStacks[$Variable.ToLower()].Push( (get-content "Env:\\$Variable") )
}
$paths = Split-EnvPathVariable $Variable
if( $Value ) {
$ofs = ';'
if($ReturnRemoved) {
write-verbose "Removing Items like '$Value'... "
foreach($item in @($Value)) {
write-output ($paths -like $item)
}
} else {
write-verbose "Removing Items like '$Value'... "
foreach($item in @($Value)) {
write-verbose ("Removing {0}" -f ($paths -like $item))
}
}
foreach($item in @($Value)) {
$paths = $paths -notlike $item
}
} elseif($Index) {
if($ReturnRemoved) {
write-verbose "Removing Items by Index, $Index"
write-output $paths[$Index]
} else {
write-verbose "Removing Items by Index, $Index: $($paths[$index])"
}
foreach($i in $index) { $paths[$i] = "" }
$paths = $paths -ne ""
} elseif($First) {
if($ReturnRemoved) {
write-verbose "Removing Last Item"
write-output $paths[0]
} else {
write-verbose "Removing First Item $($paths[0])"
}
$paths = $paths[1..($paths.Length-1)]
} elseif($Last) {
if($ReturnRemoved) {
write-verbose "Removing Last Item"
write-output $paths[-1]
} else {
write-verbose "Removing Last Item $($paths[-1])"
}
$paths = $paths[0..($paths.Length-2)]
}
$ofs = ';'
Set-Content "Env:\\$Variable" "$paths"
}
function Push-EnvVariable {
param([string]$Variable = $(throw "Parameter '-Variable' (position 1) is required"),
$Value = $(throw "Parameter '-Value' (position 2) is required"),
[Switch]$ReturnOld
)
if(!$EnvStackStacks.ContainsKey($Variable.ToLower())) {
$EnvStackStacks.Add( $Variable.ToLower(), (new-object $stringStackType))
}
$EnvStackStacks[$Variable.ToLower()].Push( (get-content "Env:\\$Variable") )
if($ReturnOld) {
Get-Content "Env:\\$Variable"
}
$ofs = ';'
Set-Content "Env:\\$Variable" "$Value"
}
function Clear-EnvStack {
param([string]$Variable = $(throw "Parameter '-Variable' (position 1) is required"))
if($EnvStackStacks.ContainsKey($Variable.ToLower())) {
Write-Verbose ("{0} Items Removed" -f $EnvStackStacks[$Variable.ToLower()].Count)
$EnvStackStacks[$Variable.ToLower()].Clear()
}
}
Export-ModuleMember Push-EnvVariable, Pop-EnvVariable, Add-EnvPathItem, Remove-EnvPathItem
Set-Alias pushp Add-PathItem -Option AllScope -scope Global -Description "Module Function alias from EnvStacks"
Set-Alias popp Remove-PathItem -Option AllScope -scope Global -Description "Module Function alias from EnvStacks"
Set-Alias pushe Push-EnvVariable -Option AllScope -scope Global -Description "Module Function alias from EnvStacks"
Set-Alias pope Pop-EnvVariable -Option AllScope -scope Global -Description "Module Function alias from EnvStacks"
|
PowerShellCorpus/PoshCode/Set-Computername_6.ps1
|
Set-Computername_6.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/Get-FileEncoding.ps1
|
Get-FileEncoding.ps1
|
<#
.SYNOPSIS
Gets file encoding.
.DESCRIPTION
The Get-FileEncoding function determines encoding by looking at Byte Order Mark (BOM).
Based on port of C# code from http://www.west-wind.com/Weblog/posts/197245.aspx
.EXAMPLE
Get-ChildItem *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {$_.Encoding -ne 'ASCII'}
This command gets ps1 files in current directory where encoding is not ASCII
.EXAMPLE
Get-ChildItem *.ps1 | select FullName, @{n='Encoding';e={Get-FileEncoding $_.FullName}} | where {$_.Encoding -ne 'ASCII'} | foreach {(get-content $_.FullName) | set-content $_.FullName -Encoding ASCII}
Same as previous example but fixes encoding using set-content
#>
function Get-FileEncoding
{
[CmdletBinding()] Param (
[Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] [string]$Path
)
[byte[]]$byte = get-content -Encoding byte -ReadCount 4 -TotalCount 4 -Path $Path
if ( $byte[0] -eq 0xef -and $byte[1] -eq 0xbb -and $byte[2] -eq 0xbf )
{ Write-Output 'UTF8' }
elseif ($byte[0] -eq 0xfe -and $byte[1] -eq 0xff)
{ Write-Output 'Unicode' }
elseif ($byte[0] -eq 0 -and $byte[1] -eq 0 -and $byte[2] -eq 0xfe -and $byte[3] -eq 0xff)
{ Write-Output 'UTF32' }
elseif ($byte[0] -eq 0x2b -and $byte[1] -eq 0x2f -and $byte[2] -eq 0x76)
{ Write-Output 'UTF7'}
else
{ Write-Output 'ASCII' }
}
|
PowerShellCorpus/PoshCode/SharePoint build script_2.ps1
|
SharePoint build script_2.ps1
|
@@#BASEPATH variable should be explicitly set in every
@@#build script. It represents the "root"
@@#of the project folder, underneath which all tools, source, config settings,
@@#and deployment folder lie.
@@$global:basepath = (resolve-path ..).path
@@function Set-BasePath([string]$path)
@@{
@@ $global:basepath = $path
@@}
function Get-FullPath($localPath)
{
return join-path -path $global:basepath -childPath $localPath
}
function Clean-DeploymentFolder
{
Clean-Path -dir (Get-FullPath 'deployment')
}
function Compile-Project
{
Run-MSBuild -msBuildArgs @(
((Get-FirstSolutionFileUnderneathSrc).Fullname),
"/target:Clean",
"/target:Build",
"/p:Configuration=Release")
}
function Create-DeploymentBatchFilesWithFeatureActivation($siteUrls)
{
#Convention: project name == project folder name == Feature name == Solution name
$projectName = (Get-FirstDirectoryUnderneathSrc).name
$siteUrls.Keys | foreach {
Create-DeploymentBatchFile -url $siteUrls[$_] -filename (Get-FullPath "deployment\\deploy-$($_).bat") -featureName $projectName -solutionName "$($projectName).wsp"
Create-UpgradeBatchFile -url $siteUrls[$_] -filename (Get-FullPath "deployment\\upgrade-$($_).bat") -featureName $projectName -solutionName "$($projectName).wsp"
Create-RetractionBatchFile -url $siteUrls[$_] -filename (Get-FullPath "deployment\\z-retract-$($_).bat") -featureName $projectName -solutionName "$($projectName).wsp"
}
}
function Get-FirstDirectoryUnderneathSrc
{
dir (Get-FullPath "src") | where { $_.PSIsContainer -eq $true } | select -first 1
}
function Get-FirstSolutionFileUnderneathSrc
{
dir (Get-FullPath "src\\*") -include "*.sln" -recurse | select -first 1
}
function Run-DosCommand($program, [string[]]$programArgs)
{
write-host "Running command: $program";
write-host " Args:"
0..($programArgs.Count-1) | foreach { Write-Host " $($_+1): $($programArgs[$_])" }
& $program $programArgs
}
$wspbuilder = Get-FullPath "tools\\WSPBuilder.exe"
function Run-WspBuilder()
{
$rootDirectory = (Get-FirstDirectoryUnderneathSrc).fullname
pushd
cd $rootDirectory
Run-DosCommand -program $WSPBuilder -programArgs @("-BuildWSP",
"true",
"-OutputPath",
(Get-FullPath "deployment"),
"-ExcludePaths",
([string]::Join(";", @(
(Join-Path -path $rootDirectory -childPath "bin\\Debug"),
(Join-Path -path $rootDirectory -childPath "bin\\deploy")
))))
popd
}
$msbuild = "C:\\Windows\\Microsoft.NET\\Framework\\v3.5\\msbuild.exe"
function Run-MSBuild([string[]]$msBuildArgs)
{
Run-DosCommand $msbuild $msBuildArgs
}
function Clean-Path($dir)
{
#I don't like the SilentlyContinue option, but we need to ignore the case
#where there is no directory to delete (in this situation, an error is thrown)
del $dir -recurse -force -erroraction SilentlyContinue
mkdir $dir -erroraction SilentlyContinue | out-null
}
function Create-DeploymentBatchFile($filename, $featureName, $solutionName, $url, [switch]$allcontenturls)
{
$contents = @"
%STSADM% -o deactivatefeature -name $featureName -url $url
%STSADM% -o retractsolution $(if ($allcontenturls) { "-allcontenturls" }) -immediate -name $solutionName
%STSADM% -o execadmsvcjobs
%STSADM% -o deletesolution -name $solutionName -override
%STSADM% -o addsolution -filename $solutionName
%STSADM% -o deploysolution $(if ($allcontenturls) { "-allcontenturls" }) -immediate -allowgacdeployment -name $solutionName
%STSADM% -o execadmsvcjobs
REM second call to execadmsvcjobs allows for a little more delay. Shouldn't be necessary, but is.
%STSADM% -o execadmsvcjobs
%STSADM% -o activatefeature -url $url -name $featureName
"@
Create-StsadmBatchFile -filename $filename -contents $contents
}
function Create-UpgradeBatchFile($filename, $featureName, $solutionName, $url)
{
$contents = @"
%STSADM% -o deactivatefeature -name $featureName -url $url
%STSADM% -o upgradesolution -immediate -allowgacdeployment -name $solutionName -filename $solutionName
%STSADM% -o execadmsvcjobs
REM second call to execadmsvcjobs allows for a little more delay. Shouldn't be necessary, but is.
%STSADM% -o execadmsvcjobs
%STSADM% -o activatefeature -url $url -name $featureName
"@
Create-StsadmBatchFile -filename $filename -contents $contents
}
function Create-RetractionBatchFile($filename, $featureName, $solutionName, $url, [switch]$allcontenturls)
{
$contents = @"
echo RETRACTING solution--press any key to continue, or CTRL+C to cancel
pause
%STSADM% -o deactivatefeature -name $featureName -url $url
%STSADM% -o retractsolution $(if ($allcontenturls) { "-allcontenturls" }) -immediate -name $solutionName
%STSADM% -o execadmsvcjobs
%STSADM% -o deletesolution -name $solutionName -override
%STSADM% -o execadmsvcjobs
"@
Create-StsadmBatchFile -filename $filename -contents $contents
}
function Create-StsadmBatchFile($filename, $contents)
{
$header= @"
SET STSADM="%PROGRAMFILES%\\Common Files\\Microsoft Shared\\web server extensions\\12\\BIN\\stsadm.exe"
"@
$footer = @"
echo off
ECHO -------------------------------------------------------------
%STSADM% -o displaysolution -name $solutionName
pause
"@
$wholeFileContents = $header + "`n" + $contents + "`n" + $footer
Out-File -inputObject $wholeFileContents -filePath $filename -encoding ASCII
}
######################
#
# Deployment functions - not used at this time, can be REALLY useful
# if we ever switch to PowerShell-based deployments.
#
######################
[reflection.assembly]::LoadWithPartialName("Microsoft.SharePoint") | out-null
[reflection.assembly]::LoadWithPartialName("Microsoft.Office.Server") | out-null
#Do-Deployment - regardless of current status, will install the Solution
function Do-Deployment($featureName, $solutionName, $rootDirectory)
{
echo $featureName, $solutionName, $rootDirectory
if (-not (Is-Installed $solutionName)) {
Install-Solution -solutionName $solutionName -filename (join-path $rootDirectory $solutionName)
}
if (-not (Is-Deployed $solutionName)) {
Deploy-Solution -solutionName $solutionName
} else {
Upgrade-Solution -solutionName $solutionName -featureName $featureName -filename (join-path $rootDirectory $solutionName)
}
#post-step: somehow
#a) ON EACH SERVER run execadmsvcjobs - sub-note:
# - verify all timer services are healthy (?)
# - verify all IIS instances are healthy (?)
#b) wait until we are 100% sure that step a) is finished
#c) look at deployment status, and post-deployment,
# - ON EACH SERVER, run Fix-LocalDeployments
#
#Until that day, manually run Fix-LocalDeployments
}
function Fix-LocalDeployments
{
[Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions | `
where { (Identify-FailedDeployments $_) -contains $env:computername } | `
foreach { write-host "$($_.Name)"; DeployLocal-Solution -solutionName $_.Name -force }
}
$stsadm = [microsoft.sharepoint.utilities.sputility]::GetGenericSetupPath("bin\\stsadm.exe")
function Exec-AdmSvcJobs
{
& $stsadm -o execadmsvcjobs
#sleep for a few more seconds to account for concurrency bugs/timing issues
sleep -seconds 2
}
function Install-Solution($solutionName, $filename)
{
#Assumes solution is NOT already installed. For "unsure installation", use Do-Deployment
[Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions.psbase.Add($filename) | out-null
}
#Assumes solution is already installed. For "unsure installation", use Do-Deployment
function Deploy-Solution($solutionName, [switch]$force)
{
$dateToGuaranteeInstantAction = [datetime]::Now.AddDays(-2)
$solution = [Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions[$solutionName]
if ($solution.ContainsWebApplicationResource) {
$webApplicationsCollection = Get-WebApplicationCollection
[Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions[$solutionName].Deploy($dateToGuaranteeInstantAction, $true, $webApplicationsCollection, $force)
} else {
[Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions[$solutionName].Deploy($dateToGuaranteeInstantAction, $true, $force)
}
}
#Assumes solution is already installed. For "unsure installation", use Do-Deployment
function DeployLocal-Solution($solutionName, [switch]$force)
{
$solution = [Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions[$solutionName]
if ($solution.ContainsWebApplicationResource) {
$webApplicationsCollection = Get-WebApplicationCollection
[Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions[$solutionName].DeployLocal($true, $webApplicationsCollection, $force)
} else {
[Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions[$solutionName].DeployLocal($true, $force)
}
}
function Upgrade-Solution($featureName, $solutionName, $filename)
{
[Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions[$solutionName].Upgrade($filename)
}
function Retract-Solution($solutionName)
{
#Assumes solution is already installed. For "unsure installation", use Do-Deployment
$dateToGuaranteeInstantAction = [datetime]::Now.AddDays(-2)
$solution = [Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions[$solutionName]
if ($solution.ContainsWebApplicationResource) {
#method signature requires typed Collection<SPWebApplication>, so we're unrolling into it
$webApplicationsCollection = Get-WebApplicationCollection
[Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions[$solutionName].Retract($dateToGuaranteeInstantAction, $webApplicationsCollection)
} else {
[Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions[$solutionName].Retract($dateToGuaranteeInstantAction)
}
}
#method signature requires typed Collection<SPWebApplication>, so we're unrolling into it
function Get-WebApplicationCollection
{
$coll = new-GenericObject -type "System.Collections.ObjectModel.Collection" -typeParameters ([Microsoft.SharePoint.Administration.SPWebApplication])
[Microsoft.SharePoint.Administration.SPWebService]::ContentService.WebApplications | foreach { $coll.psbase.Add($_) }
#explanation of oddball return syntax lies here:
#http://stackoverflow.com/questions/695474
return @(,$coll)
}
function Is-Installed($solutionName)
{
#is Solution in the Solution store at all?
return [Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions[$solutionName] -ne $null
}
function Is-Deployed($solutionName)
{
#Is Solution successfully deployed everywhere? Partial/failed deployments don't count as deployed
$solution = [Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions[$solutionName]
if ($solution -eq $null) { return false; }
return $solution.Deployed
}
function Identify-FailedDeployments([Microsoft.SharePoint.Administration.SPSolution]$solution)
{
#NOTE TO SELF: rewrite without regex, the : in the URLs are terrible and are breaking the regexes
if ($solution.ContainsWebApplicationResource) {
#SERVERNAME : http://VIRTUAL-SERVER-URL:PORT/ : The solution was successfully deployed.
$operationDetailsIndex = 2
} else {
#SERVERNAME : The solution was successfully deployed.
$operationDetailsIndex = 1
}
$solution.LastOperationDetails.Split("`n") | `
select `
@{N="Server"; E={([regex]::Split($_, " : "))[0]}}, `
@{N="Details"; E={ ([regex]::Split($_, " : "))[$operationDetailsIndex] }} | `
where { -not ($_.details -like "*successfully deployed*") } | `
foreach { $_.Server }
}
#acquired the following two functions from: http://solutionizing.net/2009/01/01/powershell-get-type-simplified-generics/
function New-GenericObject(
$type = $(throw "Please specify a type"),
[object[]] $typeParameters = $null,
[object[]] $constructorParameters = @()
)
{
$closedType = (Get-Type $type $typeParameters)
,[Activator]::CreateInstance($closedType, $constructorParameters)
}
function Get-Type (
$type = $(throw "Please specify a type")
)
{
trap [System.Management.Automation.RuntimeException] { throw ($_.Exception.Message) }
if($args -and $args.Count -gt 0)
{
$types = $args[0] -as [type[]]
if(-not $types) { $types = [type[]] $args }
if($genericType = [type] ($type + '`' + $types.Count))
{
$genericType.MakeGenericType($types)
}
}
else
{
[type] $type
}
}
@@#
@@#USAGE
@@#. ./helper-functions.ps1
@@#
@@# Set-BasePath -path ((resolve-path ..).path)
@@# Clean-DeploymentFolder
@@# Compile-Project
@@# Run-WspBuilder
@@# Create-DeploymentBatchFilesWithSolutionOnly
@@#
@@#
@@#
@@#
@@#
|
PowerShellCorpus/PoshCode/Get-ExpiredCert.ps1
|
Get-ExpiredCert.ps1
|
Function Get-ExpiredCert {
<#
.SYNOPSIS
Reports the number of expired certificates published to a user account
in Active Directory.
.DESCRIPTION
This will give you a total count of expired certs for each user account.
.PARAMETER InputObject
Specifies the user object. This would be one or more DirectoryServices.DirectoryEntry object,
DirectoryServices.SearchResult object, or ArsUserObject object.
.EXAMPLE
Get-ExpiredCert -InputObject (Get-QADUser testuser1)
.EXAMPLE
Get-QADUser | Get-ExpiredCert
.EXAMPLE
$searcher = New-Object System.DirectoryServices.DirectorySearcher
$searcher.Filter = "(&(objectCategory=person)(objectClass=user))"
$users = $searcher.FindAll()
$users | Get-ExpiredCert
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[Object]$InputObject
)
Process
{
foreach ($object in $InputObject) {
$user = [adsi]$object.path
$s = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cExpired = 0
foreach ($i in ($user.properties["usercertificate"])) {
$s.import([byte[]]($i))
If (($s.verify()) -eq $false) {
$cExpired ++
}
}
New-Object PSObject -Property @{
Name=$user.name[0];
CertsExpired=$cExpired;}
}
}
}
|
PowerShellCorpus/PoshCode/Show-ADGroupMembership.ps1
|
Show-ADGroupMembership.ps1
|
# Author: Steven Murawski http://www.mindofroot.com
# This script requires the Show-NetMap script from Doug Finke and the NetMap files
# These can be found at http://dougfinke.com/blog/?p=465
#
# Also required are the Quest AD Cmdlets.
#requires -pssnapin Quest.ActiveRoles.ADManagement
param([string]$SearchRoot= 'yourdomain.local/usersOU')
Function New-SourceTarget ($s,$t) {
New-Object PSObject |
Add-Member -pass noteproperty source $s |
Add-Member -pass noteproperty target $t
}
$groups = Get-QADGroup -GroupType Security -SearchRoot $SearchRoot
[string[]]$GroupNames = $groups | foreach {$_.name}
$sources = @()
foreach ($group in $groups)
{
$name = $group.name
foreach ($member in $group.members)
{
$SubGroupName = $member -replace '^CN=(.+?),OU=.*', '$1'
if ($GroupNames -contains $SubGroupName)
{
$sources += New-SourceTarget $SubGroupName $name
}
}
}
. c:\\scripts\\powershell\\Show-NetMap
$sources | Show-NetMap
|
PowerShellCorpus/PoshCode/Server Inventory.ps1
|
Server Inventory.ps1
|
#This script requires:
#Windows Powershell 1.0 = http://www.microsoft.com/windowsserver2003/technologies/management/powershell/download.mspx
#PowerGui = http://www.powergui.org/downloads.jspa
#Quest ActiveRoles Management Shell for Active Directory = http://www.quest.com/powershell/activeroles-server.aspx
#VMware Infrastructure Toolkit (for Windows) = http://www.vmware.com/sdk/vitk_win/index.html
#Uncomment the next line to creat a server list
#Change "OU=Servers,DC=company,DC=net" to match your OU structure
#Change .\\sp2list.csv to match the path and file name of your output
#Get-QADComputer -SearchRoot "OU=Servers,DC=company,DC=net" | Sort Name | Select Name | Export-Csv .\\sp2list.csv -NoTypeInformation
$ListFile = Read-Host "Please Enter full path to Server list"
$FileLocation = Read-Host "Please Enter Complete Path and file name to save the output. Must end in .csv or .txt"
#Comment out the next two lines if you do not use VMware
$VCServer = Read-Host "Please Enter Name/IP of Virtual Center Server"
Connect-VIServer $VCServer
$stats = @()
Get-Content $ListFile | % {
$OS = get-wmiobject Win32_OperatingSystem -computername $_
$drive = get-wmiobject win32_logicaldisk -ComputerName $_
$Computer = Get-QADComputer -Name $_
$IP = Get-WmiObject -Class Win32_PingStatus -filter "address='$_'"
#Comment out the next line if you do not use VMware
$VMSession = Get-VM $_*
$row= "" | Select "Date of Report","Server Name","IP Address","Operating System","Service Pack","Description","OU","ESX Host","RAM (GB)","Drive 1","Drive 1 Description","Drive 1 Free Space","Drive 1 Total Size","Drive 2","Drive 2 Description","Drive 2 Free Space","Drive 2 Total Size","Drive 3","Drive 3 Description","Drive 3 Free Space","Drive 3 Total Size","Drive 4","Drive 4 Description","Drive 4 Free Space","Drive 4 Total Size","Drive 5","Drive 5 Description","Drive 5 Free Space","Drive 5 Total Size","Drive 6","Drive 6 Description","Drive 6 Free Space","Drive 6 Total Size","Drive 7","Drive 7 Description","Drive 7 Free Space","Drive 7 Total Size","Drive 8","Drive 8 Description","Drive 8 Free Space","Drive 8 Total Size"
$row."Date of Report" = Get-date
$row."Server Name" = $_
$row."IP Address" = $IP.ProtocolAddress
$row."Operating System" = $OS.Caption
$row."Service Pack" = $OS.CSDVersion
$row."Description" = $Computer.Description
$row."OU" = $Computer.DN
#Comment out the next line if you do not use VMware
$row."ESX Host" = $VMSession.Host.Name
$row."RAM (GB)" = [math]::Round($VMSession.MemoryMB/1024,3)
$row."Drive 1" = $drive[0].Caption
$row."Drive 1 Description" = $drive[0].Description
$row."Drive 1 Free Space" = [math]::Round($drive[0].Freespace/1024/1024/1024,2)
$row."Drive 1 Total Size" = [math]::Round($drive[0].Size/1024/1024/1024,2)
$row."Drive 2" = $drive[1].Caption
$row."Drive 2 Description" = $drive[1].Description
$row."Drive 2 Free Space" = [math]::Round($drive[1].Freespace/1024/1024/1024,2)
$row."Drive 2 Total Size" = [math]::Round($drive[1].Size/1024/1024/1024,2)
$row."Drive 3" = $drive[2].Caption
$row."Drive 3 Description" = $drive[2].Description
$row."Drive 3 Free Space" = [math]::Round($drive[2].Freespace/1024/1024/1024,2)
$row."Drive 3 Total Size" = [math]::Round($drive[2].Size/1024/1024/1024,2)
$row."Drive 4" = $drive[3].Caption
$row."Drive 4 Description" = $drive[3].Description
$row."Drive 4 Free Space" = [math]::Round($drive[3].Freespace/1024/1024/1024,2)
$row."Drive 4 Total Size" = [math]::Round($drive[3].Size/1024/1024/1024,2)
$row."Drive 5" = $drive[4].Caption
$row."Drive 5 Description" = $drive[4].Description
$row."Drive 5 Free Space" = [math]::Round($drive[4].Freespace/1024/1024/1024,2)
$row."Drive 5 Total Size" = [math]::Round($drive[4].Size/1024/1024/1024,2)
$row."Drive 6" = $drive[5].Caption
$row."Drive 6 Description" = $drive[5].Description
$row."Drive 6 Free Space" = [math]::Round($drive[5].Freespace/1024/1024/1024,2)
$row."Drive 6 Total Size" = [math]::Round($drive[5].Size/1024/1024/1024,2)
$row."Drive 7" = $drive[6].Caption
$row."Drive 7 Description" = $drive[6].Description
$row."Drive 7 Free Space" = [math]::Round($drive[6].Freespace/1024/1024/1024,2)
$row."Drive 7 Total Size" = [math]::Round($drive[6].Size/1024/1024/1024,2)
$row."Drive 8" = $drive[7].Caption
$row."Drive 8 Description" = $drive[7].Description
$row."Drive 8 Free Space" = [math]::Round($drive[7].Freespace/1024/1024/1024,2)
$row."Drive 8 Total Size" = [math]::Round($drive[7].Size/1024/1024/1024,2)
$stats += $row
}
$stats | Export-Csv $FileLocation -NoTypeInformation
|
PowerShellCorpus/PoshCode/Logger.psm1 0.6.ps1
|
Logger.psm1 0.6.ps1
|
<#
Name : Universal NLog Logging Module (NLog.psm1)
Version : 0.6 2010-05-17
Author : Joel Bennett (MVP)
Site : http://www.HuddledMasses.org/
Version History:
0.6 - Removed a few references to Log4Net that had been left behind (oops).
0.5 - Port to NLog from Log4Net ( http://nlog-project.org )
Include support for Growl plugin for NLog, but left out the rotating log files stuff (I'll get to that later).
http://ryanfarley.com/blog/archive/2010/05/06/announcing-the-growl-for-windows-target-for-nlog.aspx
0.4 - Bugfix, Viewer and Documentation release.
Fixed a few typo-bugs
Added documentation (man page) comments for Get-Logger.
Changed a few parameter names (sorry) to make the default parameters more unique (so you have to type less on the command-line)
Changed the default logger to use the logger module's folder as a backup
(Some people might not have the Profile path -- this module could be installed anywhere and loaded by file name)
Fixed up the xml output with a nice stylesheet http`://poshcode.org/1750 that formats and makes the page refresh.
0.3 - Cleanupable release.
Added Udp, Email, Xml and RollingXml, as well as a "Chainsaw":http`://logging.apache.org/log4j/docs/chainsaw.html logger based on "Szymon Kobalczyk's configuration":http`://geekswithblogs.net/kobush/archive/2005/07/15/46627.aspx.
Note: there is a "KNOWN BUG with Log4Net UDP":http`://odalet.wordpress.com/2007/01/13/log4net-ip-parsing-bug-when-used-with-framework-net-20/ which can be patched, but hasn't been released.
Added a Close-Logger method to clean up the Xml logger
NOTE: the Rolling XML Logger produces invalid XML, and the XML logger only produces valid xml after it's been closed...
I did contribute an "XSLT stylesheet for Log4Net":http`://poshcode.org/1746 which you could use as well
0.2 - Configless release.
Now configures with inline XML, and supports switches to create "reasonable" default loggers
Changed all the functions to Write-*Log so they don't overwrite the cmdlets
Added -Logger parameter to take the name of the logger to use (it must be created beforehand via Get-Logger)
Created aliases for Write-* to override the cmdlets -- these are easy for users to remove without breaking the module
** NEED to write some docs, but basically, this is stupid simple to use, just:
Import-Module Logger
Write-Verbose "This message will be saved in your profile folder in a file named PowerShellLogger.log (by default)"
To change the defaults for your system, edit the last line in the module!!
0.1 - Initial release. http`://poshcode.org/1744 (Required config: http`://poshcode.org/1743)
Uses NLog 2.0 : http://nlog-project.org
Documentation : http://nlog-project.org/documentation.html
NOTES:
By default, this overwrites the Write-* cmdlets for Error, Warning, Debug, Verbose, and even Host.
This means that you may end up logging a lot of stuff you didn't intend to log (ie: verbose output from other scripts)
To avoid this behavior, remove the aliases after importing it
Import-Module Logger; Remove-Item Alias:Write-*
Write-Warning "This is your warning"
Write-Debug "You should know that..."
Write-Verbose "Everything would be logged, otherwise"
***** NOTE: IT ONLY OVERRIDES THE DEFAULTS FOR SCRIPTS *****
It currently has no effect on error/verbose/warning that is logged from cmdlets.
#>
Add-Type -Path $PSScriptRoot\\NLog.dll
function Get-RelativePath {
<#
.SYNOPSIS
Get a path to a file (or folder) relative to another folder
.DESCRIPTION
Converts the FilePath to a relative path rooted in the specified Folder
.PARAMETER Folder
The folder to build a relative path from
.PARAMETER FilePath
The File (or folder) to build a relative path TO
.PARAMETER Resolve
If true, the file and folder paths must exist
.Example
Get-RelativePath ~\\Documents\\WindowsPowerShell\\Logs\\ ~\\Documents\\WindowsPowershell\\Modules\\Logger\\log4net.xslt
..\\Modules\\Logger\\log4net.xslt
Returns a path to log4net.xslt relative to the Logs folder
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0)]
[string]$Folder
,
[Parameter(Mandatory=$true, Position=1, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[string]$FilePath
,
[switch]$Resolve
)
process {
$from = $Folder = split-path $Folder -NoQualifier -Resolve:$Resolve
$to = $filePath = split-path $filePath -NoQualifier -Resolve:$Resolve
while($from -and $to -and ($from -ne $to)) {
if($from.Length -gt $to.Length) {
$from = split-path $from
} else {
$to = split-path $to
}
}
$filepath = $filepath -replace "^"+[regex]::Escape($to)+"\\\\"
$from = $Folder
while($from -and $to -and $from -gt $to ) {
$from = split-path $from
$filepath = join-path ".." $filepath
}
Write-Output $filepath
}
}
function Get-Logger {
<#
.SYNOPSIS
Get an existing Logger by name, or create a new logger
.DESCRIPTION
Returns a logger matching the name (wildcards allowed) provided.
If the logger already exists, it is returned with it's settings as-is, unless the -Force switch is specified, in which case the new settings are used
If only one logger matches the name, that logger becomes the new default logger.
.PARAMETER Name
The name of the logger to find or create. If no name is specified, all existing loggers are returned.
.PARAMETER Level
The level at which to log in this new logger. Defaults to "DEBUG"
Possible levels are as follows (each level includes all levels above it):
FATAL
ERROR
WARN (aka WARNING)
INFO (aka VERBOSE, HOST)
DEBUG
.PARAMETER MessagePattern
The pattern for loggers which use patterns (mostly the file loggers). Defaults to:
' ${longdate} ${level:uppercase=true} ${logger} [${ndc}] [${ndc}] - ${message}${newline}'
For a complete list of possible pattern names, see:
http://nlog-project.org/layoutrenderers.html
.PARAMETER Growl
Outputs log messages to growl
For reference see:
http://ryanfarley.com/blog/archive/2010/05/06/announcing-the-growl-for-windows-target-for-nlog.aspx
.PARAMETER Folder
The folder where log files are kept. Defaults to your Documents\\WindowsPowerShell folder.
NOTE: if the specified folder does not exist, the fallback is your Documents\\WindowsPowerShell folder,
but if that doesn't exist, the folder where this file is stored is used.
.PARAMETER EmailTo
An email address to send WARNING or above messages to. REQUIRES that your $PSEmailServer variable be set
.PARAMETER Console
Creates a colored console logger
.PARAMETER EventLog
Creates an EventLog logger
.PARAMETER TraceLog
Creates a .Net Trace logger
.PARAMETER DebugLog
Creates a .Net Debug logger
.PARAMETER FileLog
Creates a file logger. Note the LogLock parameter!
.PARAMETER RollingFileLog
Creates a rolling file logger with a max size of 250KB. Note the LogLock parameter!
.PARAMETER XmlLog
Creates an Xml-formatted file logger. Note the LogLock parameter!
Note: the XmlLog will output an XML Header and will add a footer when the logger is closed.
This results in a log file which is readable in xml viewers like IE, particularly if you have a copy of the XSLT stylesheet for Log4Net (http://poshcode.org/1750) named log4net.xslt in the same folder with the log file.
WARNING: Because of this, it does not APPEND to the file, but overwrites it each time you create the logger.
.PARAMETER RollingXmlLog
Creates a rolling file Xml logger with a max size of 500KB. Note the LogLock parameter!
Note: the rolling xml logger cannot create "valid" xml because it appends to the end of the file (and therefore can't guarantee the file is well-formed XML).
In order to get a valid Xml file, you can use a "*View.xml" file with contents like this (which this script will create):
<?xml version="1.0" ?>
<?xml-stylesheet type="text/xsl" href="log4net.xslt"?>
<!DOCTYPE events [<!ENTITY data SYSTEM "PowerShellLogger.xml">]>
<log4net:events version="1.2" xmlns:log4net="http://logging.apache.org/log4net/schemas/log4net-events-1.2">
&data;
</log4net:events>
.PARAMETER LogLock
Determines the type of file locking used (defaults to SHARED):
SHARED is the "MinimalLocking" model which opens the file once for each AcquireLock/ReleaseLock cycle, thus holding the lock for the minimal amount of time. This method of locking is considerably slower than...
EXCLUSIVE is the "ExclusiveLocking" model which opens the file once for writing and holds it open until the logger is closed, maintaining an exclusive lock on the file the whole time..
.PARAMETER UdpSend
Creates an UdpAppender which sends messages to the localmachine port 8080
We'll probably tweak this in a future release, but for now if you need to change that you need to edit the script
.PARAMETER ChainsawSend
Like UdpSend, creates an UdpAppender which sends messages to the localmachine port 8080.
This logger uses the log4j xml formatter which is somewhat different than the default, and uses their namespace.
.PARAMETER Force
Force resetting the logger switches even if the logger already exists
#>
param(
[Parameter(Mandatory=$false, Position=0)]
[string]$Name = "*"
,
[Parameter(Mandatory=$false)]
# Actual Values: Trace, Debug, Info, Warn, Error, Fatal
[ValidateSet("Verbose","Trace","Debug","Info","Host","Warn","Warning","Error","Fatal")]
[string]$Level = "Trace"
,
[Parameter(Mandatory=$false)]
#" %date %-5level %logger [%property{NDC}] - %message%newline"
$MessagePattern = ' ${longdate} ${level:uppercase=true} ${logger} - ${message}'
,
[Parameter(Mandatory=$false)]
[string]$Folder = $(Split-Path $Profile.CurrentUserAllHosts)
, [String]$EmailTo
, [Switch]$Force
, [Switch]$ConsoleLog
, [Switch]$EventLog
, [Switch]$TraceLog
, [Switch]$DebugLog
, [Switch]$FileLog
#, [Switch]$RollingFileLog
, [Switch]$XmlLog
#, [Switch]$RollingXmlLog
, [Switch]$UdpSend
, [Switch]$ChainsawSend
, [Switch]$Growl
# ,
# [Parameter(Mandatory=$false, Position=99)]
# [ValidateSet("Shared","Exclusive")]
# [String]$LogLock = "Shared"
)
## Make sure the folder exists
if(!(Test-Path $Folder)) {
$Folder = Split-Path $Profile.CurrentUserAllHosts
if(!(Test-Path $Folder)) {
$Folder = $PSScriptRoot
}
}
$Script:NLogLoggersCollection | Where-Object { $_.Name -Like $Name } | Tee -var LoggerOutputBuffer
if((!(test-path Variable:LoggerOutputBuffer) -or $Force) -and !$Name.Contains('*')) {
if($Level -eq "VERBOSE") { $Level = "Trace" }
if($Level -eq "HOST") { $Level = "Info" }
if($Level -eq "WARNING") { $Level = "Warn" }
$Targets = @()
if(test-path Variable:Email) {
if(!$PSEmailServer) { throw "You need to specify your SMTP mail server by setting the global $PSEmailServer variable" }
$Targets += "Mail"
$Null,$Domain = $email -split "@",2
} else { $Domain = "no.com" }
# if($LogLock -eq "Shared") {
# $LockMode = "MinimalLock"
# } else {
# $LockMode = "ExclusiveLock"
# }
$xslt = ""
if(Test-Path $PSScriptRoot\\log4net.xslt) {
$xslt = @"
<?xml-stylesheet type="text/xsl" href="$(Get-RelativePath $Folder $PSScriptRoot\\NLog.xslt)"?>
"@
}
Set-Content "${Folder}\\${Name}View.Xml" @"
<?xml version="1.0" ?>
$xslt
<!DOCTYPE events [<!ENTITY data SYSTEM "$Name.xml">]>
<events version="1.2" xmlns:log4net="http`://logging.apache.org/log4net/schemas/log4net-events-1.2">
<logname>$Name</logname>
&data;
</events>
"@
if($EventLog) { $Targets += "EventLog" }
if($TraceLog) { $Targets += "Trace" }
if($DebugLog) { $Targets += "Debug" }
if($FileLog) { $Targets += "File" }
# if($RollingFileLog) { $Targets += "<appender-ref ref=""RollingFileAppender"" />`n" }
if($UdpSend) { $Targets += "Udp" }
if($Growl) { $Targets += "Growl" }
if($ChainsawSend) { $Targets += "Chainsaw" }
if($XmlLog) { $Targets += "Xml" }
# if($RollingXmlLog) { $Targets += "<appender-ref ref=""RollingXmlAppender"" />`n"
if($VerbosePreference -gt "SilentlyContinue") { "Created XML viewer for you at: ${Folder}\\${Name}View.Xml" }
$xslt = $xslt -replace "<","<" -replace ">",">" -replace '"',"'"
if($ConsoleLog -or ($Targets.Count -eq 0)) { $Targets += "Console" }
$extensions = ""
if($Growl -and (Test-Path $PSScriptRoot\\NLog.Targets.GrowlNotify.dll)){
$extensions = @"
<extensions>
<add assembly="NLog.Targets.GrowlNotify" />
</extensions>
"@ }
$OFS = ","
[xml]$config = @"
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
$extensions
<targets>
<target name="Console" xsi:type="ColoredConsole" layout="$MessagePattern"/>
<target name="File" xsi:type="File" fileName="$Folder\\$Name.log" layout="$MessagePattern"/>
<target name="Xml" xsi:type="File" fileName="$Folder\\$Name.xml" layout="`${log4jxmlevent}"/>
$(if($EventLog){ '<target name="EventLog" xsi:type="EventLog" log="Application" source="$Name" layout="$MessagePattern"/>' })
<target name="Trace" xsi:type="Trace" layout="$MessagePattern"/>
<target name="Debug" xsi:type="Debugger" layout="$MessagePattern"/>
<target name="Udp" xsi:type="Network" address="udp://localhost:8080" layout="$MessagePattern"/>
<target name="Chainsaw" xsi:type="Chainsaw" address="udp://localhost:8080" />
$(if($Growl){ '<target name="Growl" xsi:type="GrowlNotify" layout="$MessagePattern"/>' })
<target name="Mail" xsi:type="FilteringWrapper" condition="level > LogLevel.Debug or contains(message,'email')" >
<target xsi:type="Mail" addNewLines="True" smtpServer="$PSEmailServer" layout="$MessagePattern"
from="PoshLogger@$Domain" to="$EmailTo" subject="PowerShell Logger Message" />
</target>
</targets>
<rules>
<logger name="$Name" minlevel="$Level" writeTo="$Targets"/>
</rules>
</nlog>
"@
$config.Save("${PSScriptRoot}\\NLog.config")
[NLog.LogManager]::Configuration = New-Object 'NLog.Config.XmlLoggingConfiguration' $config.nlog, $PSScriptRoot\\NLog.config
$Script:NLogLoggersCollection += $Script:Logger = [NLog.LogManager]::GetLogger($Name)
write-output $Script:Logger
}
elseif($LoggerOutputBuffer.Count -eq 1) {
$script:Logger = $LoggerOutputBuffer[0]
write-output $Script:Logger
}
}
function Set-Logger {
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[NLog.Logger]$Logger
)
$script:Logger = $Logger
}
function Push-LogContext {
param(
[Parameter(Mandatory=$true)]
[string]$Name
)
[NLog.Contexts.NestedDiagnosticsContext]::Push($Name)
}
function Pop-LogContext {
[NLog.Contexts.NestedDiagnosticsContext]::Pop()
}
function Write-DebugLog {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
[Alias('Msg')]
[AllowEmptyString()]
[System.String]
${Message}
,
[Parameter(Mandatory=$false, Position=99)]
${Logger})
begin
{
try {
if($PSBoundParameters.ContainsKey("Logger")) {
if($Logger -is [NLog.Logger]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" }
$null = $PSBoundParameters.Remove("Logger")
}
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Debug', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$script:logger.Debug($Message) #Write-Debug
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Write-Debug
.ForwardHelpCategory Cmdlet
#>
}
function Write-VerboseLog {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
[Alias('Msg')]
[AllowEmptyString()]
[System.String]
${Message}
,
[Parameter(Mandatory=$false, Position=99)]
${Logger})
begin
{
try {
if($PSBoundParameters.ContainsKey("Logger")) {
if($Logger -is [NLog.Logger]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" }
$null = $PSBoundParameters.Remove("Logger")
}
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Verbose', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$script:logger.Trace($Message)
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Write-Verbose
.ForwardHelpCategory Cmdlet
#>
}
function Write-WarningLog {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
[Alias('Msg')]
[AllowEmptyString()]
[System.String]
${Message}
,
[Parameter(Mandatory=$false, Position=99)]
${Logger})
begin
{
try {
if($PSBoundParameters.ContainsKey("Logger")) {
if($Logger -is [NLog.Logger]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" }
$null = $PSBoundParameters.Remove("Logger")
}
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Warning', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$script:logger.Warn($Message) #Write-Warning
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Write-Warning
.ForwardHelpCategory Cmdlet
#>
}
function Write-ErrorLog {
[CmdletBinding(DefaultParameterSetName='NoException')]
param(
[Parameter(ParameterSetName='WithException', Mandatory=$true)]
[System.Exception]
${Exception},
[Parameter(ParameterSetName='NoException', Mandatory=$true, Position=0, ValueFromPipeline=$true)]
[Parameter(ParameterSetName='WithException')]
[Alias('Msg')]
[AllowNull()]
[AllowEmptyString()]
[System.String]
${Message},
[Parameter(ParameterSetName='ErrorRecord', Mandatory=$true)]
[System.Management.Automation.ErrorRecord]
${ErrorRecord},
[Parameter(ParameterSetName='NoException')]
[Parameter(ParameterSetName='WithException')]
[System.Management.Automation.ErrorCategory]
${Category},
[Parameter(ParameterSetName='WithException')]
[Parameter(ParameterSetName='NoException')]
[System.String]
${ErrorId},
[Parameter(ParameterSetName='NoException')]
[Parameter(ParameterSetName='WithException')]
[System.Object]
${TargetObject},
[System.String]
${RecommendedAction},
[Alias('Activity')]
[System.String]
${CategoryActivity},
[Alias('Reason')]
[System.String]
${CategoryReason},
[Alias('TargetName')]
[System.String]
${CategoryTargetName},
[Alias('TargetType')]
[System.String]
${CategoryTargetType}
,
[Parameter(Mandatory=$false, Position=99)]
${Logger})
begin
{
try {
if($PSBoundParameters.ContainsKey("Logger")) {
if($Logger -is [NLog.Logger]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" }
$null = $PSBoundParameters.Remove("Logger")
}
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Error', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$script:logger.ErrorException($Message,$Exception) #Write-Error
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Write-Error
.ForwardHelpCategory Cmdlet
#>
}
function Write-HostLog {
[CmdletBinding()]
param(
[Parameter(Mandatory=$false, Position=1, ValueFromPipeline=$true)]
[System.Object]
${Object},
[Switch]
${NoNewline},
[System.Object]
${Separator} = $OFS,
[System.ConsoleColor]
${ForegroundColor},
[System.ConsoleColor]
${BackgroundColor},
[Parameter(Mandatory=$false, Position=99)]
${Logger})
begin
{
try {
if($PSBoundParameters.ContainsKey("Logger")) {
if($Logger -is [NLog.Logger]) { Set-Logger $Logger } else { $script:Logger = Get-Logger "$Logger" }
$null = $PSBoundParameters.Remove("Logger")
}
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Host', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$script:logger.Info(($Object -join $Separator | Out-String)) #Write-Verbose
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName Write-Host
.ForwardHelpCategory Cmdlet
#>
}
Set-Alias Write-Debug Write-DebugLog
Set-Alias Write-Verbose Write-VerboseLog
Set-Alias Write-Warning Write-WarningLog
Set-Alias Write-Error Write-ErrorLog
#Set-Alias Write-Host Write-HostLog
Export-ModuleMember -Function * -Alias *
$NLogLoggersCollection = @()
## THIS IS THE DEFAULT LOGGER. CONFIGURE AS YOU SEE FIT
$script:Logger = Get-Logger "PowerShellLogger" -File # -Console -Growl
|
PowerShellCorpus/PoshCode/Invoke-SqlCmd2.ps1
|
Invoke-SqlCmd2.ps1
|
function Invoke-Sqlcmd2
{
param(
[string]$ServerInstance,
[string]$Database,
[string]$Query,
[Int32]$QueryTimeout=30
)
$conn=new-object System.Data.SqlClient.SQLConnection
$conn.ConnectionString="Server={0};Database={1};Integrated Security=True" -f $ServerInstance,$Database
$conn.Open()
$cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn)
$cmd.CommandTimeout=$QueryTimeout
$ds=New-Object system.Data.DataSet
$da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd)
[void]$da.fill($ds)
$ds.Tables[0]
$conn.Close()
}
|
PowerShellCorpus/PoshCode/Findup_27.ps1
|
Findup_27.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;
using System.Text.RegularExpressions;
namespace Findup
{
public class FileLengthComparer : IComparer<FileInfo>
{
public int Compare(FileInfo x, FileInfo y)
{
return (x.Length.CompareTo(y.Length));
}
}
class Findup
{
public static Dictionary<string, List<string>> optionspaths = new Dictionary<string, List<string>>
{ {"/x", new List<string>()},{"/i",new List<string>()},{"/xf",new List<string>()},{"/if",new List<string>()},
{"/xd",new List<string>()},{"/id",new List<string>()},{"/paths",new List<string>()} };
public static Dictionary<string, List<Regex>> optionsregex = new Dictionary<string, List<Regex>>
{ {"/xr", new List<Regex>()},{"/ir",new List<Regex>()},{"/xfr",new List<Regex>()},{"/ifr",new List<Regex>()},
{"/xdr",new List<Regex>()},{"/idr",new List<Regex>()} };
public static Dictionary<string, Boolean> optionsbools = new Dictionary<string, bool> { { "/recurse", false }, { "/noerr", false }, {"/delete",false}, {"/xj", false}};
public static long numOfDupes, dupeBytes, bytesrecovered, deletedfiles = 0; // number of duplicate files found, bytes in duplicates, bytes recovered from deleting dupes, number of deleted dupes.
public static long errors = 0;
public static string delconfirm;
public static void Main(string[] args)
{
DateTime startTime = DateTime.Now;
Console.WriteLine("Findup.exe v2.0 - By James Gentile - JamesRaymondGentile@gmail.com - 2012.");
Console.WriteLine("Findup.exe matches sizes, then SHA512 hashes to identify duplicate files.");
Console.WriteLine(" ");
string optionskey = "/paths";
List<FileInfo> files = new List<FileInfo>();
int i = 0;
for (i = 0; i < args.Length; i++)
{
string argitem = args[i].ToLower();
if ((System.String.Compare(argitem, "/help", true) == 0) || (System.String.Compare(argitem, "/h", true) == 0))
{
Console.WriteLine("Usage: findup.exe <file/directory #1..#N> [/recurse] [/noerr] [/x /i /xd /id /xf /if + [r]] <files/directories/regex> [/delete]");
Console.WriteLine(" ");
Console.WriteLine("Options: /help - displays this help message.");
Console.WriteLine(" /recurse - recurses through subdirectories when directories or file specifications (e.g. *.txt) are specified.");
Console.WriteLine(" /noerr - discards error messages.");
Console.WriteLine(" /delete - delete each duplicate file with confirmation.");
Console.WriteLine(" /x - eXcludes if full file path starts with (or RegEx matches if /xr) one of the items following this switch until another switch is used.");
Console.WriteLine(" /i - include if full file path starts with (or Regex matches if /ir) one of the items following this switch until another switch is used.");
Console.WriteLine(" /xd - eXcludes all directories - minus drive/files - (using RegEx if /xdr) including subdirs following this switch until another switch is used.");
Console.WriteLine(" /id - Include only directories - minus drive/files - (using RegEx if /idr) including subdirs following this switch until another switch is used.");
Console.WriteLine(" /xf - eXcludes all files - minus drive/directories - (using RegEx if /xfr) following this switch until another switch is used.");
Console.WriteLine(" /if - Include only files - minus drive/directories - (using RegEx if /ifr) following this switch until another switch is used.");
Console.WriteLine(" [r] - Use regex for include/exclude by appending an 'r' to the option, e.g. -ir, -ifr, -idr, -xr, -xfr, -xdr.");
Console.WriteLine(" /paths - not needed unless you want to specify files/dirs after an include/exclude without using another non-exclude/non-include option.");
Console.WriteLine(" /xj - Exclude File and Directory Junctions.");
Console.WriteLine(" ");
Console.WriteLine("Examples: findup.exe c:\\\\finances /recurse /noerr /delete");
Console.WriteLine(" - Find dupes in c:\\\\finance.");
Console.WriteLine(" - recurse all subdirs of c:\\\\finance.");
Console.WriteLine(" - suppress error messages.");
Console.WriteLine(" - deletes duplicates after consent is given.");
Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data /recurse /x d:\\\\data\\\\webpics");
Console.WriteLine(" - Find dupes in c:\\\\users\\\\alice\\\\plan.txt, d:\\\\data");
Console.WriteLine(" - recurse subdirs in d:\\\\data.");
Console.WriteLine(" - exclude any files in d:\\\\data\\\\webpics and subdirs.");
Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\quarter.doc /xfr \\"(jim)\\"");
Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\quarter.doc");
Console.WriteLine(" - exclude any file with 'jim' in the name as specified by the Regex item \\"(jim)\\"");
Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\*quarter.doc /xr \\"[bf]\\" /ir \\"(smith)\\"");
Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\*quarter.doc");
Console.WriteLine(" - Include only files with 'smith' and exclude any file with letters b or f in the path name as specified by the Regex items \\"[bf]\\",\\"(smith)\\"");
Console.WriteLine("Note: Exclude takes precedence over Include.");
return;
}
if (optionsbools.ContainsKey(argitem))
{
optionsbools[argitem] = true;
optionskey = "/paths";
continue;
}
if (optionspaths.ContainsKey(argitem) || optionsregex.ContainsKey(argitem))
{
optionskey = argitem;
continue;
}
if (optionspaths.ContainsKey(optionskey))
optionspaths[optionskey].Add(args[i]);
else
{
try {
Regex rgx = new Regex(args[i], RegexOptions.Compiled);
optionsregex[optionskey].Add(rgx);
}
catch (Exception e) {WriteErr("Regex compilation failed: " + e.Message);}
}
}
if (optionspaths["/paths"].Count == 0)
{
WriteErr("No files, file specifications, or directories specified. Try findup.exe -help. Assuming current directory.");
optionspaths["/paths"].Add(".");
}
Console.Write("Getting file info and sorting file list...");
getFiles(optionspaths["/paths"], "*.*", optionsbools["/recurse"], files);
if (files.Count < 2)
{
WriteErr("\\nFindup.exe needs at least 2 files to compare. Try findup.exe -help");
Console.WriteLine("\\n");
return;
}
files.Sort(new FileLengthComparer());
Console.WriteLine("Completed!");
Console.Write("Building dictionary of file sizes, SHA512 hashes and full paths...");
var SizeHashFile = new Dictionary<long, Dictionary<string,List<FileInfo>>>();
long filesize = 0;
for (i = 0; i < (files.Count - 1); i++)
{
if (files[i].Length != files[i + 1].Length) continue;
var breakout = false;
while (true)
{
filesize = (files[i].Length);
try
{
var _SHA512 = SHA512.Create();
using (var fstream = File.OpenRead(files[i].FullName))
{
_SHA512.ComputeHash(fstream);
}
string SHA512string = Hash2String(_SHA512.Hash);
if (!SizeHashFile.ContainsKey(filesize))
SizeHashFile.Add(filesize, new Dictionary<string,List<FileInfo>>());
if (!SizeHashFile[filesize].ContainsKey(SHA512string))
{
SizeHashFile[filesize][SHA512string] = new List<FileInfo>() {};
}
SizeHashFile[filesize][SHA512string].Add(files[i]);
}
catch (Exception e) { WriteErr("Hash error: " + e.Message); }
if (breakout == true) {break;}
i++;
if (i == (files.Count - 1)) { breakout = true; continue; }
breakout = (files[i].Length != files[i + 1].Length);
}
if (SizeHashFile.ContainsKey(filesize))
{
foreach (var HG in SizeHashFile[filesize])
{
if (HG.Value.Count > 1)
{
Console.WriteLine("{0:N0} Duplicate files. {1:N0} Bytes each. {2:N0} Bytes total : ", HG.Value.Count, filesize, filesize * HG.Value.Count);
foreach (var finfo in HG.Value)
{
Console.WriteLine(finfo.FullName);
numOfDupes++;
dupeBytes += finfo.Length;
if (optionsbools["/delete"])
if (DeleteDupe(finfo)) { bytesrecovered += finfo.Length; deletedfiles++; }
}
}
}
}
}
Console.WriteLine("\\n ");
Console.WriteLine("Files checked : {0:N0}", files.Count); // display statistics and return to OS.
Console.WriteLine("Duplicate files : {0:N0}", numOfDupes);
Console.WriteLine("Duplicate bytes : {0:N0}", dupeBytes);
Console.WriteLine("Deleted duplicates : {0:N0}", deletedfiles);
Console.WriteLine("Bytes recovered : {0:N0}", bytesrecovered);
Console.WriteLine("Errors : {0:N0}", errors);
Console.WriteLine("Execution time : " + (DateTime.Now - startTime));
}
private static void WriteErr(string Str)
{
errors++;
if (!optionsbools["/noerr"])
Console.WriteLine(Str);
}
private static string Hash2String(Byte[] hasharray)
{
string SHA512string = "";
foreach (var c in hasharray)
{
SHA512string += String.Format("{0:x2}", c);
}
return SHA512string;
}
private static Boolean DeleteDupe(FileInfo Filenfo)
{
Console.Write("Delete this file <y/N> <ENTER>?");
delconfirm = Console.ReadLine();
if ((delconfirm[0] == 'Y') || (delconfirm[0] == 'y'))
{
try
{
Filenfo.Delete();
Console.WriteLine("File Successfully deleted.");
return true;
}
catch (Exception e) { Console.WriteLine("File could not be deleted: " + e.Message); }
}
return false;
}
private static Boolean CheckNames(string fullname)
{
var filePart = Path.GetFileName(fullname); // get file name only (e.g. "d:\\temp\\data.txt" -> "data.txt")
var dirPart = Path.GetDirectoryName(fullname).Substring(fullname.IndexOf(Path.VolumeSeparatorChar)+2); // remove drive & file (e.g. "d:\\temp\\data.txt" -> "temp")
if (CheckNamesWorker(fullname, "/x", "/xr", true))
return false;
if (CheckNamesWorker(filePart, "/xf", "/xfr", true))
return false;
if (CheckNamesWorker(dirPart, "/xd", "/xdr", true))
return false;
if (CheckNamesWorker(fullname, "/i", "/ir", false))
return false;
if (CheckNamesWorker(filePart, "/if", "/ifr", false))
return false;
if (CheckNamesWorker(dirPart, "/id", "/idr", false))
return false;
return true;
}
private static Boolean CheckNamesWorker(string filestr, string pathskey, string rgxkey, Boolean CheckType)
{
foreach (var filepath in optionspaths[pathskey])
{
if (filestr.ToLower().StartsWith(filepath) == CheckType)
return true;
}
foreach (var rgx in optionsregex[rgxkey])
{
if (rgx.IsMatch(filestr) == CheckType)
return true;
}
return false;
}
private static void getFiles(List<string> pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList)
{
foreach (string d in pathRec) { getFiles(d, searchPattern, recursiveFlag, returnList); }
}
private static void getFiles(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList)
{
foreach (string d in pathRec) { getFiles(d, searchPattern, recursiveFlag, returnList); }
}
private static void getFiles(string pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList)
{
string dirPart;
string filePart;
if (File.Exists(pathRec))
{
try
{
FileInfo addf = (new FileInfo(pathRec));
if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) || !optionsbools["/xj"])
if (CheckNames(addf.FullName))
returnList.Add(addf);
}
catch (Exception e) { WriteErr("Add file error: " + e.Message); }
}
else if (Directory.Exists(pathRec))
{
try
{
DirectoryInfo Dir = new DirectoryInfo(pathRec);
if (((Dir.Attributes & FileAttributes.ReparsePoint) == 0) || !optionsbools["/xj"])
foreach (FileInfo addf in (Dir.GetFiles(searchPattern)))
{
if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) || !optionsbools["/xj"])
if (CheckNames(addf.FullName))
returnList.Add(addf);
}
}
catch (Exception e) { WriteErr("Add files from Directory error: " + e.Message); }
if (recursiveFlag)
{
try { getFiles((Directory.GetDirectories(pathRec)), searchPattern, recursiveFlag, returnList); }
catch (Exception e) { WriteErr("Add Directory error: " + e.Message); }
}
}
else
{
try
{
filePart = Path.GetFileName(pathRec);
dirPart = Path.GetDirectoryName(pathRec);
}
catch (Exception e)
{
WriteErr("Parse error on: " + pathRec);
WriteErr(@"Make sure you don't end a directory with a \\ when using quotes. The console arg parser doesn't accept that.");
WriteErr("Exception: " + e.Message);
return;
}
if (filePart.IndexOfAny(new char[] {'?','*'}) >= 0)
{
if ((dirPart == null) || (dirPart == ""))
dirPart = Directory.GetCurrentDirectory();
if (Directory.Exists(dirPart))
{
getFiles(dirPart, filePart, recursiveFlag, returnList);
return;
}
}
WriteErr("Invalid file path, directory path, file specification, or program option specified: " + pathRec);
}
}
}
}
|
PowerShellCorpus/PoshCode/replace-regexgroup.ps1
|
replace-regexgroup.ps1
|
#region @3
## Function to do a regex replace of all matches with an expression per match that has local variables
##created automatically for the named groups so that you can use those varibles in your expression
function replace-regexgroup ([regex]$regex, [string]$text ,[scriptblock] $replaceexpression)
{
$regex.Replace($text,{
$thematch = $args[0]
$groupnames = $regex.GetGroupNames()
for ($count = 0; $count -lt ( $thematch.groups.count) ; $count++)
{
set-variable -name $($groupnames[$count]) -visibility private -value $($thematch.groups[$count] )
}
if ($replaceexpression -ne $Null) { &$replaceexpression}
} )
}
$example = @"
<P><a href="wiki://284_636">links to test page 2</a></P>
<P><a href="wiki://109_49">
"@
replace-regexgroup 'wiki://(?<wholething>(?<folder>\\d+)_(?<page>\\d+))' $example { "$folder/$page/index.html" }
#endregion
|
PowerShellCorpus/PoshCode/8014f3e2-68e3-4145-bd77-badc10360e30.ps1
|
8014f3e2-68e3-4145-bd77-badc10360e30.ps1
|
param([Parameter(Mandatory=$true)][string]$Path,[Parameter(Mandatory=$true)][string]$Destination)
Get-ChildItem -Path $Path | Where-Object { !$_.PSIsContainer } | foreach {
$Target = Join-Path -Path $Destination -ChildPath (Split-Path -Leaf $_)
if ( Test-Path -Path $Target -PathType Leaf ) {
Rename-Item -Path $Target -NewName ([System.IO.Path]::ChangeExtension($Target, ".old"))
}
Copy-Item -Path $_ -Destination $Target
}
|
PowerShellCorpus/PoshCode/Create SP2010 Farm V03.ps1
|
Create SP2010 Farm V03.ps1
|
############################################################################
## Create-SPFarm
## V 0.3
## Jos.Verlinde
############################################################################
Param ( [String] $Farm = "SP2010",
[String] $SQLServer = $env:COMPUTERNAME,
[String] $Passphrase = "pass@word1",
[int] $CAPort = 26101 ,
[switch] $Force = $false )
# Disable the Loopback Check on stand alone demo servers.
# This setting usually kicks out a 401 error when you try to navigate to sites that resolve to a loopback address e.g. 127.0.0.1
New-ItemProperty HKLM:\\System\\CurrentControlSet\\Control\\Lsa -Name "DisableLoopbackCheck" -value "1" -PropertyType dword
#region Process Input Parameters
$SecPhrase=ConvertTo-SecureString $Passphrase –AsPlaintext –Force
$Passphrase = $null
## get Farm Account
$cred_farm = $host.ui.PromptForCredential("FARM Setup", "SP Farm Account (SP_farm)", "contoso\\sp_farm", "NetBiosUserName" )
#Endregion
# Create a new farm
New-SPConfigurationDatabase –DatabaseName “$FARM-Config” –DatabaseServer $SQLServer –AdministrationContentDatabaseName “$FARM-Admin-Content” –Passphrase $SecPhrase –FarmCredentials $Cred_Farm
# Create Central Admin
New-SPCentralAdministration -Port $CAPort -WindowsAuthProvider "NTLM"
#Install Help Files
Install-SPApplicationContent
#Secure resources
Initialize-SPResourceSecurity
#Install (all) features
If ( $Force ) {
$Features = Install-SPFeature –AllExistingFeatures -force
} else {
$Features = Install-SPFeature –AllExistingFeatures
}
## Report features installed
$Features
# Provision all Services works only on stand alone servers (ie one-click-install )
# Install-SPService -Provision
## Todo : Check for Errors in the evenlog
##
## Start Central Admin
Start-Process "http://$($env:COMPUTERNAME):$CAPort"
## Run Farm configuration Wizard
Start-Process "http://$($env:COMPUTERNAME):$CAPort/_admin/adminconfigintro.aspx?scenarioid=adminconfig&welcomestringid=farmconfigurationwizard_welcome"
##@@ Todo - Run Farm Wizard or better yet create required service applications (minimal - normal - all template)
|
PowerShellCorpus/PoshCode/CertMgmt pack.ps1
|
CertMgmt pack.ps1
|
#####################################################################
# CertMgmtPack.ps1
# Version 0.51
#
# Digital certificate management pack
#
# Vadims Podans (c) 2009
# http://www.sysadmins.lv/
#####################################################################
#requires -Version 2.0
function Import-Certificate {
<#
.Synopsis
Imports digital certificates to Certificate Store from files
.Description
Improrts digital certificates to Certificate Store from various types of
certificates files, such .CER, .DER, .PFX (password required), .P7B.
.Parameter Path
Specifies the path to certificate file
.Parameter Password
Specifies password to PFX/PKCS#12 file only. For other certificate types
is not required.
Note: this parameter must be passed as SecureString.
.Parameter Storage
Specifies place in Sertificate Store for certificate. For user certificates
(default) you MAY specify 'User' and importing certificate will be stored
in CurrentUser Certificate Store. For computer certificates you MUST specify
'Computer' and importing certificates will be stored in LocalMachine Certificate
Store.
.Parameter Container
Specifies container within particular Certificate Store location. Container may
be one of AuthRoot/CA/Disallowed/My/REQUEST/Root/SmartCardRoot/Trust/TrustedPeople/
TrustedPublisher/UserDS. These containers represent MMC console containers
as follows:
AddressBook - AddressBook
AuthRoot - Third-Party Root CAs
CA - Intermediate CAs
Disallowed - Untrused Certificates
My - Personal
REQUEST - Certificate Enrollment Requests
Root - Trusted Root CAs
SmartCardRoot - Smart Card Trusted Roots
Trust - Enterprise Trust
TrustedPeople - Trusted People
TrustedPublishers - Trusted Publishers
UserDS - Active Directory User Object
.Parameter Exportable
Marks imported certificates private key as exportable. May be used only for PFX
files only. If this switch is not presented for PFX files, after importing you
will not be able to export this certificate with private key again.
.Parameter StrongProtection
Enables private key strong protection that requires user password each time
when certificate private key is used. Not available for computer certificates,
because computers certificates are used under LocalSystem account and here is
no UI for user to type password.
.Outputs
This command provide a simple message if the export is successful.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
[string]$Path,
[Parameter(Position = 1)]
[System.Security.SecureString]$Password,
[Parameter(Position = 2)]
[string][ValidateSet("CurrentUser", "LocalMachine")]$Storage = "CurrentUser",
[string][ValidateSet("AddressBook", "AuthRoot", "CA", "Disallowed", "My", "REQUEST",
"Root", "SmartCardRoot", "Trust", "TrustedPeople", "TrustedPublisher", "UserDS")]$Container = "My",
[switch]$Exportable,
[switch]$StrongProtection
)
if (!(Resolve-Path $Path)) {throw "Looks like your specified certificate file doesn't exist"}
$file = gi $Path -Force -ErrorAction Stop
$certs = New-Object system.security.cryptography.x509certificates.x509certificate2
switch ($Storage) {
"CurrentUser" {$flags = "UserKeySet"}
"LocalMachine" {$flags = "MachineKeySet"}
}
switch -regex ($file.Extension) {
".CER|.DER" {$certs.Import($file.FullName, $null, $flags)}
".PFX" {
if (!$password) {throw "For PFX files password is required."}
if ($StrongProtection -and $Storage -eq "Computer") {
throw "You cannot use Private Key Strong Protection for computer certificates!"
}
if ($Exportable) {$flags = $flags + ", Exportable"}
if ($StrongProtection) {$flags = $flags + ", UserProtected"}
$certs.Import($file.FullName, $password, $flags)
}
".P7B|.SST" {
$certs = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
$certs.Import([System.IO.File]::ReadAllBytes($file.FullName))
}
default {throw "Looks like your specified file is not a certificate file"}
}
$store = New-Object system.security.cryptography.X509Certificates.X509Store $Container, $Storage
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$certs | %{$store.Add($_)}
if ($?) {Write-Host -ForegroundColor Green Certificate file`: $file.fullname was successfully added to $Container container}
$store.Close()
}
function Export-Certificate {
<#
.Synopsis
Exports digital certificates to file Certificate Store.
.Description
Exports digital certificates from Certificate Store to various types of certificate
file such .CER, .DER, .PFX (password required), .P7B or .SST (serializd store).
.Parameter Path
Specifies the path to certificate storing folder
.Parameter Type
Specifies type of imported certificate. May be one of CERT/PFX/PKCS#12/P7B/PKCS#7.
.Parameter Password
Specifies a password for PFX files and used only if type is specified as PFX/PKCS#12.
Note: password must be supplied as SecureString.
.Parameter Storage
Specifies place in Sertificate Store for certificate. For user certificates
(default) you MAY specify 'User' to export certificates from CurrentUser Certificate Store.
For computer certificates you MUST specify 'Computer' to export certificates from
LocalMachine Certificate Store.
.Parameter Container
Specifies container within particular Certificate Store location. Container may
be one of AuthRoot/CA/Disallowed/My/REQUEST/Root/SmartCardRoot/Trust/TrustedPeople/
TrustedPublisher/UserDS. These containers represent MMC console containers
as follows:
AddressBook - AddressBook
AuthRoot - Third-Party Root CAs
CA - Intermediate CAs
Disallowed - Untrused Certificates
My - Personal
REQUEST - Certificate Enrollment Requests
Root - Trusted Root CAs
SmartCardRoot - Smart Card Trusted Roots
Trust - Enterprise Trust
TrustedPeople - Trusted People
TrustedPublishers - Trusted Publishers
UserDS - Active Directory User Object
.EXAMPLE
.Outputs
This command doesn't provide any output, except errors.
.Link
#>
[CmdletBinding()]
param (
[Parameter(Position = 0)]
[string]$Path,
[Parameter(Mandatory = $true, Position = 1)]
[string][ValidatePattern("Cert|Pfx|pkcs12|pkcs7|SST")]$Type,
[Parameter(Position = 2)]
[System.Security.SecureString]$Password,
[Parameter(Position = 3)]
[string][ValidateSet("CurrentUser", "LocalMachine")]$Storage = "CurrentUser",
[Parameter(ValueFromPipeline = $true, Position = 4)]
[string][ValidateSet("AddressBook", "AuthRoot", "CA", "Disallowed", "My", "REQUEST",
"Root", "SmartCardRoot", "Trust", "TrustedPeople", "TrustedPublisher", "UserDS")]$Container = "My",
[string]$Thumbprint,
[string]$Subject,
[string]$Issuer,
[string]$SerialNumber,
[string]$NotAfter,
[string]$NotBefore,
[switch]$DeleteKey,
[switch]$Recurse
)
if (!(Test-Path $Path)) {
New-Item -ItemType directory -Path $Path -Force -ErrorAction Stop
}
if ((Resolve-Path $Path).Provider.Name -ne "FileSystem") {
throw "Spicifed path is not recognized as filesystem path. Try again"
}
if ($Recurse) {
function dirx ($Storage) {
dir cert:\\$Storage -Recurse | ?{!$_.PsIsContainer}
}
} else {
function dirx ($Storage, $Container) {
dir cert:\\$Storage\\$Container
}
}
# îďđĺäĺëĺíčĺ, ÷ňî äë˙ PFX ńĺđňčôčęŕňîâ óęŕçŕí ďŕđîëü
if ($Type -eq 'pkcs12') {$Type = "PFX"}
if ($Type -eq 'SST') {$Type = "SerializedStore"}
if ($Type -eq "PFX" -and !$Password) {throw "For PFX files password is required."}
# ęîíâĺđňŕöč˙ ďđĺäâŕđčňĺëüíűő çíŕ÷ĺíčé ŕđăóěĺíňîâ â ęîíĺ÷íűĺ çíŕ÷ĺíč˙ č ňčďű
# .NET ęëŕńńîâ
$Type = [System.Security.Cryptography.X509Certificates.X509ContentType]::$Type
if ($NotAfter) {$NotAfter = [datetime]::ParseExact($NotAfter, "dd.MM.yyy", $null)}
if ($NotBefore) {$NotBefore = [datetime]::ParseExact($NotBefore, "dd.MM.yyy", $null)}
# ďđîâĺđęŕ îńíîâíűő ęđčňĺđčĺâ)
if ($Thumbprint) {$certs = @(dirx | ?{$_.Thumbprint -like "*$Thumbprint*"})}
elseif ($Subject) {$certs = @(dirx | ?{$_.Subject -like "*$Subject*"})}
elseif ($Issuer) {$certs = @(dirx | ?{$_.Issuer -like "*$Issuer*"})}
elseif ($SerialNumber) {$certs = @(dirx | ?{$_.SerialNumber -like "*$SerialNumber*"})}
elseif ($NotAfter -and !$NotBefore) {$certs = @(dirx | ?{$_.NotAfter -lt $NotAfter})}
elseif (!$NotAfter -and $NotBefore) {$certs = @(dirx | ?{$_.NotBefore -gt $NotBefore})}
elseif ($NotAfter -and $NotBefore) {$certs = @(dirx | ?{$_.NotAfter -lt $NotAfter `
-and $_.NotBefore -gt $NotBefore})}
else {$certs = @(dirx)}
if ($certs.Count -eq 0) {Write-Warning "Sorry, we unable to find certificates that correspond your filter :("; return}
switch -regex ($Type) {
"Cert" {
foreach ($cert in $certs) {
[void]($cert.Subject -match 'CN=([^,]+)')
$CN = $matches[1] -replace '[\\\\/:\\*?`"<>|]', ''
$bytes = $cert.Export($type)
$base64Data = [System.Convert]::ToBase64String($bytes)
Set-Content -LiteralPath $(Join-Path $Path ($CN + "_" + $cert.Thumbprint + ".cer")) -Value $base64Data
}
}
"PFX" {
foreach ($cert in $certs) {
[void]($cert.Subject -match 'CN=([^,]+)')
$CN = $matches[1] -replace '[\\\\/:\\*?`"<>|]', ''
$bytes = $cert.Export($Type, $Password)
[System.IO.File]::WriteAllBytes($(Join-Path $Path ($CN + "_" + $cert.Thumbprint + ".pfx")), $bytes)
if ($DeleteKey) {
$tempcert = $cert.Export("Cert")
$store = New-Object system.security.cryptography.X509Certificates.X509Store $container, $Storage
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$store.Remove($cert)
$store.Add($tempcert)
$store.Close()
}
}
}
"Pkcs7|SerializedStore" {
# ńîçäŕ¸ě îáúĺęň ěŕńńčâŕ x509Certificate2 îáúĺęňîâ
$certcol = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
# äîáŕâë˙ĺě âńĺ ńĺđňčôčęŕňű čç $certs â ýňîň ěŕńńčâ
$certs | %{[void]$certcol.Add($_)}
# ýęńďîđňčđóĺě ýňîň ěŕńńčâ â áŕéňîâűé ěŕńńčâ
$bytes = $certcol.Export($Type)
# çŕďčńűâŕĺě ěŕńńčâ áŕéňîâ â p7b ôŕéë
if ($Type -eq "Pkcs7") {$ext = ".p7b"} else {$ext = ".sst"}
[System.IO.File]::WriteAllBytes($("ExportedCertificates" + $ext, $bytes))
}
}
}
|
PowerShellCorpus/PoshCode/egg_timer_2.ps1
|
egg_timer_2.ps1
|
function GenerateForm {
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
$form_main = New-Object System.Windows.Forms.Form
$reset_button = New-Object System.Windows.Forms.Button
$label1 = New-Object System.Windows.Forms.Label
$start_button = New-Object System.Windows.Forms.Button
$progressBar1 = New-Object System.Windows.Forms.ProgressBar
$timer1 = New-Object System.Windows.Forms.Timer
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
$start_button_OnClick = {
$timer1.Enabled = $true
$timer1.Start()
$start_button.Text = 'Countdown Started.'
}
$reset_button_OnClick = {
$timer1.Enabled = $false
$progressBar1.Value = 0
$start_button.Text = 'Start'
$label1.Text = '3:00'
}
@@ $timer1_OnTick = {
$progressBar1.PerformStep()
$time = 180 - $progressBar1.Value
[char[]]$mins = "{0}" -f ($time / 60)
$secs = "{0:00}" -f ($time % 60)
$label1.Text = "{0}:{1}" -f $mins[0], $secs
if ($progressBar1.Value -eq $progressBar1.Maximum) {
$timer1.Enabled = $false
$start_button.Text = 'FINISHED!'
}
}
$OnLoadForm_StateCorrection = {
#Correct the initial state of the form to prevent the .Net maximized form issue
$form_main.WindowState = $InitialFormWindowState
}
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 628
$System_Drawing_Size.Height = 295
$form_main.MaximumSize = $System_Drawing_Size
$form_main.Text = 'Super Duper Over-engineered Egg Timer'
$form_main.MaximizeBox = $False
$form_main.Name = 'form_main'
$form_main.ShowIcon = $False
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 628
$System_Drawing_Size.Height = 295
$form_main.MinimumSize = $System_Drawing_Size
$form_main.StartPosition = 1
$form_main.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 612
$System_Drawing_Size.Height = 259
$form_main.ClientSize = $System_Drawing_Size
$reset_button.TabIndex = 4
$reset_button.Name = 'button2'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 209
$System_Drawing_Size.Height = 69
$reset_button.Size = $System_Drawing_Size
$reset_button.UseVisualStyleBackColor = $True
$reset_button.Text = 'Reset'
$reset_button.Font = New-Object System.Drawing.Font("Verdana",12,0,3,0)
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 362
$System_Drawing_Point.Y = 13
$reset_button.Location = $System_Drawing_Point
$reset_button.DataBindings.DefaultDataSourceUpdateMode = 0
$reset_button.add_Click($reset_button_OnClick)
$form_main.Controls.Add($reset_button)
$label1.TabIndex = 3
$label1.TextAlign = 32
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 526
$System_Drawing_Size.Height = 54
$label1.Size = $System_Drawing_Size
$label1.Text = '3:00'
$label1.Font = New-Object System.Drawing.Font("Courier New",20.25,1,3,0)
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 45
$System_Drawing_Point.Y = 89
$label1.Location = $System_Drawing_Point
$label1.DataBindings.DefaultDataSourceUpdateMode = 0
$label1.Name = 'label1'
$form_main.Controls.Add($label1)
$start_button.TabIndex = 2
$start_button.Name = 'button1'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 310
$System_Drawing_Size.Height = 70
$start_button.Size = $System_Drawing_Size
$start_button.UseVisualStyleBackColor = $True
$start_button.Text = 'Start'
$start_button.Font = New-Object System.Drawing.Font("Verdana",12,0,3,0)
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 45
$System_Drawing_Point.Y = 12
$start_button.Location = $System_Drawing_Point
$start_button.DataBindings.DefaultDataSourceUpdateMode = 0
$start_button.add_Click($start_button_OnClick)
$form_main.Controls.Add($start_button)
$progressBar1.DataBindings.DefaultDataSourceUpdateMode = 0
$progressBar1.Maximum = 180
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 526
$System_Drawing_Size.Height = 87
$progressBar1.Size = $System_Drawing_Size
$progressBar1.Step = 1
$progressBar1.TabIndex = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 45
$System_Drawing_Point.Y = 146
$progressBar1.Location = $System_Drawing_Point
$progressBar1.Style = 1
$progressBar1.Name = 'progressBar1'
$form_main.Controls.Add($progressBar1)
@@ $timer1.Interval = 1000
@@ $timer1.add_tick($timer1_OnTick)
$InitialFormWindowState = $form_main.WindowState
$form_main.add_Load($OnLoadForm_StateCorrection)
$form_main.ShowDialog()| Out-Null
}
#Call the Function
GenerateForm
|
PowerShellCorpus/PoshCode/h20 -Hashtables 2 object_2.ps1
|
h20 -Hashtables 2 object_2.ps1
|
#hashtable to object function.
#used to be able to make custom objects with math inside the pipeline
#e.g. 1..10 | h20 { @{karl = $_;dude = $_+1} }
#gps | h20 { @{name = $_.processname; mem = $_.workingset / 1MB} }
function h20([scriptblock]$sb )
{
begin {}
process{ if ($sb -ne $null)
{
$ht = &$sb;
if ($ht -is [hashtable])
{
New-Object PSObject -Property $ht}
}
if ($ht -is [object[]])
{
$ht | where { $_ -is [hashtable]} | % { New-Object PSObject -Property $_ }
}
}
end{}
}
|
PowerShellCorpus/PoshCode/Get-NaVolumeLatency.ps1
|
Get-NaVolumeLatency.ps1
|
<#
.SYNOPSIS
Get the different protocol latencies for a specified volume.
.DESCRIPTION
Get the different protocol latencies for a specified volume.
.PARAMETER Volume
Volume to retrieve the latency.
.PARAMETER Protocol
Protocol to collect latency for valid values are 'all','nfs','cifs','san','fcp','iscsi'
.PARAMETER Interval
The interval between iterations in seconds, default is 15 seconds
.PARAMETER Count
the number of iterations to execute, default is infinant
.PARAMETER Controller
NetApp Controller to query.
.EXAMPLE
.\\Get-NaVolumeLatency.ps1 -Volume vol0
Get the average latency for all protocols on vol0
.EXAMPLE
Get-NaVol | .\\Get-NaVolumeLatency.ps1 -Interval 5 -count 5 | ft
Get the average latency for all protocols, all volumes, 5 samples, 5 seconds apart.
.EXAMPLE
.\\Get-NaVolumeLatency.ps1 -Volume vol0 -protocol nfs
Get the NFS latency for vol0
.NOTE
#Requires -Version 2
Uses the DataOnTap Toolkit Available http://communities.netapp.com/community/interfaces_and_tools/data_ontap_powershell_toolkit
#>
[cmdletBinding()]
Param(
[Parameter(Mandatory=$true,
HelpMessage="Volume name to retrieve latency counters from.",
ValueFromPipelineByPropertyName=$true,
ValueFromPipeLine=$true
)]
[Alias("Name")]
[string]
$Volume
,
[Parameter(Mandatory=$false)]
[ValidateSet('all','nfs','cifs','san','fcp','iscsi')]
[string]
$Protocol='all'
,
[Parameter(Mandatory=$false)]
[int]
$Interval=15
,
[Parameter(Mandatory=$false)]
[string]
$count
,
[Parameter(Mandatory=$false)]
[NetApp.Ontapi.Filer.NaController]
$Controller=($CurrentNaController)
)
Begin
{
IF ($Protocol -eq 'all')
{
$Counters = @(
@{
Counter = 'read_latency'
Base = ''
unit = ''
}
,
@{
Counter = 'write_latency'
Base = ''
unit = ''
}
,
@{
Counter = 'other_latency'
Base = ''
unit = ''
}
,
@{
Counter = 'avg_latency'
Base = ''
unit = ''
}
)
}
Else
{
$Counters = @(
@{
Counter = "$($Protocol.ToLower())_read_latency"
Base = ''
unit = ''
}
,
@{
Counter = "$($Protocol.ToLower())_write_latency"
Base = ''
unit = ''
}
,
@{
Counter = "$($Protocol.ToLower())_other_latency"
Base = ''
unit = ''
}
)
}
foreach ($c in $Counters)
{
Get-NaPerfCounter -Name 'volume' -Controller $Controller |
Where-Object {$_.name -eq $c.Counter} |
ForEach-Object {
$c.Base = $_.BaseCounter
$c.unit = switch ($_.unit) {
"microsec" {10000}
"millisec" {1}
}
}
}
}
Process
{
# Check if volume exists.
if (-Not ((get-navol -Controller $Controller|select -ExpandProperty Name) -contains $Volume)) {
Write-Warning "$volume doesn't exist!"
break;
}
$iteration = 0
$first = $null
#loop untill we're done or Cntr ^c
while ((!$Count) -or ($iteration -le $count))
{
$second = New-Object Collections.HashTable
Get-NaPerfData -Name volume `
-Instances $Volume `
-Controller $Controller `
-Counters ($Counters|%{$_.base,$_.counter}) |
Select-Object -ExpandProperty Counters |
ForEach-Object {
$second.add($_.Name,$_.value)
}
if ($first -and $second)
{
$results = "" | Select-Object -Property ($Counters|%{$_.base,$_.counter})
foreach ($v in $Counters)
{
IF ($second[$v.Base] -gt $first[$v.Base])
{
#calculate the average over our interval
$avg = ($second[$v.Counter] - $first[$v.Counter])/($second[$v.Base] - $first[$v.Base])
#conver to ms
$results."$($v.Base)" = [math]::Round((($second[$v.Base] - $first[$v.Base])/$Interval))
$results."$($v.Counter)" = ("{0} ms" -f [math]::Round($avg/$v.unit))
}
Else
{
$results."$($v.Base)" = 0
$results."$($v.Counter)" = "0 ms"
}
}
Write-Output $results| Add-Member NoteProperty 'Volume' $Volume -PassThru
}
Start-Sleep -Seconds $Interval
$first = $second.clone()
$iteration++
}
}
|
PowerShellCorpus/PoshCode/Manage ASP_4.NET Providers.ps1
|
Manage ASP_4.NET Providers.ps1
|
# Manage_ASP_NET_Providers.ps1
# by Chistian Glessner
# http://iLoveSharePoint.com
# have to be initialized. If you want to change the app config you have to restart PowerShell
param($appConfigPath=$null)
# App config path have to be set before loading System.Web.dll
[System.AppDomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $appConfigPath )
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Web")
function global:Get-MembershipProvider($providerName=$null, [switch]$all)
{
if($all)
{
return [System.Web.Security.Membership]::Providers
}
if($providerName -eq $null)
{
return [System.Web.Security.Membership]::Provider
}
else
{
return [System.Web.Security.Membership]::Providers[$providerName]
}
}
function global:Add-MembershipUser($login=$(throw "-login is required"), $password=$(throw "$password is required"), $mail=$(throw "-mail is required"),$question, $answer, $approved=$true)
{
$provider = $input | select -First 1
if($provider -isnot [System.Web.Security.MembershipProvider])
{
$provider = Get-MembershipProvider
}
$status = 0
$provider.CreateUser($login, $password, $mail, $question, $answer, $approved, $null, [ref]$status)
return [System.Web.Security.MembershipCreateStatus]$status
}
function global:Get-MembershipUser($identifier, $maxResult=100)
{
$provider = $input | select -First 1
if($provider -isnot [System.Web.Security.MembershipProvider])
{
$provider = Get-MembershipProvider
}
if($identifier -ne $null)
{
$name = $provider.GetUserNameByEmail($identifier)
if($name -ne $null){$identifier = $name}
return $provider.GetUser($identifier,$false)
}
$totalUsers = 0
$users = $provider.GetAllUsers(0,$maxResult,[ref]$totalUsers)
$users
if($totalUsers -gt $maxResult)
{
throw "-maxResult limit exceeded"
}
}
function global:Reset-MembershipUserPassword($identifier=$(throw "-identifier is required"), $questionAnswer)
{
$provider = $input | select -First 1
if($provider -isnot [System.Web.Security.MembershipProvider])
{
$provider = Get-MembershipProvider
}
$name = $provider.GetUserNameByEmail($identifier)
if($name -ne $null){$identifier = $name}
return $provider.ResetPassword($identifier, $questionAnswer)
}
function global:Get-RoleProvider($providerName=$null, [switch]$all)
{
if($all)
{
return [System.Web.Security.Roles]::Providers
}
if($providerName -eq $null)
{
return [System.Web.Security.Roles]::Provider
}
else
{
return [System.Web.Security.Roles]::Providers[$providerName]
}
}
function global:Get-ProfileProvider($providerName=$null)
{
if($all)
{
return [System.Web.Security.ProfileManager]::Providers
}
if($providerName -eq $null)
{
return [System.Web.Profile.ProfileManager]::Provider
}
else
{
return [System.Web.Profile.ProfileManager]::Providers[$providerName]
}
}
|
PowerShellCorpus/PoshCode/Invoke-ExecuteTSQL _1.ps1
|
Invoke-ExecuteTSQL _1.ps1
|
#######################
<#
.SYNOPSIS
Execute T-SQL Statments and return messages from SQL Server (print).
.DESCRIPTION
Execute T-SQL Statments and return messages from SQL Server (print).
.INPUTS
None
You cannot pipe objects to Invoke-ExecuteTSQL
.OUTPUTS
PSObject :
Boolean Exitcode = $True or $False indicating if the query ran successfully
String ErrorMessage = The ErrorMessage if not ran successfully
String Message = Messages from SQL Server (print)
.EXAMPLE
Invoke-ExecuteTSQL -SQLInstanceName . -DatabaseName YourDB -UserName YourUserName -PassWord YourPassword -Query $Query -verbose
This command runs a T-SQL Query using UserName and Password
.EXAMPLE
Invoke-ExecuteTSQL -SQLInstanceName . -DatabaseName YourDB -Query $Query -verbose
This command runs a T-SQL Query using TrustedConnection
.LINK
Invoke-ExecuteTSQL
#>
function Invoke-ExecuteTSQL {
[cmdletbinding()]
Param(
[Parameter(Position=0,Mandatory = $true)]
[ValidateNotNullorEmpty()]
[string]$SQLInstanceName,
[Parameter(Position=1,Mandatory = $true)]
[ValidateNotNullorEmpty()]
[string]$DatabaseName,
[Parameter(Position=2)]
[string]$UserName,
[Parameter(Position=3)]
[string]$PassWord,
[Parameter(Position=4,Mandatory = $true)]
[ValidateNotNullorEmpty()]
[string]$Query
)
function Get-SQLConnectionEvent($EventID) {
write-output (Get-Event -SourceIdentifier $EventID -ErrorAction SilentlyContinue |
Select -ExpandProperty SourceEventArgs |
Select -ExpandProperty message)
Remove-Event -SourceIdentifier $EventID -ErrorAction SilentlyContinue
}
try {
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
if($Username -and $Password) {
Write-Verbose "Connecting to SQL Server using trusted connection"
$SqlConnection.ConnectionString = "Server=$($SQLInstanceName);Database=$($DatabaseName);Integrated Security=True"
} else {
Write-Verbose "Connecting to SQL Server using Username and Password"
$SqlConnection.ConnectionString = "Server=$($SQLInstanceName);Database=$($DatabaseName);UID=$($Username);PWD=$($Password)"
}
$eventID = "SQLConnectionEvent$(Get-date -format 'yyyyMMddhhmmss')";
write-verbose "Registering the event $eventID"
Register-ObjectEvent -inputObject $SqlConnection -eventName InfoMessage -sourceIdentifier $eventID
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.Connection = $SqlConnection
$SqlCmd.CommandTimeout = 0
$SqlCmd.Connection.Open()
write-verbose "Running the Query"
$SqlCmd.CommandText = $Query
$SqlCmd.ExecuteNonQuery() | Out-Null
$ExitCode = $true
$Message = Get-SQLConnectionEvent $eventID
$ErroMessage = ""
} catch {
$ExitCode = $false
$Message = ""
$ErroMessage = $_.exception
}
Finally {
if ($SqlCmd.Connection.State -eq [System.Data.ConnectionState]::Open) {
write-verbose "Closing Connection"
$SqlCmd.Connection.Close()
$SqlCmd.Connection.Dispose()
}
}
Write-Output (New-Object psobject -Property @{ 'ExitCode' = $ExitCode
'Message' = $Message
'ErrorMessage' =$ErroMessage})
}
|
PowerShellCorpus/PoshCode/Get-SiSReport.ps1
|
Get-SiSReport.ps1
|
Function New-LocalUser
{
<#
.SYNOPSIS
Create a new user account on the local computer.
.DESCRIPTION
This function will create a user account on the local computer.
.PARAMETER Computer
The NetBIOS name of the computer that you will create the account on.
.PARAMETER User
The user name of the account that will be created.
.PARAMETER Password
The password for the account, this must follow password policies enforced
on the destination computer.
.PARAMETER Description
A description of what this account will be used for.
.NOTES
You will need to run this with either UAC disabled or from an elevated prompt.
.EXAMPLE
New-LocalUser -ComputerName MyComputer -User MyUserAccount -Password MyP@ssw0rd -Description "Account."
Description
-----------
Creates a user named MyUserAccount on MyComputer.
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/ComputerManagemenet#New-LocalUser
#>
Param
(
[Parameter(Mandatory=$true)]
[string]$ComputerName = (& hostname),
[Parameter(Mandatory=$true)]
[string]$User,
[Parameter(Mandatory=$true)]
[string]$Password,
[string]$Description
)
Begin
{
}
Process
{
Try
{
$objComputer = [ADSI]("WinNT://$($ComputerName)")
$objUser = $objComputer.Create("User", $User)
$objUser.SetPassword($password)
$objUser.SetInfo()
$objUser.description = $Description
$objUser.SetInfo()
Return $?
}
Catch
{
Return $Error[0].Exception.InnerException.Message.ToString().Trim()
}
}
End
{
}
}
Function Set-Pass
{
<#
.SYNOPSIS
Change the password of an existing user account.
.DESCRIPTION
This function will change the password for an existing user account.
.PARAMETER ComputerName
The NetBIOS name of the computer that you will add the account to.
.PARAMETER UserName
The user name of the account that will be created.
.PARAMETER Password
The password for the account, this must follow password policies enforced
on the destination computer.
.NOTES
You will need to run this with either UAC disabled or from an elevated prompt.
.EXAMPLE
Set-Pass -ComputerName MyComputer -UserName MyUserAccount -Password N3wP@ssw0rd
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/ComputerManagemenet#Set-Pass
#>
Param
(
[Parameter(Mandatory=$true)]
[string]$ComputerName = (& hostname),
[Parameter(Mandatory=$true)]
[string]$UserName,
[Parameter(Mandatory=$true)]
[string]$Password
)
Begin
{
}
Process
{
Try
{
$User = [adsi]("WinNT://$ComputerName/$UserName, user")
$User.psbase.invoke("SetPassword", $Password)
Return "Password updated"
}
Catch
{
Return $Error[0].Exception.InnerException.Message.ToString().Trim()
}
}
End
{
}
}
Function Add-LocalUserToGroup
{
<#
.SYNOPSIS
Add an existing user to a local group.
.DESCRIPTION
This function will add an existing user to an existing group.
.PARAMETER Computer
The NetBIOS name of the computer that you will add the account to.
.PARAMETER User
The user name of the account that will be created.
.PARAMETER Group
The name of an existing group to add this user to.
.NOTES
You will need to run this with either UAC disabled or from an elevated prompt.
.EXAMPLE
Add-LocalUserToGroup -ComputerName MyComputer -User MyUserAccount -Group Administrators
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/ComputerManagemenet#Add-LocalUserToGroup
#>
Param
(
[Parameter(Mandatory=$true)]
[string]$ComputerName = (& hostname),
[Parameter(Mandatory=$true)]
[string]$User,
[Parameter(Mandatory=$true)]
[string]$Group
)
Begin
{
}
Process
{
Try
{
$objComputer = [ADSI]("WinNT://$($ComputerName)/$($Group),group")
$objComputer.add("WinNT://$($ComputerName)/$($User),group")
Return $?
}
Catch
{
Return $Error[0].Exception.InnerException.Message.ToString().Trim()
}
}
End
{
}
}
Function New-ScheduledTask
{
<#
.SYNOPSIS
Create a Scheduled Task on a computer.
.DESCRIPTION
Create a Scheduled Task on a local or remote computer.
.PARAMETER TaskName
Specifies a name for the task.
.PARAMETER TaskRun
Specifies the program or command that the task runs. Type
the fully qualified path and file name of an executable file,
script file, or batch file. If you omit the path, SchTasks.exe
assumes that the file is in the Systemroot\\System32 directory.
.PARAMETER TaskSchedule
Specifies the schedule type. Valid values are
MINUTE
HOURLY
DAILY
WEEKLY
MONTHLY
ONCE
ONSTART
ONLOGON
ONIDLE
.PARAMETER StartTime
Specifies the time of day that the task starts in HH:MM:SS 24-hour
format. The default value is the current local time when the command
completes. The /st parameter is valid with MINUTE, HOURLY, DAILY,
WEEKLY, MONTHLY, and ONCE schedules. It is required with a ONCE
schedule.
.PARAMETER StartDate
Specifies the date that the task starts in MM/DD/YYYY format. The
default value is the current date. The /sd parameter is valid with all
schedules, and is required for a ONCE schedule.
.PARAMETER TaskUser
Runs the tasks with the permission of the specified user account. By
default, the task runs with the permissions of the user logged on to the
computer running SchTasks.
.PARAMETER Server
The NetBIOS name of the computer to create the scheduled task on.
.NOTES
You will need to run this with either UAC disabled or from an elevated prompt.
The full syntax of the command can be found here:
http://technet.microsoft.com/en-us/library/bb490996.aspx
.EXAMPLE
New-ScheduledTask -TaskName "Reboot Computer" -TaskRun "shutdown /r" -TaskSchedule ONCE `
-StartTime "18:00:00" -StartDate "03/16/2011" -TaskUser SYSTEM -Server MyDesktopPC
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/ComputerManagemenet#New-ScheduledTask
#>
Param
(
[Parameter(Mandatory=$true)]
[string]$TaskName,
[Parameter(Mandatory=$true)]
[string]$TaskRun,
[Parameter(Mandatory=$true)]
[string]$TaskSchedule,
[Parameter(Mandatory=$true)]
[string]$StartTime,
[Parameter(Mandatory=$true)]
[string]$StartDate,
[Parameter(Mandatory=$true)]
[string]$TaskUser,
[Parameter(Mandatory=$true)]
[string]$Server
)
schtasks /create /tn $TaskName /tr $TaskRun /sc $TaskSchedule /st $StartTime /sd $StartDate /ru $TaskUser /s $Server
}
Function Remove-UserFromLocalGroup
{
<#
.SYNOPSIS
Removes a user/group from a local computer group.
.DESCRIPTION
Removes a user/group from a local computer group.
.PARAMETER Computer
Name of the computer to connect to.
.PARAMETER User
Name of the user or group to remove.
.PARAMETER GroupName
Name of the group where that the user/group is a member of.
.NOTES
You will need to run this with either UAC disabled or from an elevated prompt.
.EXAMPLE
Remove-UserFromLocalGroup -ComputerName MyComputer -UserName RandomUser
Description
-----------
This example removes a user from the local administrators group.
.Example
Remove-UserFromLocalGroup -ComputerName MyComputer -UserName RandomUser -GroupName Users
Description
-----------
This example removes a user from the local users group.
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/ComputerManagemenet#Remove-UserFromLocalGroup
#>
Param
(
[Parameter(Mandatory=$true)]
[string]$ComputerName = (& hostname),
[Parameter(Mandatory=$true)]
[string]$UserName,
[Parameter(Mandatory=$true)]
[string]$GroupName="Administrators"
)
$Group = $Computer.psbase.children.find($GroupName)
$Group.Remove("WinNT://$Computer/$User")
}
Function Get-Services
{
<#
.SYNOPSIS
Get a list of services
.DESCRIPTION
This function returns a list of services on a given computer. This list can be filtered based on the
given StartMode (ie. Running, Stopped) as well as filtered on StartMode (ie. Auto, Manual).
.PARAMETER State
Most often this will be either Running or Stopped, but possible values include
Running
Stopped
Paused
.PARAMETER StartMode
Most often this will be either Auto or Manual, but possible values include
Auto
Manual
Disabled
.PARAMETER Computer
The NetBIOS name of the computer to retrieve services from
.NOTES
Depending on how you are setup you may need to provide credentials in order to access remote machines
You may need to have UAC disabled or run PowerShell as an administrator to see services locally
.EXAMPLE
Get-Services |Format-Table -AutoSize
ExitCode Name ProcessId StartMode State Status
-------- ---- --------- --------- ----- ------
0 atashost 1380 Auto Running OK
0 AudioEndpointBuilder 920 Auto Running OK
0 AudioSrv 880 Auto Running OK
0 BFE 1236 Auto Running OK
0 BITS 964 Auto Running OK
0 CcmExec 2308 Auto Running OK
0 CryptSvc 1088 Auto Running OK
Description
-----------
This example shows the default options in place
.EXAMPLE
Get-Services -State "stopped" |Format-Table -AutoSize
ExitCode Name ProcessId StartMode State Status
-------- ---- --------- --------- ----- ------
0 AppHostSvc 0 Auto Stopped OK
0 clr_optimization_v4.0.30319_32 0 Auto Stopped OK
0 clr_optimization_v4.0.30319_64 0 Auto Stopped OK
0 MMCSS 0 Auto Stopped OK
0 Net Driver HPZ12 0 Auto Stopped OK
0 Pml Driver HPZ12 0 Auto Stopped OK
0 sppsvc 0 Auto Stopped OK
Description
-----------
This example shows the output when specifying the state parameter
.EXAMPLE
Get-Services -State "stopped" -StartMode "disabled" |Format-Table -AutoSize
ExitCode Name ProcessId StartMode State Status
-------- ---- --------- --------- ----- ------
1077 clr_optimization_v2.0.50727_32 0 Disabled Stopped OK
1077 clr_optimization_v2.0.50727_64 0 Disabled Stopped OK
1077 CscService 0 Disabled Stopped OK
1077 Mcx2Svc 0 Disabled Stopped OK
1077 MSSQLServerADHelper100 0 Disabled Stopped OK
1077 NetMsmqActivator 0 Disabled Stopped OK
1077 NetPipeActivator 0 Disabled Stopped OK
Description
-----------
This example shows how to specify a different state and startmode.
.EXAMPLE
Get-Services -Computer dpm -Credential "Domain\\Administrator" |Format-Table -AutoSize
ExitCode Name ProcessId StartMode State Status
-------- ---- --------- --------- ----- ------
0 AppHostSvc 1152 Auto Running OK
0 BFE 564 Auto Running OK
0 CryptSvc 1016 Auto Running OK
0 DcomLaunch 600 Auto Running OK
0 Dhcp 776 Auto Running OK
0 Dnscache 1016 Auto Running OK
0 DPMAMService 1184 Auto Running OK
Description
-----------
This example shows how to specify a remote computer and credentials to authenticate with.
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/ComputerManagemenet#Get-Services
#>
Param
(
[string]$Computer = (& hostname),
$Credential,
[string]$State = "Running",
[string]$StartMode = "Auto"
)
If ($Computer -eq (& hostname))
{
$Services = Get-WmiObject win32_service -filter "State = '$State' and StartMode = '$StartMode'"
}
Else
{
If ($Credential -eq $null)
{
$Credential = Get-Credential
}
$Services = Get-WmiObject win32_service -filter "State = '$State' and StartMode = '$StartMode'" `
-ComputerName $Computer -Credential $Credential
}
Return $Services
}
Function Get-NonStandardServiceAccounts()
{
<#
.SYNOPSIS
Return a list of services using Non-Standard accounts.
.DESCRIPTION
This function returns a list of services from local or remote coputers that have non-standard
user accounts for logon credentials.
.PARAMETER Computer
The NetBIOS name of the computer to pull services from.
.PARAMETER Credentials
The DOMAIN\\USERNAME of an account with permissions to access services.
.PARAMETER Filter
This is a pipe (|) seperated list of accounts to filter out of the returned services list.
.EXAMPLE
Get-NonStandardServiceAccounts
StartName Name DisplayName
--------- ---- -----------
.\\Jeff Patton MyService My Test Service
Description
-----------
This example shows no parameters provided
.EXAMPLE
Get-NonStandardServiceAccounts -Computer dpm -Credentials $Credentials
StartName Name DisplayName
--------- ---- -----------
.\\MICROSOFT$DPM$Acct MSSQL$MS$DPM2007$ SQL Server (MS$DPM2007$)
.\\MICROSOFT$DPM$Acct MSSQL$MSDPM2010 SQL Server (MSDPM2010)
NT AUTHORITY\\NETWORK SERVICE MSSQLServerADHelper100 SQL Active Directory Helper S...
NT AUTHORITY\\NETWORK SERVICE ReportServer$MSDPM2010 SQL Server Reporting Services...
.\\MICROSOFT$DPM$Acct SQLAgent$MS$DPM2007$ SQL Server Agent (MS$DPM2007$)
.\\MICROSOFT$DPM$Acct SQLAgent$MSDPM2010 SQL Server Agent (MSDPM2010)
Description
-----------
This example shows all parameters in use
.EXAMPLE
Get-NonStandardServiceAccounts -Computer dpm -Credentials $Credentials `
-Filter "localsystem|NT Authority\\LocalService|NT Authority\\NetworkService|NT AUTHORITY\\NETWORK SERVICE"
StartName Name DisplayName
--------- ---- -----------
.\\MICROSOFT$DPM$Acct MSSQL$MS$DPM2007$ SQL Server (MS$DPM2007$)
.\\MICROSOFT$DPM$Acct MSSQL$MSDPM2010 SQL Server (MSDPM2010)
.\\MICROSOFT$DPM$Acct SQLAgent$MS$DPM2007$ SQL Server Agent (MS$DPM2007$)
.\\MICROSOFT$DPM$Acct SQLAgent$MSDPM2010 SQL Server Agent (MSDPM2010)
Description
-----------
This example uses the Filter parameter to filter out NT AUTHORITY\\NETWORK SERVICE account from the
preceeding example.
The back-tick (`) was used for readability purposes only.
.NOTES
Powershell may need to be run elevated to run this script.
UAC may need to be disabled to run this script.
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/ComputerManagemenet#Get-NonStandardServiceAccounts
#>
Param
(
[string]$Computer = (& hostname),
$Credentials,
[string]$Filter = "localsystem|NT Authority\\LocalService|NT Authority\\NetworkService"
)
$Filter = $Filter.Replace("\\","\\\\")
If ($Computer -eq (& hostname))
{
$Services = Get-WmiObject win32_service |Select-Object __Server, StartName, Name, DisplayName
}
Else
{
$Result = Test-Connection -Count 1 -Computer $Computer -ErrorAction SilentlyContinue
If ($result -ne $null)
{
$Services = Get-WmiObject win32_service -ComputerName $Computer -Credential $Credentials `
|Select-Object __Server, StartName, Name, DisplayName
}
Else
{
# Should do something with unreachable computers here.
}
}
$Suspect = $Services |Where-Object {$_.StartName -notmatch $Filter}
Return $Suspect
}
Function Remove-LocalUser
{
<#
.SYNOPSIS
Delete a user account from the local computer.
.DESCRIPTION
This function will delete a user account from the local computer
.PARAMETER ComputerName
The NetBIOS name of the computer the account is found on
.PARAMETER UserName
The username to delete
.EXAMPLE
Remove-LocalUser -ComputerName Desktop -UserName TestAcct
Description
-----------
Basic syntax of the command.
.NOTES
The user context the script is run under must be able to delete accounts on the remote computer
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/ComputerManagemenet#Remove-LocalUser
#>
Param
(
[Parameter(Mandatory=$true)]
$ComputerName = (& hostname),
[Parameter(Mandatory=$true)]
$UserName
)
$isAlive = Test-Connection -ComputerName $ComputerName -Count 1 -ErrorAction SilentlyContinue
if ($isAlive -ne $null)
{
$ADSI = [adsi]"WinNT://$ComputerName"
$Users = $ADSI.psbase.children |Where-Object {$_.psBase.schemaClassName -eq "User"} |Select-Object -ExpandProperty Name
foreach ($User in $Users)
{
if ($User -eq $UserName)
{
$ADSI.Delete("user", $UserName)
$Return = "Deleted"
}
else
{
$Return = "User not found"
}
}
}
else
{
$Return = "$ComputerName not available"
}
Return $Return
}
Function Get-LocalUserAccounts
{
<#
.SYNOPSIS
Return a list of local user accounts.
.DESCRIPTION
This function returns the Name and SID of any local user accounts that are found
on the remote computer.
.PARAMETER ComputerName
The NetBIOS name of the remote computer
.EXAMPLE
Get-LocalUserAccounts -ComputerName Desktop-PC01
Name SID
---- ---
Administrator S-1-5-21-1168524473-3979117187-4153115970-500
Guest S-1-5-21-1168524473-3979117187-4153115970-501
Description
-----------
This example shows the basic usage
.EXAMPLE
Get-LocalUserAccounts -ComputerName citadel -Credentials $Credentials
Name SID
---- ---
Administrator S-1-5-21-1168524473-3979117187-4153115970-500
Guest S-1-5-21-1168524473-3979117187-4153115970-501
Description
-----------
This example shows using the optional Credentials variable to pass administrator credentials
.NOTES
You will need to provide credentials when running this against computers in a diffrent domain.
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/ComputerManagemenet#Get-LocalUserAccounts
#>
Param
(
[string]$ComputerName = (& hostname),
[System.Management.Automation.PSCredential]$Credentials
)
$Filter = "LocalAccount=True"
$ScriptBlock = "Get-WmiObject Win32_UserAccount -Filter $Filter"
$isAlive = Test-Connection -ComputerName $ComputerName -Count 1 -ErrorAction SilentlyContinue
if ($isAlive -ne $null)
{
$ScriptBlock += " -ComputerName $ComputerName"
if ($Credentials)
{
if ($isAlive.__SERVER.ToString() -eq $ComputerName)
{}
else
{
$ScriptBlock += " -Credential `$Credentials"
}
}
}
else
{
Return "Unable to connect to $ComputerName"
}
Return Invoke-Expression $ScriptBlock |Select-Object Name, SID
}
Function Get-PendingUpdates
{
<#
.SYNOPSIS
Retrieves the updates waiting to be installed from WSUS
.DESCRIPTION
Retrieves the updates waiting to be installed from WSUS
.PARAMETER ComputerName
Computer or computers to find updates for.
.EXAMPLE
Get-PendingUpdates
Description
-----------
Retrieves the updates that are available to install on the local system
.NOTES
Author: Boe Prox
Date Created: 05Mar2011
RPC Dynamic Ports need to be enabled on inbound remote servers.
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/ComputerManagemenet#Get-PendingUpdates
#>
Param
(
[Parameter(ValueFromPipeline = $True)]
[string]$ComputerName
)
Begin
{
}
Process
{
ForEach ($Computer in $ComputerName)
{
If (Test-Connection -ComputerName $Computer -Count 1 -Quiet)
{
Try
{
$Updates = [activator]::CreateInstance([type]::GetTypeFromProgID("Microsoft.Update.Session",$Computer))
$Searcher = $Updates.CreateUpdateSearcher()
$searchresult = $Searcher.Search("IsInstalled=0")
}
Catch
{
Write-Warning "$($Error[0])"
Break
}
}
}
}
End
{
Return $SearchResult.Updates
}
}
Function Get-ServiceTag
{
<#
.SYNOPSIS
Get the serial number (Dell ServiceTag) from Win32_BIOS
.DESCRIPTION
This function grabs the SerialNumber property from Win32_BIOS for the
provided ComputerName
.PARAMETER ComputerName
The NetBIOS name of the computer.
.EXAMPLE
Get-ServiceTag -ComputerName Desktop-01
SerialNumber
------------
1AB2CD3
Description
-----------
An example showing the only parameter.
.NOTES
This space intentionally left blank.
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/ComputerManagemenet#Get-ServiceTag
#>
Param
(
$ComputerName
)
Begin
{
$ErrorActionPreference = "SilentlyContinue"
}
Process
{
Try
{
$null = Test-Connection -ComputerName $ComputerName -Count 1 -quiet
$Return = New-Object PSObject -Property @{
ComputerName = $ComputerName
SerialNumber = (Get-WmiObject -Class Win32_BIOS -ComputerName $ComputerName -Credential $Credentials).SerialNumber
}
}
Catch
{
$Return = New-Object PSObject -Property @{
ComputerName = $ComputerName
SerialNumber = "Offline"
}
}
}
End
{
Return $Return
}
}
Function Backup-EventLogs
{
<#
.SYNOPSIS
Backup Eventlogs from remote computer
.DESCRIPTION
This function copies event log files from a remote computer to a backup location.
.PARAMETER ComputerName
The NetBIOS name of the computer to connect to.
.PARAMETER LogPath
The path to the logs you wish to backup. The default logpath "C:\\Windows\\system32\\winevt\\Logs"
is used if left blank.
.PARAMETER BackupPath
The location to copy the logs to.
.EXAMPLE
Backup-EventLogs -ComputerName dc1
.NOTES
May need to be a user with rights to access various logs, such as security on remote computer.
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/ComputerManagemenet#Backup-EventLogs
#>
Param
(
[string]$ComputerName,
[string]$LogPath = "C:\\Windows\\system32\\winevt\\Logs",
[string]$BackupPath = "C:\\Logs"
)
Begin
{
$EventLogs = "\\\\$($Computername)\\$($LogPath.Replace(":","$"))"
If ((Test-Path $BackupPath) -ne $True)
{
New-Item $BackupPath -Type Directory |Out-Null
}
}
Process
{
Try
{
Copy-Item $EventLogs -Destination $BackupPath -Recurse
}
Catch
{
Return $Error
}
}
End
{
Return $?
}
}
Function Export-EventLogs
{
<#
.SYNOPSIS
Export Eventlogs from remote computer
.DESCRIPTION
This function backs up all logs on a Windows computer that have events written in them. This
log is stored as a .csv file in the current directory, where the filename is the ComputerName+
Logname+Date+Time the backup was created.
.PARAMETER ComputerName
The NetBIOS name of the computer to connect to.
.EXAMPLE
Export-EventLogs -ComputerName dc1
.NOTES
May need to be a user with rights to access various logs, such as security on remote computer.
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/ComputerManagemenet#Export-EventLogs
#>
Param
(
[string]$ComputerName
)
Begin
{
$EventLogs = Get-WinEvent -ListLog * -ComputerName $ComputerName
}
Process
{
Foreach ($EventLog in $EventLogs)
{
If ($EventLog.RecordCount -gt 0)
{
$LogName = ($EventLog.LogName).Replace("/","-")
$BackupFilename = "$($ComputerName)-$($LogName)-"+(Get-Date -format "yyy-MM-dd HH-MM-ss").ToString()+".csv"
Get-WinEvent -LogName $EventLog.LogName -ComputerName $ComputerName |Export-Csv -Path ".\\$($BackupFilename)"
}
}
}
End
{
Return $?
}
}
Function Get-SiSReport
{
<#
.SYNOPSIS
Get the overall SIS usage information.
.DESCRIPTION
This function uses the sisadmin command to get the usage
information for a SIS enabled drive.
.PARAMETER SisDisk
The drive letter of a disk that has SiS enabled
.EXAMPLE
Get-SiSReport -SisDisk o
LinkFiles : 20004
Used : 442378481664
Disk : o
InaccessibleLinkFiles : 0
CommonStoreFiles : 6678
SpaceSaved : 7708860 KB
Free : 0
Description
-----------
This example shows the basic usage of the command
.NOTES
This function will return nothing if the drive being analyzed does not have SiS enabled
This function will return a message if the sisadmin command returns any error
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/ComputerManagemenet#Get-SiSReport
#>
Param
(
$SisDisk = "c"
)
Begin
{
$SisAdmin = "& sisadmin /v $($SisDisk):"
Try
{
$SisResult = Invoke-Expression $SisAdmin
}
Catch
{
Return "Single Instance Storage is not available on this computer"
}
}
Process
{
If ($SisResult.Count)
{
$ThisDisk = Get-PSDrive $SisDisk
$SisReport = New-Object -TypeName PSObject -Property @{
Disk = $SisDisk
Used = $ThisDisk.Used
Free = $ThisDisk.Free
CommonStoreFiles = ($SisResult[($SisResult.Count)-4]).TrimStart("Common store files:")
LinkFiles = ($SisResult[($SisResult.Count)-3]).TrimStart("Link files:")
InaccessibleLinkFiles = ($SisResult[($SisResult.Count)-2]).TrimStart("Inaccessible link files:")
SpaceSaved = ($SisResult[($SisResult.Count)-1]).TrimStart("Space saved:")
}
}
}
End
{
Return $SisReport
}
}
|
PowerShellCorpus/PoshCode/Remove-XmlNamespace.ps1
|
Remove-XmlNamespace.ps1
|
function Remove-XmlNamespace {
#.Synopsis
# Removes namespace definitions and prefixes from xml documents
#.Description
# Runs an xml document through an XSL Transformation to remove namespaces from it if they exist.
# Entities are also naturally expanded
#.Parameter Content
# Specifies a string that contains the XML to transform.
#.Parameter Path
# Specifies the path and file names of the XML files to transform. Wildcards are permitted.
#
# There will bne one output document for each matching input file.
#.Parameter Xml
# Specifies one or more XML documents to transform
#
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(ParameterSetName="Content",Mandatory=$true)]
[String[]]$Content
,
[Parameter(Position=0,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[String[]]$Path
,
[Parameter(Position=0,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true)]
[Alias("IO","InputObject")]
[System.Xml.XmlDocument[]]$Xml
)
BEGIN {
$xslt = New-Object System.Xml.Xsl.XslCompiledTransform
$xslt.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader @"
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/|comment()|processing-instruction()">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
"@))))
}
PROCESS {
switch($PSCmdlet.ParameterSetName) {
"Content" {
[System.Xml.XmlDocument[]]$Xml = @( [Xml]($Content -Join "`n") )
}
"Path" {
[System.Xml.XmlDocument[]]$Xml = @()
foreach($file in Get-ChildItem $Path) {
$Xml += [Xml](Get-Content $file)
}
}
"Xml" {
}
}
foreach($input in $Xml) {
$Output = New-Object System.Xml.XmlDocument
$writer =$output.CreateNavigator().AppendChild()
$xslt.Transform( $input.CreateNavigator(), $null, $writer )
$writer.Close() # $writer.Dispose()
Write-Output $output
}
}
}
|
PowerShellCorpus/PoshCode/28fbc2a5-866d-4bb2-8d93-78099b503621.ps1
|
28fbc2a5-866d-4bb2-8d93-78099b503621.ps1
|
function cpu-usage
{ if ($Args)
{$machine=$Args}
else
{$machine="localhost"}
#loop to refresh information cpu usage
while($auxiliary -ne 'Q')
{
#first sample of processes
$before = gwmi win32_perfrawdata_perfproc_process -ComputerName $machine
sleep -Milliseconds (100)
#second sample of processes
$after = gwmi win32_perfrawdata_perfproc_process -ComputerName $machine
#hash list with the difference of two samples
$difference = @{}
#array with cpu percentage for each process
$result = @{}
#compare two samples and store difference in $difference["processname"]
foreach ($process_before in $before)
{ foreach ($process_after in $after)
{ if ($process_after.name -eq $process_before.name)
{$difference_process = [long]$process_after.percentprocessortime -[long]$process_before.percentprocessortime
$difference[$process_before.name] = $difference_process
}
}
}
#total cpu time
$sum = $difference["_Total"]
#with all processes, we calculate percentaje
foreach ($i in $difference.keys)
{$result[$i] = ((($difference.$i)/$sum)*100)
}
#sort array descending
$result= (($result.GetEnumerator() | sort value -Descending)[1..10])
Clear-Host
Write-Host ""
Write-Host "press Q to quit, another key to refresh"
format-table -AutoSize -InputObject $result @{Label= "Name:"; Expression = {$_.name}},`
@{Label = "percentaje CPU"; Expression= {"{0:n2}" -f ($_.Value)}}
$auxiliary = $Host.UI.RawUI.ReadKey()
$auxiliary = [string]$auxiliary.character
$auxiliary=$auxiliary.toupper()
}
}
|
PowerShellCorpus/PoshCode/FuncionInfo.types.ps1xml.ps1
|
FuncionInfo.types.ps1xml.ps1
|
<?xml version="1.0" encoding="utf-8" ?>
<Types>
<Type>
<Name>System.Management.Automation.FunctionInfo</Name>
<Members>
<ScriptProperty>
<Name>Verb</Name>
<GetScriptBlock>
if ($this.Name.Contains("-")) {
$this.Name.Substring(0,$this.Name.Indexof("-"))
} else {
$null
}
</GetScriptBlock>
</ScriptProperty>
<ScriptProperty>
<Name>Noun</Name>
<GetScriptBlock>
if ($this.Name.Contains("-")){
$this.Name.Substring(($this.Name.Indexof("-")+1),($this.Name.length - ($this.Name.Indexof("-")+1)))
} else {
$this.Name
}
</GetScriptBlock>
</ScriptProperty>
<ScriptProperty>
<Name>Prefix</Name>
<GetScriptBlock>
$prefix_val = $((gmo $this.Module).ExportedCommands.Values + (gcm -mo $this.ModuleName) |
where { $_.Verb -eq $this.Verb } |
group {
if($_.ImplementingType){
$_.ImplementingType
}else{
$_.Definition
}
} |
% {
$names = $_.Group |
Select -Expand Name;
$ofs = "-";
$verb,[string]$noun = @($names)[0] -split "-";
foreach($name in $names){
if ( $name.contains("-") ) {
$name.substring($name.IndexOf("-") + 1, $name.LastIndexOf($noun) - $name.IndexOf("-") - 1 )
}
}
} | where {$_} | select -unique | foreach { $_ | where {$this.Noun -match $_ } })
if ( $prefix_val ) {
$prefix_val
} else {
$null
}
</GetScriptBlock>
</ScriptProperty>
<ScriptProperty>
<Name>InternalName</Name>
<GetScriptBlock>
$prefix = $this.Prefix
if ($prefix) {
"$($this.Verb)-$($this.Noun.Replace($prefix, $null))"
} else {
"$($this.Name)"
}
</GetScriptBlock>
</ScriptProperty>
</Members>
</Type>
</Types>
|
PowerShellCorpus/PoshCode/New-BootsGadget.ps1
|
New-BootsGadget.ps1
|
New-BootsGadget {
#.Synopsis
# Create desktop gadgets with no window chrome
#.Description
# Provides a wrapper for generating gadget windows with PowerBoots. It adds two parameters to the usual New-PowerBoots command: RefreshRate and On_Refresh.
#
# Gadget windows are created with AllowsTransparency, Background = Transparent, and WindowStyle = None (among other things) and provide an automatic timer for updating the window contents, and support dragging with the mouse anywhere on the window.
#.Param Content
# The PowerBoots content of the gadget
#.Param RefreshRate
# The timespan to wait between refreshes, like "0:0:0.5" for 5 seconds
#.Param On_Refresh
# The scriptblock to execute for each refresh.
[CmdletBinding(DefaultParameterSetName='DataTemplate')]
param (
[Parameter(ParameterSetName='DataTemplate', Mandatory=$False, Position=0)]
[ScriptBlock]
${Content},
[Parameter(Mandatory=$True, Position=1)]
[TimeSpan][Alias("Rate","Interval")]
${RefreshRate},
[Parameter(Mandatory=$True, Position=2)]
[ScriptBlock]
${On_Refresh},
[Parameter(ParameterSetName='FileTemplate', Mandatory=$true, Position=0, HelpMessage='XAML template file')]
[System.IO.FileInfo]
${FileTemplate},
[Parameter(ParameterSetName='SourceTemplate', Mandatory=$true, Position=0, HelpMessage='XAML template XmlDocument')]
[System.Xml.XmlDocument]
${SourceTemplate},
[Parameter(HelpMessage='Do not show in a popup Window (currently only works on PoshConsole)')]
[Switch]
${Inline},
[Parameter(HelpMessage='Write out the window')]
[Switch]
${Passthru},
[Switch]
${AllowDrop},
[Switch]
${NoTransparency},
[Switch]
${ClipToBounds},
[Switch]
${Focusable},
[Switch]
${ForceCursor},
[Switch]
${IsEnabled},
[Switch]
${IsHitTestVisible},
[Switch]
${IsTabStop},
[Switch]
${OverridesDefaultStyle},
[Switch]
${ShowActivated},
[Switch]
${ShowInTaskbar},
[Switch]
${SnapsToDevicePixels},
[Switch]
${Topmost},
[Switch]
${DialogResult},
[PSObject]
${FontSize},
[PSObject]
${Height},
[PSObject]
${Left},
[PSObject]
${MaxHeight},
[PSObject]
${MaxWidth},
[PSObject]
${MinHeight},
[PSObject]
${MinWidth},
[PSObject]
${Opacity},
[PSObject]
${Top},
[PSObject]
${Width},
[PSObject]
${TabIndex},
[System.Object]
${DataContext},
[System.Object]
${ToolTip},
[System.String]
${ContentStringFormat},
[System.String]
${Name},
[System.String]
${Title},
[System.String]
${Uid},
[PSObject]
${ContextMenu},
[PSObject]
${Template},
[PSObject]
${ContentTemplateSelector},
[PSObject]
${BindingGroup},
[PSObject]
${ContentTemplate},
[PSObject]
${FlowDirection},
[PSObject]
${FontStretch},
[PSObject]
${FontStyle},
[PSObject]
${FontWeight},
[PSObject]
${HorizontalAlignment},
[PSObject]
${HorizontalContentAlignment},
[PSObject]
${CommandBindings},
[PSObject]
${Cursor},
[PSObject[]]
${InputBindings},
[PSObject]
${InputScope},
[PSObject]
${Language},
[PSObject]
${BorderBrush},
[PSObject]
${Foreground},
[PSObject]
${OpacityMask},
[PSObject]
${BitmapEffect},
[PSObject]
${BitmapEffectInput},
[PSObject]
${Effect},
[PSObject]
${FontFamily},
[PSObject]
${Clip},
[PSObject]
${Icon},
[PSObject]
${LayoutTransform},
[PSObject]
${RenderTransform},
[PSObject]
${RenderTransformOrigin},
[PSObject]
${Resources},
[PSObject]
${RenderSize},
[PSObject]
${SizeToContent},
[PSObject]
${FocusVisualStyle},
[PSObject]
${Style},
[PSObject]
${BorderThickness},
[PSObject]
${Margin},
[PSObject]
${Padding},
[PSObject]
${Triggers},
[PSObject]
${VerticalAlignment},
[PSObject]
${VerticalContentAlignment},
[PSObject]
${Visibility},
[PSObject]
${Owner},
[PSObject]
${WindowStartupLocation},
[PSObject]
${On_Closing},
[PSObject]
${On_Activated},
[PSObject]
${On_Closed},
[PSObject]
${On_ContentRendered},
[PSObject]
${On_Deactivated},
[PSObject]
${On_Initialized},
[PSObject]
${On_LayoutUpdated},
[PSObject]
${On_LocationChanged},
[PSObject]
${On_StateChanged},
[PSObject]
${On_SourceUpdated},
[PSObject]
${On_TargetUpdated},
[PSObject]
${On_ContextMenuClosing},
[PSObject]
${On_ContextMenuOpening},
[PSObject]
${On_ToolTipClosing},
[PSObject]
${On_ToolTipOpening},
[PSObject]
${On_DataContextChanged},
[PSObject]
${On_FocusableChanged},
[PSObject]
${On_IsEnabledChanged},
[PSObject]
${On_IsHitTestVisibleChanged},
[PSObject]
${On_IsKeyboardFocusedChanged},
[PSObject]
${On_IsKeyboardFocusWithinChanged},
[PSObject]
${On_IsMouseCapturedChanged},
[PSObject]
${On_IsMouseCaptureWithinChanged},
[PSObject]
${On_IsMouseDirectlyOverChanged},
[PSObject]
${On_IsStylusCapturedChanged},
[PSObject]
${On_IsStylusCaptureWithinChanged},
[PSObject]
${On_IsStylusDirectlyOverChanged},
[PSObject]
${On_IsVisibleChanged},
[PSObject]
${On_DragEnter},
[PSObject]
${On_DragLeave},
[PSObject]
${On_DragOver},
[PSObject]
${On_Drop},
[PSObject]
${On_PreviewDragEnter},
[PSObject]
${On_PreviewDragLeave},
[PSObject]
${On_PreviewDragOver},
[PSObject]
${On_PreviewDrop},
[PSObject]
${On_GiveFeedback},
[PSObject]
${On_PreviewGiveFeedback},
[PSObject]
${On_GotKeyboardFocus},
[PSObject]
${On_LostKeyboardFocus},
[PSObject]
${On_PreviewGotKeyboardFocus},
[PSObject]
${On_PreviewLostKeyboardFocus},
[PSObject]
${On_KeyDown},
[PSObject]
${On_KeyUp},
[PSObject]
${On_PreviewKeyDown},
[PSObject]
${On_PreviewKeyUp},
[PSObject]
${On_MouseDoubleClick},
[PSObject]
${On_MouseDown},
[PSObject]
${On_MouseLeftButtonUp},
[PSObject]
${On_MouseRightButtonDown},
[PSObject]
${On_MouseRightButtonUp},
[PSObject]
${On_MouseUp},
[PSObject]
${On_PreviewMouseDoubleClick},
[PSObject]
${On_PreviewMouseDown},
[PSObject]
${On_PreviewMouseLeftButtonDown},
[PSObject]
${On_PreviewMouseLeftButtonUp},
[PSObject]
${On_PreviewMouseRightButtonDown},
[PSObject]
${On_PreviewMouseRightButtonUp},
[PSObject]
${On_PreviewMouseUp},
[PSObject]
${On_GotMouseCapture},
[PSObject]
${On_LostMouseCapture},
[PSObject]
${On_MouseEnter},
[PSObject]
${On_MouseLeave},
[PSObject]
${On_MouseMove},
[PSObject]
${On_PreviewMouseMove},
[PSObject]
${On_MouseWheel},
[PSObject]
${On_PreviewMouseWheel},
[PSObject]
${On_QueryCursor},
[PSObject]
${On_PreviewStylusButtonDown},
[PSObject]
${On_PreviewStylusButtonUp},
[PSObject]
${On_StylusButtonDown},
[PSObject]
${On_StylusButtonUp},
[PSObject]
${On_PreviewStylusDown},
[PSObject]
${On_StylusDown},
[PSObject]
${On_GotStylusCapture},
[PSObject]
${On_LostStylusCapture},
[PSObject]
${On_PreviewStylusInAirMove},
[PSObject]
${On_PreviewStylusInRange},
[PSObject]
${On_PreviewStylusMove},
[PSObject]
${On_PreviewStylusOutOfRange},
[PSObject]
${On_PreviewStylusUp},
[PSObject]
${On_StylusEnter},
[PSObject]
${On_StylusInAirMove},
[PSObject]
${On_StylusInRange},
[PSObject]
${On_StylusLeave},
[PSObject]
${On_StylusMove},
[PSObject]
${On_StylusOutOfRange},
[PSObject]
${On_StylusUp},
[PSObject]
${On_PreviewStylusSystemGesture},
[PSObject]
${On_StylusSystemGesture},
[PSObject]
${On_PreviewTextInput},
[PSObject]
${On_TextInput},
[PSObject]
${On_PreviewQueryContinueDrag},
[PSObject]
${On_QueryContinueDrag},
[PSObject]
${On_RequestBringIntoView},
[PSObject]
${On_GotFocus},
[PSObject]
${On_Loaded},
[PSObject]
${On_LostFocus},
[PSObject]
${On_Unloaded},
[PSObject]
${On_SizeChanged}
)
PROCESS {
# We need to get rid of these before we pass this on
$null = $PSBoundParameters.Remove("RefreshRate")
$null = $PSBoundParameters.Remove("On_Refresh")
$PSBoundParameters["AllowsTransparency"] = New-Object "Switch" $true
$PSBoundParameters["Async"] = New-Object "Switch" $true
$PSBoundParameters["WindowStyle"] = "None"
$PSBoundParameters["Background"] = "Transparent"
$PSBoundParameters["On_MouseLeftButtonDown"] = { $this.DragMove() }
$PSBoundParameters["On_Closing"] = { $this.Tag["Timer"].Stop() }
$PSBoundParameters["Tag"] = @{"UpdateBlock"=$On_Refresh; "Interval"= $RefreshRate}
$PSBoundParameters["On_SourceInitialized"] = {
$this.Tag["Temp"] = {
$this.Interval = [TimeSpan]$this.Tag.Tag.Interval
$this.Remove_Tick( $this.Tag.Tag.Temp )
}
$this.Tag["Timer"] = DispatcherTimer -Interval "0:0:02" -On_Tick $this.Tag.UpdateBlock -Tag $this
$this.Tag["Timer"].Add_Tick( $this.Tag.Temp )
$this.Tag["Timer"].Start()
}
$PSBoundParameters["ResizeMode"] = "NoResize"
$PSBoundParameters["Passthru"] = $True
$Window = New-BootsWindow @PSBoundParameters
if($Window) { [Huddled.Dwm]::RemoveFromAeroPeek( $Window.Handle ) }
if($Passthru) { Write-Output $Window }
}
BEGIN {
try {
$null = [Huddled.DWM]
} catch {
Add-Type -Type @"
using System;
using System.Runtime.InteropServices;
namespace Huddled {
public static class Dwm {
[DllImport("dwmapi.dll", PreserveSig = false)]
public static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);
[Flags]
public enum DwmWindowAttribute
{
NCRenderingEnabled = 1,
NCRenderingPolicy,
TransitionsForceDisabled,
AllowNCPaint,
CaptionButtonBounds,
NonClientRtlLayout,
ForceIconicRepresentation,
Flip3DPolicy,
ExtendedFrameBounds,
HasIconicBitmap,
DisallowPeek,
ExcludedFromPeek,
Last
}
[Flags]
public enum DwmNCRenderingPolicy
{
UseWindowStyle,
Disabled,
Enabled,
Last
}
public static void RemoveFromAeroPeek(IntPtr Hwnd) //Hwnd is the handle to your window
{
int renderPolicy = (int)DwmNCRenderingPolicy.Enabled;
DwmSetWindowAttribute(Hwnd, (int)DwmWindowAttribute.ExcludedFromPeek, ref renderPolicy, sizeof(int));
}
}
}
"@
[Reflection.Assembly]::Load("UIAutomationClient, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
function global:Select-Window {
PARAM( [string]$Title="*",
[string]$Process="*",
[switch]$Recurse,
[System.Windows.Automation.AutomationElement]$Parent = [System.Windows.Automation.AutomationElement]::RootElement )
PROCESS {
$search = "Children"
if($Recurse) { $search = "Descendants" }
$Parent.FindAll( $search, [System.Windows.Automation.Condition]::TrueCondition ) |
Add-Member -Type ScriptProperty -Name Title -Value {
$this.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::NameProperty)} -Passthru |
Add-Member -Type ScriptProperty -Name Handle -Value {
$this.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::NativeWindowHandleProperty)} -Passthru |
Add-Member -Type ScriptProperty -Name ProcessId -Value {
$this.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ProcessIdProperty)} -Passthru |
Where-Object {
((Get-Process -Id $_.ProcessId).ProcessName -like $Process) -and ($_.Title -like $Title)
}
}}
}
}
|
PowerShellCorpus/PoshCode/Get Twitter RSS Feed_3.ps1
|
Get Twitter RSS Feed_3.ps1
|
param ([String] $ScreenName)
$client = New-Object System.Net.WebClient
$idUrl = "https://api.twitter.com/1/users/show.json?screen_name=$ScreenName"
$data = $client.DownloadString($idUrl)
$start = 0
$findStr = '"id":'
do {
$start = $data.IndexOf($findStr, $start + 1)
if ($start -gt 0) {
$start += $findStr.Length
$end = $data.IndexOf(',', $start)
$userId = $data.SubString($start, $end-$start)
}
} while ($start -le $data.Length -and $start -gt 0)
$feed = "http://twitter.com/statuses/user_timeline/$userId.rss"
$feed
|
PowerShellCorpus/PoshCode/Inventory_1.ps1
|
Inventory_1.ps1
|
############################################################################
#
# Collect.ps1
# Version: 0.2
# Script to Collect Information from PCs in a Subnet
# By: Brad Blaylock
# For: St. Bernards RMC
# Date: 3-25-2010
#
############################################################################
############################################################################
# Collect.ps1 Script -- Output to OpenOffice Calc
############################################################################
#
#
#___________________________________________________________________________
############################################################################
#__________________CREATE OPEN OFFICE CALC SHEET____________________________
[System.Reflection.Assembly]::LoadWithPartialName('cli_basetypes')
[System.Reflection.Assembly]::LoadWithPartialName('cli_cppuhelper')
[System.Reflection.Assembly]::LoadWithPartialName('cli_oootypes')
[System.Reflection.Assembly]::LoadWithPartialName('cli_ure')
[System.Reflection.Assembly]::LoadWithPartialName('cli_uretypes')
$localContext = [uno.util.Bootstrap]::bootstrap()
$multiComponentFactory = [unoidl.com.sun.star.uno.XComponentContext].getMethod('getServiceManager').invoke($localContext, @())
$desktop = [unoidl.com.sun.star.lang.XMultiComponentFactory].getMethod('createInstanceWithContext').invoke($multiComponentFactory, @('com.sun.star.frame.Desktop', $localContext))
$calc = [unoidl.com.sun.star.frame.XComponentLoader].getMethod('loadComponentFromURL').invoke($desktop, @('private:factory/scalc', '_blank', 0, $null))
$sheets = [unoidl.com.sun.star.sheet.XSpreadsheetDocument].getMethod('getSheets').invoke($calc, @())
$sheet = [unoidl.com.sun.star.container.XIndexAccess].getMethod('getByIndex').invoke($sheets, @(0))
#Cell definitions - Header Row
$cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(0,0))
[unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @('IP Address'))
$cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(1,0))
[unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @('Hostname'))
$cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(2,0))
[unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @('Serial'))
$cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(3,0))
[unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @('OS'))
$cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(4,0))
[unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @('SvcPk'))
$cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(5,0))
[unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @('CPU'))
$cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(6,0))
[unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @('RAM'))
$cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(7,0))
[unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @('C: Size'))
$cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(8,0))
[unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @('C: Free'))
$i=1 #Establish variable for Row Imcrementation.
#___________________________END OPEN OFFICE DEFINE____________________________
#Establish Ping Object
$ping = new-object System.Net.NetworkInformation.Ping;
#Encorporate Error handling
ri $env:temp\\*.txt -r -v –ea 0
#________________________________________________________________________________
# BEGIN GUI INTERFACE
#________________________________________________________________________________
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = "Collect.ps1"
$objForm.Size = New-Object System.Drawing.Size(200,300)
$objForm.StartPosition = "CenterScreen"
$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
{$subnet=$objTextBoxsub.Text;[int]$start=$objTextBoxstart.Text;$end=$objTextBoxend.Text;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
{$objForm.Close()}})
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(15,220)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Add_Click({$subnet=$objTextBoxsub.Text;[int]$start=$objTextBoxstart.Text;$end=$objTextBoxend.Text;$objForm.Close()})
$objForm.Controls.Add($OKButton)
$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Size(105,220)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = "Cancel"
$CancelButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CancelButton)
$objLabelsub = New-Object System.Windows.Forms.Label
$objLabelsub.Location = New-Object System.Drawing.Size(10,20)
$objLabelsub.Size = New-Object System.Drawing.Size(150,20)
$objLabelsub.Text = "Enter Subnet (1st 3 octets):"
$objForm.Controls.Add($objLabelsub)
$objTextBoxsub = New-Object System.Windows.Forms.TextBox
$objTextBoxsub.Location = New-Object System.Drawing.Size(10,40)
$objTextBoxsub.Size = New-Object System.Drawing.Size(160,20)
$objForm.Controls.Add($objTextBoxsub)
$objLabelstart = New-Object System.Windows.Forms.Label
$objLabelstart.Location = New-Object System.Drawing.Size(10,70)
$objLabelstart.Size = New-Object System.Drawing.Size(150,20)
$objLabelstart.Text = "Enter beginning node below:"
$objForm.Controls.Add($objLabelstart)
$objTextBoxstart = New-Object System.Windows.Forms.TextBox
$objTextBoxstart.Location = New-Object System.Drawing.Size(10,90)
$objTextBoxstart.Size = New-Object System.Drawing.Size(160,20)
$objForm.Controls.Add($objTextBoxstart)
$objLabelend = New-Object System.Windows.Forms.Label
$objLabelend.Location = New-Object System.Drawing.Size(10,120)
$objLabelend.Size = New-Object System.Drawing.Size(150,20)
$objLabelend.Text = "Enter ending node below:"
$objForm.Controls.Add($objLabelend)
$objTextBoxend = New-Object System.Windows.Forms.TextBox
$objTextBoxend.Location = New-Object System.Drawing.Size(10,140)
$objTextBoxend.Size = New-Object System.Drawing.Size(160,20)
$objForm.Controls.Add($objTextBoxend)
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate();$objTextBoxsub.Focus()})
[Void] $objForm.ShowDialog()
$objForm.Dispose()
#________________________________________________________________________
# END GUI INTERFACE
#________________________________________________________________________
#Main Script Section
while ($start -le $end)
{
#----------------==Subnet Arguments==----------------------
$strAddress = "$subnet.$start"
#***
#***
#_____________________________________________________________
$start++
$stat=$ping.Send($strAddress).status;
if($stat -ne "Success")
{
#If Host is NOT online Exit here with message of unavailability.
write-warning "$strAddress is not available <$stat>";
Write-Host
Write-Host
}
else
#Collect Desired Data from Live IP Addresses.
{
#Write IP Address to OpenOffice Calc
$cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(0,$i))
[unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @($strAddress))
#Set $strComputer variable to Hostname.
$ErrorActionPreference = "SilentlyContinue"
$strComputer = [System.Net.Dns]::GetHostByAddress($strAddress).HostName | Foreach-Object {$_ -replace ".ma.dl.cox.net", ""}
$ErrorActionPreference = "Continue"
#Get Computer Name
$ErrorActionPreference = "SilentlyContinue"
$colPCName = get-wmiobject -class "Win32_BIOS" -namespace "root\\CIMV2" `
-computername $strComputer
$ErrorActionPreference = "Continue"
foreach ($objItem in $colPCName)
{
#Write Computer Name to OpenOffice Calc
$cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(1,$i))
[unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @($strComputer))
}
#Get System Serial Number from BIOS.
$ErrorActionPreference = "SilentlyContinue"
$colItems = get-wmiobject -class “Win32_BIOS” -computername $strComputer
$ErrorActionPreference = "Continue"
foreach ($objItem in $colItems)
{
$serial = $objItem.SerialNumber
$cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(2,$i))
[unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @($serial))
}
#Get Operating System and Service Pack.
$ErrorActionPreference = "SilentlyContinue"
$colItems = get-wmiobject -class “Win32_OperatingSystem” -computername $strComputer
$ErrorActionPreference = "Continue"
foreach ($objItem in $colItems)
{
$Opersys = $objItem.Caption
$ServicePk = $objItem.CSDVersion
#Write Operating System to OpenOffice Calc
$cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(3,$i))
[unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @($Opersys))
#Write Service Pack to OpenOffice Calc
$cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(4,$i))
[unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @($ServicePk))
}
#Get Processor and Speed.
$ErrorActionPreference = "SilentlyContinue"
$colProcessor = get-wmiobject -class “Win32_Processor” -computername $strComputer
$ErrorActionPreference = "Continue"
foreach ($objItem in $colProcessor)
{
$cpu = $objItem.Name
#Write CPU to OpenOffice Calc
$cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(5,$i))
[unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @($cpu))
}
#Get Memory Info.
$ErrorActionPreference = "SilentlyContinue"
$colItems = get-wmiobject -class “Win32_MemoryArray” -computername $strComputer
$ErrorActionPreference = "Continue"
foreach ($objItem in $colItems)
{
if ($objItem.EndingAddress -gt 4096)
{
$memory = "{0:N0}MB" -f($objItem.EndingAddress / 1024)
#Write Memory to OpenOffice Calc
$cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(6,$i))
[unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @($memory))
}
}
#Get Disk Information.
$ErrorActionPreference = "SilentlyContinue"
$colProcessor = get-wmiobject -class “Win32_LogicalDisk” -computername $strComputer
$ErrorActionPreference = "Continue"
foreach ($objItem in $colProcessor)
{
$drivename = $objItem.DeviceID
$drivetype = $objItem.DriveType
if ($drivename -ne "C:", $drivetype -eq 3)
{
#If not equal C: - Do Nothing.
}
if ($objItem.Size -gt 1073741824 -and $drivename -eq "C:")
{
$drivespace = "{0:N1}GB" -f($objItem.Size / 1073741824)
$freespace = "{0:N1}GB" -f($objItem.FreeSpace / 1073741824)
#Write C: Size to OpenOffice Calc
$cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(7,$i))
[unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @($drivespace))
#Write C: Freespace to OpenOffice Calc
$cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(8,$i))
[unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @($freespace))
}
else
{
}
}
#Increment row
$i=$i+1
}
}
|
PowerShellCorpus/PoshCode/Tac (reverse cat).ps1
|
Tac (reverse cat).ps1
|
param([string]$path)
Set-PSDebug -Strict
$fs = New-Object System.IO.FileStream ((Resolve-Path $path), 'Open', 'Read')
trap { $fs.Close(); break }
$pos = $fs.Length
$sb = New-Object System.Text.StringBuilder
while (--$pos -ge 0) {
[void]$fs.Seek($pos, 'Begin')
$ch = [char]$fs.ReadByte()
if ($ch -eq "`n" -and $sb.Length -gt 0) {
$sb.ToString().TrimEnd()
$sb.Length = 0
}
[void]$sb.Insert(0, [char]$ch)
}
$sb.ToString().TrimEnd()
|
PowerShellCorpus/PoshCode/Execute-SQLCommand_3.ps1
|
Execute-SQLCommand_3.ps1
|
function Execute-SQLCommand {param( [string]$Server, #the host name of the SQL server
[string]$Database, #the name of the database
[System.Data.SqlClient.SqlCommand]$Command) #the command to execute (name of stored procedure)
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "Integrated Security=SSPI;Persist Security Info=False;User ID=user;Initial Catalog=$Database;Data Source=$Server"
$Command.CommandType = [System.Data.CommandType]::Text
$Command.Connection = $sqlConnection
$sqlConnection.Open()
$Result = $Command.ExecuteNonQuery()
$sqlConnection.Close()
if ($Result -gt 0) {return $TRUE} else {return $FALSE}
}
|
PowerShellCorpus/PoshCode/h20 -Hashtables 2 object_1.ps1
|
h20 -Hashtables 2 object_1.ps1
|
#hashtable to object function.
#used to be able to make custom objects with math inside the pipeline
#e.g. 1..10 | h20 { @{karl = $_;dude = $_+1} }
#gps | h20 { @{name = $_.processname; mem = $_.workingset / 1MB} }
function h20([scriptblock]$sb )
{
begin {}
process{ if ($sb -ne $null)
{
$ht = &$sb;
if ($ht -is [hashtable])
{
New-Object PSObject -Property $ht}
}
if ($ht -is [object[]])
{
$ht | % { New-Object PSObject -Property $_ }
}
}
end{}
}
|
PowerShellCorpus/PoshCode/Get-Sysinternals_1.ps1
|
Get-Sysinternals_1.ps1
|
function Get-SysInternals {
param ( $sysIntDir=(join-path $env:systemroot "\\Sysinternals\\") )
if(!(Test-Path -Path $sysIntDir -PathType Container))
{
$null = New-Item -Type Directory -Path $sysIntDir -Force
}
$log = join-path $sysIntDir "changes.log"
Add-Content -force $log -value "`n`n[$(get-date)]SysInternals sync has been started"
net use \\\\live.sysinternals.com\\tools /persistent:no
New-PSDrive -Name SYS -PSProvider filesystem -Root \\\\live.sysinternals.com\\tools
dir Sys: -recurse | foreach {
$fileName = $_.name
$localFile = join-path $sysIntDir $_.name
$exist = test-path $localFile
$msgNew = "new utility found: $fileName , downloading..."
$msgUpdate = "file : $fileName is newer, updating..."
$msgNoChange = "nothing changed for: $fileName"
if($exist){
if($_.lastWriteTime -gt (Get-Item $localFile).lastWriteTime)
{
Copy-Item $_.fullname $sysIntDir -force
Write-Host $msgUpdate -fore yellow
Add-Content -force $log -value $msgUpdate
}
else
{
Add-Content $log -force -value $msgNoChange
Write-Host $msgNoChange
}
}
else
{
if($_.extension -eq ".exe")
{
Write-Host $msgNew -fore green
Add-Content -force $log -value $msgNew
}
Copy-Item $_.fullname $sysIntDir -force
}
}
Update-Path "Sysinternals" $sysIntDir ""
net use \\\\live.sysinternals.com\\tools\\ /delete
}
function Update-Path ( [string] $Product, [string] $productPath, [string] $Property)
{
# Get our existing path as an array
$pathArray = @()
foreach ($pathItem in [Environment]::GetEnvironmentVariable('Path', 'Machine').Split(';')) {
# Remove trailing \\ if any
$pathItem = $pathItem.TrimEnd(('\\'));
$pathItem = $pathItem.Replace('"',"");
#$pathItem =('"{0}"' -f $pathItem)
if ($pathArray -contains $pathItem) {
"Removing duplicate item: " + $pathItem;
}
else {
"Keeping item: " + $pathItem;
$pathArray += $pathItem
}
}
# Append new paths.
"test path "+$productPath
#TODO: encapsulate to a function
if (Test-Path $productPath) {
if ([string]::IsNullOrEmpty($Property)) {
[string] $path = $productPath
}
else {
[string] $path = (Get-ItemProperty $produuctPath).($Property)
}
#$path
if (-not [string]::IsNullOrEmpty($path)) {
$Product + " found"
$path = $path.TrimEnd(('\\'));
$path = $path.Replace('"',"");
#$path =('"{0}"' -f $path)
if ($pathArray -notcontains $path ) {
" Appending " + $path + " to path"
$pathArray += $path
}
else {
" " + $path + " already in path"
}
}
}
else {
$product + " not found"
}
[Array]::Sort([array]$pathArray)
#$pathArray
""
"Old Path: "
([Environment]::GetEnvironmentVariable('Path', 'Machine').Split(';'))|format-list
""
""
[string] $newPath = [string]::Join(';', $pathArray);
[Environment]::SetEnvironmentVariable('Path', $newPath, 'Machine');
"New Path: "
([Environment]::GetEnvironmentVariable('Path', 'Machine').Split(';'))|format-list
}
$wid=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$prp=new-object System.Security.Principal.WindowsPrincipal($wid)
$adm=[System.Security.Principal.WindowsBuiltInRole]::Administrator
$IsAdmin=$prp.IsInRole($adm)
if($IsAdmin)
{
if ($args.Length -eq 0)
{
Get-Sysinternals
}
else
{
Get-Sysinternals $args[0]
}
#Get-Sysinternals "c:\\sys\\"
}
else
{
Write-Warning "This script requires running as an elevated administrator."
}
|
PowerShellCorpus/PoshCode/Hash Checker_3.ps1
|
Hash Checker_3.ps1
|
#.Synopsis
# Test the HMAC hash(es) of a file
#.Description
# Takes the HMAC hash of a file using specified algorithm, and optionally, compare it to a baseline hash
#.Example
# Test-Hash npp.5.3.1.Installer.exe -HashFile npp.5.3.1.release.md5
#
# Searches the provided hash file for a line matching the "npp.5.3.1.Installer.exe" file name
# and take the hash of the file (using the extension of the HashFile as the Type of Hash).
#
#.Example
# Test-Hash npp.5.3.1.Installer.exe 360293affe09ffc229a3f75411ffa9a1 MD5
#
# Takes the MD5 hash and compares it to the provided hash
#
#.Example
# Test-Hash npp.5.3.1.Installer.exe 5e6c2045f4ddffd459e6282f3ff1bd32b7f67517
#
# Tests all of the hashes against the provided (Sha1) hash
#
function Test-Hash {
#[CmdletBinding(DefaultParameterSetName="NoExpectation")]
PARAM(
#[Parameter(Position=0,Mandatory=$true)]
[string]$FileName
,
#[Parameter(Position=2,Mandatory=$true,ParameterSetName="ManualHash")]
[string]$ExpectedHash = $(if($HashFileName){ ((Get-Content $HashFileName) -match $FileName)[0].split(" ")[0] })
,
#[Parameter(Position=1,Mandatory=$true,ParameterSetName="FromHashFile")]
[string]$HashFileName
,
#[Parameter(Position=1,Mandatory=$true,ParameterSetName="ManualHash")]
[string[]]$TypeOfHash = $(if($HashFileName){
[IO.Path]::GetExtension((Convert-Path $HashFileName)).Substring(1)
} else { "MD5","SHA1","SHA256","SHA384","SHA512","RIPEMD160" })
)
$ofs=""
$hashes = @{}
foreach($Type in $TypeOfHash) {
[string]$hash = [Security.Cryptography.HashAlgorithm]::Create(
$Type
).ComputeHash(
[IO.File]::ReadAllBytes( (Convert-Path $FileName) )
) | ForEach { "{0:x2}" -f $_ }
$hashes.$Type = $hash
}
if($ExpectedHash) {
($hashes.Values -eq $hash).Count -ge 1
} else {
foreach($hash in $hashes.GetEnumerator()) {
"{0,-8}{1}" -f $hash.Name, $hash.Value
}
}
}
|
PowerShellCorpus/PoshCode/TabExpansion_4.ps1
|
TabExpansion_4.ps1
|
## Tab-Completion
#################
## Please dot souce this script file.
## In first loading, it may take a several minutes, in order to generate ProgIDs and TypeNames list.
## What this can do is:
##
## [datetime]::n<tab>
## [datetime]::now.d<tab>
## $a = New-Object "Int32[,]" 2,3; $b = "PowerShell","PowerShell"
## $c = [ref]$a; $d = [ref]$b,$c
## $d[0].V<tab>[0][0].Get<tab>
## $d[1].V<tab>[0,0].tos<tab>
## $function:a<tab>
## $env:a<tab>
## [System.Type].a<tab>
## [datetime].Assembly.a<tab>
## ).a<tab> # shows System.Type properties and methods...
## #native command name expansion
## fsu<tab>
## #command option name expansion (for fsutil ipconfig net powershell only)
## fsutil <tab>
## ipconfig <tab>
## net <tab>
## powershell <tab>
## #TypeNames expansion
## [Dec<tab>
## [Microsoft.PowerShell.Com<tab>
## New-Object -TypeName IO.Dir<tab>
## New-Object System.Management.Auto<tab>
## #ProgIDs expansion
## New-Object -Com shel<tab>
## #Enum option expansion
## Set-ExecutionPolicy <tab>
## Set-ExecutionPolicy All<tab>
## Set-ExcusionPolisy -ex <tab>
## Get-TraceSourceÅ@Inte<tab>
## iex -Err <tab> -wa Sil<tab>
## #WmiClasses expansion
## Get-WmiObject -class Win32_<tab>
## gwmi __Instance<tab>
## #Encoding expansion
## [Out-File | Export-CSV | Select-String | Export-Clixml] -enc <tab>
## [Add-Content | Get-Content | Set-Content} -Encoding Big<tab>
## #PSProvider name expansion
## [Get-Location | Get-PSDrive | Get-PSProvider | New-PSDrive | Remove-PSDrive] [-PSProvider] <tab>
## Get-PSProvider <tab>
## pwd -psp al<tab>
## #PSDrive name expansion
## [Get-PSDrive | New-PSDrive | Remove-PSDrive] [-Name] <tab>
## Get-PSDrive <tab>
## pwd -psd <tab>
## #PSSnapin name expansion
## [Add-PSSnapin | Get-PSSnapin | Remove-PSSnapin ] [-Name] <tab>
## Get-Command -PSSnapin <tab>
## Remove-PSSnapin <tab>
## Get-PSSnapin M<tab>
## #Eventlog name and expansion
## Get-Eventlog -Log <tab>
## Get-Eventlog w<tab>
## #Eventlog's entrytype expansion
## Get-EventLog -EntryType <tab>
## Get-EventLog -EntryType Er<tab>
## Get-EventLog -Ent <tab>
## #Service name expansion
## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-Name] <tab>
## New-Service -DependsOn <tab>
## New-Service -Dep e<tab>
## Get-Service -n <tab>
## Get-Service <tab>,a<tab>,p<tab>
## gsv <tab>
## #Service display name expansion
## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-DisplayName] <tab>
## Get-Service -Dis <tab>
## gsv -Dis <tab>,w<tab>,b<tab>
## #Cmdlet and Topic name expansion
## Get-Help [-Name] about_<tab>
## Get-Help <tab>
## #Category name expansion
## Get-Help -Category c<tab>,<tab>
## #Command name expansion
## Get-Command [-Name] <tab>
## Get-Command -Name <tab>
## gcm a<tab>,<tab>
## #Scope expansion
## [Clear-Variable | Export-Alias | Get-Alias | Get-PSDrive | Get-Variable | Import-Alias
## New-Alias | New-PSDrive | New-Variable | Remove-Variable | Set-Alias | Set-Variable] -Scope <tab>
## Clear-Variable -Scope G<tab>
## Set-Alias -s <tab>
## #Process name expansion
## [Get-Process | Stop-Process] [-Name] <tab>
## Stop-Process -Name <tab>
## Stop-Process -N pow<tab>
## Get-Process <tab>
## ps power<tab>
## #Trace sources expansion
## [Trace-Command | Get-TraceSource | Set-TraceSource] [-Name] <tab>,a<tab>,p<tab>
## #Trace -ListenerOption expansion
## [Set-TraceSource | Trace-Command] -ListenerOption <tab>
## Set-TraceSource -Lis <tab>,n<tab>
## #Trace -Option expansion
## [Set-TraceSource | Trace-Command] -Option <tab>
## Set-TraceSource -op <tab>,con<tab>
## #ItemType expansion
## New-Item -Item <tab>
## ni -ItemType d<tab>
## #ErrorAction and WarningAction option expansion
## CMDLET [-ErrorAction | -WarningAction] <tab>
## CMDLET -Error 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 -exp <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
## [ 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>
### Generate ProgIDs list...
if ($_ProgID -eq $null) {
$_HKCR = [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\")
[Object[]] $_ProgID = $null
foreach ( $_subkey in $_HKCR.GetSubKeyNames() )
{
foreach ( $_i in [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\$_subkey\\ProgID") )
{
if ($_i -ne $null)
{
$_ProgID += $_i.GetValue("")
}
}
}
'$_ProgID was updated...' | Out-Host
$_ProgID = $_ProgID|sort -Unique
Set-Content -Value $_ProgID -Path $PSHOME\\ProgIDs.txt
Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_ProgID = Get-Content -Path C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\ProgIDs.txt;'
}
### Generate TypeNames list...
if ( $_TypeNames -eq $null ) {
[Object[]] $_TypeNames = $null
foreach ( $_asm in [AppDomain]::CurrentDomain.GetAssemblies() )
{
foreach ( $_type in $_asm.GetTypes() )
{
$_TypeNames += $_type.FullName
}
}
'$_TypeNames was updated...' | Out-Host
$_TypeNames = $_TypeNames | sort -Unique
Set-Content -Value $_TypeNames -Path $PSHOME\\TypeNames.txt
Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_TypeNames = Get-Content -Path $PSHOME\\TypeNames.txt;'
}
if ( $_TypeNames_System -eq $null ) {
[Object[]] $_TypeNames_System = $null
foreach ( $_type in $_TypeNames -like "System.*" )
{
$_TypeNames_System += $_type.Substring(7)
}
'$_TypeNames_System was updated...' | Out-Host
Set-Content -Value $_TypeNames_System -Path $PSHOME\\TypeNames_System.txt
Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_TypeNames_System = Get-Content -Path $PSHOME\\TypeNames_System.txt;'
}
### Generate WMIClasses list...
if ( $_WMIClasses -eq $null ) {
[Object[]] $_WMIClasses = $null
foreach ( $_class in gwmi -List )
{
$_WMIClasses += $_class.Name
}
$_WMIClasses = $_WMIClasses | sort -Unique
'$_WMIClasses was updated...' | Out-Host
Set-Content -Value $_WMIClasses -Path $PSHOME\\WMIClasses.txt
Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_WMIClasses = Get-Content -Path $PSHOME\\WMIClasses.txt;'
}
$global:_snapin = $null
# Load Get-PipeLineObject function for $_ and property name expansion.
$_scriptpath = gi $MyInvocation.MyCommand.Path
iex (". " + (Join-Path $_scriptpath.DirectoryName "Get-PipeLineObject.ps1"))
function TabExpansion {
# 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 '.')
{
$members =
(
[Object[]](Get-Member -InputObject $_val.PSextended $_pat) +
[Object[]](Get-Member -InputObject $_val.PSadapted $_pat) +
[Object[]](Get-Member -InputObject $_val.PSbase $_pat)
)
if ( $_val -is [Hashtable] )
{
[Microsoft.PowerShell.Commands.MemberDefinition[]]$_keys = $null
foreach ( $_name in $_val.Keys )
{
$_keys += `
New-Object Microsoft.PowerShell.Commands.MemberDefinition `
[int],$_name,"Property",0
}
$members += [Object[]]$_keys | ? { $_.Name -like $_pat }
}
foreach ($_m in $members | sort membertype,name -Unique)
{
if ($_m.MemberType -band $_method)
{
# Return a method...
$_base + $_expression + $sep + $_m.name + '('
}
else {
# Return a property...
$_base + $_expression + $sep + $_m.name
}
}
}
else
{
foreach ($_m in Get-Member -Static -InputObject $_val $_pat |
Sort-Object membertype,name)
{
if ($_m.MemberType -band $_method)
{
# Return a method...
$_base + $_expression + $sep + $_m.name + '('
}
else {
# Return a property...
$_base + $_expression + $sep + $_m.name
}
}
}
}
switch -regex ($lastWord)
{
# Handle property and method expansion at '$_'
'(^.*)(\\$_\\.)(\\w*)$' {
$_base = $matches[1]
$_expression = '$global:_dummy'
$_pat = $matches[3] + '*'
$global:_dummy = $null
Get-PipeLineObject
if ( $global:_dummy -eq $null )
{
if ( $global:_exp -match '^\\$.*\\(.*$' )
{
$type = ( iex $_exp.Split("(")[0] ).OverloadDefinitions[0].Split(" ")[0] -replace '\\[[^\\[\\]]*\\]$' -as [type]
if ( $_expression -match '^\\$global:_dummy' )
{
$temp = $_expression -replace '^\\$global:_dummy(.*)','$1'
$_expression = '$_' + $temp
}
foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } )
{
if ($_m.MemberType -eq "Method")
{
$_base + $_expression + '.' + $_m.name + '('
}
else {
$_base + $_expression + '.' + $_m.name
}
}
break;
}
elseif ( $global:_exp -match '^\\[.*\\:\\:.*\\(.*$' )
{
$tname, $mname = $_exp.Split(":(", "RemoveEmptyEntries"-as [System.StringSplitOptions])[0,1]
$type = @(iex ($tname + '.GetMember("' + $mname + '")'))[0].ReturnType.FullName -replace '\\[[^\\[\\]]*\\]$' -as [type]
if ( $_expression -match '^\\$global:_dummy' )
{
$temp = $_expression -replace '^\\$global:_dummy(.*)','$1'
$_expression = '$_' + $temp
}
foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } )
{
if ($_m.MemberType -eq "Method")
{
$_base + $_expression + '.' + $_m.name + '('
}
else {
$_base + $_expression + '.' + $_m.name
}
}
break;
}
elseif ( $global:_exp -match '^(\\$\\w+(\\[[0-9,\\.]+\\])*(\\.\\w+(\\[[0-9,\\.]+\\])*)*)$' )
{
$global:_dummy = @(iex $Matches[1])[0]
}
else
{
$global:_dummy = $global:_mix
}
}
Write-Members
break;
}
# Handle property and method expansion rooted at variables...
# e.g. $a.b.<tab>
'(^.*)(\\$(\\w|\\.)+)\\.(\\w*)$' {
$_base = $matches[1]
$_expression = $matches[2]
[void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock]
$_pat = $matches[4] + '*'
if ( $_expression -match '^\\$_\\.' )
{
$_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1')
}
Write-Members
break;
}
# Handle simple property and method expansion on static members...
# e.g. [datetime]::n<tab>
'(^.*)(\\[(\\w|\\.)+\\])\\:\\:(\\w*)$' {
$_base = $matches[1]
$_expression = $matches[2]
$_pat = $matches[4] + '*'
Write-Members '::'
break;
}
# Handle complex property and method expansion on static members
# where there are intermediate properties...
# e.g. [datetime]::now.d<tab>
'(^.*)(\\[(\\w|\\.)+\\]\\:\\:(\\w+\\.)+)(\\w*)$' {
$_base = $matches[1] # everything before the expression
$_expression = $matches[2].TrimEnd('.') # expression less trailing '.'
$_pat = $matches[5] + '*' # the member to look for...
Write-Members
break;
}
# Handle variable name expansion...
'(^.*\\$)(\\w+)$' {
$_prefix = $matches[1]
$_varName = $matches[2]
foreach ($_v in Get-ChildItem ('variable:' + $_varName + '*'))
{
$_prefix + $_v.name
}
break;
}
# Handle env&function drives variable name expansion...
'(^.*\\$)(.*\\:)(\\w+)$' {
$_prefix = $matches[1]
$_drive = $matches[2]
$_varName = $matches[3]
if ($_drive -eq "env:" -or $_drive -eq "function:")
{
foreach ($_v in Get-ChildItem ($_drive + $_varName + '*'))
{
$_prefix + $_drive + $_v.name
}
}
break;
}
# Handle array's element property and method expansion
# where there are intermediate properties...
# e.g. foo[0].n.b<tab>
'(^.*)(\\$((\\w+\\.)|(\\w+(\\[(\\w|,)+\\])+\\.))+)(\\w*)$'
{
$_base = $matches[1]
$_expression = $matches[2].TrimEnd('.')
$_pat = $Matches[8] + '*'
[void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock]
if ( $_expression -match '^\\$_\\.' )
{
$_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1')
}
Write-Members
break;
}
# Handle property and method expansion rooted at type object...
# e.g. [System.Type].a<tab>
'(^\\[(\\w|\\.)+\\])\\.(\\w*)$'
{
if ( $(iex $Matches[1]) -isnot [System.Type] ) { break; }
$_expression = $Matches[1]
$_pat = $Matches[$matches.Count-1] + '*'
Write-Members
break;
}
# Handle complex property and method expansion on type object members
# where there are intermediate properties...
# e.g. [datetime].Assembly.a<tab>
'^(\\[(\\w|\\.)+\\]\\.(\\w+\\.)+)(\\w*)$' {
$_expression = $matches[1].TrimEnd('.') # expression less trailing '.'
$_pat = $matches[4] + '*' # the member to look for...
if ( $(iex $_expression) -eq $null ) { break; }
Write-Members
break;
}
# Handle property and method expansion rooted at close parenthes...
# e.g. (123).a<tab>
'^(.*)\\)((\\w|\\.)*)\\.(\\w*)$' {
$_base = $Matches[1] + ")"
if ( $matches[3] -eq $null) { $_expression = '[System.Type]' }
else { $_expression = '[System.Type]' + $Matches[2] }
$_pat = $matches[4] + '*'
iex "$_expression | Get-Member $_pat | sort MemberType,Name" |
% {
if ( $_.MemberType -like "*Method*" -or $_.MemberType -like "*Parameterized*" ) { $parenthes = "(" }
if ( $Matches[2] -eq "" ) { $_base + "." + $_.Name + $parenthes }
else { $_base + $Matches[2] + "." + $_.Name + $parenthes }
}
break;
}
# Handle .NET type name expansion ...
# e.g. [Microsoft.PowerShell.Com<tab>
'^\\[((\\w+\\.?)+)$' {
$_opt = $matches[1] + '*'
foreach ( $_exp in $_TypeNames_System -like $_opt )
{
'[' + $_exp
}
foreach ( $_exp in $_TypeNames -like $_opt )
{
'[' + $_exp
}
break;
}
# 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.
$_cmdlet = [regex]::Split($line, '[|;=]')[-1]
# Extract the trailing unclosed block e.g. ls | foreach { cp
if ($_cmdlet -match '\\{([^\\{\\}]*)$')
{
$_cmdlet = $matches[1]
}
# Extract the longest unclosed parenthetical expression...
if ($_cmdlet -match '\\(([^()]*)$')
{
$_cmdlet = $matches[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]
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'cmdlet,alias,function,filter,ExternalScript' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias,function,filter,ExternalScript' $_cmdlet.Definition)[0]
}
if ( $_cmdlet.CommandType -eq "Cmdlet" )
{
# expand the parameter sets and emit the matching elements
foreach ($_n in $_cmdlet.ParameterSets |
Select-Object -expand parameters | Sort-Object -Unique name)
{
$_n = $_n.name
if ($_n -like $_pat) { '-' + $_n }
}
break;
}
if ( "ExternalScript", "Function", "Filter" -contains $_cmdlet.CommandType )
{
if ( $_cmdlet.CommandType -eq "ExternalScript" )
{
$_fsr = New-Object IO.StreamReader $_cmdlet.Definition
$_def = "Function _Dummy { $($_fsr.ReadToEnd()) }"
$_fsr.Close()
iex $_def
$_cmdlet = "_Dummy"
}
if ( ((gi "Function:$_cmdlet").Definition -replace '\\n').Split("{")[0] -match 'param\\((.*\\))\\s*[;\\.&a-zA-Z]*\\s*$' )
{
( ( ( $Matches[1].Split('$', "RemoveEmptyEntries" -as [System.StringSplitOptions]) -replace `
'^(\\w+)(.*)','$1' ) -notmatch '^\\s+$' ) -notmatch '^\\s*\\[.*\\]\\s*$' ) -like $_pat | sort | % { '-' + $_ }
}
break;
}
}
# try to find a matching command...
default {
$lastex = [regex]::Split($line, '[|;]')[-1]
if ( $lastex -match '^\\s*(\\$\\w+(\\[[0-9,]+\\])*(\\.\\w+(\\[[0-9,]+\\])*)*)\\s*=\\s+(("\\w+"\\s*,\\s+)*)"\\w+"\\s*-as\\s+$' )
{
if ( $Matches[6] -ne $nul )
{
$brackets = "[]"
}
'['+ $global:_enum + $brackets + ']'
break;
}
if ( $lastex -match '^\\s*(\\$\\w+(\\[[0-9,]+\\])*(\\.\\w+(\\[[0-9,]+\\])*)*)\\s*=\\s+(("\\w+"\\s*,\\s+)*)\\s*(\\w*)$' )
{
$_pat = $Matches[7] + '*'
$_type = @(iex $Matches[1])[0].GetType()
if ( $_type.IsEnum )
{
$global:_enum = $_type.FullName
[Enum]::GetValues($_type) -like $_pat -replace '^(.*)$','"$1"'
break;
}
}
$lastex = [regex]::Split($line, '[|;=]')[-1]
if ($lastex -match '[[$].*\\w+\\(.*-as\\s*$')
{
'['+ $global:_enum + ']'
}
elseif ( $lastex -match '([[$].*(\\w+))\\((.*)$' )
#elseif ( $lastex -match '([[$].*(\\w+))\\(([^)]*)$' )
{
$_method = $Matches[1]
if ( $Matches[3] -match "(.*)((`"|')(\\w+,)+(\\w*))$" )
{
$continuous = $true
$_opt = $Matches[5] + '*'
$_base = $Matches[2].TrimStart('"') -replace '(.*,)\\w+$','$1'
$position = $Matches[1].Split(",").Length
}
else
{
$continuous = $false
$_opt = ($Matches[3].Split(',')[-1] -replace '^\\s*','') + "*"
$position = $Matches[3].Split(",").Length
}
if ( ($_mdefs = iex ($_method + ".OverloadDefinitions")) -eq $null )
{
$tname, $mname = $_method.Split(":", "RemoveEmptyEntries" -as [System.StringSplitOptions])
$_mdefs = iex ($tname + '.GetMember("' + $mname + '") | % { $_.ToString() }')
}
foreach ( $def in $_mdefs )
{
[void] ($def -match '\\((.*)\\)')
foreach ( $param in [regex]::Split($Matches[1], ', ')[$position-1] )
{
if ($param -eq $null -or $param -eq "")
{
continue;
}
$type = $param.split()[0]
if ( $type -like '*`[*' -or $type -eq "Params" -or $type -eq "" )
{
continue;
}
$fullname = @($_typenames -like "*$type*")
foreach ( $name in $fullname )
{
if ( $continuous -eq $true -and ( $name -as [System.Type] ).IsEnum )
{
$output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$',($_base + '$1')
$output | sort
}
elseif ( ( $name -as [System.Type] ).IsEnum )
{
$global:_enum = $name
$output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$','"$1"'
$output | sort
}
}
}
}
if ( $output -ne $null )
{
break;
}
}
if ( $line[-1] -eq " " )
{
$_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-1]
# 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 ( "Set-ExecutionPolicy" -eq $_cmdlet.Name )
{
"Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" | sort
break;
}
if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name )
{
Get-TraceSource | % { $_.Name } | sort -Unique
break;
}
if ( "New-Object" -eq $_cmdlet.Name )
{
$_TypeNames_System
$_TypeNames
break;
}
if ( $_cmdlet.Noun -like "*WMI*" )
{
$_WMIClasses
break;
}
if ( "Get-Process" -eq $_cmdlet.Name )
{
Get-Process | % { $_.Name } | sort
break;
}
if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name )
{
if ( $global:_snapin -ne $null )
{
$global:_snapin
break;
}
else
{
$global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique;
$global:_snapin
break;
}
}
if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" `
-contains $_cmdlet.Name -and "Name" )
{
Get-PSDrive | sort
break;
}
if ( "Get-Eventlog" -eq $_cmdlet.Name )
{
Get-EventLog -List | % { $_base + ($_.Log -replace '\\s','` ') }
break;
}
if ( "Get-Help" -eq $_cmdlet.Name )
{
Get-Help -Category all | % { $_.Name } | sort -Unique
break;
}
if ( "Get-Service", "Restart-Service", "Resume-Service",
"Start-Service", "Stop-Service", "Suspend-Service" `
-contains $_cmdlet.Name )
{
Get-Service | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Get-Command" -eq $_cmdlet.Name )
{
Get-Command -CommandType All | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object",
"ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" `
-contains $_cmdlet.Name )
{
Get-PipeLineObject
$_dummy | Get-Member -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
}
if ( $line[-1] -eq " " )
{
# 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($line, '[|;=]')[-1]
# Extract the trailing unclosed block e.g. ls | foreach { cp
if ($_cmdlet -match '\\{([^\\{\\}]*)$')
{
$_cmdlet = $matches[1]
}
# Extract the longest unclosed parenthetical expression...
if ($_cmdlet -match '\\(([^()]*)$')
{
$_cmdlet = $matches[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]
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'Application' $_cmdlet)[0]
if ( $_cmdlet.Name -eq "powershell.exe" )
{
"-PSConsoleFile", "-Version", "-NoLogo", "-NoExit", "-Sta", "-NoProfile", "-NonInteractive",
"-InputFormat", "-OutputFormat", "-EncodedCommand", "-File", "-Command" | sort
break;
}
if ( $_cmdlet.Name -eq "fsutil.exe" )
{
"behavior query", "behavior set", "dirty query", "dirty set",
"file findbysid", "file queryallocranges", "file setshortname", "file setvaliddata", "file setzerodata", "file createnew",
"fsinfo drives", "fsinfo drivetype", "fsinfo volumeinfo", "fsinfo ntfsinfo", "fsinfo statistics",
"hardlink create", "objectid query", "objectid set", "objectid delete", "objectid create",
"quota disable", "quota track", "quota enforce", "quota violations", "quota modify", "quota query",
"reparsepoint query", "reparsepoint delete", "sparse setflag", "sparse queryflag", "sparse queryrange", "sparse setrange",
"usn createjournal", "usn deletejournal", "usn enumdata", "usn queryjournal", "usn readdata", "volume dismount", "volume diskfree" | sort
break;
}
if ( $_cmdlet.Name -eq "net.exe" )
{
"ACCOUNTS ", " COMPUTER ", " CONFIG ", " CONTINUE ", " FILE ", " GROUP ", " HELP ",
"HELPMSG ", " LOCALGROUP ", " NAME ", " PAUSE ", " PRINT ", " SEND ", " SESSION ",
"SHARE ", " START ", " STATISTICS ", " STOP ", " TIME ", " USE ", " USER ", " VIEW" | sort
break;
}
if ( $_cmdlet.Name -eq "ipconfig.exe" )
{
"/?", "/all", "/renew", "/release", "/flushdns", "/displaydns",
"/registerdns", "/showclassid", "/setclassid"
break;
}
}
if ( $line -match '\\w+\\s+(\\w+(\\.|[^\\s\\.])*)$' )
{
#$_opt = $Matches[1] + '*'
$_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-2]
$_opt = $Matches[1].Split(" ,")[-1] + '*'
$_base = $Matches[1].Substring(0,$Matches[1].Length-$Matches[1].Split(" ,")[-1].length)
# 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 ( "Set-ExecutionPolicy" -eq $_cmdlet.Name )
{
"Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" -like $_opt | sort
break;
}
if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name )
{
Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "New-Object" -eq $_cmdlet.Name )
{
$_TypeNames_System -like $_opt
$_TypeNames -like $_opt
break;
}
if ( $_cmdlet.Name -like "*WMI*" )
{
$_WMIClasses -like $_opt
break;
}
if ( "Get-Process" -eq $_cmdlet.Name )
{
Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name )
{
if ( $global:_snapin -ne $null )
{
$global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') }
break;
}
else
{
$global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique;
$global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') }
break;
}
}
if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" `
-contains $_cmdlet.Name -and "Name" )
{
Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-PSProvider" -eq $_cmdlet.Name )
{
Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Eventlog" -eq $_cmdlet.Name )
{
Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') }
break;
}
if ( "Get-Help" -eq $_cmdlet.Name )
{
Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique
break;
}
if ( "Get-Service", "Restart-Service", "Resume-Service",
"Start-Service", "Stop-Service", "Suspend-Service" `
-contains $_cmdlet.Name )
{
Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Get-Command" -eq $_cmdlet.Name )
{
Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object",
"ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" `
-contains $_cmdlet.Name )
{
Get-PipeLineObject
$_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
}
if ( $line -match '(-(\\w+))\\s+([^-]*$)' )
{
$_param = $matches[2] + '*'
$_opt = $Matches[3].Split(" ,")[-1] + '*'
$_base = $Matches[3].Substring(0,$Matches[3].Length-$Matches[3].Split(" ,")[-1].length)
# 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($line, '[|;=]')[-1]
# Extract the trailing unclosed block e.g. ls | foreach { cp
if ($_cmdlet -match '\\{([^\\{\\}]*)$')
{
$_cmdlet = $matches[1]
}
# Extract the longest unclosed parenthetical expression...
if ($_cmdlet -match '\\(([^()]*)$')
{
$_cmdlet = $matches[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]
# now get the info object for it...
$_cmdlet = @(Get-Command -type 'cmdlet,alias,ExternalScript,Filter,Function' $_cmdlet)[0]
# loop resolving aliases...
while ($_cmdlet.CommandType -eq 'alias')
{
$_cmdlet = @(Get-Command -type 'cmdlet,alias,ExternalScript,Filter,Function' $_cmdlet.Definition)[0]
}
if ( $_param.TrimEnd("*") -eq "ea" -or $_param.TrimEnd("*") -eq "wa" )
{
"SilentlyContinue", "Stop", "Continue", "Inquire" |
? { $_ -like $_opt } | sort -Unique
break;
}
if ( "Out-File","Export-CSV","Select-String","Export-Clixml" -contains $_cmdlet.Name `
-and "Encoding" -like $_param)
{
"Unicode", "UTF7", "UTF8", "ASCII", "UTF32", "BigEndianUnicode", "Default", "OEM" |
? { $_ -like $_opt } | sort -Unique
break;
}
if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name `
-and "Name" -like $_param)
{
Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "New-Object" -like $_cmdlet.Name )
{
if ( "ComObject" -like $_param )
{
$_ProgID -like $_opt | % { $_ -replace '\\s','` ' }
break;
}
if ( "TypeName" -like $_param )
{
$_TypeNames_System -like $_opt
$_TypeNames -like $_opt
break;
}
}
if ( "New-Item" -eq $_cmdlet.Name )
{
if ( "ItemType" -like $_param )
{
"directory", "file" -like $_opt
break;
}
}
if ( "Get-Location", "Get-PSDrive", "Get-PSProvider", "New-PSDrive", "Remove-PSDrive" `
-contains $_cmdlet.Name `
-and "PSProvider" -like $_param )
{
Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Location" -eq $_cmdlet.Name -and "PSDrive" -like $_param )
{
Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" `
-contains $_cmdlet.Name -and "Name" -like $_param )
{
Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Command" -eq $_cmdlet.Name -and "PSSnapin" -like $_param)
{
if ( $global:_snapin -ne $null )
{
$global:_snapin -like $_opt | % { $_base + $_ }
break;
}
else
{
$global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique;
$global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') }
break;
}
}
if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" `
-contains $_cmdlet.Name -and "Name" -like $_param )
{
if ( $global:_snapin -ne $null )
{
$global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') }
break;
}
else
{
$global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique;
$global:_snapin -like $_opt | % { $_base + $_ }
break;
}
}
if ( "Clear-Variable", "Export-Alias", "Get-Alias", "Get-PSDrive", "Get-Variable", "Import-Alias",
" New-Alias", "New-PSDrive", "New-Variable", "Remove-Variable", "Set-Alias", "Set-Variable" `
-contains $_cmdlet.Name -and "Scope" -like $_param )
{
"Global", "Local", "Script" -like $_opt
break;
}
if ( "Get-Process", "Stop-Process", "Wait-Process" -contains $_cmdlet.Name -and "Name" -like $_param )
{
Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') }
break;
}
if ( "Get-Eventlog" -eq $_cmdlet.Name -and "LogName" -like $_param )
{
Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') }
break;
}
if ( "Get-Help" -eq $_cmdlet.Name )
{
if ( "Name" -like $_param )
{
Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique
break;
}
if ( "Category" -like $_param )
{
"Alias", "Cmdlet", "Provider", "General", "FAQ",
"Glossary", "HelpFile", "All" -like $_opt | sort | % { $_base + $_ }
break;
}
}
if ( "Get-Service", "Restart-Service", "Resume-Service",
"Start-Service", "Stop-Service", "Suspend-Service" `
-contains $_cmdlet.Name )
{
if ( "Name" -like $_param )
{
Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "DisplayName" -like $_param )
{
Get-Service -Name $_opt | sort DisplayName | % { $_base + ($_.DisplayName -replace '\\s','` ') }
break;
}
}
if ( "New-Service" -eq $_cmdlet.Name -and "dependsOn" -like $_param )
{
Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Get-EventLog" -eq $_cmdlet.Name -and "EntryType" -like $_param )
{
"Error", "Information", "FailureAudit", "SuccessAudit", "Warning" -like $_opt | sort | % { $_base + $_ }
break;
}
if ( "Get-Command" -eq $_cmdlet.Name -and "Name" -like $_param )
{
Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( $_cmdlet.Noun -like "*WMI*" )
{
if ( "Class" -like $_param )
{
$_WMIClasses -like $_opt
break;
}
}
if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object",
"ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" `
-contains $_cmdlet.Name -and "Property" -like $_param )
{
Get-PipeLineObject
$_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "Select-Object" -eq $_cmdlet.Name )
{
if ( "ExcludeProperty" -like $_param )
{
Get-PipeLineObject
$_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') }
break;
}
if ( "ExpandProperty" -like $_param )
{
Get-PipeLineObject
$_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_.Name }
break;
}
}
if ( "ExternalScript", "Function", "Filter" -contains $_cmdlet.CommandType )
{
if ( $_cmdlet.CommandType -eq "ExternalScript" )
{
$_fsr = New-Object IO.StreamReader $_cmdlet.Definition
$_def = "Function _Dummy { $($_fsr.ReadToEnd()) }"
$_fsr.Close()
iex $_def
$_cmdlet = "_Dummy"
}
if ( ((gi "Function:$_cmdlet").Definition -replace '\\n').Split("{")[0] -match 'param\\((.*\\))\\s*[;\\.&a-zA-Z]*\\s*$' )
{
$Matches[1].Split(',', "RemoveEmptyEntries" -as [System.StringSplitOptions]) -like "*$_param" |
% { $_.Split("$ )`r`n", "RemoveEmptyEntries" -as [System.StringSplitOptions])[0] -replace '^\\[(.*)\\]$','$1' -as "System.Type" } |
? { $_.IsEnum } | % { [Enum]::GetNames($_) -like $_opt | sort } | % { $_base + $_ }
}
break;
}
select -InputObject $_cmdlet -ExpandProperty ParameterSets | select -ExpandProperty Parameters |
? { $_.Name -like $_param } | ? { $_.ParameterType.IsEnum } |
% { [Enum]::GetNames($_.ParameterType) } | ? { $_ -like $_opt } | sort -Unique | % { $_base + $_ }
}
if ( $line[-1] -match "\\s" ) { break; }
if ( $lastWord -ne $null -and $lastWord.IndexOfAny('/\\') -eq -1 ) {
$command = $lastWord.Substring( ($lastWord -replace '([^\\|\\(;={]*)$').Length )
$_base = $lastWord.Substring( 0, ($lastWord -replace '([^\\|\\(;={]*)$').Length )
$pattern = $command + "*"
gcm -Name $pattern -CommandType All | % { $_base + $_.Name } | sort -Unique
}
}
}
}
}
|
PowerShellCorpus/PoshCode/Reset Time Sync Setting_1.ps1
|
Reset Time Sync Setting_1.ps1
|
########################################################
# Created by Brian English
# Brian.English@charlottefl.com
# eddiephoenix@gmail.com
#
# for Charlotte County Government
# No warranty suggested or implied
########################################################
# Purpose: Cycle through all VMs on a Virtualcenter Server
# and update the 'SyncTimeWithHost' to either true or false
########################################################
# Notes: VMware Tools must be installed on guest vm
########################################################
#################
$prodhost = "virtualcenter"
$devhost = "virtualtest"
#################
#############
###########
#
"1 Prod Hosts"
"2 Dev Hosts"
$hosts = read-host "What hosts to copy to"
switch($hosts)
{ "1"{$hosts = $prodhost}
"2"{$hosts = $devhost}
}
get-esx $hosts
$swtch = read-host "Sync time to host yes/no"
switch($swtch)
{
"yes"{$swtch = $true}
"no"{$swtch = $false}
}
$vms = Get-VM
foreach($vm in $vms)
{
$view = get-view $vm.ID
$config = $view.config
$tools = $config.tools
$spec = new-object VMware.Vim.VirtualMachineConfigSpec
$spec.tools = $tools
$spec.tools.SyncTimeWithHost = $swtch
@@ #this line executes the update to VMTools
@@ $rslt = $view.ReconfigVM_task($spec)
write-host ($vm.name + " " + $tools.SyncTimeWithHost)
}
|
PowerShellCorpus/PoshCode/Add-SqlTable_3.ps1
|
Add-SqlTable_3.ps1
|
try {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop}
catch {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo"}
try {add-type -AssemblyName "Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop}
catch {add-type -AssemblyName "Microsoft.SqlServer.Smo"}
#######################
function Get-SqlType
{
param([string]$TypeName)
switch ($TypeName)
{
'Boolean' {[Data.SqlDbType]::Bit}
'Byte[]' {[Data.SqlDbType]::VarBinary}
'Byte' {[Data.SQLDbType]::VarBinary}
'Datetime' {[Data.SQLDbType]::DateTime}
'Decimal' {[Data.SqlDbType]::Decimal}
'Double' {[Data.SqlDbType]::Float}
'Guid' {[Data.SqlDbType]::UniqueIdentifier}
'Int16' {[Data.SQLDbType]::SmallInt}
'Int32' {[Data.SQLDbType]::Int}
'Int64' {[Data.SqlDbType]::BigInt}
default {[Data.SqlDbType]::VarChar}
}
} #Get-SqlType
#######################
<#
.SYNOPSIS
Creates a SQL Server table from a DataTable
.DESCRIPTION
Creates a SQL Server table from a DataTable using SMO.
.EXAMPLE
$dt = Invoke-Sqlcmd2 -ServerInstance "Z003\\R2" -Database pubs "select * from authors"; Add-SqlTable -ServerInstance "Z003\\R2" -Database pubscopy -TableName authors -DataTable $dt
This example loads a variable dt of type DataTable from a query and creates an empty SQL Server table
.EXAMPLE
$dt = Get-Alias | Out-DataTable; Add-SqlTable -ServerInstance "Z003\\R2" -Database pubscopy -TableName alias -DataTable $dt
This example creates a DataTable from the properties of Get-Alias and creates an empty SQL Server table.
.NOTES
Add-SqlTable uses SQL Server Management Objects (SMO). SMO is installed with SQL Server Management Studio and is available
as a separate download: http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=ceb4346f-657f-4d28-83f5-aae0c5c83d52
Version History
v1.0 - Chad Miller - Initial Release
v1.1 - Chad Miller - Updated documentation
v1.2 - Chad Miller - Add loading Microsoft.SqlServer.ConnectionInfo
v1.3 - Chad Miller - Added error handling
#>
function Add-SqlTable
{
[CmdletBinding()]
param(
[Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance,
[Parameter(Position=1, Mandatory=$true)] [string]$Database,
[Parameter(Position=2, Mandatory=$true)] [String]$TableName,
[Parameter(Position=3, Mandatory=$true)] [System.Data.DataTable]$DataTable,
[Parameter(Position=4, Mandatory=$false)] [string]$Username,
[Parameter(Position=5, Mandatory=$false)] [string]$Password,
[ValidateRange(1,8000)]
[Parameter(Position=6, Mandatory=$false)] [Int32]$MaxLength=1000
)
try {
if($Username)
{ $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $ServerInstance,$Username,$Password }
else
{ $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $ServerInstance }
$con.Connect()
$server = new-object ("Microsoft.SqlServer.Management.Smo.Server") $con
$db = $server.Databases[$Database]
$table = new-object ("Microsoft.SqlServer.Management.Smo.Table") $db, $TableName
foreach ($column in $DataTable.Columns)
{
$sqlDbType = [Microsoft.SqlServer.Management.Smo.SqlDataType]"$(Get-SqlType $column.DataType.Name)"
if ($sqlDbType -eq 'VarBinary' -or $sqlDbType -eq 'VarChar')
{ $dataType = new-object ("Microsoft.SqlServer.Management.Smo.DataType") $sqlDbType, $MaxLength }
else
{ $dataType = new-object ("Microsoft.SqlServer.Management.Smo.DataType") $sqlDbType }
$col = new-object ("Microsoft.SqlServer.Management.Smo.Column") $table, $column.ColumnName, $dataType
$col.Nullable = $column.AllowDBNull
$table.Columns.Add($col)
}
$table.Create()
}
catch {
$message = $_.Exception.GetBaseException().Message
Write-Error $message
}
} #Add-SqlTable
|
PowerShellCorpus/PoshCode/finddupe_23.ps1
|
finddupe_23.ps1
|
function Get-SHA512([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]'))
{
$stream = $null
$cryptoServiceProvider = [System.Security.Cryptography.SHA512CryptoServiceProvider]
$hashAlgorithm = new-object $cryptoServiceProvider
try
{
$stream = $file.OpenRead()
}
catch { return $null }
$hashByteArray = $hashAlgorithm.ComputeHash($stream)
$stream.Close()
trap
{
if ($stream -ne $null) {$stream.Close()}
return $null
}
foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }}
return [string]$result
}
$starttime=[datetime]::now
write-host "FindDupe.ps1 - find and optionally delete duplicate files. FindDupe.ps1 /help or FindDupe.ps1 /h for usage options."
$m = 0
$args3=$args
$args2=$args3|?{$_ -ne "/delete" -and $_ -ne "/recurse" -and $_ -ne "/hidden" -and $_ -ne "/h" -and $_ -ne "/help"}
if ($args3 -eq "/help" -or $args3 -eq "/h")
{
""
"Usage:"
" PS>.\\FindDupe.ps1 <directory/file #1> <directory/file #2> ... <directory/file #N> [-delete] [-noprompt] [-recurse] [-help]"
"Options:"
" /recurse recurses through all subdirectories of any specified directories."
" /delete prompts to delete duplicates (user must be careful not to select delete for all copies)."
" /hidden checks hidden files, default is to ignore hidden files."
" /help displays this usage option data, and ignores all other arguments."
""
"Examples:"
" PS>.\\finddupe.ps1 c:\\data d:\\finance /recurse"
" PS>.\\finddupe.ps1 d: -recurse /delete"
" PS>.\\finddupe.ps1 c:\\users\\alice\\pictures\\ /recurse /delete"
exit
}
$files=@(dir -ea 0 $args2 -recurse:$([bool]($args3 -eq "/recurse")) -force:$([bool]($args3 -eq "/hidden")) |?{$_.psiscontainer -eq $false})|sort length
if ($files.count -lt 2) {"Not enough files specified."; exit}
$hashname=New-Object 'system.collections.generic.dictionary[[string],[system.collections.generic.list[string]]]'
$hashsize=0
$hashfiles=0
$dupebytes=0
for ($i=0;$i -lt ($files.count-1); $i++)
{
if ($files[$i].length -ne $files[$i+1].length) {continue}
$breakout=$false
while($true)
{
$sha512 = (get-SHA512 $files[$i].fullname)
if ($sha512 -ne $null)
{
$hashsize+=$files[$i].length
$hashfiles++
if (!$hashname.containskey($sha512))
{
$hashname+=@{$sha512=@($files[$i].fullname)}
}
else
{
$hashname[$sha512]+=$files[$i].fullname
}
}
if ($breakout -eq $true) {break}
$i++
if ($i -eq ($files.count-1)) {$breakout=$true; continue}
$breakout=(($files[$i+1].length -ne $files[$i].length ))
}
foreach ($k in $hashname.keys)
{
if ($hashname[$k].count -gt 1)
{
write-host ("Duplicates - ({0:N0} Bytes each, {1:N0} matches, {2:N0} Bytes total)):" -f $files[$i].length , $hashname[$k].count, ($files[$i].length*$hashname[$k].count)) -f red
$hashname[$k]
$dupebytes+=$hashname[$k].count*$files[$i].length
if ($args3 -eq "/delete") {$hashname[$k]|%{del $_ -confirm}}
$m+=$hashname[$k].count
}
}
$hashname=@{}
}
""
write-host "Number of Files checked: $($files.count)."
write-host "Number of duplicate files: $m."
Write-host "$($hashfiles) files hashed."
Write-Host "$($hashsize) bytes hashed."
write-host "$dupebytes duplicates bytes."
""
write-host "Time to run: $(([datetime]::now)-$starttime|select hours, minutes, seconds, milliseconds)"
""
|
PowerShellCorpus/PoshCode/Computer Inventory_1.ps1
|
Computer Inventory_1.ps1
|
# ========================================================
#
# Script Information
#
# Title: Remote Computer Inventory
# Author: Assaf Miron
# Originally created: 21/06/2008
# Original path: Computer-Inventory.PS1
# Description: Collects Remote Computer Data Using WMI and Registry Access
# Outputs all information to a Data Grid Form and to a CSV Log File
#
# ========================================================
#region Constructor
# Import Assembly
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
# Log File where the results are Saved
$LogFile = "C:\\Monitoring\\Test-Monitor.csv"
# Check to see if the Log File Directory exists
If((Test-Path ($LogFile.Substring(0,$logFile.LastIndexof("\\")))) -eq $False)
{
# Create The Directory
New-Item ($LogFile.Substring(0,$logFile.LastIndexof("\\"))) -Type Directory
}
#endregion
#region Form Creation
#~~< Form1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$Form1 = New-Object System.Windows.Forms.Form
$Form1.AutoSize = $TRUE
$Form1.ClientSize = New-Object System.Drawing.Size(522, 404)
$Form1.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen
$Form1.Text = "Computer Inventory"
#~~< Panel1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$Panel1 = new-object System.Windows.Forms.Panel
$Panel1.Dock = [System.Windows.Forms.DockStyle]::Fill
$Panel1.Location = new-object System.Drawing.Point(0, 24)
$Panel1.Size = new-object System.Drawing.Size(522, 380)
$Panel1.TabIndex = 20
$Panel1.Text = ""
#~~< btnRun >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$btnRun = New-Object System.Windows.Forms.Button
$btnRun.Enabled = $FALSE
$btnRun.Location = New-Object System.Drawing.Point(431, 30)
$btnRun.Size = New-Object System.Drawing.Size(75, 23)
$btnRun.TabIndex = 2
$btnRun.Text = "Run"
$btnRun.UseVisualStyleBackColor = $TRUE
$btnRun.add_Click({ RunScript($btnRun) })
#~~< Label1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$Label1 = New-Object System.Windows.Forms.Label
$Label1.AutoSize = $False#$TRUE
$Label1.Location = New-Object System.Drawing.Point(12, 31)
$Label1.Size = New-Object System.Drawing.Size(163, 13)
$Label1.TabIndex = 15
$Label1.Text = "File containing Computer Names"
#~~< TextBox1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$TextBox1 = New-Object System.Windows.Forms.TextBox
$TextBox1.Location = New-Object System.Drawing.Point(177, 30)
$TextBox1.Size = New-Object System.Drawing.Size(161, 20)
$TextBox1.TabIndex = 0
$TextBox1.Text = ""
#~~< btnBrowse >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$btnBrowse = New-Object System.Windows.Forms.Button
$btnBrowse.Location = New-Object System.Drawing.Point(347, 30)
$btnBrowse.Size = New-Object System.Drawing.Size(75, 23)
$btnBrowse.TabIndex = 1
$btnBrowse.Text = "Browse"
$btnBrowse.UseVisualStyleBackColor = $TRUE
$btnBrowse.add_Click({ BrowseFile($btnBrowse) })
#~~< DataGridView1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$DataGridView1 = new-object System.Windows.Forms.DataGridView
$DataGridView1.Anchor = ([System.Windows.Forms.AnchorStyles]([System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right))
$DataGridView1.ColumnHeadersHeightSizeMode = [System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode]::AutoSize
$DataGridView1.Location = New-Object System.Drawing.Point(12, 59)
$DataGridView1.Size = New-Object System.Drawing.Size(497, 280)
$DataGridView1.TabIndex = 4
$DataGridView1.ClipboardCopyMode = [System.Windows.Forms.DataGridViewClipboardCopyMode]::Disable
$DataGridView1.Text = ""
#~~< ProgressBar1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$ProgressBar1 = New-Object System.Windows.Forms.ProgressBar
$ProgressBar1.Anchor = ([System.Windows.Forms.AnchorStyles] ([System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right ))
$ProgressBar1.Location = New-Object System.Drawing.Point(12, 345)
$ProgressBar1.Size = New-Object System.Drawing.Size(410, 23)
$ProgressBar1.TabIndex = 5
$ProgressBar1.Text = ""
#~~< btnExit >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$btnExit = New-Object System.Windows.Forms.Button
$btnExit.Anchor = ([System.Windows.Forms.AnchorStyles]([System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Right))
$btnExit.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$btnExit.Location = New-Object System.Drawing.Point(431, 345)
$btnExit.Size = New-Object System.Drawing.Size(78, 23)
$btnExit.TabIndex = 3
$btnExit.Text = "Exit"
$btnExit.UseVisualStyleBackColor = $TRUE
$btnExit.add_Click({ CloseForm($btnExit) })
#~~< MenuStrip1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$MenuStrip1 = new-object System.Windows.Forms.MenuStrip
$MenuStrip1.Location = new-object System.Drawing.Point(0, 0)
$MenuStrip1.Size = new-object System.Drawing.Size(292, 24)
$MenuStrip1.TabIndex = 6
$MenuStrip1.Text = "MenuStrip1"
#~~< FileToolStripMenuItem >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$FileToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem
$FileToolStripMenuItem.Size = new-object System.Drawing.Size(35, 20)
$FileToolStripMenuItem.Text = "File"
#~~< OpenLogFileToolStripMenuItem >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$OpenLogFileToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem
$OpenLogFileToolStripMenuItem.Size = new-object System.Drawing.Size(152, 22)
$OpenLogFileToolStripMenuItem.Text = "Open Log File"
$OpenLogFileToolStripMenuItem.add_Click({Open-file($OpenLogFileToolStripMenuItem)})
#~~< ExitToolStripMenuItem >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$ExitToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem
$ExitToolStripMenuItem.Size = new-object System.Drawing.Size(152, 22)
$ExitToolStripMenuItem.Text = "Exit"
$ExitToolStripMenuItem.add_Click({CloseForm($ExitToolStripMenuItem)})
$FileToolStripMenuItem.DropDownItems.AddRange([System.Windows.Forms.ToolStripItem[]](@($OpenLogFileToolStripMenuItem, $ExitToolStripMenuItem)))
#~~< HelpToolStripMenuItem >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$HelpToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem
$HelpToolStripMenuItem.Size = new-object System.Drawing.Size(40, 20)
$HelpToolStripMenuItem.Text = "Help"
#~~< AboutToolStripMenuItem >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$AboutToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem
$AboutToolStripMenuItem.Size = new-object System.Drawing.Size(152, 22)
$AboutToolStripMenuItem.Text = "About"
$AboutToolStripMenuItem.add_Click({Show-About($AboutToolStripMenuItem)})
#~~< HowToToolStripMenuItem >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$HowToToolStripMenuItem = new-object System.Windows.Forms.ToolStripMenuItem
$HowToToolStripMenuItem.Size = new-object System.Drawing.Size(152, 22)
$HowToToolStripMenuItem.Text = "How To?"
$HowToToolStripMenuItem.add_Click({Show-HowTo($HowToToolStripMenuItem)})
$HelpToolStripMenuItem.DropDownItems.AddRange([System.Windows.Forms.ToolStripItem[]](@($AboutToolStripMenuItem, $HowToToolStripMenuItem)))
$MenuStrip1.Items.AddRange([System.Windows.Forms.ToolStripItem[]](@($FileToolStripMenuItem, $HelpToolStripMenuItem)))
$Panel1.Controls.Add($MenuStrip1)
$Panel1.Controls.Add($btnRun)
$Panel1.Controls.Add($Label1)
$Panel1.Controls.Add($TextBox1)
$Panel1.Controls.Add($btnBrowse)
$Panel1.Controls.Add($ProgressBar1)
$Panel1.Controls.Add($btnExit)
$Panel1.Controls.Add($DataGridView1)
$Panel1.Controls.Add($Menu)
$Form1.Controls.Add($Panel1)
#~~< Ping1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$Ping1 = New-Object System.Net.NetworkInformation.Ping
#~~< OpenFileDialog1 >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$OpenFileDialog1 = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog1.Filter = "Text Files|*.txt|CSV Files|*.csv|All Files|*.*"
$OpenFileDialog1.InitialDirectory = "C:"
$OpenFileDialog1.Title = "Open Computers File"
#~~< objNotifyIcon >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon
# Assign an Icon and Icon Type For the NotifyIcon Object
$objNotifyIcon.Icon = "D:\\Assaf\\Scripts\\Icons\\XP\\people15.ico"
$objNotifyIcon.BalloonTipIcon = "Info"
#endregion
#region Functions
function out-DataTable
# Function Creates a New Data Table that will be set as the Data Source of the Data Grid View
# Thanks to /\\/\\o\\/\\/ http:\\\\thePowerShellGuy.com
{
$dt = New-Object Data.datatable
$First = $TRUE
foreach ($item in $Input)
{
$DR = $DT.NewRow()
$Item.PsObject.get_properties() | foreach {
if ($first)
{
$Col = New-Object Data.DataColumn
$Col.ColumnName = $_.Name.ToString()
$DT.Columns.Add($Col) }
if ($_.value -eq $null)
{
$DR.Item($_.Name) = "[empty]"
}
elseif ($_.IsArray) {
$DR.Item($_.Name) = [string]::Join($_.value, ";")
}
else
{
$DR.Item($_.Name) = $_.value
}
}
$DT.Rows.Add($DR)
$First = $FALSE
}
return @(, ( $dt ))
}
function Join-Data
# Function Joins arrays and Strings to a Single Object with Members
# I Used the same principle of the Out-DataTable and converted it to Join Objects into one
# Using the Add-Member cmdlet. the Function writes to a predefiend object named $DataObject
{
param($objName="") # This parameter is used for objects that don't have member other than Length like Strings
foreach ($item in $Input)
{
$Item.PsObject.get_properties() | foreach{
if ($_.value -eq $null)
{
$DataObject | Add-Member noteproperty $_.Name "[empty]"
}
elseif ($_.IsArray) {
$DataObject | Add-Member noteproperty $_.Name [string]::Join($_.value, ";")
}
elseif ($objName -ne "") {
$DataObject | Add-Member noteproperty $objName $Item
}
else
{
$DataObject | Add-Member noteproperty $_.Name $_.value -Force
}
}
}
return @(,$DataObject)
}
function Get-Reg {
# Function Connects to a remote computer Registry using the Parameters it recievs
param(
$Hive,
$Key,
$Value,
$RemoteComputer="." # If not enterd Local Computer is Selected
)
# Connect to Remote Computer Registry
$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($Hive, $RemoteComputer)
# Open Remote Sub Key
$regKey= $reg.OpenSubKey($Key)
if($regKey.ValueCount -gt 0) # check if there are Values
{$regKey.GetValue($Value)} # Return Value
}
function Get-WMIItem {
# Function Retreives a specific Item from a remote computer's WMI
param(
$Class,
$RemoteComputer=".", # If not enterd Local Computer is Selected
$Item,
$Query="", # If not enterd an empty WMI SQL Query is Entered
$Filter="" # If not enterd an empty Filter is Entered
)
if ($Query -eq "") # No Specific WMI SQL Query
{
# Execute WMI Query, Return only the Requsted Items
gwmi -Class $Class -ComputerName $RemoteComputer -Filter $Filter -Property $Item | Select $Item
}
else # User Entered a WMI SQL Query
{gwmi -ComputerName $RemoteComputer -Query $Query | select $Item}
}
function Show-NotifyIcon {
# Function Controls the Notification Icon
# Changes its Title and Text
param(
$Title,
$Text
)
# Change Notify Icon Title
$objNotifyIcon.BalloonTipTitle = $Title
# Change Notify Icon Text
$objNotifyIcon.BalloonTipText = $Text
# Show Notify Icon for 10 Secs
$objNotifyIcon.Visible = $TRUE
$objNotifyIcon.ShowBalloonTip(10000)
}
#endregion
#region Event Loop
function Main
# Main Function, Runs the Form
{
[System.Windows.Forms.Application]::EnableVisualStyles()
[System.Windows.Forms.Application]::Run($Form1)
}
#endregion
#region Event Handlers
function BrowseFile($object)
# Function for Running the OpenFileDialog
# Used when Clicking on the Browse Button
{
$OpenFileDialog1.showdialog()
$TextBox1.Text = $OpenFileDialog1.FileName
$btnRun.Enabled = $TRUE
}
function Open-File( $object ){
# Function Open the Log File
if(Test-Path $LogFile){
Invoke-Item $LogFile
}
}
function Show-PopUp
# Function for Showing Custom Pop up Forms
{
param(
$PopupTitle,
$PopupText
)
#~~< PopupForm >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$PopupForm = New-Object System.Windows.Forms.Form
$PopupForm.ClientSize = New-Object System.Drawing.Size(381, 356)
$PopupForm.ControlBox = $false
$PopupForm.ShowInTaskbar = $false
$PopupForm.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterParent
$PopupForm.Text = $PopupTitle
#~~< PopupColse >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$PopupColse = New-Object System.Windows.Forms.Button
$PopupColse.Anchor = ([System.Windows.Forms.AnchorStyles]([System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right))
$PopupColse.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$PopupColse.Location = New-Object System.Drawing.Point(137, 321)
$PopupColse.Size = New-Object System.Drawing.Size(104, 23)
$PopupColse.TabIndex = 0
$PopupColse.Text = "Close"
$PopupColse.UseVisualStyleBackColor = $true
$PopupForm.AcceptButton = $PopupColse
$PopupForm.CancelButton = $PopupColse
#~~< PopupHeader >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$PopupHeader = New-Object System.Windows.Forms.Label
$PopupHeader.Font = New-Object System.Drawing.Font("Calibri", 15.75, ([System.Drawing.FontStyle]([System.Drawing.FontStyle]::Bold -bor [System.Drawing.FontStyle]::Italic)), [System.Drawing.GraphicsUnit]::Point, ([System.Byte](0)))
$PopupHeader.Location = New-Object System.Drawing.Point(137, 9)
$PopupHeader.Size = New-Object System.Drawing.Size(104, 23)
$PopupHeader.TabIndex = 2
$PopupHeader.Text = $PopupTitle
$PopupHeader.TextAlign = [System.Drawing.ContentAlignment]::MiddleCenter
#~~< PopUpTextArea >~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$PopUpTextArea = New-Object System.Windows.Forms.Label
$PopUpTextArea.Anchor = ([System.Windows.Forms.AnchorStyles]([System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right))
$PopUpTextArea.Location = New-Object System.Drawing.Point(12, 15)
$PopUpTextArea.Size = New-Object System.Drawing.Size(357, 265)
$PopUpTextArea.TabIndex = 1
$PopUpTextArea.Text = $PopupText
$PopUpTextArea.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft
$PopupForm.Controls.Add($PopupHeader)
$PopupForm.Controls.Add($PopUpTextArea)
$PopupForm.Controls.Add($PopupColse)
# Show Form
$PopupForm.Add_Shown({$PopupForm.Activate()})
[void]$PopupForm.showdialog()
}
function Show-About( $object ){
# Function Opens the About Page
$AboutText = @("
Script Title: Remote Computer Inventory`n
Script Author: Assaf Miron`n
Script Description: Collects Remote Computer Data Using WMI and Registry Access Outputs all information to a Data Grid Form and to a CSV Log File.`n
Log File Name: $LogFile")
Show-Popup -PopupTitle "About" -PopupText $AboutText
}
function Show-HowTo( $object ){
# Function Opens the Help Page
$HowToText = @("
1. Click on the Browse Button and select a TXT or a CSV File Containing Computer Names`n
2. After File is Selected click on the Run Button.`n
3. You will see a Notify Icon with the Coresponding Text.`n
4. The Script has begon collecting Remote Computer Inventory!`n
`nWhen The script is Done you will see a Popup Message and all data will be presented in the DataGrid.`n
** Because Poweshell works only in MTA mode there is no Option Copying the Data off the DataGrid...`n
5. All Data will be Exported to a Log File Located Here: $LogFile")
Show-Popup -PopupTitle "How To?" -PopupText $HowToText
}
function CloseForm($object)
# Function End the Program
{
$Form1.Close()
}
function RunScript($object)
# Function Runs the Program and starts collecting data
{
# Create an Array of Computers Enterd in the Input File
$arrComputers = Get-Content -path $textBox1.Text -encoding UTF8
# Create an Array to Keep all Computers Objects
$AllComputers = @()
# Init the Progress bar to it's Maximum Value
if(($arrComputers -is [array]) -eq $FALSE) { $ProgressBar1.Maximum = 1 }
else { $ProgressBar1.Maximum = $arrComputers.Count }
$ProgressBar1.Minimum = 0
$ProgressBar1.Value = 0
$ProgressBar1.Step = 1 # Define the Progress bar Step value
# Scan all Computers in the Array $arrComputers
foreach ($strComputer in $arrComputers)
{
# Uses the Ping Command to check if the Computer is Alive
if($Ping1.Send($strComputer).Status -eq "Success"){
Show-NotifyIcon -Title "Retriving Computer Information" -Text "Scanning $strComputer For Hardware Data"
# Collect Computer Details from Win32_computersystem Using WMI
$ComputerDet = Get-WMIItem -Class "Win32_computersystem" -RemoteComputer $strComputer -Item Caption,Domain,SystemType,Manufacturer,Model,NumberOfProcessors,TotalPhysicalMemory,UserName
if($ComputerDet.Caption.Length -gt 1) # Check to See if Any data was Collected at all
{
#region Total Memory Formating
# Check Total Physical Memory Size and Format it acourdingly
if($ComputerDet.TotalPhysicalMemory -ge 1GB){
$ComputerDet.TotalPhysicalMemory = ($ComputerDet.TotalPhysicalMemory/1GB).Tostring("# GB")} # Format to GB
else {$ComputerDet.TotalPhysicalMemory = ($ComputerDet.TotalPhysicalMemory/1MB).Tostring("# MB")} # Format to MB
#endregion
#region CPU Name
# Collect CPU Name Using WMI
$CPUName = Get-WMIItem -Class "Win32_Processor" -RemoteComputer $strComputer -Item Name
# CPU Names Can Contain Multiple Values, in Order to Insert Them into the DataGridView I Divde them to String with ";" Seperators
$arrCPUNames = @()
foreach($CPU in $CPUName){
$arrCPUNames = $CPU.Name.Trim()+";"+$arrCPUNames # the Sting of the CPU Name has White Space in The Begining - Trim It
}
#endregion
#region Operating System Data
# Collect Operating System and Service Pack Information Usin WMI
$OS = Get-WMIItem -Class "win32_operatingsystem" -RemoteComputer $strComputer -Item Caption,csdversion
#endregion
#region Chassis Type
# Collect Machine Chassis Using WMI
$ChassisType = Get-WMIItem -Class Win32_SystemEnclosure -RemoteComputer $strComputer -Item ChassisTypes
# Select Machine Chassis
switch ($ChassisType.ChassisTypes) {
1 {$ChassisType = "Other"}
2 {$ChassisType = "Unknown"}
3 {$ChassisType = "Desktop"}
4 {$ChassisType = "Low Profile Desktop"}
5 {$ChassisType = "Pizza Box"}
6 {$ChassisType = "Mini Tower"}
7 {$ChassisType = "Tower"}
8 {$ChassisType = "Portable"}
9 {$ChassisType = "Laptop"}
10 {$ChassisType = "Notebook"}
11 {$ChassisType = "Handheld"}
12 {$ChassisType = "Docking Station"}
13 {$ChassisType = "All-in-One"}
14 {$ChassisType = "Sub-Notebook"}
15 {$ChassisType = "Space Saving"}
16 {$ChassisType = "Lunch Box"}
17 {$ChassisType = "Main System Chassis"}
18 {$ChassisType = "Expansion Chassis"}
19 {$ChassisType = "Sub-Chassis"}
20 {$ChassisType = "Bus Expansion Chassis"}
21 {$ChassisType = "Peripheral Chassis"}
22 {$ChassisType = "Storage Chassis"}
23 {$ChassisType = "Rack Mount Chassis"}
24 {$ChassisType = "Sealed- PC"}
default {$ChassisType = "Unknown"}
}
#endregion
#region Automatic Updates
# Collect the Automatic Updates Options Using Registry Access
$AUOptions = Get-Reg -Hive LocalMachine -Key "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update" -Value "AUOptions"
# Collect the Automatic Updates Install Day Using Registry Access
$AUDay = Get-Reg -Hive LocalMachine -Key "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update" -Value "ScheduledInstallDay"
# Collect the Automatic Updates Install Time Using Registry Access
$AUTime = Get-Reg -Hive LocalMachine -Key "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update" -Value "ScheduledInstallTime"
if($AUOptions -eq $null){ # Automatic Updates is defined in Group Policy
$AUOptions = Get-Reg -Hive LocalMachine -Key "SOFTWARE\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU" -Value "AUOptions"
$AUDay = Get-Reg -Hive LocalMachine -Key "SOFTWARE\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU" -Value "ScheduledInstallDay"
$AUTime = Get-Reg -Hive LocalMachine -Key "SOFTWARE\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU" -Value "ScheduledInstallTime"
}
switch ($AUOptions){ # Check Wich Automatic Update Option is Selected
1 {$AUClient = "Automatic Updates is Turnd off."}
2 {$AUClient = "Notify for download and notify for install "}
3 {$AUClient = "Auto download and notify for install "}
4 {
switch ($AUDay) # Check on What day the Automatic Update Installs
{
0 {$InstDay = "Every Day"}
1 {$InstDay = "Sunday"}
2 {$InstDay = "Monday"}
3 {$InstDay = "Tuesday"}
4 {$InstDay = "Wensday"}
5 {$InstDay = "Thursday"}
6 {$InstDay = "Friday"}
7 {$InstDay = "Saturday"}
}
# Check on What time the Automatic Update Installs
if ($AUTime -le 12) { $AUTime = $AUTime.ToString() + " AM" } else { $AUTime = ($AUTime -12) + " PM" }
$AUClient = "Auto download and schedule the install - "+$InstDay+" "+$AUTime}
Defualt {"Automatic Updates is not Set."} # No setting Collected
}
#endregion
#region Computer Total Health
# Collect Avialable Memory with WMI
$AvialableMem = Get-WMIItem -Class "Win32_PerfFormattedData_PerfOS_Memory" -RemoteComputer $strComputer -Item "AvailableMBytes"
# Collect Disk Queue,Queue Length, Processor time Data Using WMI
$DiskQueue = Get-WMIItem -Class "Win32_PerfFormattedData_PerfDisk_LogicalDisk" -RemoteComputer $strComputer -Item CurrentDiskQueueLength
$QueueLength = Get-WMIItem -Class "Win32_PerfFormattedData_PerfNet_ServerWorkQueues" -RemoteComputer $strComputer -Item QueueLength
$Processor = Get-WMIItem -Class "Win32_PerfFormattedData_PerfOS_Processor" -RemoteComputer $strComputer -Item PercentProcessorTime
$intHealth = 0 # integer for Collecting Computer Total Health
# Using the Avialable Memory to Check Computer Totla Health
if($AvialableMem.AvailableMBytes -lt 4) { $intHealth += 1; $strHealth += "Low Free Memory;" }
# Using Current Disk Queue Length to Check Computer Total Health
if($DiskQueue.CurrentDiskQueueLength -gt 2) { $intHealth += 1; $strHealth += "High Disk Queue;" }
# Using Queue Length to Check Computer Total Health
if($QueueLength.QueueLength -gt 4) { $intHealth += 1; $strHealth += "Long Disk Queue;" }
# Using Processor Time(%) to Check Computer Total Health
if($Processor.PercentProcessorTime -gt 90) { $intHealth += 1; $strHealth += "Processor Usage Over 90%;" }
# If the integer is Bigger than 1 so the computer is Unhealthy, Describe Computer Problems
# Else The Computer is Healthy
if($intHealth -gt 1) { $ComputerTotalHealth = "UnHealthy, " + $strHealth } else { $ComputerTotalHealth = "Healthy" }
#endregion
#region Avialable Memory Formating
# Format Avialable Memory MB
$AvialableMem.AvailableMBytes = $AvialableMem.AvailableMBytes.ToString("# MB")
#endregion
#region Disk Drive Info
# Collect Disk Drive Information Using WMI
$DriveInfo = Get-WMIItem -Class "Win32_LogicalDisk" -RemoteComputer $strComputer -Item Caption,Size,FreeSpace
# Format Every Drive Size and Free Space
foreach($DRSize in $DriveInfo)
{ # Check Object Size and Format Acourdingly
if($DRSize.Size -ge 1GB){
$DRSize.Size = ($DRSize.Size/1GB).ToString("# GB") } # Format to GB
else { $DRSize.Size = ($DRSize.Size/1MB).ToString("# MB") } # Format to MB
if($DRSize.FreeSpace -ge 1GB){
$DRSize.FreeSpace = ($DRSize.FreeSpace/1GB).ToString("# GB") } # Format to GB
else { $DRSize.FreeSpace = ($DRSize.FreeSpace/1MB).ToString("# MB") } # Format to MB
}
# Disk Drives Can Contain Multiple Values, in Order to Insert Them into the DataGridView I divide them to Strings with ";" Seperators
$arrDiskDrives = @()
$arrDiskSize = @()
$arrDiskFreeSpace = @()
foreach($Drive in $DriveInfo){
$arrDiskDrives = $Drive.Caption+";"+$arrDiskDrives
$arrDiskSize = $Drive.Size+";"+$arrDiskSize
$arrDiskFreeSpace = $Drive.FreeSpace+";"+$arrDiskFreeSpace
}
#endregion
#region IP Addresses
# Collect IPAddresses Using WMI, Filter only Enabled IPs
$IPAddress = Get-WmiItem -Class "Win32_NetworkAdapterConfiguration" -Filter "IPEnabled = True" -RemoteComputer $strComputer -Item IPAddress
# IPAddress Can Contain Multiple Values, in Order to Insert Them into the DataGridView I divide them to Strings with ";" Seperators
$arrIPAddress = @()
foreach($IP in $IPAddress){
$arrIPAddress = $IP.IPAddress[0]+";"+$arrIPAddress
}
#endregion
#region Time Zone
# Collect Time Zone Information Using WMI
$TimeZone = Get-WMIItem -Class "Win32_TimeZone" -RemoteComputer $strComputer -Item Bias,StandardName
$TimeZone.Bias = $TimeZone.Bias/60
#endregion
#region System Restore Status
# Collect System Restore Information Using Remote Registry
$SysRestoreStatus = Get-Reg -Hive LocalMachine -RemoteComputer $strComputer -Key "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\SystemRestore" -Value "DisableSR"
if ($SysRestoreStatus -eq 0) { $SysRestoreStatus = "Enabled" } else { $SysRestoreStatus = "Disabled" }
#endregion
#region Offline Files Status
# Collect Offline Files Information Using Remote Registry
$OfflineFolStatus = Get-Reg -Hive LocalMachine -RemoteComputer $strComputer -Key "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\NetCache" -Value "Enabled"
if ($OfflineFolStatus -eq 1) { $OfflineFolStatus = "Enabled" } else { $OfflineFolStatus = "Disabled" }
#endregion
#region Printers
# Collect Printers Information Using WMI
$Printers = Get-WMIItem -Class "Win32_Printer" -RemoteComputer $strComputer -Item Name,PortName,Caption
# Printers Contain Multiple Values, in Order to Insert Them into the DataGridView I divide them to Strings with ";" Seperators
$arrPrinters = @()
foreach($Printer in $Printers){
$arrPrinters = $Printer.Name+"("+$Printer.PortName+");"+$arrPrinters
}
#endregion
#region BIOS Serial Number
# Collect BIOS Serial Number Using WMI
$BIOSSN = Get-WMIItem -Class "Win32_Bios" -RemoteComputer $strComputer -Item SerialNumber
#endregion
#region Network Drives
# Collect Network Drives Using WMI
$NetDrives = Get-WMIItem -Query "Select * From Win32_LogicalDisk Where DriveType = 4" -RemoteComputer $strComputer -Item DeviceID,ProviderName
# Network Drives Contain Multiple Values, in Order to Insert Them into the DataGridView I divide them to Strings with ";" Seperators
$arrNetDrives = @()
foreach($NetDrive in $NetDrives){
$arrNetDrives = $NetDrive.DeviceID+"("+$NetDrive.ProviderName+");"+$arrNetDrives
}
#endregion
#region Anti-Virus Client Data
# Collect Anti-Virus Info Using Remote Registry
$AVParentServer = Get-Reg -Hive LocalMachine -RemoteComputer $strComputer -Key "SOFTWARE\\Intel\\LANDesk\\VirusProtect6\\CurrentVersion" -Value "Parent"
# Read the Anti-Virus Virus Definition File and Format it to an actual Date
$VirusDefFile = "C:\\Program Files\\Common Files\\Symantec Shared\\VirusDefs\\definfo.dat"
If(Test-Path $VirusDefFile){
$AVDefs = Get-Content $VirusDefFile | where { $_ -match "CurDefs" }
$AVDefs = $AVDefs.Substring(8)
$AVDefs = [datetime]($AVDefs.Substring(5,1) + "/" + $AVDefs.Substring(6,2) + "/" + $AVDefs.substring(0,4))
}
Else { $AVDefs = "" }
#endregion
#region Operating Systems Hotfixes
# Collect all Hotfix Information Using WMI
$HotFixes = Get-WMIItem -Class "Win32_QuickFixEngineering" -RemoteComputer $strComputer -Item Description,HotFixID,ServicePackInEffect
# HotFixes Contain Multiple Values, in Order to Insert Them into the DataGridView I divide them to Strings with ";" Seperators
$arrHotFixes = @()
foreach($Fix in $HotFixes){
if($Fix.Description -eq ""){
if($Fix.HotFixID -eq "File 1"){ $arrHotFixes = $Fix.ServicePackInEffect+";"+$arrHotFixes }
else { $arrHotFixes =$Fix.HotFixID+";"+$arrHotFixes }
}
else { $arrHotFixes = $Fix.Description+";"+$arrHotFixes }
}
#endRegion
#region Remote Desktop Status
# Collect Remote Desktop Protocol Status Using Remote Registry
$RDPStatus = Get-Reg -Hive LocalMachine -remoteComputer $strComputer -Key "SYSTEM\\CurrentControlSet\\Control\\Terminal Server" -Value "fAllowToGetHelp"
if($RDPStatus -eq 0) {$RDPStatus = "Enabled" } else {$RDPStatus = "Disabled" }
#endregion
#region Remote Assistance Status
# Collect Remote Assistance Status Using Remote Registry
$RAStatus = Get-Reg -Hive LocalMachine -remoteComputer $strComputer -Key "SYSTEM\\CurrentControlSet\\Control\\Terminal Server" -Value "fDenyTSConnections"
if($RAStatus -eq 1) {$RAStatus = "Enabled" } else {$RAStatus = "Disabled" }
#endregion
# Change the Notify Icon to Show Exporting Text
Show-NotifyIcon -Text "Exporting $strComputer Information" -Title "Exporting..."
#region Check the Null Valued Paramters
# If one of the Parameters are Null, Enter Space (looks better in the Table)
if($ComputerDet -eq $Null){ $ComputerDet = " " }
if($ChassisType -eq $Null){ $ChassisType = " " }
if($BIOSSN -eq $Null){ $BIOSSN = " " }
if($CPUName -eq $Null){ $CPUName = " " }
if($AvialableMem -eq $Null){ $AvialableMem = " " }
if($OS -eq $Null){ $OS = " " }
if($SP -eq $Null){ $SP = " " }
if($IPAddress -eq $Null){ $IPAddress = " " }
if($HotFixes -eq $Null){ $HotFixes = " " }
if($arrDiskDrives -eq $Null){ $arrDiskDrives=" " }
if($arrDiskFreeSpace -eq $Null){ $arrDiskFreeSpace=" " }
if($arrDiskSize -eq $Null){ $arrDiskSize=" " }
if($RDPStatus -eq $Null){ $RDPStatus = " " }
if($RAStatus -eq $Null){ $RAStatus = " " }
if($AUClient -eq $Null){ $AUClient = " " }
if($AVParentServer -eq $Null){ $AVParentServer = " " }
if($AVDefs -eq $Null){ $AVDefs = " " }
if($Printers -eq $Null){ $Printers = " " }
if($ComputerTotalHealth -eq $Null){ $ComputerTotalHealth = " " }
#endregion
#region Creating the Data Object - $DataObject
# Create an Empty psObject, $DataObjcet - Used by this Name in the Join-Data Function
$DataObject = New-Object psobject
# Join all the Data to the DataObject
$ComputerDet | Join-Data # Contians Multiple Values, No need to Define a Name
$ChassisType | Join-Data -objName "Chassis Type" # String with no Values - Define a Name
$BIOSSN | Join-Data # Contians Multiple Values, No need to Define a Name
$CPUName | Join-Data # Contians Multiple Values, No need to Define a Name
$AvialableMem | Join-Data # Contians Multiple Values, No need to Define a Name
$OS.Caption | Join-Data -objName "Operating System" # Contians Multiple Values, Caption Value canot be overwritten - Define a Name to a certian Value
$OS.CsdVersion | Join-Data -objName "Service Pack" # String with no Values - Define a Name
$arrIPAddress | Join-Data -objName "IP Addresses" # String with no Values - Define a Name
$arrHotFixes| Join-Data -objName "HotFixes" # String with no Values - Define a Name
$arrDiskDrives| Join-Data -objName "Disk Drives" # String with no Values - Define a Name
$RDPStatus.ToString() | Join-Data -objName "Remote Desktop" # String with no Values - Define a Name
$RAStatus.ToString() | Join-Data -objName "Remote Assistance" # String with no Values - Define a Name
$AUClient | Join-Data -objName "Automatic Updates" # String with no Values - Define a Name
$AVParentServer | Join-Data -objName "Anti-Virus Server" # String with no Values - Define a Name
$AVDefs | Join-Data -objName "Anti-Virus Defs" # String with no Values - Define a Name
$arrPrinters | Join-Data -objName "Printers" # String with no Values - Define a Name
$ComputerTotalHealth | Join-Data -objName "Computer Totla Health" # String with no Values - Define a Name
#endregion
$AllComputers += $DataObject
#region Exporting data
# Export the DataObject to the DataGridView Using the out-DataTable
$DataTable = $AllComputers | out-dataTable
# Define Data Grid's Data Source to the DataTable we Created
$DataGridView1.DataSource = $DataTable.psObject.baseobject
$DataGridView1.Refresh() # Refresh the Table View in order to View the new lines
# Export all the Data to the Log File
$DataObject | Export-Csv -Encoding OEM -Path $LogFile
#endregion
}
}
else { # No Ping to Computer
$objNotifyIcon.BalloonTipIcon = "Error"
Show-NotifyIcon -Title "$strComputer is not avialable" -Text "No Ping to $strComputer.`nNo Data was Collected"
$objNotifyIcon.BalloonTipIcon = "Info"
}
$ProgressBar1.PerformStep()
}
#region Finishing - Script is Done
# Assign an Icon and Icon Type For the NotifyIcon Object
$objNotifyIcon.Icon = "D:\\Assaf\\Scripts\\Icons\\XP\\people5.ico"
$objNotifyIcon.BalloonTipIcon = "Info"
# Pop Up a Message box
$MSGObject = new-object -comobject wscript.shell
$MSGResult = $MSGObject.popup("Script Has Finished Running!",0,"I'm Done",0)
# Show Notify Icon with Finishing Text
$objNotifyIcon.BalloonTipText = "Done!`nFile Saved in "+$LogFile
$objNotifyIcon.Visible = $TRUE
$objNotifyIcon.ShowBalloonTip(10000)
$objNotifyIcon.Visible = $FALSE # Set to False so that the Notify Icon will Disapear after the Script is Done
#endregion
}
Main # This call must remain below all other event functions
#endregion
|
PowerShellCorpus/PoshCode/Get-OpenLDAP.ps1
|
Get-OpenLDAP.ps1
|
Param($user,
$password = $(Read-Host "Enter Password" -asSec),
$filter = "(objectclass=user)",
$server = $(throw '$server is required'),
$path = $(throw '$path is required'),
[switch]$all,
[switch]$verbose)
function GetSecurePass ($SecurePassword) {
$Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($SecurePassword)
$password = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr)
[System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($Ptr)
$password
}
if($verbose){$verbosepreference = "Continue"}
$DN = "LDAP://$server/$path"
Write-Verbose "DN = $DN"
$auth = [System.DirectoryServices.AuthenticationTypes]::FastBind
Write-Verbose "Auth = FastBind"
$de = New-Object System.DirectoryServices.DirectoryEntry($DN,$user,(GetSecurePass $Password),$auth)
Write-Verbose $de
Write-Verbose "Filter: $filter"
$ds = New-Object system.DirectoryServices.DirectorySearcher($de,$filter)
Write-Verbose $ds
if($all)
{
Write-Verbose "Finding All"
$ds.FindAll()
}
else
{
Write-Verbose "Finding One"
$ds.FindOne()
}
|
PowerShellCorpus/PoshCode/coolprompt.ps1
|
coolprompt.ps1
|
$global:wmilocalcomputer = get-WMIObject -class Win32_OperatingSystem -computer "."
$global:lastboottime=[System.Management.ManagementDateTimeconverter]::ToDateTime($wmilocalcomputer.lastbootuptime)
$global:originaltitle = [console]::title
function prompt
{
$up=$(get-date)-$lastboottime
$upstr="$([datetime]::now.toshorttimestring()) $([datetime]::now.toshortdatestring()) up $($up.days) days, $($up.hours) hours, $($up.minutes) minutes"
$dir = $pwd.path
$homedir = (get-psprovider 'FileSystem').home
if ($homedir -ne "" -and $dir.toupper().startswith($homedir.toupper()))
{
$dir=$dir.remove(0,$homedir.length).insert(0,'~')
}
$retstr = "$env:username@$($env:computername.tolower())●$dir"
[console]::title = "$global:originaltitle ♦ $retstr ♦ $upstr"
return "$retstr►"
}
|
PowerShellCorpus/PoshCode/d5ae4c48-9aa7-424e-9d74-61c687175d1b.ps1
|
d5ae4c48-9aa7-424e-9d74-61c687175d1b.ps1
|
get-vc virtualCenterServerName
get-vmhost | Get-VirtualSwitch -Name SwitchName | New-VirtualPortGroup -Name VLAN_12 -VLANID 12
|
PowerShellCorpus/PoshCode/Set-SecureAutoLogon.ps1
|
Set-SecureAutoLogon.ps1
|
[cmdletbinding()]
param (
[Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [string]
$Username,
[Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [System.Security.SecureString]
$Password,
[Parameter()] [string]
$Domain,
[Parameter()] [Int]
$AutoLogonCount,
[Parameter()] [switch]
$RemoveLegalPrompt,
[Parameter()] [System.IO.FileInfo]
$BackupFile
)
begin {
[string] $WinlogonPath = "HKLM:\\Software\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon"
[string] $WinlogonBannerPolicyPath = "HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"
[string] $Enable = 1
[string] $Disable = 0
# C# Code to P-invoke LSA LsaStorePrivateData function.
Add-Type @"
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace ComputerSystem
{
public class LSAutil
{
[StructLayout(LayoutKind.Sequential)]
private struct LSA_UNICODE_STRING
{
public UInt16 Length;
public UInt16 MaximumLength;
public IntPtr Buffer;
}
[StructLayout(LayoutKind.Sequential)]
private struct LSA_OBJECT_ATTRIBUTES
{
public int Length;
public IntPtr RootDirectory;
public LSA_UNICODE_STRING ObjectName;
public uint Attributes;
public IntPtr SecurityDescriptor;
public IntPtr SecurityQualityOfService;
}
private enum LSA_AccessPolicy : long
{
POLICY_VIEW_LOCAL_INFORMATION = 0x00000001L,
POLICY_VIEW_AUDIT_INFORMATION = 0x00000002L,
POLICY_GET_PRIVATE_INFORMATION = 0x00000004L,
POLICY_TRUST_ADMIN = 0x00000008L,
POLICY_CREATE_ACCOUNT = 0x00000010L,
POLICY_CREATE_SECRET = 0x00000020L,
POLICY_CREATE_PRIVILEGE = 0x00000040L,
POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080L,
POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100L,
POLICY_AUDIT_LOG_ADMIN = 0x00000200L,
POLICY_SERVER_ADMIN = 0x00000400L,
POLICY_LOOKUP_NAMES = 0x00000800L,
POLICY_NOTIFICATION = 0x00001000L
}
[DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
private static extern uint LsaRetrievePrivateData(
IntPtr PolicyHandle,
ref LSA_UNICODE_STRING KeyName,
out IntPtr PrivateData
);
[DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
private static extern uint LsaStorePrivateData(
IntPtr policyHandle,
ref LSA_UNICODE_STRING KeyName,
ref LSA_UNICODE_STRING PrivateData
);
[DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
private static extern uint LsaOpenPolicy(
ref LSA_UNICODE_STRING SystemName,
ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
uint DesiredAccess,
out IntPtr PolicyHandle
);
[DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
private static extern uint LsaNtStatusToWinError(
uint status
);
[DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
private static extern uint LsaClose(
IntPtr policyHandle
);
[DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
private static extern uint LsaFreeMemory(
IntPtr buffer
);
private LSA_OBJECT_ATTRIBUTES objectAttributes;
private LSA_UNICODE_STRING localsystem;
private LSA_UNICODE_STRING secretName;
public LSAutil(string key)
{
if (key.Length == 0)
{
throw new Exception("Key lenght zero");
}
objectAttributes = new LSA_OBJECT_ATTRIBUTES();
objectAttributes.Length = 0;
objectAttributes.RootDirectory = IntPtr.Zero;
objectAttributes.Attributes = 0;
objectAttributes.SecurityDescriptor = IntPtr.Zero;
objectAttributes.SecurityQualityOfService = IntPtr.Zero;
localsystem = new LSA_UNICODE_STRING();
localsystem.Buffer = IntPtr.Zero;
localsystem.Length = 0;
localsystem.MaximumLength = 0;
secretName = new LSA_UNICODE_STRING();
secretName.Buffer = Marshal.StringToHGlobalUni(key);
secretName.Length = (UInt16)(key.Length * UnicodeEncoding.CharSize);
secretName.MaximumLength = (UInt16)((key.Length + 1) * UnicodeEncoding.CharSize);
}
private IntPtr GetLsaPolicy(LSA_AccessPolicy access)
{
IntPtr LsaPolicyHandle;
uint ntsResult = LsaOpenPolicy(ref this.localsystem, ref this.objectAttributes, (uint)access, out LsaPolicyHandle);
uint winErrorCode = LsaNtStatusToWinError(ntsResult);
if (winErrorCode != 0)
{
throw new Exception("LsaOpenPolicy failed: " + winErrorCode);
}
return LsaPolicyHandle;
}
private static void ReleaseLsaPolicy(IntPtr LsaPolicyHandle)
{
uint ntsResult = LsaClose(LsaPolicyHandle);
uint winErrorCode = LsaNtStatusToWinError(ntsResult);
if (winErrorCode != 0)
{
throw new Exception("LsaClose failed: " + winErrorCode);
}
}
public void SetSecret(string value)
{
LSA_UNICODE_STRING lusSecretData = new LSA_UNICODE_STRING();
if (value.Length > 0)
{
//Create data and key
lusSecretData.Buffer = Marshal.StringToHGlobalUni(value);
lusSecretData.Length = (UInt16)(value.Length * UnicodeEncoding.CharSize);
lusSecretData.MaximumLength = (UInt16)((value.Length + 1) * UnicodeEncoding.CharSize);
}
else
{
//Delete data and key
lusSecretData.Buffer = IntPtr.Zero;
lusSecretData.Length = 0;
lusSecretData.MaximumLength = 0;
}
IntPtr LsaPolicyHandle = GetLsaPolicy(LSA_AccessPolicy.POLICY_CREATE_SECRET);
uint result = LsaStorePrivateData(LsaPolicyHandle, ref secretName, ref lusSecretData);
ReleaseLsaPolicy(LsaPolicyHandle);
uint winErrorCode = LsaNtStatusToWinError(result);
if (winErrorCode != 0)
{
throw new Exception("StorePrivateData failed: " + winErrorCode);
}
}
}
}
"@
}
process {
try {
$decryptedPass = [Runtime.InteropServices.Marshal]::PtrToStringAuto(
[Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password)
)
if ($BackupFile) {
#Initialize the hash table with a string comparer to allow case sensitive keys.
#This allows differentiation between the winlogon and system policy logon banner strings.
$OrigionalSettings = New-Object System.Collections.Hashtable ([system.stringcomparer]::CurrentCulture)
$OrigionalSettings.AutoAdminLogon = (Get-ItemProperty $WinlogonPath ).AutoAdminLogon
$OrigionalSettings.ForceAutoLogon = (Get-ItemProperty $WinlogonPath).ForceAutoLogon
$OrigionalSettings.DefaultUserName = (Get-ItemProperty $WinlogonPath).DefaultUserName
$OrigionalSettings.DefaultDomainName = (Get-ItemProperty $WinlogonPath).DefaultDomainName
#$OrigionalSettings.DefaultPassword = (Get-ItemProperty $WinlogonPath).DefaultPassword
$OrigionalSettings.AutoLogonCount = (Get-ItemProperty $WinlogonPath).AutoLogonCount
#The winlogon logon banner settings.
$OrigionalSettings.LegalNoticeCaption = (Get-ItemProperty $WinlogonPath).LegalNoticeCaption
$OrigionalSettings.LegalNoticeText = (Get-ItemProperty $WinlogonPath).LegalNoticeText
#The system policy logon banner settings.
$OrigionalSettings.legalnoticecaption = (Get-ItemProperty $WinlogonBannerPolicyPath).legalnoticecaption
$OrigionalSettings.legalnoticetext = (Get-ItemProperty $WinlogonBannerPolicyPath).legalnoticetext
$OrigionalSettings | Export-Clixml -Depth 10 -Path $BackupFile
}
# Store the password securely.
$lsaUtil = New-Object ComputerSystem.LSAutil -ArgumentList "DefaultPassword"
$lsaUtil.SetSecret($decryptedPass)
Set-ItemProperty -Path $WinlogonPath -Name AutoAdminLogon -Value $Enable -Force -ErrorAction Stop
Set-ItemProperty -Path $WinlogonPath -Name DefaultUserName -Value $Username -Force -ErrorAction Stop
Set-ItemProperty -Path $WinlogonPath -Name DefaultDomainName -Value $Domain -Force -ErrorAction Stop
if ($AutoLogonCount) {
Set-ItemProperty -Path $WinlogonPath -Name AutoLogonCount -Value $AutoLogonCount -Force -ErrorAction Stop
} else {
Remove-ItemProperty -Path $WinlogonPath -Name AutoLogonCount -ErrorAction SilentlyContinue
}
if ($RemoveLegalPrompt) {
Set-ItemProperty -Path $WinlogonPath -Name LegalNoticeCaption -Value $null -Force
Set-ItemProperty -Path $WinlogonPath -Name LegalNoticeText -Value $null -Force
Set-ItemProperty -Path $WinlogonBannerPolicyPath -Name legalnoticecaption -Value $null -Force
Set-ItemProperty -Path $WinlogonBannerPolicyPath -Name legalnoticetext -Value $null -Force
}
} catch {
throw 'Failed to set auto logon. The error was: "{0}".' -f $_
}
}
<#
.SYNOPSIS
Enables auto logon using the specified username and password.
.PARAMETER Username
The username of the user to automatically logon as.
.PARAMETER Password
The password for the user to automatically logon as.
.PARAMETER Domain
The domain of the user to automatically logon as.
.PARAMETER AutoLogonCount
The number of logons that auto logon will be enabled.
.PARAMETER RemoveLegalPrompt
Removes the system banner to ensure interventionless logon.
.PARAMETER BackupFile
If specified the existing settings such as the system banner text will be backed up to the specified file.
.EXAMPLE
PS C:\\> Set-AutoLogon `
-Username $env:USERNAME `
-Password $AdminUserPass `
-AutoLogonCount 2 `
-RemoveLegalPrompt `
-BackupFile "$scriptHome\\WinlogonBackup.xml"
.INPUTS
None.
.OUTPUTS
None.
.NOTES
Revision History:
2011-04-19 : Andy Arismendi - Created.
2011-09-29 : Andy Arismendi - Changed to use LSA secrets to store password securely.
.LINK
http://support.microsoft.com/kb/324737
.LINK
http://msdn.microsoft.com/en-us/library/aa378750
#>
|
PowerShellCorpus/PoshCode/Get-FileTail 1.0.ps1
|
Get-FileTail 1.0.ps1
|
#.Synopsis
# Show the last n lines of a text file
#.Description
# This is just a tail script for PowerShell, using seekable streams to avoid reading the whole file and using v2 eventing to detect changes and provide a -Continuous mode.
#.Parameter Name
# The file name to tail
#.Parameter Lines
# The number of lines to display (or start with, in -Continuous mode)
#.Parameter Continuous
# Whether or not to continue watching for new content to be added to the tail of the function
#.Parameter Linesep
# Allows you to override the line separator character used for counting lines.
# By default we use `n, which works for Windows `r`n and Linux `n but not old-school Mac `r files
#.Parameter Encoding
# Allows you to manually override the text encoding.
# By default we can detect various unicode formats, and we default to UTF-8 which will handle ASCII
#.Example
# Get-FileTail ${Env:windir}\\Windowsupdate.log 25
#
# get the last 25 lines from the specified log
#.Example
# Get-FileTail ${Env:windir}\\Windowsupdate.log -Continuous
#
# Start reading from WindowsUpdate.log as it is written to.
#function Get-FileTail {
PARAM( $Name, [int]$lines=10, [switch]$continuous, $linesep = "`n", [string]$encoding )
BEGIN {
if(Test-Path $Name) {
$Name = (Convert-Path (Resolve-Path $Name))
}
[byte[]]$buffer = new-object byte[] 1024
if($encoding) {
[System.Text.Encoding]$encoding = [System.Text.Encoding]::GetEncoding($encoding)
Write-Debug "Specified Encoding: $encoding"
}
# else {
# $detector = New-Object System.IO.StreamReader $Name, $true
# [Text.Encoding]$encoding = $detector.CurrentEncoding
# Write-Debug "Detected Encoding: $encoding"
# $detector.Dispose()
# }
function tailf {
PARAM($StartOfTail=0)
[string[]]$content = @()
#trap { return }
## You must use ReadWrite sharing so you can open files which other apps are writing to...
$reader = New-Object System.IO.FileStream $Name, "OpenOrCreate", "Read", "ReadWrite", 8, "None"
if(!$encoding) {
$b1 = $reader.ReadByte()
$b2 = $reader.ReadByte()
$b3 = $reader.ReadByte()
$b4 = $reader.ReadByte()
if (($b1 -eq 0xEF) -and ($b2 -eq 0xBB) -and ($b3 -eq 0xBF)) {
Write-Debug "Detected Encoding: UTF-8"
[System.Text.Encoding]$encoding = [System.Text.Encoding]::UTF8
} elseif (($b1 -eq 0) -and ($b2 -eq 0) -and ($b3 -eq 0xFE) -and ($b4 -eq 0xFF)) {
Write-Debug "Detected Encoding: 12001 UTF-32 Big-Endian"
[System.Text.Encoding]$encoding = [System.Text.Encoding]::GetEncoding(12001)
} elseif (($b1 -eq 0xFF) -and ($b2 -eq 0xFE) -and ($b3 -eq 0) -and ($b4 -eq 0)) {
Write-Debug "Detected Encoding: 12000 UTF-32 Little-Endian"
[System.Text.Encoding]$encoding = [System.Text.Encoding]::UTF32
} elseif (($b1 -eq 0xFE) -and ($b2 -eq 0xFF)) {
Write-Debug "Detected Encoding: 1201 UTF-16 Big-Endian"
[System.Text.Encoding]$encoding = [System.Text.Encoding]::BigEndianUnicode
} elseif (($b1 -eq 0xFF) -and ($b2 -eq 0xFE)) {
Write-Debug "Detected Encoding: 1200 UTF-16 Little-Endian"
[System.Text.Encoding]$encoding = [System.Text.Encoding]::Unicode
} elseif (($b1 -eq 0x2B) -and ($b2 -eq 0x2F) -and ($b3 -eq 0x76) -and (
($b4 -eq 0x38) -or ($b4 -eq 0x39) -or ($b4 -eq 0x2b) -or ($b4 -eq 0x2f))) {
Write-Debug "Detected Encoding: UTF-7"
[System.Text.Encoding]$encoding = [System.Text.Encoding]::UTF7
} else {
Write-Debug "Unknown Encoding: [$('0x{0:X}' -f $b1) $('0x{0:X}' -f $b2) $('0x{0:X}' -f $b3) $('0x{0:X}' -f $b4)] using UTF-8"
[System.Text.Encoding]$encoding = [System.Text.Encoding]::UTF8
}
}
#trap { Write-Warning $_; $reader.Close(); throw }
if($StartOfTail -eq 0) {
$StartOfTail = $reader.Length - $buffer.Length
} else {
$OnlyShowNew = $true
}
#Write-Verbose "Starting Tail: $StartOfTail of $($reader.Length)"
do {
$pos = $reader.Seek($StartOfTail, "Begin")
#Write-Verbose "Seek: $Pos"
do {
$count = $reader.Read($buffer, 0, $buffer.Length);
#Write-Verbose "Read: $Count"
$content += $encoding.GetString($buffer,0,$count).Split($linesep)
} while( $count -gt 0 )
$StartOfTail -= $buffer.Length
# keep going if we don't have enough lines,
} while(!$OnlyShowNew -and ($content.Length -lt $lines) -and $StartOfTail -gt 0)
## ADJUST OUR OUTPUT ...
$end = $reader.Length
#Write-Verbose "Ended Tail: $end of $($reader.Length)"
if($content) {
$output = [string]::Join( "`n", @($content[-$lines..-1]) )
$len = $output.Length
$output = $output.TrimEnd("`n")
$end -= ($len - $output.Length) - 1
}
Write-Output $end
if($output.Length -ge 1) {
Write-Host $output -NoNewLine
}
#trap { continue }
$reader.Close();
}
}
PROCESS {
[int]$StartOfTail = tailf 0
if($continuous) {
$Null = unregister-event "FileChanged" -ErrorAction 0
$fsw = new-object system.io.filesystemwatcher
$fsw.Path = split-path $Name
$fsw.Filter = Split-Path $Name -Leaf
$fsw.EnableRaisingEvents = $true
$null = Register-ObjectEvent $fsw Changed "FileChanged" -MessageData $Name
while($true) {
wait-event FileChanged | % {
[int]$StartOfTail = tailf $StartOfTail -newonly
$null = Remove-Event $_.EventIdentifier
}
}
unregister-event "FileChanged"
}
Write-Host
}
#}
|
PowerShellCorpus/PoshCode/Get-FSMORoleOwner_1.ps1
|
Get-FSMORoleOwner_1.ps1
|
Function Get-FSMORoleOwner {
<#
.SYNOPSIS
Retrieves the list of FSMO role owners of a forest and domain
.DESCRIPTION
Retrieves the list of FSMO role owners of a forest and domain
.NOTES
Name: Get-FSMORoleOwner
Author: Boe Prox
DateCreated: 06/9/2011
.EXAMPLE
Get-FSMORoleOwner
DomainNamingMaster : dc1.rivendell.com
Domain : rivendell.com
RIDOwner : dc1.rivendell.com
Forest : rivendell.com
InfrastructureOwner : dc1.rivendell.com
SchemaMaster : dc1.rivendell.com
PDCOwner : dc1.rivendell.com
Description
-----------
Retrieves the FSMO role owners each domain in a forest. Also lists the domain and forest.
#>
Try {
$forest = [system.directoryservices.activedirectory.Forest]::GetCurrentForest()
ForEach ($domain in $forest.domains) {
$forestproperties = @{
Forest = $Forest.name
Domain = $domain.name
SchemaMaster = $forest.SchemaRoleOwner
DomainNamingMaster = $forest.NamingRoleOwner
RIDOwner = $Domain.RidRoleOwner
PDCOwner = $Domain.PdcRoleOwner
InfrastructureOwner = $Domain.InfrastructureRoleOwner
}
$newobject = New-Object PSObject -Property $forestproperties
$newobject.PSTypeNames.Insert(0,"ForestRoles")
$newobject
}
}
Catch {
Write-Warning "$($Error)"
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.