full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PoshCode/Get-IISLogLocation.ps1
|
Get-IISLogLocation.ps1
|
Function Get-IISLogLocation {
<#
.SYNOPSIS
This function can be ran against a server or multiple servers to locate
the log file location for each web site configured in IIS.
.DESCRIPTION
This function can be ran against a server or multiple servers to locate
the log file location for each web site configured in IIS.
.PARAMETER computer
Name of computer to query log file location.
.NOTES
Name: Get-IISLogLocation
Author: Boe Prox
DateCreated: 11Aug2010
.LINK
http://boeprox.wordpress.com
.EXAMPLE
Get-IISLogLocation -computer 'server1'
Description
-----------
This command will list the IIS log location for each website configured on 'Server1'
#>
[cmdletbinding(
SupportsShouldProcess = $True,
DefaultParameterSetName = 'computer',
ConfirmImpact = 'low'
)]
param(
[Parameter(
Mandatory = $False,
ParameterSetName = 'computer',
ValueFromPipeline = $True)]
[string[]]$computer
)
Begin {
$report = @()
}
Process {
ForEach ($c in $Computer) {
If (Test-Connection -comp $c -count 1) {
$sites = [adsi]"IIS://$c/W3SVC"
$children = $sites.children
ForEach ($child in $children) {
If ($child.KeyType -eq "IIsWebServer") {
$temp = "" | Select Server, WebSite, LogLocation
$temp.Server = $c
$temp.WebSite = $child.ServerComment
$temp.LogLocation = $child.LogFileDirectory
}
$report += $temp
}
}
}
}
End {
$report
}
}
|
PowerShellCorpus/PoshCode/Get-DellWarranty_4.ps1
|
Get-DellWarranty_4.ps1
|
function Get-DellWarranty {
<#
.Synopsis
Provides warranty information for one or more Dell service tags.
.Description
Queries the Dell Website for a list of service tags and returns the warranty information as a custom object.
If a service tag has multiple warranties, they are returned as multiple separate objects.
If no service tag is specified, it will attempt to retrieve and lookup the local system's service tag.
The service tag can be provided to the command in several ways:
1. Using the -servicetag parameter
2. By passing one or more Service Tags via the pipeline
3. By passing objects that have either servicetag or serialnumber defined as a property, such as win32_bios WMI objects
See examples for details.
.Parameter ServiceTag
ALIAS: serialnumber
The Dell service tag you wish to query. Example: XYZ12A3
.Example
C:\\PS> Get-DellWarranty
Service Tag : XXXX123
Description : 4 Hour On-Site Service
Provider : UNY
Warranty Extension Notice * : No
Start Date : 6/19/2009
End Date : 6/20/2011
Days Left : 140
Description
-----------
If no service tags are provided, the script retrieves the local computer's serial number from WMI and queries for it.
.Example
C:\\PS> Get-DellWarranty -ServiceTag XXXX123
Service Tag : XXXX123
Description : 4 Hour On-Site Service
Provider : UNY
Warranty Extension Notice * : No
Start Date : 6/19/2009
End Date : 6/20/2011
Days Left : 140
Description
-----------
You can pass the service tag as a parameter, or as the first positional parameter (e.g. Get-DellWarranty XXXX123)
.Example
C:\\PS> "XXXX123","XXXX124","XXXX125" | get-dellwarranty
Service Tag : XXXX123
Description : 4 Hour On-Site Service
Provider : UNY
Warranty Extension Notice * : No
Start Date : 6/19/2009
End Date : 6/20/2011
Days Left : 140
Service Tag : XXXX124
Description : 4 Hour On-Site Service
Provider : UNY
Warranty Extension Notice * : No
Start Date : 6/14/2009
End Date : 6/15/2011
Days Left : 145
Service Tag : XXXX125
Description : NBD On-Site Service
Provider : DELL
Warranty Extension Notice * : No
Start Date : 6/14/2008
End Date : 6/15/2010
Days Left : 0
Description
-----------
You can pass serial numbers via the pipeline either directly or as a variable.
.Example
C:\\PS> get-wmiobject win32_bios -computername "computer1","computer2","1.2.3.4" | get-dellwarranty
Service Tag : XXXX123
Description : 4 Hour On-Site Service
Provider : UNY
Warranty Extension Notice * : No
Start Date : 6/19/2009
End Date : 6/20/2011
Days Left : 140
Service Tag : XXXX124
Description : 4 Hour On-Site Service
Provider : UNY
Warranty Extension Notice * : No
Start Date : 6/14/2009
End Date : 6/15/2011
Days Left : 145
Service Tag : XXXX125
Description : NBD On-Site Service
Provider : DELL
Warranty Extension Notice * : No
Start Date : 6/14/2008
End Date : 6/15/2010
Days Left : 0
Description
-----------
You can also pass any object that has a "serialnumber" or "servicetag" property. In this example, we query computers directly for their serial numbers,
and pass those results (which are WMI objects that have a serialnumber property) via pipeline directly to the command to obtain warranty information.
.Notes
AUTHOR: Justin Grote <jgrote NOSPAM-AT allieddigital NOSPAM-DOT net>
WARNING: Since Dell does not provide a formal API, this script works by screen-scraping the HTML from the Dell product support site.
Any future change to the layout or logic of this site will break the script or cause unpredictable results.
HISTORY: v1.0 [31 Jan 2011] - Initial Module Creatio
.Link
http://support.dell.com/support/topics/global.aspx/support/my_systems_info
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$False,Position=0,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
[alias("serialnumber")]
[string[]]$ServiceTag
)
PROCESS {
# If nothing was passed, retrieve the local system service tag
if ($ServiceTag -eq $null) {
write-verbose "No Service Tags provided. Using Local Computer's Service Tag"
write-verbose "START Obtaining Serial number via WMI for localhost"
$ServiceTag = (get-wmiobject win32_bios).SerialNumber
write-verbose "SUCCESS Obtaining Serial number via WMI for localhost - $ServiceTag"
}
# Detect if an array of service tags were passed via parameter and unwind them.
foreach ($strServicetag in $servicetag) {
write-verbose "START Querying Dell for Service Tag $_"
Get-DellWarrantyWorker $strServicetag
write-verbose "SUCCESS Querying Dell for Service Tag $_"
}
}
}
Function Get-DellWarrantyWorker {
Param(
[String]$serviceTag
)
#Dell Warranty URL Path
$URL = "http://support.dell.com/support/topics/global.aspx/support/my_systems_info/details?c=us&l=en&s=gen&ServiceTag=$serviceTag"
trap [System.FormatException] {
write-error -category invalidresult "The service tag $serviceTag was not found. This is either because you entered the tag incorrectly, it is not present in Dell's database, or Dell changed the format of their website causing this search to fail." -recommendedaction "Please check that you entered the service tag correctly"
return;
}
#Screenscrape the HTML for the warranty Table
$HTML = (New-Object Net.WebClient).DownloadString($URL)
If ($HTML -Match '<table[\\w\\s\\d"=%]*contract_table">.+?</table>') {
$htmltable = $Matches[0]
} else {
throw (New-Object System.FormatException)
}
$HtmlLines = $htmltable -Split "<tr" | Where-Object { $_ -Match '<td' }
$Header = ($HtmlLines[0] -Split '<td') -Replace '[\\w\\s\\d"=%:;\\-]*>|</.*' | Where-Object { $_ -ne '' }
#Convert the warranty table fields into a powershell object
For ($i = 1; $i -lt $HtmlLines.Count; $i++) {
$Output = New-Object PSObject
$Output | Add-Member NoteProperty "Service Tag" -value $serviceTag
$Values = ($HtmlLines[$i] -Split '<td') -Replace '[\\w\\s\\d"=%:;\\-]*>|</.*|<a.+?>'
For ($j = 1; $j -lt $Values.Count; $j++) {
$Output | Add-Member NoteProperty $Header[$j - 1] -Value $Values[$j]
}
#Minor formatting fix if days remaining on warranty is zero
if ($output.'Days Left' -match '<<0') {write-host -fore darkgreen "match!";$output.'Days Left' = 0}
return $Output
}
}
|
PowerShellCorpus/PoshCode/Test-UserCredential_4.ps1
|
Test-UserCredential_4.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 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.
.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/Make a phone call_3.ps1
|
Make a phone call_3.ps1
|
<#
.NOTES
AUTHOR: Sunny Chakraborty(sunnyc7@gmail.com)
WEBSITE: http://tekout.wordpress.com
VERSION: 0.1
CREATED: 17th April, 2012
LASTEDIT: 17th April, 2012
Requires: PowerShell v2 or better
.CHANGELOG
4/17/2012 Try passing powershell objects to PROTO API and pass the variables to .JS file
Pass other system variables and check if text to speech can translate double or a double-to-char conversion is required.
4/18/2012 Changed get-diskusage to gwmi -class win32_logicaldisk
.SYNOPSIS
Make a phone call from Powershell.
.DESCRIPTION
The script demonstrates how you can collect state-data in powershell and pass it as an argument to a REST API call and alert a System Admin.
For this example, TROPO REST API's were used. (www.tropo.com)
The phone-number will receive a Call with the following text To speech
Please check the server $this.
The percent Free Space on C Drive is $inDecimals.
This is a proof of concept. V 0.1
There are numerous areas of improvement.
.IMPORTANT
Please create a new account and setup your application in tropo. Its free for dev use. http://www.tropo.com
Copy and replace the TOKEN in your application with the TOKEN below to initiate a call.
.OTHER
JAVASCRIPT (Hosted on Tropo)
TropoTest.js
call('+' + numToCall , {
timeout:30,
callerID:'19172688401',
onAnswer: function() {
say("Houston ! We have a problem ");
say("Please check the server" + sourceServer );
say("The percent Free Space on C Drive is" + freeCDisk );
say("Goodbye.");
log("Call logged Successfully");
},
onTimeout: function() {
log("Call timed out");
},
onCallFailure: function() {
log("Call could not be completed as dialed");
}
});
#>
# Proto API section. Please replace protoToken with your own Application Token,
# I am posting my API token here so that someone can download and run the script by editing just the cell # field.
$baseUrl = "https://api.tropo.com/1.0/sessions?action=create&"
# Modify these variables.
$protoToken = "10b0026696a79f448eb21d8dbc69d78acf12e2f1f62f291feecec8f2b8d1eac76da63d91dd317061a5a9eeb0"
#US 10 Digit only for now. For Example 17327911234,19177911234
# Calls to Outside US are not allowed during the dev trials on Tropo.
# You will receive a call from this number - 19172688401. That's the callerID
$myCell = '11234567890'
# Functions
#4.18.12 -- Previous versoin used Get-DiskUsage and was erroring out if the cmldet is not installed.
#modified it to use GWMI
Function get-FreeDiskPercentForC {
$disk = gwmi -class "win32_LogicalDisk"
$free = $disk[0].FreeSpace / $disk[0].Size
$freeDiskCPercent = [System.Math]::Round($free, 2)
$freeDiskCPercent
}
# Get some more parameters here.
$sourceServer =hostname
$cDisk = get-FreeDiskPercentForC
# Concatenate and form the Proto API string. I am sure someone can figure out a better way to do this than just adding.
$callThis = $baseUrl+ 'token=' + $protoToken + '&numToCall=' + $myCell + '&sourceServer=' + $sourceServer + '&freeCDisk=' + $cDisk
# Call the Proto API
# I could have tested this with Invoke-RestMethod, but I didn't see the point. I am not receiving any data from the URL.
$newClient = new-object System.Net.WebClient
$newClient.DownloadString($callThis)
|
PowerShellCorpus/PoshCode/Get-SiSReport_2.ps1
|
Get-SiSReport_2.ps1
|
Function Get-SiSReport
{
<#
.SYNOPSIS
Get the overall SIS usage information.
.DESCRIPTION
This function uses the sisadmin command to get the usage
information for a SIS enabled drive.
.PARAMETER SisDisk
The drive letter of a disk that has SiS enabled
.EXAMPLE
Get-SiSReport -SisDisk o
LinkFiles : 20004
Used : 442378481664
Disk : o
InaccessibleLinkFiles : 0
CommonStoreFiles : 6678
SpaceSaved : 7708860 KB
Free : 0
Description
-----------
This example shows the basic usage of the command
.NOTES
This function will return nothing if the drive being analyzed does not have SiS enabled
This function will return a message if the sisadmin command returns any error
.LINK
#>
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 (GB)" = [math]::round(($ThisDisk.Used /1024 /1024 /1024),2)
"Free (GB)" = [math]::round(($ThisDisk.Used /1024 /1024 /1024),2)
"Common Store Files" = ($SisResult[($SisResult.Count)-4]).TrimStart("Common store files:")
"Link Files" = ($SisResult[($SisResult.Count)-3]).TrimStart("Link files:")
"Inaccessible Link Files" = ($SisResult[($SisResult.Count)-2]).TrimStart("Inaccessible link files:")
"Space Saved (GB)" = [math]::round(((($SisResult[($SisResult.Count)-1]).TrimStart("Space saved:")).TrimEnd(" KB")/1024 /1024),2)
}
}
}
End
{
Return $SisReport
}
}
|
PowerShellCorpus/PoshCode/Apache Log Browser Count.ps1
|
Apache Log Browser Count.ps1
|
Select-String "(MSIE [0-9]\\.[0-9]|Firefox\\/[0-9]+|Safari|-)" $log -all |
Group { $_.matches[-1].Value } |
ForEach -begin { $total = 0 } `
-process { $total += $_.Count; $_ } |
Sort Count | Select Count, Name |
Add-Member ScriptProperty Percent { "{0,7:0.000}%" -f (100*$this.Count/$Total) } -Passthru
#### Or if you prefer, the way I originally wrote it ######
##
## sls "(MSIE [0-9]\\.[0-9]|Firefox\\/[0-9]+|Safari|-)" $log -a |
## Group { $_.matches[-1].Value } | % {$t+=$_.Count; $_ } -b {$t=0} |
## Sort Count | Select Count, Name |
## Add-Member ScriptProperty Percent { "{0,7:0.000}%" -f (100*$this.Count/$t) } -Pass
#### Sample output ######
Count Name Percent
----- ---- -------
34 Firefox/1 2.4%
139 MSIE 8.0 0.3%
290 - 1.2%
363 Firefox/2 3.0%
632 MSIE 6.0 5.3%
1708 Safari 14.3%
3207 MSIE 7.0 27.0%
5534 Firefox/3 46.4%
|
PowerShellCorpus/PoshCode/SharePoint build script_1.ps1
|
SharePoint build script_1.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) {
#ECDCSPSPMS04 : http://forum.mycenterpointenergy.com:8080/ : The solution was successfully deployed.
$operationDetailsIndex = 2
} else {
#ECDCSPSPMS04 : 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/Select-EnumeratedType_1.ps1
|
Select-EnumeratedType_1.ps1
|
#requires -version 2
if (-not(test-path variable:script:_helpcache))
{
$SCRIPT:_helpCache = @{}
}
function Select-EnumeratedType
{
<#
.SYNOPSIS
Visually create an instance of an enum.
.DESCRIPTION
Visually create an instance of an enum with an easy to use menu system.
Supports both single value enumerated types and bitmask (flags) enums.
Also supports inline help for enumerated values (powershell.exe only)
.PARAMETER EnumeratedType
The enum type to provide choices for. Pass as a string or Type.
.PARAMETER IncludeHelp
Allows the caller to view help for the enumerated type, including all values.
This help is pulled from the local .NET installation and does not require online
access.
.PARAMETER DefaultValue
A dynamic parameter that is added and typed to the provided enum. Use this to
provide default values should the caller press <enter> without choosing a value
or value(s). This parameter will absorb all trailing arguments.
(ValueFromRemainingArguments = $true)
.EXAMPLE
$rights = Select-EnumeratedType System.Security.AccessControl.CryptoKeyRights Delete,Synchronize
.EXAMPLE
$access = Select-EnumeratedType System.IO.FileAccess Read -IncludeHelp
#>
[cmdletbinding()]
param(
[parameter(position=0, mandatory=$true)]
[validatescript({ $_.isenum })]
[validatenotnull()]
[type]$EnumeratedType,
[parameter()]
[switch]$IncludeHelp
)
dynamicparam {
# only create dynamic parameter if enum provided
if ($PSCmdlet.MyInvocation.BoundParameters["EnumeratedType"]) {
write-verbose "Adding DefaultValue ($enumeratedType) parameter."
# dynamically create -Default parameter with the correct enum type for easy validation
$dict = new-object management.automation.RuntimeDefinedParameterDictionary
$defaultParam = new-object System.Management.Automation.RuntimeDefinedParameter
$defaultParam.Name = "DefaultValue"
$defaultParam.ParameterType = $enumeratedType
# create parameter attribute for positional info etc.
$p = new-object System.Management.Automation.ParameterAttribute
$p.ParameterSetName = $PSCmdlet.ParameterSetName
$p.ValueFromRemainingArguments = $true
$p.Position = 1
$p.Mandatory = $false
$defaultParam.Attributes.Add($p)
$dict.Add("DefaultValue", $defaultParam)
$dict
}
}
end {
# ugly. why doesn't $defaultvalue just work?
$default = $pscmdlet.MyInvocation.BoundParameters["DefaultValue"]
$help = @{}
if ($IncludeHelp) {
$xmldoc = Get-XmlDocumentation -type $enumeratedType
if ($xmlDoc) {
# use readallines over get-content - 10x faster.
$f = [xml][io.file]::readAllLines($xmlDoc)
$selector = "F:$($enumeratedType.fullName)"
foreach ($node in $f.doc.members.selectnodes("member[starts-with(@name,'$selector')]")) {
if ($node.summary) {
$help[$node.name] = $node.summary.trim()
}
}
}
}
$choices = new-object collections.generic.list[System.Management.Automation.Host.ChoiceDescription]
$names = [enum]::getnames($enumeratedType)
[double[]]$values = [enum]::getvalues($enumeratedType)|%{[double]$_}
# compute hotkeys for enum choices
$hot = new-hotkeytable $names
# insert ampersand (&) for hotkey hints
$names | % {
$i = $_.indexof([string]$hot[$_], [stringcomparison]::ordinalignorecase)
if ($i -ne -1) {
# hotkey exists in word
$name = $_.insert($i, "&")
} else {
# hotkey is not part of word - need to append (blech)
$name = "$_ (&$($hot[$_]))"
}
$helpKey = "F:$($enumeratedType.fullname).$_"
if ($includehelp -and $help[$helpKey]) {
# doesn't work in ISE - never renders the '?'
$choiceParams = @($name, $help[$helpKey])
} else {
$choiceParams = $name
}
$choices.add((new-object Management.Automation.Host.ChoiceDescription -Args $choiceParams))
}
# are we a flags enum?
$isFlags = $enumeratedType.GetCustomAttributes([FlagsAttribute], $false)
# does this host support multiple choice?
$supportsMultipleChoice = $host.ui -is [Management.Automation.Host.IHostUISupportsMultipleChoiceSelection]
if ($isFlags -and (-not $supportsMultipleChoice)) {
throw ("{0} enum is flags decorated and this host ({1}) does not support multiple choice selections. Sorry!" -f $enumeratedType.name, $host.name)
}
$title = $enumeratedType.name
if ($isFlags) {
if (-not $default) {
# no default provided
$default = [int[]]@()
} else {
# need to parse default
[int[]]$defaults = @()
$limit = [math]::log([enum]::GetUnderlyingType($enumeratedType)::maxvalue + 1, 2)
# cast to [int] required or else we get non-zero result
# as we approach limit (double trouble)
for ($index = [int]$limit; $index -ge 0; $index--) {
$bit = [math]::pow(2,$index) # double
if (([int]$default) -band $bit) {
$defaults += [array]::indexof($values, $bit)
}
}
$default = $defaults
}
$message = "Choose one or more values for mask:"
$title += " (Flags)"
} else {
if (-not $default) {
# this is menu position, not enum value
$default = -1
} else {
# convert to index
$default = [array]::indexof($values, [double]$default)
}
$message = "Choose single value:"
}
$result = @()
# invoke host support for multiple choice
$host.ui.promptforchoice($title, $message, $choices, $default) | % {
$result += $names[$_]
}
# cast back to enum
$result -as $enumeratedtype
}
}
function Get-HelpSummary
{
[CmdletBinding()]
param
(
[string]$file,
[reflection.assembly]$assembly,
[string]$selector
)
if ($helpCache.ContainsKey($assembly))
{
$xml = $helpCache[$assembly]
}
else
{
# cache it
Write-Progress -id 1 "Caching Help Documentation" $assembly.getname().name
# cache this for future lookups. It's a giant pig. Oink.
$xml = [xml](gc $file)
$helpCache.Add($assembly, $xml)
Write-Progress -id 1 "Caching Help Documentation" $assembly.getname().name -completed
}
# TODO: support overloads
$summary = $xml.doc.members.SelectSingleNode("member[@name='$selector' or starts-with(@name,'$selector(')]").summary
$summary
}
function New-HotKeyTable {
param([string[]]$names)
$hot = @{}
# assign hot keys
$names | % {
$c = [char]::toupper($_[0])
# prioritize first letter
if (-not $hot.containsvalue($c)) {
$hot[$_] = $c
write-debug "1) assigned $c to $_"
}
}
$names | ? {
# unallocated?
-not $hot.containskey($_)
} | % {
# try camel humps
for ($i=1; $i -lt $_.length; $i++) {
$c = $_[$i]
if ([char]::IsUpper($c) -and (-not $hot.containsvalue($c))) {
$hot[$_] = $c
write-debug "2) assigned $c to $_"
break
}
}
}
$names | ? {
# unallocated?
-not $hot.containskey($_)
} | % {
# try sequential from pos 1
for ($i=1; $i -lt $_.length; $i++) {
$c = [char]::toupper($_[$i])
# available?
if (-not $hot.containsvalue($c)) {
$hot[$_] = $c
write-debug "3) assigned $c to $_"
break
}
}
}
# alphabetic search
$names | ? {
# unallocated?
-not $hot.containskey($_)
} | % {
$word = $_
$s = [int]"A"[0]
for ($i = $s; $i -lt ($s + 26); $i++) {
$c = [char]$i
if (-not $hot.containsvalue($c)) {
$hot[$word] = $c
write-debug "4) assigned $c to $word"
break
}
}
}
# todo: if the above fails, use 0-9?
$hot
}
function Get-XmlDocumentation {
[cmdletbinding()]
param([type]$type)
$docFilename = [io.path]::changeextension([io.path]::getfilename($type.assembly.location), ".xml")
$location = [io.path]::getdirectoryname($type.assembly.location)
$codebase = (new-object uri $type.assembly.codebase).localpath
# try localized location (typically newer than base framework dir)
$frameworkDir = "${env:windir}\\Microsoft.NET\\framework\\v2.0.50727"
$lang = [system.globalization.cultureinfo]::CurrentUICulture.parent.name
switch
(
"${frameworkdir}\\${lang}\\$docFilename",
"${frameworkdir}\\$docFilename",
"$location\\$docFilename",
"$codebase\\$docFilename"
)
{
{ test-path $_ } { $_; return; }
default
{
# try next path
continue;
}
}
}
|
PowerShellCorpus/PoshCode/Performance Monitoring.ps1
|
Performance Monitoring.ps1
|
<#
.SYNOPSIS
Multiple functions to build a config file and to use file to launch PerfMon background jobs.
.DESCRIPTION
Multiple functions to build a config file and to use file to launch PerfMon background jobs.
.NOTES
Name: WinPerfv2.PS1
Author: Boe Prox
DateCreated: 28June2010
To-Do:
1. Add a function for building the table where data will be stored at
2. Build a GUI for the XML Config file build
.LINK
http://www.powershell.com
#>
Function Build-SQLTable {
<#
.SYNOPSIS
Builds a SQL Table named Counters on a SQL server database.
.DESCRIPTION
Builds a SQL Table named Counters on a SQL server database.
.PARAMETER computer
Name of the server that hosts the database
.PARAMETER database
Name of the database that the table will be created on
.NOTES
Name: Build-SQLTable
Author: Boe Prox
DateCreated: 29June2010
.LINK
http://www.powershell.com
.EXAMPLE
Build-SQLTable -computer 'Server' -database 'database'
#>
[cmdletbinding(
SupportsShouldProcess = $True,
DefaultParameterSetName = 'perf',
ConfirmImpact = 'low'
)]
param(
[Parameter(
Mandatory = $False,
ParameterSetName = 'sql',
ValueFromPipeline = $True)]
[string]$computer,
[Parameter(
Mandatory = $False,
ParameterSetName = 'sql',
ValueFromPipeline = $True)]
[string]$database
)
Write-Host -foregroundcolor Green "Building a SQL table: 'Counters' on Database: `'$($database)`' residing on Server: `'$($Computer)`'."
#TSQL Statement to create table required for script
$tsql = CREATE TABLE Counters (ServerName varchar(20),"Date" varchar (50),CounterName varchar (25),CounterType varchar (25),InstanceName varchar (25),Data float (20))
}
Function Get-UserChoice
{
<#
.SYNOPSIS
Prompts user for choice.
.DESCRIPTION
Prompts user for choice.
#>
#Determine Values for Choice
$choice = [System.Management.Automation.Host.ChoiceDescription[]] @("&Continue","&Quit")
#Determine Default Selection
[int]$default = 0
#Present choice option to user
$userchoice = $host.ui.PromptforChoice(" ","Do you want to continue performance counters to the config file?",$choice,$default)
Return $userchoice
}
Function Build-PerfConfig {
<#
.SYNOPSIS
Builds an xml config file to be used with WinPerf.ps1 script
.DESCRIPTION
Builds an xml config file to be used with WinPerf.ps1 script
.PARAMETER file
Name of the file that will be saved
.PARAMETER flag
.PARAMETER assist
.NOTES
Name: Build-PerfConfig.ps1
Author: Boe Prox
DateCreated: 28June2010
.LINK
http://www.powershell.com
.EXAMPLE
Build-PerfConfig -file "exchange.xml"
#>
[cmdletbinding(
SupportsShouldProcess = $True,
DefaultParameterSetName = 'perf',
ConfirmImpact = 'low'
)]
param(
[Parameter(
Mandatory = $False,
ParameterSetName = 'perf',
ValueFromPipeline = $True)]
[string]$file = 'config.xml',
[Parameter(
Mandatory = $False,
ParameterSetName = 'perf',
ValueFromPipeline = $True)]
[string]$flag = $True,
[Parameter(
Mandatory = $False,
ParameterSetName = 'perf',
ValueFromPipeline = $True)]
[switch]$assist
)
#Clear screen
Clear
#Display welcome message
Write-Host -ForegroundColor Green -Backgroundcolor Black "Use this tool to build a config file for the WinPerf.ps1 perfmon script."
Write-Host -ForegroundColor Green -Backgroundcolor Black "You must know what performance counters you need before running this tool!"
Write-Host -ForegroundColor Green -Backgroundcolor Black "If you do not know, then it is advised to look up the counters before proceeding."
Write-Host -ForegroundColor Green -Backgroundcolor Black "`t`t`t`t`t`t`t`t`t`t"
Write-Host -ForegroundColor Green -Backgroundcolor Black "You can quit and save at anytime by typing 'q' and then pressing 'Enter' `n"
If ($assist) {
Write-Host -ForegroundColor Cyan -Backgroundcolor Black "You will be assisted with determining what Categories, Counters and Instances to type. `n"
}
#Prepare the array
$arr = @()
#Loop until user decides to quit and save xml file
While ($flag -eq $True) {
#Create temporary array
$t_array = "" | Select CategoryName, CounterName, InstanceName, CounterType, CounterHelp
#Begin gathering information
#Help user if requested from Assist switch
If ($assist) {
$flag2 = $False
While ($flag2 -eq $False) {
#Clear any errors
$Error.Clear()
Write-Host -ForegroundColor Green "Please enter a type of counter you are looking for."
$d_counter = Read-Host "Category"
Write-Host "Counter: $d_counter"
Write-Host -ForegroundColor Green "Listing Categories based on your query. `n"
#Configure error handling
Write-Verbose "Configuring error preference"
$ErrorActionPreference = 'stop'
Try {
Get-Counter -ListSet "*$d_counter*" | FT @{Name="Available Categories";Expression = "CounterSetName"}
}
Catch {
Write-Warning "$_"
}
#Only continue script if no errors occurred, otherwise try again
If (!($error)) {
#Set flag so script can continue
$flag2 = $True
}
}
#Change preference back to continue
$ErrorActionPreference = 'continue'
}
If ($flag -eq $True) {
#Prompt for Category Name
Write-Host -ForegroundColor Green "Enter the Category"
$t_array.CategoryName = Read-Host "Category"
#Change flag state if 'q' is typed
If ($($t_array.CategoryName) -eq "q") {
Write-Verbose "User typed 'q', quitting loop"
$flag = $False
}
}
#Help user if requested from Assist switch
If ($assist) {
Write-Host -ForegroundColor Green "Listing Counters based on your Category selection. `n"
(Get-Counter -ListSet "$($t_array.CategoryName)").counter | % {$_.split("\\")[2]}
}
If ($flag -eq $True) {
#Prompt for Counter Name
Write-Host -ForegroundColor Green "`nEnter the Counter Name"
$t_array.CounterName = Read-Host "Counter"
#Change flag state if 'q' is typed
If ($($t_array.CounterName) -eq "q") {
Write-Verbose "User typed 'q', quitting loop"
$flag = $False
}
}
#Help user if requested from Assist switch
If ($assist) {
Write-Host -ForegroundColor Green "Listing Instance Names based on your Category selection. `n"
$counter = $t_array.CounterName
(get-counter -list "$($t_array.CategoryName)").pathswithinstances | % {
$compare = ($_.split("(")[1]).split(")")[1]
Try {
If ("$counter" -match $compare) {
($_.split("(")[1]).split(")")[0]
}
}
Catch {
Write-Verbose "$_"
}
}
}
If ($flag -eq $True) {
#Prompt for Instance Name
Write-Host -ForegroundColor Green "`nEnter the Instance Name (can be blank if not needed)"
$t_array.InstanceName = Read-Host "Instance Name"
#Change flag state if 'q' is typed
If ($($t_array.CategoryName) -eq "q") {
Write-Verbose "User typed 'q', quitting loop"
$flag = $False
}
}
#Process the temporay array with the main array
If ($flag -eq $True) {
Write-Verbose "Adding temp array to main array"
$arr += $t_array
}
#Build the help comment and retrieve the Type of counter
If ($flag -eq $True) {
#We need to partially build this counter to retrieve the help comments
$counter = New-Object System.Diagnostics.PerformanceCounter
$counter.CategoryName = $($t_array.CategoryName)
$counter.CounterName = $($t_array.CounterName)
#Retrieve the help comments
$t_array.CounterHelp = $counter.CounterHelp
#Retrieve the Counter Type
$t_array.CounterType = $counter.CounterType
#Remove the $counter object
$counter = $Null
}
#Ask user if they want to continue adding to the config file
If ($flag -eq $True) {
$answer = Get-UserChoice
If ($answer -eq 1) {
Write-Verbose "User typed 'q', quitting loop"
$flag = $False
}
}
} #End While Loop
#Begin compiling xml file
Write-Verbose "Building XML file: $file"
$arr | Export-Clixml $file
Write-Host -ForegroundColor Green "`n$file saved to $pwd"
Write-Host -ForegroundColor Green "Opening $file to verify contents. If anything is missing, you will need to rebuild."
Import-Clixml $file
Return $file
} #End Build-PerfConfig Function
Function Get-PerfCounter {
<#
.SYNOPSIS
Runs a pre-defined perfmon counter against a selected server or servers.
.DESCRIPTION
Runs a pre-defined perfmon counter against a selected server or servers.
.PARAMETER interval
Interval for performance counters. Default Value is 10 seconds.
.PARAMETER computers
List or name of a computer to run against. Default Value is the local machine.
.PARAMETER endat
When to end the perfmon counter. Default Value is 10 minutes.
.NOTES
Name: WinPerf.ps1
Author: Boe Prox
DateCreated: 28June2010
.LINK
http://www.powershell.com
.EXAMPLE
Get-PerfCounter -configfile "OS_Baseline.xml" -computers Server -endat "06/20/2010 04:00 PM" -interval 60
Uses the counters listed in the OS_Baseline.xml file on server 'Server' which will collect data at 60 second
intervals and will end on 06/20/2010 at 04:00PM.
#>
[cmdletbinding(
SupportsShouldProcess = $True,
DefaultParameterSetName = 'perf',
ConfirmImpact = 'low'
)]
param(
[Parameter(
Mandatory = $False,
ParameterSetName = 'perf',
ValueFromPipeline = $True)]
[array]$computers = $env:Computername, #Computer or computers to run perfmon against
[Parameter(
Mandatory = $False,
ParameterSetName = 'perf')]
[string]$configfile, #Configuration file that lists what perfmon counters to check
[Parameter(
Mandatory = $False,
ParameterSetName = 'perf')]
[int]$interval = 10, #Time in seconds to wait before beginning next set of counters
[Parameter(
Mandatory = $False,
ParameterSetName = 'perf')]
[datetime]$endat = (Get-Date).AddMinutes(10), #When to end the perf counter
[Parameter(
Mandatory = $False,
ParameterSetName = 'perf')]
[string]$sqlsvr = "R49", #Name of the SQL server that hosts the perf counter database
[Parameter(
Mandatory = $False,
ParameterSetName = 'perf')]
[string]$database = "PerfMon", #Name of the database storing the perf counters
[Parameter(
Mandatory = $False,
ParameterSetName = 'perf')]
[string]$file #List of host names to run perfmon against
)
If ($computers -eq $Null -OR $computers -eq "") {
$computers = $env:Computername
}
If ($File) {
$computers = Get-Content $file
}
$path = $pwd
#Check to see if a config file was used, if not begin building the file.
If ($configfile -eq $Null -OR $configfile -eq "") {
Write-Warning "No config file given! `nLaunching file builder..."
Start-Sleep -s 2
Build-PerfConfig -assist
$configfile = 'config.xml'
}
ForEach ($computer in $computers) {
#Initialize Background Job
Start-Job -Name $computer -ArgumentList $computer, $configfile, $interval, $endat,$conn,$sqlsvr,$database,$path -ScriptBlock {
param ($computer, $configfile, $interval, $endat,$conn,$sqlsvr,$database,$path)
#Register SQL assemblies
Write-Verbose "Loading SQL Assemblies"
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo.DLL")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO.DLL")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMOEnum.DLL")
#Create SQL Connection
Write-Verbose "Creating SQL Connection"
$conn = New-Object System.Data.SqlClient.SqlConnection("Data Source=$sqlsvr;
Initial Catalog=$database; Integrated Security=SSPI")
$conn.Open()
$cmd = $conn.CreateCommand()
#Define location of XML file
Set-Location $path
#Import the XML file
Write-Verbose "Importing XML file $($configfile)"
$counters = Import-Clixml $configfile
#Set an increment
Write-Verbose "Setting increment to 0"
$inc = 0
#Build Array for counters
$total = $counters.Count
$perfcounter = New-Object 'object[]' $total
#Iterate through counters
ForEach ($counter in $counters) {
Write-Verbose "Looking at $($counter.CategoryName)"
#Initialize the Performance Counters for the machine
$perfcounter[$inc] = New-Object System.Diagnostics.PerformanceCounter
$perfcounter[$inc].MachineName = $computer
$perfcounter[$inc].CategoryName = $counter.CategoryName
$perfcounter[$inc].CounterName = $counter.CounterName
$perfcounter[$inc].InstanceName = $counter.InstanceName
#Initial counter increment so the first value will not be 0
$nothing = $perfcounter[$inc].NextValue()
#Increment counter
$inc++
}
$inc--
Write-Host -ForegroundColor Green $inc
While ($endat -gt (get-date)) {
#Iterate through perfcounters
0..$inc | % {
#Make variables for SQL command easier to read
$CouName = $perfcounter[$_].CounterName
$CatName = $perfcounter[$_].CategoryName
$InsName = $perfcounter[$_].InstanceName
$value = $perfcounter[$_].NextValue()
#Create Date String
$dt = (get-date) -f ""
#Create query string
#Must matching the table layout (Server, Date, CounterName, CounterType, InstanceName, Value)
Write-Verbose "Sending PerfMon data for $catname \\ $couname to SQL database"
$cmd.CommandText = "INSERT INTO Counters (ServerName, Date, CounterName, CounterType, InstanceName, Data) VALUES ('$computer','$dt','$CouName','$CatName','$InsName','$Value')"
#Execute Query
$cmd.ExecuteNonQuery() | Out-Null
}
Start-Sleep -s $interval
}
}
}
}
|
PowerShellCorpus/PoshCode/Invoke-AppAsAdmin.ps1
|
Invoke-AppAsAdmin.ps1
|
#requires -version 2.0
<#
.SYNOPSIS
Script to run executable with alternate credentials as admin.
.DESCRIPTION
This script will try to invoke itself with alternate credentials (using Get-Credential cmdlet) and once it's there it will try to run any executable as elevated.
Designed to work around problem with elevating process when working remotely via OFC and other remoting tools.
Using GUI to prompt SD person about executable that is needed.
#>
param (
# Parameter that should be added to re-run the script once we pass credentials/ alternate user step
[switch]$Invoke,
# Name of the process that will be used in re-run scenario
[string]$ProcessName,
# User that was passing his credentials - just to double-check if that's the one we need.
[string]$RunAs
)
$MyPath = $MyInvocation.InvocationName
Add-Type -AssemblyName System.Windows.Forms -PassThru | Foreach -Begin { $Form = @{} } -Process { try { $Form.Add($_.Name,$_) } catch {return} }
Add-Type -AssemblyName System.Drawing
if ($Invoke) {
$MyPrincipals = [security.principal.WindowsIdentity]::GetCurrent()
if ($Runas -eq $MyPrincipals.Name) {
try {
Start-Process -FilePath $ProcessName -Verb RunAs
} catch {
$Form.MessageBox::Show("Error: $_",'Error!','OK','Error')
}
}
exit
}
# ScriptBlocks to be used by events
$handler_buttonBrowse_Click = {
$Dialog = New-Object $Form.OpenFileDialog -Property @{
Filter = 'Application (*.exe)|*.exe|All files (*.*)|*.*'
}
if ($Dialog.ShowDialog() -eq 'OK' -and $Dialog.FileName) {
$textboxCmd.Text = $Dialog.FileName
}
}
$handler_buttonOK_Click = {
if ($textboxCmd.Text) {
try {
$creds = Get-Credential
$RunAs = $creds.UserName
$ProcessName = $textboxCmd.Text
Start-Process -FilePath PowerShell.exe -Credential $creds -ArgumentList "-noprofile -windowStyle Hidden -file $MyPath -Invoke -ProcessName $ProcessName -RunAs $RunAs"
$MainWindow.Close()
} catch {
$Form.MessageBox::Show("Error: $_",'Error!','OK','Error')
}
} else {
$Form.MessageBox::Show('You have to give a path/ name of thing to run!','Path/ name is missing','OK','Error')
}
}
$handler_buttonCancel_Click = {
$Form.MessageBox::Show('Bye!','You canceled me...','OK','Information')
$MainWindow.Close()
}
$OnLoadForm_StateCorrection = {
$MainWindow.WindowState = New-Object $Form.FormWindowState
}
# Create controls so it will be possible to add them to the form later
$buttonsSize = New-Object Drawing.Size 75, 23
$MainWindow = New-Object $Form.Form -Property @{
Text = "Run As Admin"
MaximizeBox = $False
MinimizeBox = $False
HelpButton = $True
Name = "form1"
ClientSize = New-Object Drawing.Size 368, 144
KeyPreview = $True
}
$MainWindow.DataBindings.DefaultDataSourceUpdateMode = 0
$buttonBrowse = New-Object $Form.Button -Property @{
TabIndex = 4
Name = "buttonBrowse"
Size = $buttonsSize
UseVisualStyleBackColor = $True
Text = "Browse..."
Location = New-Object Drawing.Point 260, 85
}
$buttonBrowse.add_Click($handler_buttonBrowse_Click)
$buttonBrowse.DataBindings.DefaultDataSourceUpdateMode = 0
$buttonCancel = New-Object $Form.Button -Property @{
TabIndex = 3
Name = "buttonCancel"
Size = $buttonsSize
UseVisualStyleBackColor = $True
Text = "Cancel"
Location = New-Object Drawing.Point 179, 86
}
$buttonCancel.DataBindings.DefaultDataSourceUpdateMode = 0
$buttonCancel.add_Click($handler_buttonCancel_Click)
$buttonOK = New-Object $Form.Button -Property @{
TabIndex = 2
Name = "buttonOK"
Size = $buttonsSize
UseVisualStyleBackColor = $True
Text = "OK"
Location = New-Object Drawing.Point 98, 86
}
$buttonOK.DataBindings.DefaultDataSourceUpdateMode = 0
$buttonOK.add_Click($handler_buttonOK_Click)
$textboxCmd = New-Object $Form.TextBox -Property @{
Size = New-Object Drawing.Size 298, 20
Name = "textboxCmd"
Location = New-Object Drawing.Point 38, 60
TabIndex = 1
}
$textboxCmd.DataBindings.DefaultDataSourceUpdateMode = 0
$labelDesc = New-Object $Form.Label -Property @{
TabIndex = 0
Size = New-Object Drawing.Size 298,35
Text = "Type the name of command that you want to run. You can also try to select 'Browse to...' instead."
Location = New-Object Drawing.Point 38, 24
Name = "labelDesc"
}
$labelDesc.DataBindings.DefaultDataSourceUpdateMode = 0
$MainWindow.Controls.AddRange(@($textboxCmd, $labelDesc, $buttonBrowse, $buttonCancel, $buttonOK))
$MainWindow.add_Load($OnLoadForm_StateCorrection)
$MainWindow.add_KeyDown({if ($_.KeyCode -eq 'Enter') {& $handler_buttonOK_Click}})
$MainWindow.add_KeyDown({if ($_.KeyCode -eq 'Escape') {& $handler_buttonCancel_Click}})
$helpDescription = @"
This script will try to invoke itself with alternate credentials (using Get-Credential cmdlet) and once it's there it will try to run any executable as elevated.
Designed to work around problem with elevating process when working remotely via OFC and other remoting tools.
Using GUI to prompt SD person about executable that is needed.
"@
$MainWindow.add_HelpButtonClicked({$Form.MessageBox::Show($helpDescription,'Help','OK','Information')})
$MainWindow.ShowDialog()| Out-Null
|
PowerShellCorpus/PoshCode/Findup_13.ps1
|
Findup_13.ps1
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.IO;
namespace Findup
{
public class FileInfoExt
{
public FileInfoExt(FileInfo fi)
{
FI = fi;
}
public byte[] SHA512_1st1K;
public byte[] SHA512_All;
public FileInfo FI { get; private set; }
public bool Matched { get; set; }
}
class Findup
{
const int HashLen = 512/8; // 64-byte hash for SHA512.
public static System.Boolean noerr = false;
public static void Main(string[] args)
{
Console.WriteLine("Findup.exe v1.0 - use -help for usage information. Created in 2010 by James Gentile.");
Console.WriteLine(" ");
string[] paths = new string[0];
System.Boolean recurse = false;
System.Boolean delete = false;
System.Boolean noprompt = false;
System.Boolean b4b = false;
List<FileInfoExt> fs = new List<FileInfoExt>();
long bytesInDupes = 0; // bytes in all the duplicates
long bytesRec = 0; // number of bytes recovered.
int delFiles = 0; // number of files deleted.
int numOfDupes = 0; // number of duplicate files found.
int c = 0;
int i = 0;
string deleteConfirm;
for (i = 0; i < args.Length; i++)
{
if ((System.String.Compare(args[i], "-help", true) == 0) || (System.String.Compare(args[i], "-h", true) == 0))
{
Console.WriteLine("Usage: findup.exe <file/directory #1> <file/directory #2> ... <file/directory #N> [-recurse] [-delete] [-noprompt] [-b4b]");
Console.WriteLine(" ");
Console.WriteLine("Options: -help - displays this help infomration.");
Console.WriteLine(" -recurse - recurses through subdirectories when directories or file specifications (e.g. *.txt) are specified.");
Console.WriteLine(" -delete - deletes duplicates with confirmation prompt.");
Console.WriteLine(" -noprompt - when used with -delete option, deletes files without confirmation prompt.");
Console.WriteLine(" -noerr - discards error messages.");
Console.WriteLine(" -b4b - do a byte-for-byte comparison, instead of SHA-512 hashing. Slower in some cases, faster in others, and most secure.");
Console.WriteLine(" ");
Console.WriteLine("Examples: findup.exe c:\\\\finances -recurse -noerr");
Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data -recurse -delete -noprompt");
Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\quarter.doc -b4b");
Console.WriteLine(" ");
return;
}
if (System.String.Compare(args[i], "-recurse", true) == 0)
{
recurse = true;
continue;
}
if (System.String.Compare(args[i], "-delete", true) == 0)
{
delete = true;
continue;
}
if (System.String.Compare(args[i], "-noprompt", true) == 0)
{
noprompt = true;
continue;
}
if (System.String.Compare(args[i], "-b4b", true) == 0)
{
b4b = true;
continue;
}
if (System.String.Compare(args[i], "-noerr", true) == 0)
{
noerr = true;
continue;
}
Array.Resize(ref paths, paths.Length + 1);
paths[c] = args[i];
c++;
}
if (paths.Length == 0)
{
Console.WriteLine("No files specified, try findup.exe -help");
return;
}
Recursive(paths, "*.*", recurse, fs);
if (fs.Count < 2)
{
Console.WriteLine("Findup.exe needs at least 2 files to compare. try findup.exe -help");
return;
}
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(salt); // get 512-bit SHA-512 salt.
for (i = 0; i < fs.Count; i++)
{
if (fs[i].Matched == true) // If file was already matched, then skip to next.
continue;
for (c = i + 1; c < fs.Count; c++)
{
if (fs[c].Matched == true) // skip already matched inner loop files.
continue;
if (fs[i].FI.Length != fs[c].FI.Length) // If file size matches, then check hash.
continue;
if (System.String.Compare(fs[i].FI.FullName, fs[c].FI.FullName, true) == 0) // don't count the same file as a match.
continue;
if (fs[i].SHA512_1st1K == null) // check/hash first 1K first.
if (Compute1KHash(fs[i]) == false)
continue;
if (fs[c].SHA512_1st1K == null)
if (Compute1KHash(fs[c]) == false)
continue;
if (CompareBytes(fs[i].SHA512_1st1K, fs[c].SHA512_1st1K) == false) // if the 1st 1K has the same hash..
continue;
if (b4b == true) // byte for byte comparison specified?
{
if (B4b(fs[i].FI.FullName, fs[c].FI.FullName) == false) // call the byte for byte comparison function
continue;
}
else if (fs[i].FI.Length > 1024) // skip hashing the file again if < 1024 bytes.
{
if (fs[i].SHA512_All == null) // check/hash the rest of the files.
if (ComputeFullHash(fs[i]) == false)
continue;
if (fs[c].SHA512_All == null)
if (ComputeFullHash(fs[c]) == false)
continue;
if (CompareBytes(fs[i].SHA512_All, fs[c].SHA512_All) == false)
continue;
}
Console.WriteLine(" Match: " + fs[i].FI.FullName);
Console.WriteLine(" with: " + fs[c].FI.FullName);
Console.WriteLine(" Size: {0:N0}",fs[i].FI.Length);
fs[c].Matched = true; // do not check or match against this file again.
numOfDupes++; // increase count of matches.
bytesInDupes += fs[c].FI.Length; // accumulate number of bytes in duplicates.
if (delete != true) // if delete is specified, try to delete the duplicate file.
continue;
if (noprompt == false)
{
Console.Write("Delete the duplicate file <Y/n>?");
deleteConfirm = Console.ReadLine();
if ((deleteConfirm[0] != 'Y') && (deleteConfirm[0] != 'y')) // if user typed 'Y' then delete the file.
continue;
}
try
{
File.Delete(fs[c].FI.FullName);
Console.WriteLine("Deleted: " + fs[c].FI.FullName);
bytesRec += fs[c].FI.Length; // record bytes recovered.
delFiles++;
}
catch (Exception e)
{
WriteErr("File delete error: " + e.Message);
}
}
}
Console.WriteLine(" ");
Console.WriteLine("Files checked : {0:N0}", fs.Count);
Console.WriteLine("Duplicate files : {0:N0}", numOfDupes);
Console.WriteLine("Duplicate bytes : {0:N0}", bytesInDupes);
Console.WriteLine("Duplicates deleted : {0:N0}", delFiles);
Console.WriteLine("Recovered bytes : {0:N0}", bytesRec);
return; // Exit after displaying statistics.
}
private static Boolean B4b(string path1, string path2)
{
try
{
using (var stream = File.OpenRead(path1))
{
using (var stream2 = File.OpenRead(path2))
{
while (stream.Position != stream.Length)
{
var length = stream.Read(largeBuf, 0, largeBuf.Length);
var length2 = stream2.Read(largeBuf2, 0, largeBuf2.Length);
if (length != length2)
return false;
if (CompareBytes(largeBuf, largeBuf2, length) == false)
return false;
}
}
}
return true;
}
catch (Exception e)
{
WriteErr("Byte for Byte comparison failed: " + e.Message);
return false;
}
}
private static Boolean CompareBytes(byte[] byteArray1, byte[] byteArray2, int Len = HashLen)
{
int i = 0;
while (i < Len)
{
if (byteArray1[i] != byteArray2[i])
return false;
i++;
}
return true ;
}
private static readonly byte[] readBuf = new byte[1024];
private static readonly byte[] largeBuf = new byte[HashLen*200];
private static readonly byte[] largeBuf2 = new byte[HashLen*200];
private static readonly byte[] salt = new byte[HashLen];
private static void WriteErr(string Str)
{
if (noerr == false)
Console.WriteLine(Str);
}
private static bool Compute1KHash(FileInfoExt path)
{
try
{
using (var stream = File.OpenRead(path.FI.FullName))
{
var length = stream.Read(readBuf, 0, readBuf.Length);
var _SHA512 = SHA512.Create();
_SHA512.TransformBlock(salt, 0, salt.Length, null, 0);
_SHA512.TransformFinalBlock(readBuf, 0, length);
path.SHA512_1st1K = _SHA512.Hash;
return true;
}
}
catch (Exception e)
{
WriteErr("Hash Error: " + e.Message);
path.Matched = true; // since the file error'ed out, don't check against it again.
return false;
}
}
private static bool ComputeFullHash(FileInfoExt path)
{
try
{
var _SHA512 = SHA512.Create();
_SHA512.TransformBlock(salt, 0, salt.Length, null, 0);
using (var stream = File.OpenRead(path.FI.FullName))
{
while (true)
{
var length = stream.Read(largeBuf, 0, largeBuf.Length);
if (stream.Position < stream.Length) // if not at end of file...
_SHA512.TransformBlock(largeBuf, 0, length, null, 0); // hash the buffer, and loop.
else
{
_SHA512.TransformFinalBlock(largeBuf, 0, length); // if at end of file, hash last time and end looping
break;
}
}
}
path.SHA512_All = _SHA512.Hash;
return true;
}
catch (Exception e)
{
WriteErr("Hash error: " + e.Message);
path.Matched = true;
return false;
}
}
private static void Recursive(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfoExt> returnList)
{
foreach (string d in pathRec)
{
Recursive(d, searchPattern, recursiveFlag, returnList);
}
return;
}
private static void Recursive(string pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfoExt> returnList)
{
string dirPart;
string filePart;
if (File.Exists(pathRec))
{
try
{
FileInfo addf = (new FileInfo(pathRec));
if ((addf.Attributes & FileAttributes.ReparsePoint) == 0)
returnList.Add(new FileInfoExt(addf));
}
catch (Exception e)
{
WriteErr("Add file error: " + e.Message);
}
}
else if (Directory.Exists(pathRec))
{
try
{
DirectoryInfo Dir = new DirectoryInfo(pathRec);
foreach (FileInfo addf in (Dir.GetFiles(searchPattern)))
{
if ((addf.Attributes & FileAttributes.ReparsePoint) == 0)
returnList.Add(new FileInfoExt(addf));
}
}
catch (Exception e)
{
WriteErr("Add files from Directory error: " + e.Message);
}
if (recursiveFlag == true)
{
try
{
Recursive((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))
{
Recursive(dirPart, filePart, recursiveFlag, returnList);
return;
}
}
WriteErr("Invalid file path, directory path, file specification, or program option specified: " + pathRec);
}
}
}
}
|
PowerShellCorpus/PoshCode/Create RTF File .ps1
|
Create RTF File .ps1
|
param (
[string]$Filename
)
# Save script as NEWRTF.PS1
#
# Execute with ./NEWRTF.PS1 -filename somefilename.rtf
#
# Note for this basic example, there is no error checking
# The full path name INCLUDING RTF extension must be supplied
# for the filename
#
# For Example C:\\Folder\\Filename.RTF
#
# Four static variables for an example
$Firstname="John"
$Lastname="Smith"
# For an RTF file, you must "escape" the Backslash with an extra Backslash
$Accountname="CONTOSO\\\\jsmith"
$Password="LousyPass123"
# Header of the RTF file
$Header+="{\\rtf1\\ansi\\ansicpg1252\\deff0\\nouicompat\\deflang1033{\\fonttbl{\\f0\\fnil\\fcharset0 Consolas;}}`r`n"
$Header+="{\\*\\generator Riched20 6.2.8102}\\viewkind4\\uc1 `r`n"
$Header+="\\pard\\sl276\\slmult1\\f0\\fs22\\lang9 \\par`r`n"
# Content of the message
$Message+="Hello $Firstname $Lastname and Welcome to ABC\\par`r`n"
$Message+="Corporation.\\par`r`n"
$Message+="\\par`r`n"
$Message+="Your User ID is $Accountname\\par`r`n"
$Message+="Your Temporary Password is $Password\\par`r`n"
$Message+="\\par`r`n"
$Message+="Do not share this information and remember,\\par`r`n"
$Message+="We are watching....\\par`r`n"
$Message+="`r`n"
# Footer in the RTF File
$Footer="}`r`n"
# Build the content together
$Content=$Header+$Message+$Footer
# Create the file
ADD-CONTENT -path $Filename -value $Content -force
|
PowerShellCorpus/PoshCode/Get-Installed.ps1
|
Get-Installed.ps1
|
function Get-Installed
{
<#
.SYNOPSIS
This function lists data found in the registry associated with installed programs.
.DESCRIPTION
Describe the function in more detail
Author: Stan Miller
.EXAMPLE
Get all apps whose display names start with a specific string and display all valuenames
get-installed -re "^microsoft xna" -valuenameRE ".*"
The "^" above means starts with the following string.
The ".*" means match all including the empty string
.EXAMPLE
get-installed -re "^microsoft xna game studio platform tool$"
Display the default set of valuenames for apps whose displayname starts (^) and ends ($) with "microsoft xna game studio platform tool"
displayname=microsoft xna game studio platform tools
displayversion=1.1.0.0
installdate=20100204
installsource=C:\\Program Files (x86)\\Microsoft XNA\\XNA Game Studio\\v3.1\\Setup\\
localpackage=C:\\Windows\\Installer\\2d09d3a5.msi
madeup-gname={BED4CEEC-863F-4AB3-BA23-541764E2D2CE}
madeup-loginid=System
madeup-wow=1
uninstallstring=MsiExec.exe /I{BED4CEEC-863F-4AB3-BA23-541764E2D2CE}
windowsinstaller=1
.EXAMPLE
get-installed -re "^microsoft xna game studio platform tool" -compress $False
Display the default set of valuenames for apps whose displayname starts with "^microsoft xna"
only this time show all registry sources. In this case the products and uninstall areas
displayname=microsoft xna game studio platform tools
keypath=software\\microsoft\\windows\\currentversion\\installer\\userdata\\s-1-5-18\\products\\ceec4debf3683ba4ab324571462e2dec\\installproperties
displayversion=1.1.0.0
installdate=20100204
installsource=C:\\Program Files (x86)\\Microsoft XNA\\XNA Game Studio\\v3.1\\Setup\\
localpackage=C:\\Windows\\Installer\\2d09d3a5.msi
madeup-loginid=System
uninstallstring=MsiExec.exe /I{BED4CEEC-863F-4AB3-BA23-541764E2D2CE}
windowsinstaller=1
keypath=software\\wow6432node\\microsoft\\windows\\currentversion\\uninstall\\{bed4ceec-863f-4ab3-ba23-541764e2d2ce}
displayversion=1.1.0.0
installdate=20100204
installsource=C:\\Program Files (x86)\\Microsoft XNA\\XNA Game Studio\\v3.1\\Setup\\
madeup-gname={BED4CEEC-863F-4AB3-BA23-541764E2D2CE}
madeup-wow=1
uninstallstring=MsiExec.exe /I{BED4CEEC-863F-4AB3-BA23-541764E2D2CE}
windowsinstaller=1
.EXAMPLE
get-installed -namesummary $true
Display the frequency of valuenames for all apps in all registry location
only this time show all registry sources
in reverse order of occurrence.
UninstallString,616
DisplayName,616
Publisher,600
DisplayVersion,525
VersionMajor,490
InstallDate,474
EstimatedSize,474
InstallSource,470
Version,469
ModifyPath,461
WindowsInstaller,457
Language,396
madeup-gname,391
NoModify,366
HelpLink,323
madeup-wow,308
NoRepair,256
SystemComponent,235
LocalPackage,225
URLInfoAbout,171
VersionMinor,167
InstallLocation,159
ParentDisplayName,91
ParentKeyName,91
madeup-native,83
DisplayIcon,79
Comments,78
URLUpdateInfo,71
RegOwner,69
MoreInfoURL,66
ProductID,62
RegCompany,59
NoRemove,53
Readme,35
Contact,33
ReleaseType,26
IsMinorUpgrade,26
RegistryLocation,25
HelpTelephone,21
UninstallPath,16
LogFile,9
MajorVersion,7
APPName,6
MinorVersion,6
Size,6
QuietUninstallString,5
NoElevateOnModify,4
Inno Setup: User,3
SkuComponents,3
ShellUITransformLanguage,3
ProductGuid,3
NVI2_Package,3
Inno Setup: App Path,3
Inno Setup: Icon Group,3
CacheLocation,3
ProductCodes,3
NVI2_Timestamp,3
Inno Setup: Deselected Tasks,3
NVI2_Setup,3
Inno Setup: Setup Version,3
LogMode,3
PackageIds,3
Inno Setup: Language,2
RequiresIESysFile,2
InstanceId,2
UninstDataVerified,1
BundleVersion,1
BundleProviderKey,1
Inno Setup: Selected Components,1
FCLAppName,1
Inno Setup: Selected Tasks,1
Integrated,1
BundleUpgradeCode,1
Installed,1
SQLProductFamilyCode,1
FCLGUID,1
UninstallerCommonDir,1
BundleDetectCode,1
InstallerType,1
DisplayName_Localized,1
Inno Setup: Setup Type,1
EngineVersion,1
BundleCachePath,1
Resume,1
.EXAMPLE
get-installed -re "^microsoft xna game studio platform tools$" -makeobjects $true
Instead of displaying the valuenames create an object for further use
displayname : microsoft xna game studio platform tools
DisplayVersion : 1.1.0.0
InstallDate : 20100204
InstallLocation :
InstallSource : C:\\Program Files (x86)\\Microsoft XNA\\XNA Game Studio\\v3.1\\Setup\\
LocalPackage : C:\\Windows\\Installer\\2d09d3a5.msi
madeup-gname : {BED4CEEC-863F-4AB3-BA23-541764E2D2CE}
madeup-native :
madeup-wow : 1
QuietUninstallString :
UninstallString : MsiExec.exe /I{BED4CEEC-863F-4AB3-BA23-541764E2D2CE}
WindowsInstaller : 1
.EXAMPLE
get-installed -re "^microsoft xna game studio" -makeobjects $true|format-table
Instead of displaying the valuenames create an object for further use
displayname DisplayVersion InstallDate InstallLocation InstallSource LocalPackage madeup-gname madeup-native madeup-wow QuietUninstallStrin
g
----------- -------------- ----------- --------------- ------------- ------------ ------------ ------------- ---------- -------------------
microsoft xna ga... 3.1.10527.0 XNA Game Studio 3.1 1
microsoft xna ga... 3.1.10527.0 20100204 c:\\c3aa2d4649aa0... c:\\Windows\\Insta... {E1D78366-91DA-4... 1
microsoft xna ga... 3.1.10527.0 20100204 C:\\Program Files... C:\\Windows\\Insta... {007BECB0-17DD-4... 1
microsoft xna ga... 3.1.10527.0 20100204 c:\\c3aa2d4649aa0... c:\\Windows\\Insta... {0DC16794-7E69-4... 1
microsoft xna ga... 3.1.10527.0 20100204 C:\\Program Files... C:\\Windows\\Insta... {AF9BDE67-11A5-4... 1
microsoft xna ga... 3.1.10527.0 20100204 C:\\Program Files... C:\\Windows\\Insta... {3BA37E38-B53D-4... 1
microsoft xna ga... 3.1.10527.0 20100204 C:\\Program Files... C:\\Windows\\Insta... {DFB81F19-ED3A-4... 1
microsoft xna ga... 3.1.10527.0 20100204 C:\\Program Files... C:\\Windows\\Insta... {7FD30AE7-281D-4... 1
microsoft xna ga... 1.1.0.0 20100204 C:\\Program Files... C:\\Windows\\Insta... {BED4CEEC-863F-4... 1
.PARAMETER computername
The computer name to query. Just one.
.PARAMETER re
regular expression used to select software displayname
.PARAMETER compress
defaults to true. Merges values by valuename from many sources of installed data.
The merge means if it finds a valuename more than once it shows only the first one found.
This is true except for madeup-loginid. Instead a string is created with comma separated values
where the values are the loginids of sids found in the product sections.
Set to false the program will separate the values by registry keypath.
data from products installed by the system takes precedence over software...uninstall
.PARAMETER namesummary
displays a list of valuenames found in registry in descending order of frequency
no other data shown if this is set to $true
.PARAMETER valuenameRE
regular expression to specify which valuenames to display
defaults to "displayversion|windowsinstaller|uninstallstring|localpackage|installsource|installdate|madeup-|gp_"
specify .* to display all valuenames
valuename not in registry but madeup in this program start with madeup-
madeup-wow was set for uninstall key in the software wow6432node portion of the registry
madeup-native was set for uninstall key in the software native portion of the key
madeup-guid was set from the uninstall subkey containing the value names
madeup-loginid was set from the registry product section
valuename from group policy is prepended with "gp_"
.PARAMETER showupdates
show update entries as well
defaults to false
.PARAMETER makeobjects
Create objects whose properties are the merged valuenames defined by the value name defaults.
#>
[CmdletBinding()]
param
(
[Parameter(Mandatory=$False)]
[Alias('computer')]
[string]$computername=$env:computername,
[string]$re = ".*",
[boolean]$compress=$true,
[boolean]$namesummary=$false,
[boolean]$makeobjects=$false,
[boolean]$showupdates=$false,
[string]$valuenameRE="displayversion|windowsinstaller|uninstallstring|installlocation|localpackage|installsource|installdate|madeup-|gp_",
[string]$makeobjectsRE="displayversion|windowsinstaller|uninstallstring|installlocation|localpackage|installsource|installdate|madeup-|gp_"
)
begin {
try
{
$regbase=[Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine,$computername)
}
catch [Exception]
{
# see if remote registry is stopped
Write-Host "Failed to open registry due to " $_.Exception.Message
if ($_.Exception.HResult -eq 53)
{
# The network path was not found
exit
}
Write-Host "Checking if registry service started on " $computername
try
{
Get-Service remoteregistry -ComputerName $computername|gm
$remoteregistry=(Get-Service remoteregistry -ComputerName $computername).status
}
catch [Exception]
{
Write-Host "cannot reach service manager on " $computername
exit
}
"Remote Registry status is " + $remoteregistry
if ($remoteregistry -ieq "stopped")
{
Set-Service remoteregistry -Status Running -Computername $computername
sleep 5
try
{
$regbase=[Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine,$computername)
}
catch [Exception]
{
return $_.Exception.Message
}
}
else
{
write-Host "could not open registry for " $computername
exit
}
}
$software=@{} # Keep hash of software displaynames -> hash of keypaths -> hash of valuename->values
$valuenamesfound=@{} # keep count of valuenames found
$pg2displayname=@{} # set in getproductdata and used in getgrouppolicydata
$sid2logid=@{} # Set it
$installedbywho=@{} # track who has installed a product
Function load_sid2logid
{
# Set $sid2logid using registry profilelist
$ProfileListKey=$regbase.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList",$False)
if ($ProfileListKey -eq $null) {return "Yuck"}
foreach ($guid in $ProfileListKey.GetSubKeyNames())
{
if ($guid -imatch "^s-")
{
switch($guid.ToUpper())
{
"S-1-5-18" {$sid2logid.Add("S-1-5-18","System")}
"S-1-5-19" {$sid2logid.Add("S-1-5-19","Service")}
"S-1-5-20" {$sid2logid.Add("S-1-5-20","Network")}
default
{
[string]$ProfileImagePath=$ProfileListKey.OpenSubKey($guid).GetValue("ProfileImagePath")
$logid=$ProfileImagePath.Split("\\")[-1]
$sid2logid.Add($guid.ToUpper(),$logid)
}
}
}
}
}
load_sid2logid
Function WantedDisplayName
{
param([string]$wanteddisplayname)
if ($wanteddisplayname -ieq $null -or $wanteddisplayname -ieq "")
{
return($false)
}
if (-not ($wanteddisplayname -imatch $re))
{
return($false)
}
# displayname wanted
if ($showupdates)
{
return($true)
}
else
{
if ($wanteddisplayname -imatch "update|hotfix")
{
return($false)
}
return($true)
}
}
}
process
{
Function upvaluenamesfound
{
param([string]$valuename)
if ($valuenamesfound.ContainsKey($valuename))
{
$valuenamesfound.$valuename++
}
else
{
$valuenamesfound.Add($valuename,1)
}
}
Function getuninstalldata
{
param([STRING] $subkeyname)
$uninstallkey=$regbase.OpenSubKey($subkeyname,$False)
if ($uninstallkey -ne $null)
{
foreach ($gname in $uninstallkey.GetSubKeyNames())
{
$prodkey=$uninstallkey.OpenSubKey($gname)
$displayname=$prodkey.GetValue("displayname")
$uninstallstring=$prodkey.GetValue("uninstallstring")
if (WantedDisplayName($displayname) -and $uninstallstring -ine "" -and $uninstallstring -ine $null )
{
$KeyPath=$subkeyname+"\\"+$gname
$valuehash= @{}
#"KeyPath=" + $KeyPath
#"displayname='" + $displayname + "'"
$valuehash.Add("madeup-gname",$gname)
upvaluenamesfound("madeup-gname")
if ($subkeyname -imatch "wow6432node")
{
$valuehash.Add("madeup-wow",1)
upvaluenamesfound("madeup-wow")
}
else
{
$valuehash.Add("madeup-native",1)
upvaluenamesfound("madeup-native")
}
foreach ($valuename in $prodkey.GetValueNames())
{
$value=$prodkey.GetValue($valuename)
if ($value -ine "" -and $value -ine $null)
{
$valuehash.Add($valuename.tolower(),$prodkey.GetValue($valuename))
upvaluenamesfound($valuename)
#"added " + $valuename + "=" + $valuehash.$valuename
}
}
$guidformat="no"
if ($gname.StartsWith("{") -and $gname.EndsWith("}") -and $gname.Length -eq 38 ) {$guidformat="yes"}
$tolower=$displayname.ToLower()
if ($software.ContainsKey($tolower))
{
$software.$tolower.Add($KeyPath.ToLower(),$valuehash)
}
else
{
$subhash=@{}
$subhash.Add($KeyPath.ToLower(),$valuehash)
$software.Add($tolower,$subhash)
}
}
}
}
}
Function getproductdatabysid
{
param([string]$sid)
$subkeyname="SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData\\"+$sid+"\\Products"
$productkey=$regbase.OpenSubKey($subkeyname,$False)
foreach ($gname in $productkey.GetSubKeyNames())
{
$prodkey=$productkey.OpenSubKey($gname).OpenSubKey("InstallProperties")
try
{
$displayname=$prodkey.GetValue("displayname")
$uninstallstring=$prodkey.GetValue("uninstallstring")
$pg2displayname.Add($gname.ToLower(),$displayname) # remember packed guid
}
catch
{
$uninstallstring=""
$displayname=""
}
if (WantedDisplayName($displayname) -and $uninstallstring -ine "" -and $uninstallstring -ine $null )
{
$KeyPath=$subkeyname+"\\"+$gname + "\\InstallProperties"
#"KeyPath=" + $KeyPath
#"displayname='" + $displayname + "'"
$valuehash= @{}
$valuehash.Add("madeup-loginid",$sid2logid.$sid)
foreach ($valuename in $prodkey.GetValueNames())
{
$value=$prodkey.GetValue($valuename)
if ($value -ine "" -and $value -ine $null)
{
$valuehash.Add($valuename.tolower(),$prodkey.GetValue($valuename))
upvaluenamesfound($valuename)
#"added " + $valuename + "=" + $valuehash.$valuename
}
}
$tolower=$displayname.ToLower()
if ($software.ContainsKey($tolower))
{
$software.$tolower.Add($KeyPath.ToLower(),$valuehash)
}
else
{
$subhash=@{}
$subhash.Add($KeyPath.ToLower(),$valuehash)
$software.Add($tolower,$subhash)
}
}
}
}
Function getproductdata
{
$subkeyname="SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData"
$userdatakey=$regbase.OpenSubKey($subkeyname,$False)
foreach ($sid in $userdatakey.GetSubKeyNames())
{
getproductdatabysid($sid)
}
}
Function getgrouppolicydata
{
$subkeyname="SOFTWARE/Microsoft/Windows/CurrentVersion/Group Policy/AppMgmt"
$gpkey=$regbase.OpenSubKey($subkeyname,$False)
if ($gpkey -eq $null)
{
return
}
foreach ($gname in $gpkey.GetSubKeyNames())
{
$prodkey=$gpkey.OpenSubKey($gname)
$displayname=$pg2displayname.($gname.ToLower())
if (WantedDisplayName($displayname))
{
$keypath=$subkeyname+ "\\" + $gname
$valuehash=@{}
foreach ($valuename in $prodkey.GetValueNames())
{
$value=$prodkey.GetValue($valuename)
if ($value -ine "" -and $value -ine $null)
{
$valuehash.Add("gp_"+$valuename.tolower(),$prodkey.GetValue($valuename))
upvaluenamesfound($valuename)
#"added " + $valuename + "=" + $valuehash.$valuename
}
}
$tolower=$displayname.ToLower()
if ($software.ContainsKey($tolower))
{
$software.$tolower.Add($KeyPath.ToLower(),$valuehash)
}
else
{
$subhash=@{}
$subhash.Add($KeyPath.ToLower(),$valuehash)
$software.Add($tolower,$subhash)
}
}
}
}
getuninstalldata("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall")
getuninstalldata("SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall")
getproductdata
getgrouppolicydata
#HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData\\S-1-5-18\\Products\\00002109610090400000000000F01FEC\\InstallProperties
if ($namesummary)
{
$mykeys=$valuenamesfound.keys|sort-object -Property @{Expression={[int]$valuenamesfound.$_}; Ascending=$false}
foreach ($valuename in ($mykeys))
{
if ($valuename -ne "" -and $valuename -ne $null) {$valuename + "," + $valuenamesfound.$valuename}
}
}
elseif ($makeobjects)
{
foreach ($displayname in ($software.Keys|Sort-Object))
{
if ($displayname -imatch $re) {
#" "
#"displayname=" + $displayname
$compressedhash=@{};
foreach ($keypath in ($software.$displayname.Keys|Sort-Object))
{
foreach ($valuename in ($software.$displayname.$keypath.Keys|Sort-Object))
{
if (-not $compressedhash.ContainsKey($valuename))
{
$compressedhash.Add($valuename,$software.$displayname.$keypath.$valuename)
}
elseif ($valuename -ieq "madeup-loginid")
{
$compressedhash.$valuename += ("," + $software.$displayname.$keypath.$valuename)
}
}
}
$obj=New-Object object
$obj|Add-Member -MemberType NoteProperty "displayname" $displayname
foreach ($valuename in ($valuenamesfound.keys|Sort-Object))
{
if ($valuename -imatch $makeobjectsRE)
{
if ($compressedhash.ContainsKey($valuename))
{
$obj|Add-Member -MemberType NoteProperty $valuename $compressedhash.$valuename
}
else
{
$obj|Add-Member -MemberType NoteProperty $valuename ""
}
}
}
Write-Output $obj
}
}
}
elseif ($compress)
{
foreach ($displayname in ($software.Keys|Sort-Object))
{
if ($displayname -imatch $re) {
" "
"displayname=" + $displayname
$compressedhash=@{};
foreach ($keypath in ($software.$displayname.Keys|Sort-Object))
{
foreach ($valuename in ($software.$displayname.$keypath.Keys|Sort-Object))
{
if (-not $compressedhash.ContainsKey($valuename))
{
$compressedhash.Add($valuename,$software.$displayname.$keypath.$valuename)
}
elseif ($valuename -ieq "madeup-loginid")
{
$compressedhash.$valuename += ("," + $software.$displayname.$keypath.$valuename)
}
}
}
foreach ($valuename in ($compressedhash.Keys|Sort-Object))
{
if ($valuename -imatch $valuenameRE)
{
" " + $valuename + "=" + $compressedhash.$valuename
}
}
}
}
}
else
{
foreach ($displayname in ($software.Keys|Sort-Object))
{
if ($displayname -imatch $re) {
" "
"displayname=" + $displayname
foreach ($keypath in ($software.$displayname.Keys|Sort-Object))
{
" keypath=" + $keypath
foreach ($valuename in ($software.$displayname.$keypath.Keys|Sort-Object))
{
if ($valuename -imatch $valuenameRE)
{
" " + $valuename + "=" + $software.$displayname.$keypath.$valuename
}
}
}
}
}
}
}
}
|
PowerShellCorpus/PoshCode/Import-Certificate_8.ps1
|
Import-Certificate_8.ps1
|
#requires -Version 2.0
function Import-Certificate
{
param
(
[IO.FileInfo] $CertFile = $(throw "Paramerter -CertFile [System.IO.FileInfo] is required."),
[string[]] $StoreNames = $(throw "Paramerter -StoreNames [System.String] is required."),
[switch] $LocalMachine,
[switch] $CurrentUser,
[string] $CertPassword,
[switch] $Verbose
)
begin
{
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Security")
}
process
{
if ($Verbose)
{
$VerbosePreference = 'Continue'
}
if (-not $LocalMachine -and -not $CurrentUser)
{
Write-Warning "One or both of the following parameters are required: '-LocalMachine' '-CurrentUser'. Skipping certificate '$CertFile'."
}
try
{
if ($_)
{
$certfile = $_
}
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $certfile,$CertPassword
}
catch
{
Write-Error ("Error importing '$certfile': $_ .") -ErrorAction:Continue
}
if ($cert -and $LocalMachine)
{
$StoreScope = "LocalMachine"
$StoreNames | ForEach-Object {
$StoreName = $_
if (Test-Path "cert:\\$StoreScope\\$StoreName")
{
try
{
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store $StoreName, $StoreScope
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$store.Add($cert)
$store.Close()
Write-Verbose "Successfully added '$certfile' to 'cert:\\$StoreScope\\$StoreName'."
}
catch
{
Write-Error ("Error adding '$certfile' to 'cert:\\$StoreScope\\$StoreName': $_ .") -ErrorAction:Continue
}
}
else
{
Write-Warning "Certificate store '$StoreName' does not exist. Skipping..."
}
}
}
if ($cert -and $CurrentUser)
{
$StoreScope = "CurrentUser"
$StoreNames | ForEach-Object {
$StoreName = $_
if (Test-Path "cert:\\$StoreScope\\$StoreName")
{
try
{
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store $StoreName, $StoreScope
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$store.Add($cert)
$store.Close()
Write-Verbose "Successfully added '$certfile' to 'cert:\\$StoreScope\\$StoreName'."
}
catch
{
Write-Error ("Error adding '$certfile' to 'cert:\\$StoreScope\\$StoreName': $_ .") -ErrorAction:Continue
}
}
else
{
Write-Warning "Certificate store '$StoreName' does not exist. Skipping..."
}
}
}
}
end
{ }
}
|
PowerShellCorpus/PoshCode/Get-NestedGroups v_4.ps1
|
Get-NestedGroups v_4.ps1
|
Function Global:Get-NestedGroups {
<#
.SYNOPSIS
Enumerate all AD group memberships of an account (including nested membership).
.DESCRIPTION
This script will return the AD group objects for each group the user is a member of.
.PARAMETER UserName
The username whose group memberships to find.
.EXAMPLE
Get-NestedGroups johndoe | Out-GridView
Get-NestedGroups johndoe, janedoe | % { $_ | Out-GridView }
Get-ADUser -Filter "cn -like 'john*'" | % { Get-NestedGroups $_ | Sort-Object Name | Out-GridView -Title "Groupmembership for $($_)" }
"johndoe","janedoe" | % { Get-NestedGroups $_ | Sort-Object Name | Export-CSV Groupmembership-$($_.Name).csv -Delimiter ";" }
"johndoe","janedoe" | Get-NestedGroups | % { $_ | Sort-Object Name | Out-GridView }
.NOTES
ScriptName : Get-NestedGroups
Created By : Gilbert van Griensven
Date Coded : 06/17/2012
Updated : 08/11/2012
The script iterates through all nested groups and skips circular nested groups.
.LINK
#>
[CmdletBinding(SupportsShouldProcess=$True)]
Param (
[Parameter(Mandatory=$True,ValueFromPipeline=$True,HelpMessage="Please enter a username")] $UserName
)
Begin {
$PipelineInput = -not $PSBoundParameters.ContainsKey("UserName")
Write-Verbose "Looking for ActiveDirectory module"
If (!(Get-Module ActiveDirectory)) {
Write-Verbose "ActiveDirectory module not loaded - checking availability"
If (Get-Module -ListAvailable | ? {$_.Name -eq "ActiveDirectory"}) {
Write-Verbose "ActiveDirectory module is available - loading module"
Import-Module ActiveDirectory
$Script:ADModuleUnload = $True
} Else {
Write-Verbose "ActiveDirectory Module is not available"
Write-Error "ActiveDirectory Module is not available" -Category ResourceUnavailable
Break
}
} Else {
Write-Verbose "ActiveDirectory Module is already loaded"
$Script:ADModuleUnload = $False
}
Function GetNestedGroups {
Get-ADGroup $_ -Properties MemberOf | Select-Object -ExpandProperty MemberOf | % {
If (!(($Script:GroupMembership | Select-Object -ExpandProperty DistinguishedName) -contains (Get-ADGroup $_).DistinguishedName)) {
$Script:GroupMembership += (Get-ADGroup $_)
GetNestedGroups $_
}
}
}
Function GetDirectGroups {
$InputType = $_.GetType().Name
If (($InputType -ne "ADUser") -and ($InputType -ne "String")) {
Write-Error "Invalid input type `'$($_.GetType().FullName)`'" -Category InvalidType -TargetObject $_
Break
}
If ($InputType -eq "String") {
Try {
Write-Verbose "Querying Active Directory for user `'$($_)`'"
$UserObject = Get-ADUser $_
}
Catch {
Write-Verbose "$_"
Write-Error $_ -Category ObjectNotFound -TargetObject $_
Break
}
} Else { $UserObject = $_ }
$Script:GroupMembership = @()
$Script:GroupMembership += (Get-ADGroup "Domain Users")
Get-ADUser $UserObject -Properties MemberOf | Select-Object -ExpandProperty MemberOf | % {
$Script:GroupMembership += (Get-ADGroup $_)
}
$Script:GroupMembership | ForEach-Object {GetNestedGroups $_}
}
}
Process {
If ($PipelineInput) {
GetDirectGroups $_
, $Script:GroupMembership
} Else {
$UserName | ForEach-Object {
GetDirectGroups $_
$Script:GroupMembership
}
}
}
End {
If (($Script:ADModuleUnload)) {
Write-Verbose "Removing module ActiveDirectory"
Remove-Module ActiveDirectory -ErrorAction SilentlyContinue
}
}
}
|
PowerShellCorpus/PoshCode/Get-NestedGroups v2.ps1
|
Get-NestedGroups v2.ps1
|
Function Get-NestedGroups {
<#
.SYNOPSIS
Enumerate all AD group memberships of an account (including nested membership).
.DESCRIPTION
This script will return the AD group objects for each group the user is a member of.
.PARAMETER UserName
The username whose group memberships to find.
.EXAMPLE
Get-NestedGroups johndoe | Out-GridView
Get-NestedGroups johndoe, janedoe | % { $_ | Out-GridView }
Get-ADUser -Filter "cn -like 'john*'" | % { Get-NestedGroups $_ | Sort-Object Name | Out-GridView -Title "Groupmembership for $($_.Name)" }
"johndoe","janedoe" | % { Get-NestedGroups $_ | Sort-Object Name | Export-CSV Groupmembership-$($_).csv -Delimiter ";" }
.NOTES
ScriptName : Get-NestedGroups
Created By : Gilbert van Griensven
Date Coded : 06/17/2012
Updated : 08/11/2012
The script iterates through all nested groups and skips circular nested groups.
.LINK
#>
[CmdletBinding(SupportsShouldProcess=$True)]
Param (
[Parameter(Mandatory=$True,ValueFromPipeline=$True,HelpMessage="Please enter a username")] $UserName
)
Begin {
$PipelineInput = -not $PSBoundParameters.ContainsKey("UserName")
Write-Verbose "Looking for ActiveDirectory module"
$Script:ADModuleUnload = $False
If (!(Get-Module ActiveDirectory)) {
Write-Verbose "ActiveDirectory module not loaded - checking availability"
If (Get-Module -ListAvailable | ? {$_.Name -eq "ActiveDirectory"}) {
Write-Verbose "ActiveDirectory module is available - loading module"
Import-Module ActiveDirectory
} Else {
Write-Verbose "ActiveDirectory Module is not available"
$Script:ADModuleUnload = $True
}
} Else {
Write-Verbose "ActiveDirectory Module is already loaded"
$Script:ADModuleUnload = $True
}
Function GetNestedGroups {
Get-ADGroup $_ -Properties MemberOf | Select-Object -ExpandProperty MemberOf | % {
If (!(($Script:GroupMembership | Select-Object -ExpandProperty DistinguishedName) -contains (Get-ADGroup $_).DistinguishedName)) {
$Script:GroupMembership += (Get-ADGroup $_)
GetNestedGroups $_
}
}
}
Function GetDirectGroups {
$InputType = $_.GetType().Name
If (($InputType -ne "ADUser") -and ($InputType -ne "String")) {
Write-Error "Invalid input type `'$($_.GetType().FullName)`'" -Category InvalidType -TargetObject $_
Break
}
If ($InputType -eq "String") {
Try {
Write-Verbose "Querying Active Directory for user `'$($_)`'"
$UserObject = Get-ADUser $_
}
Catch {
Write-Verbose "$_"
Write-Error $_ -Category ObjectNotFound -TargetObject $_
Break
}
} Else { $UserObject = $_ }
$Script:GroupMembership = @()
$Script:GroupMembership += (Get-ADGroup "Domain Users")
Get-ADUser $UserObject -Properties MemberOf | Select-Object -ExpandProperty MemberOf | % {
$Script:GroupMembership += (Get-ADGroup $_)
}
$Script:GroupMembership | ForEach-Object {GetNestedGroups $_}
}
}
Process {
If ($PipelineInput) {
GetDirectGroups $_
} Else {
$UserName | ForEach-Object {
GetDirectGroups $_
}
}
$Script:GroupMembership
}
End {
If (!($Script:ADModuleUnload)) {
Write-Verbose "Removing module ActiveDirectory"
Remove-Module ActiveDirectory -ErrorAction SilentlyContinue
}
}
}
|
PowerShellCorpus/PoshCode/MachineKey.psm1.ps1
|
MachineKey.psm1.ps1
|
if((Get-Command Get-Website, Get-WebApplication, Get-WebConfiguration, Get-WebConfigFile, Set-WebConfigurationProperty -EA 0).Count -lt 5) {
throw "The required commands from the 'WebAdministration' module are not available. Import the WebAdministration module and try again.`n
The following commands are required: Get-Website, Get-WebApplication, Get-WebConfiguration, Get-WebConfigFile, Set-WebConfigurationProperty"
}
function New-MachineKeyFile {
#.Synopsis
# Generate MachineKey File
#.Description
# Uses RNGCryptoServiceProvider to generate arrays of random bytes into a CSV file
#.Parameter Path
# The Path to the file where you want to save the key
#.Links
# http://msdn.microsoft.com/en-us/library/w8h3skw9%28v=VS.100%29.aspx
param(
[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[Alias("PSPath")]
[string]$Path
,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[ValidateSet("3DES","AES","DES")]
[string]$decryptionType = "3DES" # TODO: AES is better, but 3DES is currently more compatible in our environment.
,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[ValidateSet('AES','MD5','SHA1','3DES','HMACSHA256','HMACSHA384','HMACSHA512')]
[string]$validationType = "SHA1"
)
process {
$vbytes = $(
switch($validationType) {
'AES' { 32 }
'MD5' { 16 }
'SHA1' { 64 }
'3DES' { 24 }
'HMACSHA256' { 32 }
'HMACSHA384' { 48 }
'HMACSHA512'{ 64 }
}
)
$dbytes = $(
switch($decryptionType) {
'DES' { 8 }
'3DES' { 24 }
'AES' { 32 }
}
)
New-Object PSObject -Property @{
validationKey=$(Get-CryptoBytes $vbytes -AsString)
decryptionKey =$(Get-CryptoBytes $dbytes -AsString)
decryptionType=$decryptionType.ToUpper()
validationType=$validationType.ToUpper()
} | Export-CSV -Path $Path
Get-Item $Path
}
}
function Get-CryptoBytes {
#.Synopsis
# Generate Cryptographically Random Bytes
#.Description
# Uses RNGCryptoServiceProvider to generate arrays of random bytes
#.Parameter Count
# How many bytes to generate
#.Parameter AsString
# Output hex-formatted strings instead of byte arrays
#.Notes
# Choosing an appropriate key size:
# For IIS machineKeys, the following algorithms and key lengths are recommended:
#
# For Validation, SHA1 is recommended
# For MD5: the key must be 16 bytes (32 hexadecimal characters).
# For SHA1: the key must be (at least?) 20 bytes (40 hexadecimal characters).
# For 3DES: the key must be 24 bytes (48 hexadecimal characters).
# For AES: the key must be 32 bytes (64 hexadecimal characters).
# For HMACSHA256: the key must be 32 bytes (64 hexadecimal characters).
# For HMACSHA384: the key must be 48 bytes (96 hexadecimal characters).
# For HMACSHA512: the key must be 64 bytes (128 hexadecimal characters).
# For decryption, AES is recommended, but 3DES is backwards compatible to ASP.Net 2
# For DES: the key must be 8 bytes (16 hexadecimal characters).
# For 3DES: the key must be 24 bytes (48 hexadecimal characters).
# For AES: the key should be the maximum: 32 bytes (64 hexadecimal characters).
param(
[Parameter(ValueFromPipeline=$true)]
[int[]]$count = 64
,
[switch]$AsString
)
begin {
$RNGCrypto = New-Object System.Security.Cryptography.RNGCryptoServiceProvider
$OFS = ""
}
process {
foreach($length in $count) {
$bytes = New-Object Byte[] $length
$RNGCrypto.GetBytes($bytes)
if($AsString){
Write-Output ("{0:X2}" -f $bytes)
} else {
Write-Output $bytes
}
}
}
end {
$RNGCrypto = $null
}
}
function Find-WebConfigLocation {
<#
.Synopsis
Find Web.Config which have a machineKey specified that matches the specified ValidationKey
.Description
Searches all web.config for the XSM MachineKey and replaces them with a new one (generated at runtime).
The default settings will replace all machine keys in IIS which match the current XeroxServicesManager key with keys which must be specified at runtime.
.Parameter ValidationKey
Specify the validationKey to search for (supports regular expressions).
Defaults to: ^[0-9A-F]+$ (which matches all validationKeys that are actually specified, but not the default "AutoGenerate,IsolateApps")
#>
[CmdletBinding()]
param (
[Parameter(Position=1, Mandatory=$false)]
[string[]]$SiteRoot = "IIS:\\Sites"
,
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)]
[string[]]$ValidationKey = "^[0-9A-F]+$"
,
[switch]$Force
,
[switch]$Recurse
)
process {
if($Recurse) {
## This code will get all web.config with machineKey in them, and then warn on web.config that are not apps
foreach($config in Get-WebConfiguration -Recurse system.web/machineKey -PSPath $SiteRoot) {
trap {
Write-Verbose "Ignoring non-application web.config in $($config.PSPath)"
continue
}
Get-WebConfiguration system.web/machineKey -PSPath $config.PSPath |
Where-Object { $Force -or $(foreach($key in $ValidationKey){ $_.validationKey -match $key }) -contains $true } |
Select-Object -Expand PSPath
}
} else {
## This code will get the machineKey setting for ALL apps, even those which do not specify it (they inherit it from the machine settings)
foreach($site in Get-Website *){
foreach($app in Get-WebApplication -Site $site.Name *) {
$Path = "IIS:\\Sites\\$($Site.Name)$($App.Path)"
if($Path -like "$SiteRoot*") {
Get-WebConfiguration system.web/machinekey -pspath $Path |
Where-Object { $Force -or $(foreach($key in $ValidationKey){ $_.validationKey -match $key }) -contains $true } |
Select-Object -Expand PSPath
}
}
}
}
}
}
function Set-FileWriteable {
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
$File
,
[switch]$Passthru
)
process {
foreach($path in @($file)) {
write-verbose "'$path' is on '$($path.PSComputerName)'"
if($path.PSComputerName) {
Invoke-Command $path.PSComputerName {
param([string[]]$path,[switch]$passthru)
$files = Get-Item $path
foreach($f in $files) {
if($f.Attributes -band [IO.FileAttributes]"ReadOnly") {
$f.Attributes = $f.Attributes -bxor [IO.FileAttributes]"ReadOnly"
}
}
write-output $files
} -Argument $path | Where { $Passthru }
} else {
$files = Get-Item $path
foreach($f in $files) {
if($f.Attributes -band [IO.FileAttributes]"ReadOnly") {
$f.Attributes = $f.Attributes -bxor [IO.FileAttributes]"ReadOnly"
}
}
if($Passthru) { write-output $files }
}
}
}
}
function Set-MachineKey {
<#
.Synopsis
Changes the MachineKey for the specified sites.
.Description
For every specified web.config file, changes the MachineKey setting to the new specified key settings.
.Parameter ValidationKey
You must specify the validation key as a 128 character hexadecimal string (will be generated randomly, otherwise).
.Parameter DecryptionKey
You must specify the decryption key as a 48 character hexadecimal string (will be generated randomly, otherwise).
.Parameter ConfigFiles
You must specify the files to set the machineKey in.
.Example
New-MachineKeyFile $home\\Keys.csv
C:\\PS>Import-Csv $home\\Keys.csv | Set-MachineKey $(Find-WebConfigLocation)
Description
-----------
This example shows how to generate a new key pair using New-MachineKeyFile into a csv file and reuse it on multiple machines:
* Generate the new key into a file by calling New-MachineKeyFile
* Import the Key from the CSV file and pipe it to Set-MachineKey
* Call Find-WebConfigLocation to find all config file swhich currently have hand-coded machineKeys and replace them.
.Example
$session = New-PSSession $ComputerName
C:\\PS>Invoke-Command $session {Import-Module WebAdministration}
C:\\PS>Import-PSSession $session -Module WebAdministration
ModuleType Name ExportedCommands
---------- ---- ----------------
Script tmp_98a1a0b9-eb4d-4a6d-8e8d... {Stop-Website, Get-WebConfiguration, Get-WebAppPoolState, New-WebGlobalModule...
C:\\PS>Import-Module MachineKey
C:\\PS>New-MachineKeyFile $home\\Keys.csv
C:\\PS>Import-Csv $home\\Keys.csv | Set-MachineKey $(Find-WebConfigLocation)
Description
-----------
Demonstrates how to use this module to set a machine key on a remote server by using Import-PSSession to import the WebAdministration commands from a remote computer.
.Notes
If you run this script and there are errors (eg: it only sets *some* of the web.configs), you MUST run it again to set those back, or manually correct the web.config.
#>
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact="Medium")]
param (
[Parameter(Position = 0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("PSPATH","File")]
[Array]$ConfigFile
,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[ValidateSet("3DES","AES")]
[string]$DecryptionType = "AES"
,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[ValidateSet("SHA1","MD5")]
[string]$ValidationType = "SHA1"
,
[Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[ValidateLength(16,64)]
[string]$DecryptionKey #= $(Get-CryptoBytes 24 -AsString)
,
[Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[ValidateLength(32,128)]
[string]$ValidationKey #= $(Get-CryptoBytes 64 -AsString)
)
process {
## Validate the Keys:
if($ValidationKey -notmatch "^[0-9A-F]+$") {
throw "The supplied Validation key is not hexadecimal!"
}
if($DecryptionKey -notmatch "^[0-9A-F]+$") {
throw "The supplied Decryption key is not hexadecimal!"
}
if($PSBoundParameters.ContainsKey("WhatIf")) {
Write-Host "Setting machineKey to: `n$('<machineKey validationKey="{0}" decryptionKey="{1}" decryption="{2}" validation="{3}" />' -f $ValidationKey, $DecryptionKey, $decryptionType.ToUpper(), $validationType.ToUpper())" -Fore Cyan
} else {
Write-Verbose "Setting machineKey to: $('<machineKey validationKey="{0}" decryptionKey="{1}" decryption="{2}" validation="{3}" />' -f $ValidationKey, $DecryptionKey, $decryptionType.ToUpper(), $validationType.ToUpper())"
}
foreach($config in $ConfigFile) {
if($PSCmdlet.ShouldProcess("Setting machineKey in $($config) ", "Set Machine Key in '$($config)'?", "Replace MachineKey?")) {
Get-WebConfigFile -PSPath $config | Set-FileWriteable
## Finally, set the properties:
set-webconfigurationproperty system.web/machineKey -PSPath $config -name validationKey -value $ValidationKey
set-webconfigurationproperty system.web/machineKey -PSPath $config -name decryptionKey -value $DecryptionKey
## Just to be sure, set these too:
set-webconfigurationproperty system.web/machineKey -PSPath $config -name decryption -value $decryptionType
set-webconfigurationproperty system.web/machineKey -PSPath $config -name validation -value $validationType
}
}
}
}
|
PowerShellCorpus/PoshCode/Process Count CheckAlert.ps1
|
Process Count CheckAlert.ps1
|
<#*****************************************************************************************************************
* PowerShell Script to verify Process Count Check & Email alert
*****************************************************************************************************************
Script for checking a Process Life Cycle using Windows PowerShell
Step 1) This Script checks if the Processes are Running
Step 2) If the Total Process Count is less than 10 (that's my threshold - 10) - It would send you an Email with link to Auto Fix.
Step 3) If the Total Process Count is greater or equal to 10- It would send a OK Email - no Action required.
Step 4) I also included $Process2 and it being live and embedded the OR operator to check if either of them fail to send a Email Alert
Step 5) If you have qns please email info@sankeerth.net
Variables: ABC = $Process name and XYZ = $Process2 name , SMTP and From and TO Addresses
and create Report.html & Fail Report.html to Email the to address.
******************************************************************************************************************
* Version 1.6
******************************************************************************************************************
*
* Last Modified : Modtime: 12/18/2012 11:25a
* Revision : 1.6
* By : Author: Sankeerth Ankala
******************************************************************************************************************#>
$Process = GPS "ABC"
$Process
$Process.Count
$Process2 = GPS "XYZ"
$Process2.Count
if(($Process.Count -lt 10) -or ($Process2.Count -eq 0))
{
$smtpServer = "SMTP"
$MailFrom = "fromemail@company.com"
$mailto = "toemail@company.com"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = $MailFrom
$msg.IsBodyHTML = $true
$msg.To.Add($Mailto)
$msg.Subject = "iBills Status Check - Fail"
$MailTextT = Get-Content -Path C:\\temp\\FailReport.html
$msg.Body = $MailTextT
$smtp.Send($msg)
}
Else
{
$smtpServer = "SMTP"
$MailFrom = "fromemail@company.com"
$mailto = "toemail@company.com"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = $MailFrom
$msg.IsBodyHTML = $true
$msg.To.Add($Mailto)
$msg.Subject = "iBills Status Check - Success"
$MailTextT = Get-Content -Path C:\\temp\\Report.html
$msg.Body = $MailTextT
$smtp.Send($msg)
}
|
PowerShellCorpus/PoshCode/Get-Credential 2.3.ps1
|
Get-Credential 2.3.ps1
|
## Get-Credential
## An improvement over the default cmdlet which has no options ...
###################################################################################################
## History
## v 2.3 Add -Store switch and support putting credentials into the file system
## v 2.1 Fix the comment help and parameter names to agree with each other (whoops)
## v 2.0 Rewrite for v2 to replace the default Get-Credential
## v 1.2 Refactor ShellIds key out to a variable, and wrap lines a bit
## v 1.1 Add -Console switch and set registry values accordingly (ouch)
## v 1.0 Add Title, Message, Domain, and UserName options to the Get-Credential cmdlet
###################################################################################################
function Get-Credential {
## .Synopsis
## Gets a credential object based on a user name and password.
## .Description
## The Get-Credential function creates a credential object for a specified username and password, with an optional domain. You can use the credential object in security operations.
##
## The function accepts more parameters to customize the security prompt than the default Get-Credential cmdlet (including forcing the call through the console if you're in the native PowerShell.exe CMD console), but otherwise functions identically.
[CmdletBinding(DefaultParameterSetName="Prompted")]
PARAM(
# A default user name for the credential prompt, or a pre-existing credential (would skip all prompting)
[Parameter(ParameterSetName="Prompted",Position=1,Mandatory=$false)]
[Parameter(ParameterSetName="Promptless",Position=1,Mandatory=$true)]
[Parameter(ParameterSetName="StoreCreds",Position=1,Mandatory=$true)]
[Parameter(ParameterSetName="Flush",Position=1,Mandatory=$true)]
[Alias("Credential")]
[PSObject]$UserName=$null
,
# Allows you to override the default window title of the credential dialog/prompt
#
# You should use this to allow users to differentiate one credential prompt from another. In particular, if you're prompting for, say, Twitter credentials, you should put "Twitter" in the title somewhere. If you're prompting for domain credentials. Being specific not only helps users differentiate and know what credentials to provide, but also allows tools like KeePass to automatically determine it.
[Parameter(ParameterSetName="Prompted",Position=2,Mandatory=$false)]
[string]$Title=$null
,
# Allows you to override the text displayed inside the credential dialog/prompt.
#
# You can use this for things like presenting an explanation of what you need the credentials for.
[Parameter(ParameterSetName="Prompted",Position=3,Mandatory=$false)]
[string]$Message=$null
,
# Specifies the default domain to use if the user doesn't provide one (by default, this is null)
[Parameter(ParameterSetName="Prompted",Position=4,Mandatory=$false)]
[string]$Domain=$null
,
# The Get-Credential cmdlet forces you to always return DOMAIN credentials (so even if the user provides just a plain user name, it prepends "\\" to the user name). This switch allows you to override that behavior and allow generic credentials without any domain name or the leading "\\".
[Parameter(ParameterSetName="Prompted",Mandatory=$false)]
[switch]$GenericCredentials
,
# Forces the credential prompt to occur inline in the console/host using Read-Host -AsSecureString (not implemented properly in PowerShell ISE)
[Parameter(ParameterSetName="Prompted",Mandatory=$false)]
[switch]$Inline
,
# Store the credential in the file system (and overwrite them)
[Parameter(ParameterSetName="Prompted",Mandatory=$false)]
[Parameter(ParameterSetName="Promptless",Mandatory=$false)]
[Parameter(ParameterSetName="StoreCreds",Mandatory=$true)]
[switch]$Store
,
# Remove stored credentials from the file system
[Parameter(ParameterSetName="Flush",Mandatory=$true)]
[switch]$Flush
,
# Allows you to override the path to store credentials in
[Parameter(ParameterSetName="Prompted",Mandatory=$false)]
[Parameter(ParameterSetName="Promptless",Mandatory=$false)]
[Parameter(ParameterSetName="StoreCreds",Mandatory=$false)]
$CredentialFolder = $(Join-Path ${Env:APPDATA} Credentials)
,
# The password
[Parameter(ParameterSetName="Promptless",Position=5,Mandatory=$true)]
$Password = $(
if($UserName -and (Test-Path "$(Join-Path $CredentialFolder $UserName).cred")) {
if($Flush) {
Remove-Item "$(Join-Path $CredentialFolder $UserName).cred"
} else {
Get-Content "$(Join-Path $CredentialFolder $UserName).cred" | ConvertTo-SecureString
}
})
)
process {
[PSCredential]$Credential = $null
if( $UserName -is [System.Management.Automation.PSCredential]) {
$Credential = $UserName
} elseif($UserName -ne $null) {
$UserName = $UserName.ToString()
}
if($Password) {
if($Password -isnot [System.Security.SecureString]) {
[char[]]$Chars = $Password.ToString().ToCharArray()
$Password = New-Object System.Security.SecureString
foreach($c in $chars) { $Password.AppendChar($c) }
}
$Credential = New-Object System.Management.Automation.PSCredential $UserName, $Password
}
if(!$Credential) {
if($Inline) {
if($Title) { Write-Host $Title }
if($Message) { Write-Host $Message }
if($Domain) {
if($UserName -and $UserName -notmatch "[@\\\\]") {
$UserName = "${Domain}\\${UserName}"
}
}
if(!$UserName) {
$UserName = Read-Host "User"
if(($Domain -OR !$GenericCredentials) -and $UserName -notmatch "[@\\\\]") {
$UserName = "${Domain}\\${UserName}"
}
}
$Credential = New-Object System.Management.Automation.PSCredential $UserName,$(Read-Host "Password for user $UserName" -AsSecureString)
}
if($GenericCredentials) { $Type = "Generic" } else { $Type = "Domain" }
## Now call the Host.UI method ... if they don't have one, we'll die, yay.
## BugBug? PowerShell.exe disregards the last parameter
$Credential = $Host.UI.PromptForCredential($Title, $Message, $UserName, $Domain, $Type, "Default")
}
if($Store) {
$CredentialFile = "$(Join-Path $CredentialFolder $UserName).cred"
if(!(Test-Path $CredentialFolder)) {
mkdir $CredentialFolder | out-null
}
$Credential.Password | ConvertFrom-SecureString | Set-Content $CredentialFile
}
return $Credential
}
}
|
PowerShellCorpus/PoshCode/Set-Computername_15.ps1
|
Set-Computername_15.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/FS_FindFiles.ps1
|
FS_FindFiles.ps1
|
Param (
[string[]]$Computers=$env:ComputerName,
[string[]] $Paths = @("C:\\Windows","C:\\Windows\\system32"),
[string[]] $FileNames = @("fsb.tmp","fsb.stb","notpad.exe")
)
$Global:objOut = @()
Function FindFiles ($Computer, $Filter){
try{
$Files = Gwmi -namespace "root\\CIMV2" -computername $Computer -class CIM_DataFile -filter "Name = '$Filter'"
if ($Files){
foreach ($File in $Files){
$Result = New-Object PSObject -Property @{
Host = $Computer
Path = $File.Name
FileSize = "$([math]::round($File.FileSize/1KB)) KB"
Modified = [System.Management.ManagementDateTimeconverter]::ToDateTime($File.LastModified).ToShortDateString()
InUse = ([System.Convert]::ToBoolean($File.InUseCount))
LastUsed = [System.Management.ManagementDateTimeconverter]::ToDateTime($File.LastAccessed).ToShortDateString()
}
$Global:objOut += $Result
}
}
}
catch{
$continue = $False
Write-Host $($error[0] | fl *)
}
}
foreach ($Computer in $Computers){
if (Test-Connection -ComputerName $Computer -Count 1 -Quiet){
foreach ($Path in $Paths){
foreach ($FileName in $FileNames){
# WMI needs double quotes in a path
$Filter = "$Path\\$FileName" -replace '\\\\','\\\\'
FindFiles $Computer $Filter
}
}
}
else {
Write-Host "$Computer cannot be reached"
}
}
$Global:objOut
|
PowerShellCorpus/PoshCode/f81bf3c1-15b5-492d-b806-22073181af89.ps1
|
f81bf3c1-15b5-492d-b806-22073181af89.ps1
|
# Name: zip.ps1
# Author: Shadow
# Created: 05/12/2008
param([string]$zipfilename=$(throw "ZIP archive name needed!"),
[string[]]$filetozip=$(throw "Supply the file(s) to compress (wildcards accepted)"))
trap [Exception] {break;}
#empyt zip file contents
$emptyzipfile=80,75,5,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0;
#create a new file with $ZIPFILENAME and copy the above array into it
$fmode = [System.IO.FileMode]::Create;
$zipfile = new-object -type System.IO.FileStream $zipfilename, $fmode;
$zipfile.Write($emptyzipfile,0,22);
$zipfile.Flush();
$zipfile.Close();
#open the new zip file as folder from Windows Shell Application
$shell=new-object -comobject Shell.Application;
$foldername=(ls $zipfile.Name).FullName;
$zipfolder=$shell.Namespace($foldername);
#Iterate files to zip, copying them to zip folder.
#In the process, the shell compress them
Write-Host "Compressing:";
$filetozip| %{ls $_}|
foreach{
("`t"+$_.fullname);
$zipfolder.copyhere($_.fullname,20);
[System.Threading.Thread]::Sleep(250);
}
$shell=$null;
$zipfolder=$null;
|
PowerShellCorpus/PoshCode/New-XSD.ps1
|
New-XSD.ps1
|
# ---------------------------------------------------------------------------
### <Script>
### <Author>
### Chad Miller
### </Author>
### <Description>
### Generates an XSD File with SQLXML annotations for a Powershell object
### The XSD file can be used with SQLXML to automatically create a SQL table
### and import the XML
### </Description>
### <Usage>
### New-Xsd -Object $SqlServerRole -ItemTag ServerRole -Attribute Server,Name,timestamp -ChildItems members
### </Usage>
### </Script>
# ---------------------------------------------------------------------------
param($Object,$ItemTag="ITEM", $ChildItems="*", $Attributes=$Null)
$header = @"
<?xml version="1.0" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
<xs:element name="ROOT" sql:is-constant="1">
<xs:complexType>
<xs:sequence>
"@
$footer = @"
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
"@
#######################
function Get-SqlType
{
param($definition)
$type = ([regex]'System\\.([^ ]*) ').matches($definition) | %{$_.Groups[1].Value}
switch ($type)
{
"Int64" {"bigint"}
"Byte[]" {"varbinary"}
"Boolean" {"bit"}
"Decimal" {"decimal"}
"DateTime" {"datetime"}
"Double" {"float"}
"Guid" {"uniqueidentifier"}
"Int32" {"int"}
"Single" {"real"}
"Int16" {"smallint"}
"Byte" {"tinyint"}
default {"varchar(255)"}
}
}# Get-SqlType
#######################
$xsd = $header
$xsd += "`n <xs:element name=`"$ItemTag`" sql:relation=`"$ItemTag`">`n"
$xsd += " <xs:complexType>`n"
$xsd += " <xs:sequence>`n"
$seen = @()
foreach ($prop in $Object | Get-Member -Type *Property $childItems)
{
$Name = $prop.Name
if (!($seen -contains $Name))
{
$seen += $Name
$xsd += " <xs:element name=`"$Name`" sql:field=`"$Name`" sql:datatype=`"$(Get-SqlType $prop.Definition)`" />`n"
}
}
$xsd += " </xs:sequence>`n"
if ($Attributes)
{
foreach ($attr in $Object | Get-Member -type *Property $attributes)
{
$Name = $attr.Name
if (!($seen -contains $Name))
{
$seen += $Name
$xsd += " <xs:attribute name=`"$Name`" sql:field=`"$Name`" sql:datatype=`"$(Get-SqlType $attr.Definition)`" />`n"
}
}
}
$xsd += " </xs:complexType>`n"
$xsd += " </xs:element>`n"
$xsd += $footer
$xsd
|
PowerShellCorpus/PoshCode/Get-Lotterynumbers.ps1
|
Get-Lotterynumbers.ps1
|
###########################################################################
#
# NAME: Get-Lotterynumbers.ps1
#
# AUTHOR: Jan Egil Ring
# EMAIL: jer@powershell.no
#
# COMMENT: Generates lottery numbers based on user input.
#
# 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 24.01.2010 - Initial release
#
###########################################################################
$maximumnumber = Read-Host "How many numbers are available in the lottery?"
$numbercount = Read-Host "How many numbers are drawn?"
$numbers = @()
do {
$number = Get-Random -Minimum 1 -Maximum $maximumnumber
if ($numbers -notcontains $number)
{
$numbers += $number
}
}
until ($numbers.count -eq $numbercount)
$numbers | Sort-Object
|
PowerShellCorpus/PoshCode/New-ElevatedTask 2.7.ps1
|
New-ElevatedTask 2.7.ps1
|
#requires -version 2.0
###############################################################################
## New-ElevatedTask is a script (for Vista) which creates "elevated" scheduled
## tasks by exploiting the import-from XML feature of schtasks.exe /Create /XML
##
## Creates a new "On Demand Only" scheduled task to run an "Elevated" application
## on Vista, so it MUST be run from an elevated prompt ... and then creates a
## shortcut to run that scheduled task on demand via schtasks.exe /run /tn
##
## NOTE: Depends on my New-Shortcut script which is also available on the script
## repository at http://powershellcentral.com/scripts/?q=New-Shortcut
##
## Version History
## 2.0 - First version with shortcut support
## - Still weak on documentation of the arguments, sorry ...
## 2.5 - Improved defaults and documentation (run with -?)
## 2.6 - CTP 3 version, with AutoHelp and CmdletBinding
## 2.7 - Windows 7 version (PowerShell 2) to support different XML ...
#function New-ElevatedTask {
<#
.SYNOPSIS
Creates a new "On Demand Only" scheduled task to run an "Elevated" application, and a shortcut to launch it.
.DESCRIPTION
New-ElevatedTask creates a scheduled task on Vista or Windows7 which runs "On Demand" with full priviledges (Elevated) and then creates a shortcut to launch it on demand.
It works by exploiting the import from XML feature of schtasks.exe /Create /XML ... and the ability to run tasks on demand via schtasks.exe /run /tn ...
You may specify the shortcut path as a folder path (which must exist), with a name for the new file (ending in .lnk), or you may specify one of the "SpecialFolder" names like "QuickLaunch" or "CommonDesktop" followed by the name. The shortcut feature depends on the New-Shortcut function (a separate script).
NOTE: You MUST run this in an elevated PowerShell instance.
.Example
New-ElevatedTask C:\\Windows\\Notepad.exe
Will create a task to run notepad elevated, and creates a shortcut to run it the current folder, named "Notepad.lnk"
.Example
New-ElevatedTask C:\\Windows\\Notepad.exe -Shortcut QuickLaunch\\Editor.lnk -FriendlyName "Run Notepad" -TaskName "Elevated Text Editor"
Will create a task to run notepad elevated, and names it "Elevated Text Editor". Also creates a shortcut on the QuickLaunch bar with the name "Run Notepad.lnk" and the tooltip "Elevated Text Editor"
.NOTE
Must be run from an elevated PowerShell instance
Some features depend on New-Shortcut (which is also available on the repository: http://PoshCode.org/search/New-Shortcut)
#>
[CmdletBinding()]
param(
$TargetPath = ""
, $Arguments = ""
, $WorkingDirectory = $(Split-Path -parent (Resolve-Path $TargetPath))
, $FriendlyName = $(Split-Path $TargetPath -leaf)
, $TaskName = $( "Elevated $friendlyName" )
, $IconLocation = $null
, $ShortcutPath = $null
, $Hotkey = $Null
, $UserName = $null
, $password = $null
,
[System.Management.Automation.PSCredential]
$credential = $null
)
$SchTasks = Join-Path ([Environment]::GetFolderPath("System")) "schtasks.exe"
if(-not (Test-Path $SchTasks) ) {
$SchTasks = Read-Host "You need to set the correct location for the SchTasks.exe application on your system"
}
if(!(Test-Path $TargetPath)) {
Write-Error "TargetPath must be an existing file for the scheduled task to point at!"
return
}
if([Environment]::OSVersion.Version.Major -lt 6) {
Write-Warning "OS not supported $([Environment]::OSVersion.VersionString)"
Write-Warning "Only Vista and up support the xml tasks, as far as I know"
return
}
$win7 = [bool][Environment]::OSVersion.Version.Minor
if($win7) {
$xml = @"
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.3" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
"@
} else {
$xml = @"
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
"@
}
$xml += @"
<RegistrationInfo>
<Author>{4}</Author>
<Description>Run {0} "As Administrator"</Description>
</RegistrationInfo>
<Triggers />
<Principals>
<Principal id="Author">
<UserId>{4}</UserId>
<LogonType>{5}</LogonType>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
<Actions Context="Author">
<Exec>
<Command>{1}</Command>
<Arguments>{2}</Arguments>
<WorkingDirectory>{3}</WorkingDirectory>
</Exec>
</Actions>
<Settings>
<MultipleInstancesPolicy>Parallel</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
<AllowHardTerminate>true</AllowHardTerminate>
<StartWhenAvailable>false</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>false</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>P3D</ExecutionTimeLimit>
<Priority>7</Priority>
"@
if($win7) {
$xml += @"
<DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession>
<UseUnifiedSchedulingEngine>false</UseUnifiedSchedulingEngine>
</Settings>
</Task>
"@
} else {
$xml += @"
</Settings>
</Task>
"@
}
$xFile = [IO.Path]::GetTempFileName()
# if they specify a user name, assume they want to do password authentication
if($UserName -ne $null -and $password -ne $null) {
$xml -f $friendlyName, $TargetPath, $arguments, $WorkingDirectory, $UserName, "Password" | set-content $xFile
&$SchTasks /Create /XML $xFile /TN $taskname /RU $UserName /RP $password
# if they didn't include a password, prompt them for one ...
} elseif($UserName -ne $null -and $password -eq $null) {
$xml -f $friendlyName, $TargetPath, $arguments, $WorkingDirectory, $UserName, "Password" | set-content $xFile
&$SchTasks /Create /XML $xFile /TN $taskname /RU $UserName /RP
# if they supplied credentials instead, use that
} elseif($credential -ne $null) {
$xml -f $friendlyName, $TargetPath, $arguments, $WorkingDirectory, $($Credential.UserName), "Password" | set-content $xFile
&$SchTasks /Create /XML $xFile /TN $taskname /RU $credential.UserName /RP $($Credential.GetNetworkCredential().Password)
} else {
# if they suppplied neither user nor credentials, lets assume they want the "current" user
$UserName = ([Security.Principal.WindowsIdentity]::GetCurrent().Name)
# if they passed a password, use that
if($password -ne $null) {
$xml -f $friendlyName, $TargetPath, $arguments, $WorkingDirectory, $UserName, "Password" | set-content $xFile
&$SchTasks /Create /XML $xFile /TN $taskname /RU $UserName /RP $password
# otherwise, there are no special credentials needed, "Interactive" means only "this" user can run it.
} else {
$xml -f $friendlyName, $TargetPath, $arguments, $WorkingDirectory, $UserName, "InteractiveToken" | set-content $xFile
&$SchTasks /Create /XML $xFile /TN $taskname
}
}
if(!$IconLocation) {
$IconLocation = $TargetPath
}
if($ShortcutPath -and (Get-Command New-Shortcut -ErrorAction SilentlyContinue)) {
if(([IO.FileInfo]$ShortcutPath).Extension.Length -eq 0 ) {
$ShortcutPath = "$ShortcutPath\\$FriendlyName.lnk"
$Description = $TaskName
} else {
$Description = $FriendlyName
}
## New-ShortCut $TargetPath $LinkPath $Arguments $WorkingDirectory $WindowStyle $IconLocation $Hotkey $Description
if(Get-Command New-Shortcut -ErrorAction SilentlyContinue) {
New-Shortcut -Target $SchTasks -LinkPath $ShortcutPath -Arg "/Run /TN `"$TaskName`"" -WorkingDirectory $WorkingDirectory -Window "Minimized" -Icon $IconLocation -Hotkey $Hotkey -Description $Description
}
}
#}
|
PowerShellCorpus/PoshCode/Set-VMBuildCSV.ps1
|
Set-VMBuildCSV.ps1
|
#######################################################################
#
# Purpose: Generate CSV file for VM builds without those darn Typos
# Author: David Chung
# Docs: N/A
#
# v.1 - 02/10/2011 Beta Initial Script
#
# Instruction: Launch the script from PowerCLI.
# Login to vSPhere server from the GUI. As you select cluster and Host
# servers, dropdown boxes will populate. when you have data
# you need, type in full file and path name and click Insert CSV
# Each time you click Insert CSV button, it will append to
# the file
# Note: CPU, RAM, Disk1, Disk2, Folder, Resource Pool, and Network connections
# can be left blank if you choose to. Build will choose default settings
# from the template.
########################################################################
#Generated Form Function
function GenerateForm {
########################################################################
# Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.10.0
# Generated On: 2/10/2012 12:36 AM
# Generated By: chung
########################################################################
#region Import the Assemblies
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
#endregion
#region Generated Form Objects
$FormCSVDeploy = New-Object System.Windows.Forms.Form
$GroupVMPower = New-Object System.Windows.Forms.GroupBox
$RadioPowerOFF = New-Object System.Windows.Forms.RadioButton
$RadioPowerON = New-Object System.Windows.Forms.RadioButton
$GroupVM = New-Object System.Windows.Forms.GroupBox
$LabelVMName = New-Object System.Windows.Forms.Label
$TextVMName = New-Object System.Windows.Forms.TextBox
$Statusbar1 = New-Object System.Windows.Forms.StatusBar
$GroupCSVDeploy = New-Object System.Windows.Forms.GroupBox
$ButtonReset = New-Object System.Windows.Forms.Button
$ButtonOpenCSV = New-Object System.Windows.Forms.Button
$ButtonClose = New-Object System.Windows.Forms.Button
$ButtonInsertCSV = New-Object System.Windows.Forms.Button
$GroupFile = New-Object System.Windows.Forms.GroupBox
$LabelCSV = New-Object System.Windows.Forms.Label
$TextCSV = New-Object System.Windows.Forms.TextBox
$GroupHWCustom = New-Object System.Windows.Forms.GroupBox
$CheckBoxHWConfig = New-Object System.Windows.Forms.CheckBox
$LabeCustomDescription = New-Object System.Windows.Forms.Label
$LabelDisk2 = New-Object System.Windows.Forms.Label
$LabelDisk1 = New-Object System.Windows.Forms.Label
$TextDisk2 = New-Object System.Windows.Forms.TextBox
$TextDisk1 = New-Object System.Windows.Forms.TextBox
$LabelRAM = New-Object System.Windows.Forms.Label
$ComboRAM = New-Object System.Windows.Forms.ComboBox
$LabelCPU = New-Object System.Windows.Forms.Label
$ComboCPU = New-Object System.Windows.Forms.ComboBox
$GroupNetwork = New-Object System.Windows.Forms.GroupBox
$ComboNetwork = New-Object System.Windows.Forms.ComboBox
$LabelNetwork = New-Object System.Windows.Forms.Label
$GroupTemplate = New-Object System.Windows.Forms.GroupBox
$LabelCustomSpec = New-Object System.Windows.Forms.Label
$label4 = New-Object System.Windows.Forms.Label
$ComboTemplate = New-Object System.Windows.Forms.ComboBox
$ComboCustomSpec = New-Object System.Windows.Forms.ComboBox
$GroupLocation = New-Object System.Windows.Forms.GroupBox
$LabelResourcePool = New-Object System.Windows.Forms.Label
$LabelFolder = New-Object System.Windows.Forms.Label
$ComboFolder = New-Object System.Windows.Forms.ComboBox
$ComboResourcePool = New-Object System.Windows.Forms.ComboBox
$LabelDatastore = New-Object System.Windows.Forms.Label
$LabelESX = New-Object System.Windows.Forms.Label
$LabelCluster = New-Object System.Windows.Forms.Label
$ComboDatastore = New-Object System.Windows.Forms.ComboBox
$ComboHost = New-Object System.Windows.Forms.ComboBox
$ComboCluster = New-Object System.Windows.Forms.ComboBox
$GroupLogin = New-Object System.Windows.Forms.GroupBox
$LabelPassword = New-Object System.Windows.Forms.Label
$LabelUserName = New-Object System.Windows.Forms.Label
$LabelVIServer = New-Object System.Windows.Forms.Label
$ButtonLogin = New-Object System.Windows.Forms.Button
$CheckBoxCurrentUser = New-Object System.Windows.Forms.CheckBox
$TextPassword = New-Object System.Windows.Forms.TextBox
$TextUserName = New-Object System.Windows.Forms.TextBox
$TextVIServer = New-Object System.Windows.Forms.TextBox
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects
#----------------------------------------------
#Generated Event Script Blocks
#----------------------------------------------
#Provide Custom Code for events specified in PrimalForms.
$ButtonInsertCSV_OnClick=
{
$VMName = $TextVMName.text.ToUpper() -replace " ", ""
$DatastoreName = $ComboDatastore.SelectedItem -split " -"
$Disk1 = [int]$TextDisk1.Text * 1048576
$Disk2 = [int]$TextDisk1.Text * 1048576
$RAM = [int]$ComboRAM.SelectedItem * 1024
If ($Disk1 -eq "0") {
[string]$Disk1 = $null
}
If ($Disk2 -eq "0") {
[string]$Disk2 = $null
}
If ($RAM -eq "0") {
[string]$RAM = $null
}
If ($RadioPowerOFF.Checked){
$Power = "OFF"
}
Else {
$Power = "ON"
}
$CSVBUILD = "" | Select VM_Name, VC, Host, Datastore, ResourcePool, Folder, Template, CustSpec, Network, CPU, RAM, DISK1, DISK2, Power
$CSVBUILD.VM_name = $VMName
$CSVBUILD.VC = $V
$CSVBUILD.Host = $ComboHost.SelectedItem
$CSVBUILD.Datastore = $DatastoreName[0]
$CSVBUILD.ResourcePool = $ComboResourcePool.SelectedItem
$CSVBUILD.Folder = $ComboFolder.SelectedItem
$CSVBUILD.Template = $ComboTemplate.SelectedItem
$CSVBUILD.CustSpec = $ComboCustomSpec.SelectedItem
$CSVBUILD.Network = $ComboNetwork.SelectedItem
$CSVBUILD.CPU = $ComboCPU.SelectedItem
$CSVBUILD.RAM = $RAM
$CSVBUILD.Disk1 = $Disk1
$CSVBUILD.Disk2 = $Disk2
$CSVBUILD.Power = $Power
$CSVBUILD | Export-Csv $TextCSV.text -append -NoTypeInformation
$statusbar1.Text = "Inserted $VMname in to " + $textcsv.text
# [void] $Voice.Speak( "Inserted $VMname in to CSV" )
}
$ButtonClose_OnClick=
{
$FormCSVDeploy.Close()
}
$ButtonLogin_OnClick=
{
$ButtonLogin.Enabled = $false
If ($CheckBoxCurrentUser.Checked) {
$V = $TextVIServer.text
$statusbar1.Text = "Connecting..."
$connection = Connect-VIServer $V
}
Else {
If ($TextVIServer.text -like "" -or $TextPassword.text -like "" -or $TextUserName.text -like "") {
$statusBar1.Text = "Field can not be empty. Try Again"
[Windows.Forms.Application]::DoEvents()
}
Else {
$statusbar1.Text = "Connecting..."
[Windows.Forms.Application]::DoEvents()
$connection = Connect-VIServer $TextVIServer.text -User $TextUserName.text -Password $TextPassword.text -WarningAction:SilentlyContinue -ErrorAction:SilentlyContinue
}
}
if ($connection.Port -notlike "*443*") {
$statusbar1.Text = "Login failed. Check vCenter and credentials. "
$ButtonLogin.Enabled = $true
[Windows.Forms.Application]::DoEvents()
}
Else {
$statusbar1.Text = "Getting Templates..."
[Windows.Forms.Application]::DoEvents()
$Templates = Get-Template | sort name
Foreach ($Template in $Templates){
$ComboTemplate.items.add($Template.Name)
[Windows.Forms.Application]::DoEvents()
}
$statusbar1.Text = "Getting Customization Spec..."
[Windows.Forms.Application]::DoEvents()
$CustomSpecs = Get-OSCustomizationSpec | sort Name
Foreach ($CustomSpec in $CustomSpecs) {
$ComboCustomSpec.items.add($CustomSpec.name)
[Windows.Forms.Application]::DoEvents()
}
$statusbar1.Text = "Getting Folders..."
$Folders = Get-Folder | sort name
Foreach ($folder in $folders) {
$ComboFolder.items.add($folder.Name)
}
$statusbar1.Text = "Getting Clusters..."
$clusters = Get-Cluster | sort name
Foreach ($cluster in $clusters) {
$ComboCluster.items.add($cluster.Name)
}
$statusbar1.Text = "Select Cluster"
[Windows.Forms.Application]::DoEvents()
$ComboHost.Enabled = $true
$Grouplogin.Enabled = $false
}
}
$ButtonReset_OnClick=
{
$TextVIServer.Text = $null
$CheckBoxCurrentUser.Checked = $false
$CheckBoxHWConfig.Checked = $false
$TextPassword.text = $null
$ComboHost.Items.Clear()
$ComboDatastore.Items.Clear()
$ComboTemplate.Items.Clear()
$ComboFolder.Items.clear()
$ComboResourcePool.Items.clear()
$ComboCustomSpec.items.clear()
$ComboCluster.items.clear()
$ComboNetwork.items.clear()
$TextVMName.Text = $null
$TextCSV.Text = $null
$ButtonLogin.Enabled = $true
If ($connection.IsConnected -eq $true){
Disconnect-VIServer * -ErrorAction:SilentlyContinue -Confirm:$false
}
}
$ButtonOpenCSV_OnClick=
{
If ($TextCSV.text -ne $null) {
notepad $TextCSV.text
}
}
$CheckBoxCurrentUser_CheckedChanged =
{
if ($CheckBoxCurrentUser.Checked) {
$TextUserName.Enabled = $false
$TextPassword.Enabled = $false
$user = acl | select owner -ErrorAction:SilentlyContinue
$TextUserName.Text = $user.owner
}
Else {
$TextUserName.Enabled = $true
$TextPassword.Enabled = $true
$TextUserName.text = $null
}
}
$CheckBoxHWConfig_CheckedChanged =
{
if ($CheckBoxHWConfig.Checked) {
$ComboCPU.Enabled = $true
$ComboRAM.Enabled = $true
$TextDisk1.Enabled = $true
$TextDisk2.Enabled = $true
}
Else {
$ComboCPU.Enabled = $false
$ComboRAM.Enabled = $false
$TextDisk1.Enabled = $false
$TextDisk2.Enabled = $false
$ComboCPU.selecteditem = $null
$ComboRAM.selecteditem = $null
$TextDisk1.text = $null
$TextDisk2.text = $null
}
}
$ComboCluster_Change =
{
$ComboResourcePool.items.clear()
$ComboHost.items.clear()
$ComboHost.selecteditem = ""
$statusbar1.Text = "Getting hosts in the cluster..."
$Cluster = Get-Cluster $ComboCluster.SelectedItem
$vmhosts = Get-Cluster $cluster | Get-VMHost | Where {$_.Connectionstate -eq "Connected"} | sort name -ErrorAction:SilentlyContinue
If ($vmhosts -ne $null) {
foreach ($vmhost in $vmhosts) {
$ComboHost.items.add($vmhost.Name)
}
$ComboHost.Enabled = $true
$ComboDatastore.Enabled = $true
$ResourcePools = $cluster | Get-ResourcePool | where {$_.name -ne "resources"} | sort name
If ($ResourcePools -ne $null) {
$ComboResourcePool.Items.Add("$null")|Out-Null
Foreach ($ResourcePool in $ResourcePools) {
$ComboResourcePool.items.add($ResourcePool.Name)
$ComboResourcePool.Enabled = $true
}
}
Else {
$ComboResourcePool.Selecteditem = $null
$ComboResourcePool.Enabled = $false
$ComboResourcePool.items.clear()
}
$statusbar1.Text = "Select a host..."
}
Else {
$statusbar1.Text = "There are no connected hosts in the cluster..."
$ComboHost.Enabled = $false
$ComboHost.selecteditem = $null
$ComboHost.items.clear()
$ComboDatastore.Items.clear()
$ComboDatastore.selecteditem = $null
$ComboDatastore.Enabled = $false
$ComboNetwork.Enabled = $false
$ComboNetwork.Items.clear()
$ComboNetwork.selecteditem = $null
$ComboResourcePool.Enabled = $false
$ComboResourcePool.items.clear()
$ComboResourcePool.selecteditem = $null
}
}
$ComboHost_Change =
{
$ComboNetwork.Items.clear()
$ComboDatastore.Items.clear()
$vmhost = Get-VMHost $ComboHost.Selecteditem
$statusbar1.Text = "Getting Port groups..."
$Portgroups = $VMHost | Get-VirtualPortGroup | Sort Name
$ComboNetwork.Items.Add("$null")|Out-Null
Foreach ($Portgroup in $Portgroups) {
$ComboNetwork.items.add($Portgroup.Name)
}
$statusbar1.Text = "Getting Datastores..."
$DataStores = Get-Datastore -VMHost $vmhost | Sort Name
Foreach ($DataStore in $DataStores) {
$ComboDatastore.items.add($DataStore.name + " - (" + ([Math]::Round(($Datastore.freespacemb / 1024), 2)) + "GB)" )
}
$statusbar1.Text = "Select Configurations... to build VM"
$ComboNetwork.Enabled = $true
$ComboDatastore.Enabled = $true
$ComboTemplate.Enabled = $true
}
$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
$FormCSVDeploy.WindowState = $InitialFormWindowState
}
#Initial GUI settings
$ComboCPU.Enabled = $false
$ComboRAM.Enabled = $false
$TextDisk1.Enabled = $false
$TextDisk2.Enabled = $false
#----------------------------------------------
#region Generated Form Code
$FormCSVDeploy.AutoScaleMode = 3
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 655
$System_Drawing_Size.Width = 521
$FormCSVDeploy.ClientSize = $System_Drawing_Size
$FormCSVDeploy.DataBindings.DefaultDataSourceUpdateMode = 0
$FormCSVDeploy.MaximizeBox = $False
$FormCSVDeploy.Name = "FormCSVDeploy"
$FormCSVDeploy.SizeGripStyle = 2
$FormCSVDeploy.StartPosition = 1
$FormCSVDeploy.Text = "CSV VM Deployer - by David Chung"
$GroupVMPower.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 370
$System_Drawing_Point.Y = 450
$GroupVMPower.Location = $System_Drawing_Point
$GroupVMPower.Name = "GroupVMPower"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 61
$System_Drawing_Size.Width = 139
$GroupVMPower.Size = $System_Drawing_Size
$GroupVMPower.TabIndex = 16
$GroupVMPower.TabStop = $False
$GroupVMPower.Text = "Power"
$FormCSVDeploy.Controls.Add($GroupVMPower)
$RadioPowerOFF.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 6
$System_Drawing_Point.Y = 39
$RadioPowerOFF.Location = $System_Drawing_Point
$RadioPowerOFF.Name = "RadioPowerOFF"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 16
$System_Drawing_Size.Width = 104
$RadioPowerOFF.Size = $System_Drawing_Size
$RadioPowerOFF.TabIndex = 1
$RadioPowerOFF.Text = "VM Power OFF"
$RadioPowerOFF.UseVisualStyleBackColor = $True
$GroupVMPower.Controls.Add($RadioPowerOFF)
$RadioPowerOFF.Checked = $True
$RadioPowerON.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 6
$System_Drawing_Point.Y = 20
$RadioPowerON.Location = $System_Drawing_Point
$RadioPowerON.Name = "RadioPowerON"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 17
$System_Drawing_Size.Width = 104
$RadioPowerON.Size = $System_Drawing_Size
$RadioPowerON.TabIndex = 0
$RadioPowerON.TabStop = $True
$RadioPowerON.Text = "VM Power ON"
$RadioPowerON.UseVisualStyleBackColor = $True
$RadioPowerON.add_CheckedChanged($handler_radioButton1_CheckedChanged)
$GroupVMPower.Controls.Add($RadioPowerON)
$GroupVM.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 126
$GroupVM.Location = $System_Drawing_Point
$GroupVM.Name = "GroupVM"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 47
$System_Drawing_Size.Width = 350
$GroupVM.Size = $System_Drawing_Size
$GroupVM.TabIndex = 15
$GroupVM.TabStop = $False
$GroupVM.Text = "VM"
$FormCSVDeploy.Controls.Add($GroupVM)
$LabelVMName.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 228
$System_Drawing_Point.Y = 22
$LabelVMName.Location = $System_Drawing_Point
$LabelVMName.Name = "LabelVMName"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 17
$System_Drawing_Size.Width = 116
$LabelVMName.Size = $System_Drawing_Size
$LabelVMName.TabIndex = 1
$LabelVMName.Text = "VM Name"
$GroupVM.Controls.Add($LabelVMName)
$TextVMName.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 8
$System_Drawing_Point.Y = 19
$TextVMName.Location = $System_Drawing_Point
$TextVMName.Name = "TextVMName"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 214
$TextVMName.Size = $System_Drawing_Size
$TextVMName.TabIndex = 0
$GroupVM.Controls.Add($TextVMName)
$Statusbar1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 0
$System_Drawing_Point.Y = 633
$Statusbar1.Location = $System_Drawing_Point
$Statusbar1.Name = "Statusbar1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 22
$System_Drawing_Size.Width = 521
$Statusbar1.Size = $System_Drawing_Size
$Statusbar1.TabIndex = 14
$Statusbar1.Text = "Status"
$FormCSVDeploy.Controls.Add($Statusbar1)
$GroupCSVDeploy.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 14
$System_Drawing_Point.Y = 574
$GroupCSVDeploy.Location = $System_Drawing_Point
$GroupCSVDeploy.Name = "GroupCSVDeploy"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 49
$System_Drawing_Size.Width = 495
$GroupCSVDeploy.Size = $System_Drawing_Size
$GroupCSVDeploy.TabIndex = 13
$GroupCSVDeploy.TabStop = $False
$GroupCSVDeploy.Text = "BUILD CSV / VM DEPLOY"
$FormCSVDeploy.Controls.Add($GroupCSVDeploy)
$ButtonReset.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 7
$System_Drawing_Point.Y = 19
$ButtonReset.Location = $System_Drawing_Point
$ButtonReset.Name = "ButtonReset"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 75
$ButtonReset.Size = $System_Drawing_Size
$ButtonReset.TabIndex = 3
$ButtonReset.Text = "Reset Form"
$ButtonReset.UseVisualStyleBackColor = $True
$ButtonReset.add_Click($ButtonReset_OnClick)
$GroupCSVDeploy.Controls.Add($ButtonReset)
$ButtonOpenCSV.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 333
$System_Drawing_Point.Y = 19
$ButtonOpenCSV.Location = $System_Drawing_Point
$ButtonOpenCSV.Name = "ButtonOpenCSV"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 75
$ButtonOpenCSV.Size = $System_Drawing_Size
$ButtonOpenCSV.TabIndex = 1
$ButtonOpenCSV.Text = "Open CSV"
$ButtonOpenCSV.UseVisualStyleBackColor = $True
$ButtonOpenCSV.add_Click($ButtonOpenCSV_OnClick)
$GroupCSVDeploy.Controls.Add($ButtonOpenCSV)
$ButtonClose.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 414
$System_Drawing_Point.Y = 19
$ButtonClose.Location = $System_Drawing_Point
$ButtonClose.Name = "ButtonDeployVM"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 75
$ButtonClose.Size = $System_Drawing_Size
$ButtonClose.TabIndex = 0
$ButtonClose.Text = "Close"
$ButtonClose.UseVisualStyleBackColor = $True
$ButtonClose.add_Click($ButtonClose_OnClick)
$GroupCSVDeploy.Controls.Add($ButtonClose)
$ButtonInsertCSV.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 252
$System_Drawing_Point.Y = 19
$ButtonInsertCSV.Location = $System_Drawing_Point
$ButtonInsertCSV.Name = "ButtonInsertCSV"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 75
$ButtonInsertCSV.Size = $System_Drawing_Size
$ButtonInsertCSV.TabIndex = 2
$ButtonInsertCSV.Text = "Insert CSV"
$ButtonInsertCSV.UseVisualStyleBackColor = $True
$ButtonInsertCSV.add_Click($ButtonInsertCSV_OnClick)
$GroupCSVDeploy.Controls.Add($ButtonInsertCSV)
$GroupFile.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 14
$System_Drawing_Point.Y = 517
$GroupFile.Location = $System_Drawing_Point
$GroupFile.Name = "GroupFile"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 50
$System_Drawing_Size.Width = 495
$GroupFile.Size = $System_Drawing_Size
$GroupFile.TabIndex = 12
$GroupFile.TabStop = $False
$GroupFile.Text = "FILENAME / PATH"
$FormCSVDeploy.Controls.Add($GroupFile)
$LabelCSV.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 332
$System_Drawing_Point.Y = 22
$LabelCSV.Location = $System_Drawing_Point
$LabelCSV.Name = "LabelCSV"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 17
$System_Drawing_Size.Width = 156
$LabelCSV.Size = $System_Drawing_Size
$LabelCSV.TabIndex = 4
$LabelCSV.Text = "Full Path and CSV Filename"
$GroupFile.Controls.Add($LabelCSV)
$TextCSV.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 7
$System_Drawing_Point.Y = 19
$TextCSV.Location = $System_Drawing_Point
$TextCSV.Name = "TextCSV"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 319
$TextCSV.Size = $System_Drawing_Size
$TextCSV.TabIndex = 3
$GroupFile.Controls.Add($TextCSV)
$GroupHWCustom.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 369
$System_Drawing_Point.Y = 126
$GroupHWCustom.Location = $System_Drawing_Point
$GroupHWCustom.Name = "GroupHWCustom"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 318
$System_Drawing_Size.Width = 140
$GroupHWCustom.Size = $System_Drawing_Size
$GroupHWCustom.TabIndex = 11
$GroupHWCustom.TabStop = $False
$GroupHWCustom.Text = "HW CUSTOMIZATION"
$FormCSVDeploy.Controls.Add($GroupHWCustom)
$CheckBoxHWConfig.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 7
$System_Drawing_Point.Y = 140
$CheckBoxHWConfig.Location = $System_Drawing_Point
$CheckBoxHWConfig.Name = "CheckBoxHWConfig"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 18
$System_Drawing_Size.Width = 127
$CheckBoxHWConfig.Size = $System_Drawing_Size
$CheckBoxHWConfig.TabIndex = 9
$CheckBoxHWConfig.Text = "Custom HW Config"
$CheckBoxHWConfig.UseVisualStyleBackColor = $True
$CheckBoxHWConfig.add_CheckedChanged($CheckBoxHWConfig_CheckedChanged)
$GroupHWCustom.Controls.Add($CheckBoxHWConfig)
$LabeCustomDescription.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 6
$System_Drawing_Point.Y = 178
$LabeCustomDescription.Location = $System_Drawing_Point
$LabeCustomDescription.Name = "LabeCustomDescription"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 39
$System_Drawing_Size.Width = 127
$LabeCustomDescription.Size = $System_Drawing_Size
$LabeCustomDescription.TabIndex = 8
$LabeCustomDescription.Text = "If Disk field is left blank, it will take default value from the template"
$GroupHWCustom.Controls.Add($LabeCustomDescription)
$LabelDisk2.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 7
$System_Drawing_Point.Y = 104
$LabelDisk2.Location = $System_Drawing_Point
$LabelDisk2.Name = "LabelDisk2"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 17
$System_Drawing_Size.Width = 64
$LabelDisk2.Size = $System_Drawing_Size
$LabelDisk2.TabIndex = 7
$LabelDisk2.Text = "Disk2(GB)"
$LabelDisk2.add_Click($handler_label10_Click)
$GroupHWCustom.Controls.Add($LabelDisk2)
$LabelDisk1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 7
$System_Drawing_Point.Y = 77
$LabelDisk1.Location = $System_Drawing_Point
$LabelDisk1.Name = "LabelDisk1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 17
$System_Drawing_Size.Width = 64
$LabelDisk1.Size = $System_Drawing_Size
$LabelDisk1.TabIndex = 6
$LabelDisk1.Text = "Disk1(GB)"
$GroupHWCustom.Controls.Add($LabelDisk1)
$TextDisk2.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 77
$System_Drawing_Point.Y = 101
$TextDisk2.Location = $System_Drawing_Point
$TextDisk2.Name = "TextDisk2"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 57
$TextDisk2.Size = $System_Drawing_Size
$TextDisk2.TabIndex = 5
$GroupHWCustom.Controls.Add($TextDisk2)
$TextDisk1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 77
$System_Drawing_Point.Y = 74
$TextDisk1.Location = $System_Drawing_Point
$TextDisk1.Name = "TextDisk1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 57
$TextDisk1.Size = $System_Drawing_Size
$TextDisk1.TabIndex = 4
$GroupHWCustom.Controls.Add($TextDisk1)
$LabelRAM.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 7
$System_Drawing_Point.Y = 49
$LabelRAM.Location = $System_Drawing_Point
$LabelRAM.Name = "LabelRAM"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 17
$System_Drawing_Size.Width = 64
$LabelRAM.Size = $System_Drawing_Size
$LabelRAM.TabIndex = 3
$LabelRAM.Text = "RAM(GB)"
$LabelRAM.add_Click($handler_label8_Click)
$GroupHWCustom.Controls.Add($LabelRAM)
$ComboRAM.DataBindings.DefaultDataSourceUpdateMode = 0
$ComboRAM.DropDownStyle = 2
$ComboRAM.FormattingEnabled = $True
$ComboRAM.Items.Add("$null")|Out-Null
$ComboRAM.Items.Add("1")|Out-Null
$ComboRAM.Items.Add("2")|Out-Null
$ComboRAM.Items.Add("3")|Out-Null
$ComboRAM.Items.Add("4")|Out-Null
$ComboRAM.Items.Add("5")|Out-Null
$ComboRAM.Items.Add("6")|Out-Null
$ComboRAM.Items.Add("7")|Out-Null
$ComboRAM.Items.Add("8")|Out-Null
$ComboRAM.Items.Add("9")|Out-Null
$ComboRAM.Items.Add("10")|Out-Null
$ComboRAM.Items.Add("11")|Out-Null
$ComboRAM.Items.Add("12")|Out-Null
$ComboRAM.Items.Add("13")|Out-Null
$ComboRAM.Items.Add("14")|Out-Null
$ComboRAM.Items.Add("15")|Out-Null
$ComboRAM.Items.Add("16")|Out-Null
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 77
$System_Drawing_Point.Y = 46
$ComboRAM.Location = $System_Drawing_Point
$ComboRAM.Name = "ComboRAM"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 21
$System_Drawing_Size.Width = 57
$ComboRAM.Size = $System_Drawing_Size
$ComboRAM.TabIndex = 2
$GroupHWCustom.Controls.Add($ComboRAM)
$LabelCPU.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 7
$System_Drawing_Point.Y = 22
$LabelCPU.Location = $System_Drawing_Point
$LabelCPU.Name = "LabelCPU"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 18
$System_Drawing_Size.Width = 64
$LabelCPU.Size = $System_Drawing_Size
$LabelCPU.TabIndex = 1
$LabelCPU.Text = "CPU"
$GroupHWCustom.Controls.Add($LabelCPU)
$ComboCPU.DataBindings.DefaultDataSourceUpdateMode = 0
$ComboCPU.DropDownStyle = 2
$ComboCPU.FormattingEnabled = $True
$ComboCPU.Items.Add("$null")|Out-Null
$ComboCPU.Items.Add("1")|Out-Null
$ComboCPU.Items.Add("2")|Out-Null
$ComboCPU.Items.Add("4")|Out-Null
$ComboCPU.Items.Add("6")|Out-Null
$ComboCPU.Items.Add("8")|Out-Null
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 77
$System_Drawing_Point.Y = 19
$ComboCPU.Location = $System_Drawing_Point
$ComboCPU.Name = "ComboCPU"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 21
$System_Drawing_Size.Width = 57
$ComboCPU.Size = $System_Drawing_Size
$ComboCPU.TabIndex = 0
$GroupHWCustom.Controls.Add($ComboCPU)
$GroupNetwork.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 14
$System_Drawing_Point.Y = 450
$GroupNetwork.Location = $System_Drawing_Point
$GroupNetwork.Name = "GroupNetwork"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 60
$System_Drawing_Size.Width = 349
$GroupNetwork.Size = $System_Drawing_Size
$GroupNetwork.TabIndex = 10
$GroupNetwork.TabStop = $False
$GroupNetwork.Text = "NETWORK"
$FormCSVDeploy.Controls.Add($GroupNetwork)
$ComboNetwork.DataBindings.DefaultDataSourceUpdateMode = 0
$ComboNetwork.DropDownStyle = 2
$ComboNetwork.FormattingEnabled = $True
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 7
$System_Drawing_Point.Y = 19
$ComboNetwork.Location = $System_Drawing_Point
$ComboNetwork.Name = "ComboNetwork"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 21
$System_Drawing_Size.Width = 214
$ComboNetwork.Size = $System_Drawing_Size
$ComboNetwork.TabIndex = 11
$GroupNetwork.Controls.Add($ComboNetwork)
$LabelNetwork.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 227
$System_Drawing_Point.Y = 22
$LabelNetwork.Location = $System_Drawing_Point
$LabelNetwork.Name = "LabelNetwork"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 18
$System_Drawing_Size.Width = 117
$LabelNetwork.Size = $System_Drawing_Size
$LabelNetwork.TabIndex = 10
$LabelNetwork.Text = "Network Connection"
$GroupNetwork.Controls.Add($LabelNetwork)
$GroupTemplate.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 14
$System_Drawing_Point.Y = 356
$GroupTemplate.Location = $System_Drawing_Point
$GroupTemplate.Name = "GroupTemplate"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 88
$System_Drawing_Size.Width = 349
$GroupTemplate.Size = $System_Drawing_Size
$GroupTemplate.TabIndex = 7
$GroupTemplate.TabStop = $False
$GroupTemplate.Text = "TEMPLATE"
$FormCSVDeploy.Controls.Add($GroupTemplate)
$LabelCustomSpec.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 227
$System_Drawing_Point.Y = 49
$LabelCustomSpec.Location = $System_Drawing_Point
$LabelCustomSpec.Name = "LabelCustomSpec"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 18
$System_Drawing_Size.Width = 116
$LabelCustomSpec.Size = $System_Drawing_Size
$LabelCustomSpec.TabIndex = 8
$LabelCustomSpec.Text = "Customization Spec"
$GroupTemplate.Controls.Add($LabelCustomSpec)
$label4.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 227
$System_Drawing_Point.Y = 22
$label4.Location = $System_Drawing_Point
$label4.Name = "label4"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 18
$System_Drawing_Size.Width = 116
$label4.Size = $System_Drawing_Size
$label4.TabIndex = 7
$label4.Text = "Template"
$GroupTemplate.Controls.Add($label4)
$ComboTemplate.DataBindings.DefaultDataSourceUpdateMode = 0
$ComboTemplate.DropDownStyle = 2
$ComboTemplate.FormattingEnabled = $True
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 7
$System_Drawing_Point.Y = 19
$ComboTemplate.Location = $System_Drawing_Point
$ComboTemplate.Name = "ComboTemplate"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 21
$System_Drawing_Size.Width = 214
$ComboTemplate.Size = $System_Drawing_Size
$ComboTemplate.TabIndex = 6
$GroupTemplate.Controls.Add($ComboTemplate)
$ComboCustomSpec.DataBindings.DefaultDataSourceUpdateMode = 0
$ComboCustomSpec.DropDownStyle = 2
$ComboCustomSpec.FormattingEnabled = $True
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 7
$System_Drawing_Point.Y = 46
$ComboCustomSpec.Location = $System_Drawing_Point
$ComboCustomSpec.Name = "ComboCustomSpec"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 21
$System_Drawing_Size.Width = 214
$ComboCustomSpec.Size = $System_Drawing_Size
$ComboCustomSpec.TabIndex = 2
$GroupTemplate.Controls.Add($ComboCustomSpec)
$GroupLocation.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 14
$System_Drawing_Point.Y = 179
$GroupLocation.Location = $System_Drawing_Point
$GroupLocation.Name = "GroupLocation"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 171
$System_Drawing_Size.Width = 349
$GroupLocation.Size = $System_Drawing_Size
$GroupLocation.TabIndex = 1
$GroupLocation.TabStop = $False
$GroupLocation.Text = "LOCATION"
$FormCSVDeploy.Controls.Add($GroupLocation)
$LabelResourcePool.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 227
$System_Drawing_Point.Y = 134
$LabelResourcePool.Location = $System_Drawing_Point
$LabelResourcePool.Name = "LabelResourcePool"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 18
$System_Drawing_Size.Width = 116
$LabelResourcePool.Size = $System_Drawing_Size
$LabelResourcePool.TabIndex = 10
$LabelResourcePool.Text = "Resource Pool"
$GroupLocation.Controls.Add($LabelResourcePool)
$LabelFolder.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 227
$System_Drawing_Point.Y = 107
$LabelFolder.Location = $System_Drawing_Point
$LabelFolder.Name = "LabelFolder"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 14
$System_Drawing_Size.Width = 116
$LabelFolder.Size = $System_Drawing_Size
$LabelFolder.TabIndex = 7
$LabelFolder.Text = "Folder"
$GroupLocation.Controls.Add($LabelFolder)
$ComboFolder.DataBindings.DefaultDataSourceUpdateMode = 0
$ComboFolder.DropDownStyle = 2
$ComboFolder.FormattingEnabled = $True
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 7
$System_Drawing_Point.Y = 104
$ComboFolder.Location = $System_Drawing_Point
$ComboFolder.Name = "ComboFolder"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 21
$System_Drawing_Size.Width = 214
$ComboFolder.Size = $System_Drawing_Size
$ComboFolder.TabIndex = 6
$GroupLocation.Controls.Add($ComboFolder)
$ComboResourcePool.DataBindings.DefaultDataSourceUpdateMode = 0
$ComboResourcePool.DropDownStyle = 2
$ComboResourcePool.FormattingEnabled = $True
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 7
$System_Drawing_Point.Y = 131
$ComboResourcePool.Location = $System_Drawing_Point
$ComboResourcePool.Name = "ComboResourcePool"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 21
$System_Drawing_Size.Width = 214
$ComboResourcePool.Size = $System_Drawing_Size
$ComboResourcePool.TabIndex = 9
$GroupLocation.Controls.Add($ComboResourcePool)
$LabelDatastore.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 227
$System_Drawing_Point.Y = 79
$LabelDatastore.Location = $System_Drawing_Point
$LabelDatastore.Name = "LabelDatastore"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 18
$System_Drawing_Size.Width = 116
$LabelDatastore.Size = $System_Drawing_Size
$LabelDatastore.TabIndex = 5
$LabelDatastore.Text = "Datastore"
$GroupLocation.Controls.Add($LabelDatastore)
$LabelESX.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 227
$System_Drawing_Point.Y = 51
$LabelESX.Location = $System_Drawing_Point
$LabelESX.Name = "LabelESX"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 18
$System_Drawing_Size.Width = 116
$LabelESX.Size = $System_Drawing_Size
$LabelESX.TabIndex = 4
$LabelESX.Text = "ESX Host"
$GroupLocation.Controls.Add($LabelESX)
$LabelCluster.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 227
$System_Drawing_Point.Y = 22
$LabelCluster.Location = $System_Drawing_Point
$LabelCluster.Name = "LabelCluster"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 18
$System_Drawing_Size.Width = 116
$LabelCluster.Size = $System_Drawing_Size
$LabelCluster.TabIndex = 3
$LabelCluster.Text = "Cluster"
$LabelCluster.add_Click($handler_label1_Click)
$GroupLocation.Controls.Add($LabelCluster)
$ComboDatastore.DataBindings.DefaultDataSourceUpdateMode = 0
$ComboDatastore.DropDownStyle = 2
$ComboDatastore.FormattingEnabled = $True
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 7
$System_Drawing_Point.Y = 76
$ComboDatastore.Location = $System_Drawing_Point
$ComboDatastore.Name = "ComboDatastore"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 21
$System_Drawing_Size.Width = 214
$ComboDatastore.Size = $System_Drawing_Size
$ComboDatastore.TabIndex = 2
$GroupLocation.Controls.Add($ComboDatastore)
$ComboHost.DataBindings.DefaultDataSourceUpdateMode = 0
$ComboHost.DropDownStyle = 2
$ComboHost.FormattingEnabled = $True
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 7
$System_Drawing_Point.Y = 48
$ComboHost.Location = $System_Drawing_Point
$ComboHost.Name = "ComboHost"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 21
$System_Drawing_Size.Width = 214
$ComboHost.Size = $System_Drawing_Size
$ComboHost.TabIndex = 1
$GroupLocation.Controls.Add($ComboHost)
$ComboHost.add_SelectedValueChanged($ComboHost_Change)
$ComboCluster.DataBindings.DefaultDataSourceUpdateMode = 0
$ComboCluster.DropDownStyle = 2
$ComboCluster.FormattingEnabled = $True
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 7
$System_Drawing_Point.Y = 19
$ComboCluster.Location = $System_Drawing_Point
$ComboCluster.Name = "ComboCluster"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 21
$System_Drawing_Size.Width = 214
$ComboCluster.Size = $System_Drawing_Size
$ComboCluster.TabIndex = 0
$GroupLocation.Controls.Add($ComboCluster)
$ComboCluster.add_SelectedValueChanged($ComboCluster_Change)
$GroupLogin.DataBindings.DefaultDataSourceUpdateMode = 0
$GroupLogin.ForeColor = [System.Drawing.Color]::FromArgb(255,0,0,0)
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 13
$System_Drawing_Point.Y = 13
$GroupLogin.Location = $System_Drawing_Point
$GroupLogin.Name = "GroupLogin"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 106
$System_Drawing_Size.Width = 496
$GroupLogin.Size = $System_Drawing_Size
$GroupLogin.TabIndex = 0
$GroupLogin.TabStop = $False
$GroupLogin.Text = "LOGIN"
$FormCSVDeploy.Controls.Add($GroupLogin)
$LabelPassword.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 177
$System_Drawing_Point.Y = 76
$LabelPassword.Location = $System_Drawing_Point
$LabelPassword.Name = "LabelPassword"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 17
$System_Drawing_Size.Width = 100
$LabelPassword.Size = $System_Drawing_Size
$LabelPassword.TabIndex = 7
$LabelPassword.Text = "Password"
$GroupLogin.Controls.Add($LabelPassword)
$LabelUserName.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 177
$System_Drawing_Point.Y = 49
$LabelUserName.Location = $System_Drawing_Point
$LabelUserName.Name = "LabelUserName"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 16
$System_Drawing_Size.Width = 100
$LabelUserName.Size = $System_Drawing_Size
$LabelUserName.TabIndex = 6
$LabelUserName.Text = "User Name"
$GroupLogin.Controls.Add($LabelUserName)
$LabelVIServer.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 177
$System_Drawing_Point.Y = 22
$LabelVIServer.Location = $System_Drawing_Point
$LabelVIServer.Name = "LabelVIServer"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 17
$System_Drawing_Size.Width = 119
$LabelVIServer.Size = $System_Drawing_Size
$LabelVIServer.TabIndex = 5
$LabelVIServer.Text = "vSphere Server"
$GroupLogin.Controls.Add($LabelVIServer)
$ButtonLogin.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 415
$System_Drawing_Point.Y = 71
$ButtonLogin.Location = $System_Drawing_Point
$ButtonLogin.Name = "ButtonLogin"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 75
$ButtonLogin.Size = $System_Drawing_Size
$ButtonLogin.TabIndex = 4
$ButtonLogin.Text = "Login"
$ButtonLogin.UseVisualStyleBackColor = $True
$ButtonLogin.add_Click($ButtonLogin_OnClick)
$GroupLogin.Controls.Add($ButtonLogin)
$CheckBoxCurrentUser.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 283
$System_Drawing_Point.Y = 74
$CheckBoxCurrentUser.Location = $System_Drawing_Point
$CheckBoxCurrentUser.Name = "CheckBoxCurrentUser"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 19
$System_Drawing_Size.Width = 126
$CheckBoxCurrentUser.Size = $System_Drawing_Size
$CheckBoxCurrentUser.TabIndex = 3
$CheckBoxCurrentUser.Text = "Use current user"
$CheckBoxCurrentUser.UseVisualStyleBackColor = $True
$GroupLogin.Controls.Add($CheckBoxCurrentUser)
$CheckBoxCurrentUser.add_CheckedChanged($CheckBoxCurrentUser_CheckedChanged)
$TextPassword.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 8
$System_Drawing_Point.Y = 73
$TextPassword.Location = $System_Drawing_Point
$TextPassword.Name = "TextPassword"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 164
$TextPassword.Size = $System_Drawing_Size
$TextPassword.TabIndex = 2
$TextPassword.UseSystemPasswordChar = $True
$GroupLogin.Controls.Add($TextPassword)
$TextUserName.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 8
$System_Drawing_Point.Y = 46
$TextUserName.Location = $System_Drawing_Point
$TextUserName.Name = "TextUserName"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 164
$TextUserName.Size = $System_Drawing_Size
$TextUserName.TabIndex = 1
$GroupLogin.Controls.Add($TextUserName)
$TextVIServer.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 8
$System_Drawing_Point.Y = 20
$TextVIServer.Location = $System_Drawing_Point
$TextVIServer.Name = "TextVIServer"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 165
$TextVIServer.Size = $System_Drawing_Size
$TextVIServer.TabIndex = 0
$GroupLogin.Controls.Add($TextVIServer)
#endregion Generated Form Code
#Save the initial state of the form
$InitialFormWindowState = $FormCSVDeploy.WindowState
#Init the OnLoad event to correct the initial state of the form
$FormCSVDeploy.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$FormCSVDeploy.ShowDialog()| Out-Null
} #End Function
function Export-CSV {
[CmdletBinding(DefaultParameterSetName='Delimiter',
SupportsShouldProcess=$true, ConfirmImpact='Medium')]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[System.Management.Automation.PSObject]
${InputObject},
[Parameter(Mandatory=$true, Position=0)]
[Alias('PSPath')]
[System.String]
${Path},
#region -Append (added by Dmitry Sotnikov)
[Switch]
${Append},
#endregion
[Switch]
${Force},
[Switch]
${NoClobber},
[ValidateSet('Unicode','UTF7','UTF8','ASCII','UTF32',
'BigEndianUnicode','Default','OEM')]
[System.String]
${Encoding},
[Parameter(ParameterSetName='Delimiter', Position=1)]
[ValidateNotNull()]
[System.Char]
${Delimiter},
[Parameter(ParameterSetName='UseCulture')]
[Switch]
${UseCulture},
[Alias('NTI')]
[Switch]
${NoTypeInformation})
begin
{
# This variable will tell us whether we actually need to append
# to existing file
$AppendMode = $false
try {
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Export-Csv',
[System.Management.Automation.CommandTypes]::Cmdlet)
#String variable to become the target command line
$scriptCmdPipeline = ''
# Add new parameter handling
#region Dmitry: Process and remove the Append parameter if it is present
if ($Append) {
$PSBoundParameters.Remove('Append') | Out-Null
if ($Path) {
if (Test-Path $Path) {
# Need to construct new command line
$AppendMode = $true
if ($Encoding.Length -eq 0) {
# ASCII is default encoding for Export-CSV
$Encoding = 'ASCII'
}
# For Append we use ConvertTo-CSV instead of Export
$scriptCmdPipeline += 'ConvertTo-Csv -NoTypeInformation '
# Inherit other CSV convertion parameters
if ( $UseCulture ) {
$scriptCmdPipeline += ' -UseCulture '
}
if ( $Delimiter ) {
$scriptCmdPipeline += " -Delimiter '$Delimiter' "
}
# Skip the first line (the one with the property names)
$scriptCmdPipeline += ' | Foreach-Object {$start=$true}'
$scriptCmdPipeline += '{if ($start) {$start=$false} else {$_}} '
# Add file output
$scriptCmdPipeline += " | Out-File -FilePath '$Path'"
$scriptCmdPipeline += " -Encoding '$Encoding' -Append "
if ($Force) {
$scriptCmdPipeline += ' -Force'
}
if ($NoClobber) {
$scriptCmdPipeline += ' -NoClobber'
}
}
}
}
$scriptCmd = {& $wrappedCmd @PSBoundParameters }
if ( $AppendMode ) {
# redefine command line
$scriptCmd = $ExecutionContext.InvokeCommand.NewScriptBlock(
$scriptCmdPipeline
)
} else {
# execute Export-CSV as we got it because
# either -Append is missing or file does not exist
$scriptCmd = $ExecutionContext.InvokeCommand.NewScriptBlock(
[string]$scriptCmd
)
}
# standard pipeline initialization
$steppablePipeline = $scriptCmd.GetSteppablePipeline(
$myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
}
## Intialize Text-To-Speech
#$Voice = new-object -com SAPI.SpVoice
#Call the Function
GenerateForm
|
PowerShellCorpus/PoshCode/PWD Expiration Email_1.ps1
|
PWD Expiration Email_1.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}} | Where-Object {$_.Expires -gt 0 -AND $_.Expires -le $DaysToExpire } | 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/Bootstrap psake w_ PsGet_1.ps1
|
Bootstrap psake w_ PsGet_1.ps1
|
# Get-MyModule adapted from http://blogs.technet.com/b/heyscriptingguy/archive/2010/07/11/hey-scripting-guy-weekend-scripter-checking-for-module-dependencies-in-windows-powershell.aspx
function Get-MyModule {
param ([string] $name)
write-host "Is '$name' already imported? " -NoNewline -ForegroundColor Cyan
if (-not(Get-Module -name $name)) {
write-host "No." -ForegroundColor Red
write-host "Can we import '$name'? " -NoNewline
if (Get-Module -ListAvailable | Where-Object {$_.Name -eq $name}) {
write-host "Yes. Importing '$name'." -ForegroundColor Green
import-module -name $name
return $true
}
else {
write-host "No. It is not available locally." -ForegroundColor Cyan
return $false
}
}
else {
write-host "Yes." -ForegroundColor Green
return $true
}
}
function ContainsAny( [string]$s, [string[]] $items) {
$matches = @($items | where { $_.Contains( $s ) })
return [bool]$matches
}
# detect if psake is available
if (-not(Get-MyModule -name psake)) {
#detect if PsGet available
if (-not(Get-MyModule -name PsGet)) {
write-host "Downloading and installing PsGet from repository..." -ForegroundColor Yellow
(new-object Net.WebClient).DownloadString("http://psget.net/GetPsGet.ps1") | iex
import-module PsGet
}
write-host "Installing psake..." -ForegroundColor Yellow
install-module psake
}
import-module psake
$output = invoke-psake
if (ContainsAny "Cannot bind argument to parameter 'Path' because it is an empty string." $output) {
write-host "We need to patch psake.psm1... " -ForegroundColor Red -NoNewline
$psakePath = "~\\Documents\\WindowsPowerShell\\Modules\\psake\\psake.psm1"
(get-content $psakePath) | ForEach-Object { return $_.Replace("[Parameter(Position = 0, Mandatory = 0)][string] `$buildFile,", "[Parameter(Position = 0, Mandatory = 0)][string] `$buildFile = `"default.ps1`",")} | Set-Content $psakePath
import-module psake -Force
$output = invoke-psake
if (ContainsAny "Cannot bind argument to parameter 'Path' because it is an empty string." $output) {
write-host "patch was unsuccessful!" -ForegroundColor Red
}
else {
write-host "patch was successfully applied." -ForegroundColor Green
}
}
write-host "Invoke-Psake available as alias 'psake'" -ForegroundColor Cyan
new-alias psake invoke-psake -Scope "Global"
|
PowerShellCorpus/PoshCode/f86998a1-d0da-4204-b566-a9031310d3f9.ps1
|
f86998a1-d0da-4204-b566-a9031310d3f9.ps1
|
################################################################################################################
#
# NAME
# Copy-Data
#
# SYNOPSIS
# Copy Data between Folders including a Progressbar
#
# SYNTAX
# Copy-Data [Source <PathToSource>] [Destination <PathToDestination>] [-Confirm] [-Recurse]
#
#
# DETAILED DESCRIPTION
# The Copy-Data cmdlet copies an item from one location to another in a namespace. Copy-Data does not
# delete the items being copied.
#
# PARAMETERS
# -Confirm <SwitchParameter>
# Prompts you for confirmation before executing the command.
#
# Required? false
# Position? named
# Default value
# Accept pipeline input? false
# Accept wildcard characters? false
#
# -Recurse <SwitchParameter>
# Specifies a recursive copy.
#
# Required? false
# Position? named
# Default value
# Accept pipeline input? false
# Accept wildcard characters? false
#
#
# INPUT TYPE
#
#
# RETURN TYPE
# Shows a progressbar where you can see the progress
#
# NOTES
#
# -------------------------- EXAMPLE 1 --------------------------
#
# C:\\PS>copy-Data C:\\Wabash\\Logfiles\\mar1604.log.txt C:\\Presentation
#
#
#
# -------------------------- EXAMPLE 2 --------------------------
#
# C:\\PS>copy-Data C:\\Wabash\\Logfiles\\*.txt C:\\Presentation
function copy-data {
param(
[string]$file = "",
[string]$dest = "",
[switch]$Recurse,
[switch]$Confirm
)
$copy = cp $file $dest
for ($a=1; $a -lt 100; $a++) {
Write-Progress -Activity “Copying...” -SecondsRemaining $a -Status "% Complete:" -percentComplete $a
}
}
set-Alias cpd copy-data
|
PowerShellCorpus/PoshCode/d31912bc-a156-4199-bcff-5b779e89a274.ps1
|
d31912bc-a156-4199-bcff-5b779e89a274.ps1
|
[void][system.reflection.Assembly]::LoadWithPartialName("MySql.Data")
# Open Connection
$connStr = "server=127.0.0.1;port=3306;uid=root;pwd=perilous;database=test;Pooling=False"
$conn = New-Object MySql.Data.MySqlClient.MySqlConnection($connStr)
$conn.Open()
# write the info
$sql = "INSERT INTO table1 (name) VALUES ('billy')";
$cmd = New-Object MySql.Data.MySqlClient.MySqlCommand($sql, $conn)
$da = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($cmd)
# Populate a dataset and output the query result
$ds = New-Object System.Data.DataSet
# read the info
$sql = "SELECT * FROM table1";
$cmd = New-Object MySql.Data.MySqlClient.MySqlCommand($sql, $conn)
$da = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($cmd)
# Populate a dataset and output the query result
$ds = New-Object System.Data.DataSet
$da.Fill($ds) > $null
$result = $ds.Tables[0]
$result | Format-Table id, name -auto
|
PowerShellCorpus/PoshCode/Monitor-FileSize_2.ps1
|
Monitor-FileSize_2.ps1
|
function Monitor-FileSize
{
<#
.Synopsis
Checks the file size of a given file until it reaches the specified size
.Description
Checks the file size of a given file until it reaches the specified size. AT that point, it alerts the user as to what the original file-size-boundry was and what it currently is. The interval at which the script runs can be specified by the user.
.Parameter FilePath
Path of the file that will be monitored. If not pointed to a specific file, the script will montior all sub-directories as well. ie. if pointed to C:\\ drive, will monitor ALL files on C:\\ drive
.Parameter Size
File size is monitored against this value. When file size is equal or greater than this value, user alert is triggered. Enter size constraints as integer values (ex: -Size 100 NOT -Size 100kb)
.Parameter Interval
The wait interval between the executions of the function. The value of this parameter is in seconds and default value is 5 seconds
.Example
Monitor-FileSize -FilePath C:\\Test -Size 100
Returns a message to the user alerting them when at least 100kb worth of memory is stored in the selected location.
.Example
Monitor-FileSize -FilePath C:\\Test -Size 100 -Interval 20
Checking the size of the file and all sub-directories every 20 seconds
.Notes
This script cannot be run as a background job and so must have a separate PowerShell window on which it can be running.
Author: Paul Kiri.
#>
param
(
[Parameter(mandatory=$true,position=0)]
[string[]]$FilePath
,
[Parameter(mandatory=$true,position=1)]
[int]$Size
,
[Parameter(mandatory=$false)]
[int]$Interval=5
)
if((Test-Path $FilePath))
{
While($FS -le $Size)
{
Start-Sleep -Seconds $Interval
$FileSize = get-childitem $FilePath -Recurse -Include *.* | foreach-object -Process { $_.length / 1024 } | Measure-Object -Sum | Select-Object -Property Sum
$FS = $FileSize.Sum
}
}
if (Test-Path)
{
Write-Output "The files at location, $FilePath , have exceeded $Size kb and are now $('{0:N4}' -f $FileSize.Sum) kb in size."
}
else{"File does not exist!"}
}
|
PowerShellCorpus/PoshCode/HuddledTricks_2.ps1
|
HuddledTricks_2.ps1
|
#Requires -version 2.0
## Stupid PowerShell Tricks
###################################################################################################
add-type @"
using System;
using System.Runtime.InteropServices;
public class Tricks {
[DllImport("user32.dll")]
private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll", SetLastError = true)]
private static extern UInt32 GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
[DllImport("user32.dll")]
static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, SWP uFlags);
[DllImport("dwmapi.dll", PreserveSig = false)]
public static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);
const int GWL_EXSTYLE = -20;
const int WS_EX_LAYERED = 0x80000;
const int WS_EX_TRANSPARENT = 0x20;
const int LWA_ALPHA = 0x2;
const int LWA_COLORKEY = 0x1;
static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
static readonly IntPtr HWND_TOP = new IntPtr(0);
static readonly IntPtr HWND_BOTTOM = new IntPtr(1);
[Flags]
enum SWP : uint {
NOSIZE = 0x0001,
NOMOVE = 0x0002,
NOZORDER = 0x0004,
NOREDRAW = 0x0008,
NOACTIVATE = 0x0010,
FRAMECHANGED = 0x0020, /* The frame changed: send WM_NCCALCSIZE */
SHOWWINDOW = 0x0040,
HIDEWINDOW = 0x0080,
NOCOPYBITS = 0x0100,
NOOWNERZORDER = 0x0200, /* Don't do owner Z ordering */
NOSENDCHANGING = 0x0400, /* Don't send WM_WINDOWPOSCHANGING */
}
[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 ShowWindow(IntPtr hWnd) { ShowWindowAsync(hWnd,5); }
public static void HideWindow(IntPtr hWnd) { ShowWindowAsync(hWnd,0); }
public static void GhostWindow(IntPtr hWnd, int percent) {
SetWindowLong(hWnd, GWL_EXSTYLE, (IntPtr)(GetWindowLong(hWnd, GWL_EXSTYLE) | WS_EX_LAYERED | WS_EX_TRANSPARENT));
// set transparency to X% (of 255)
if(percent > 100) { percent = 100; }
byte alpha = (byte)(255 * (percent/100.0));
SetLayeredWindowAttributes(hWnd, 0, alpha, LWA_ALPHA);
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP.NOSIZE | SWP.NOMOVE);
}
public static void UnGhostWindow(IntPtr hWnd) {
SetWindowLong(hWnd, GWL_EXSTYLE, (IntPtr)(GetWindowLong(hWnd, GWL_EXSTYLE) &~WS_EX_LAYERED &~WS_EX_TRANSPARENT));
SetWindowPos(hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP.NOSIZE | SWP.NOMOVE);
}
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));
}
public static void RestoreToAeroPeek(IntPtr Hwnd) //Hwnd is the handle to your window
{
int renderPolicy = (int)DwmNCRenderingPolicy.Disabled;
DwmSetWindowAttribute(Hwnd, (int)DwmWindowAttribute.ExcludedFromPeek, ref renderPolicy, sizeof(int));
}
}
"@
$dictionary = [System.Collections.Generic.Dictionary``2]
$list = [System.Collections.Generic.List``1]
$string = [String]
$intPtr = [IntPtr]
$intPtrList = $list.AssemblyQualifiedName -replace "1,","1[[$($intPtr.AssemblyQualifiedName)]],"
$windows = new-object ($dictionary.AssemblyQualifiedName -replace "2,","2[[$($string.AssemblyQualifiedName)],[$intPtrList]],")
function Remove-GhostWindow {
<#
.SYNOPSIS
Un-ghost a window
.PARAMETER Handle
The window handle to a specific window we want to hide.
.PARAMETER Name
The name of a running process whos windows you want to hide.
.EXAMPLE
Get-Process PowerShell | Hide-Window; Sleep 5; Show-Window
Hides the PowerShell window(s) for 5 seconds
#>
[CmdletBinding()]
PARAM (
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)]
[Alias("MainWindowHandle","Handle")]
[IntPtr]$WindowHandle=[IntPtr]::Zero
,
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)]
[Alias("ProcessName")]
[String]$Name
)
PROCESS {
(Resolve-Window $WindowHandle $Name) | ForEach-Object { [Tricks]::UnGhostWindow( $_ ) }
}
}
function Set-GhostWindow {
<#
.SYNOPSIS
Make a window partially transparent and click-through
.PARAMETER Handle
The window handle to a specific window we want to hide.
.PARAMETER Name
The name of a running process whos windows you want to hide.
.PARAMETER Percent
The percentage (from 0 to 100) of opacity you want to use (defaults to 80)
.EXAMPLE
Get-Process PowerShell | Hide-Window; Sleep 5; Show-Window
Hides the PowerShell window(s) for 5 seconds
#>
[CmdletBinding()]
PARAM (
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)]
[Alias("MainWindowHandle","Handle")]
[IntPtr]$WindowHandle=[IntPtr]::Zero
,
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)]
[Alias("ProcessName")]
[String]$Name
,
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)]
[ValidateRange(0,100)]
[int]$Percent = 80
)
PROCESS {
(Resolve-Window $WindowHandle $Name) | ForEach-Object { [Tricks]::GhostWindow( $_, $Percent ) }
}
}
function Hide-Window {
<#
.SYNOPSIS
Hide a window
.DESCRIPTION
Hide a window by handle or by process name. Hidden windows are gone: they don't show up in alt+tab, or on the taskbar, and they're invisible. The only way to get them back is with ShowWindow.
Windows hidden by Hide-Window are pushed onto a stack so they can be retrieved by Show-Window. Since they're invisible, they're very hard to find otherwise.
.NOTES
See also Show-Window
.PARAMETER WindowHandle
The window handle to a specific window we want to hide.
.PARAMETER Name
The name of a running process whos windows you want to hide.
.EXAMPLE
Get-Process PowerShell | Hide-Window; Sleep 5; Show-Window
Hides the PowerShell window(s) for 5 seconds
#>
[CmdletBinding()]
PARAM (
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)]
[Alias("MainWindowHandle","Handle")]
[IntPtr]$WindowHandle=[IntPtr]::Zero
,
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)]
[Alias("ProcessName")]
[String]$Name
)
PROCESS {
(Push-Window $WindowHandle $Name) | ForEach-Object { [Tricks]::HideWindow( $_ ) }
}
}
function Show-Window {
<#
.SYNOPSIS
Show a window
.DESCRIPTION
Show a window by handle or by process name. If you call it without any parameters, will show all hidden windows.
.NOTES
See also Hide-Window
.PARAMETER WindowHandle
The window handle to a specific window we want to show.
.PARAMETER Name
The name of a running process whos windows you want to show.
.EXAMPLE
Get-Process PowerShell | Hide-Window; Sleep 5; Show-Window
Hides the PowerShell window(s) for 5 seconds
#>
[CmdletBinding()]
PARAM (
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)]
[Alias("MainWindowHandle","Handle")]
[IntPtr]$WindowHandle=[IntPtr]::Zero
,
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)]
[Alias("ProcessName")]
[String]$Name
)
PROCESS {
(Pop-Window $WindowHandle $Name) | ForEach-Object { [Tricks]::ShowWindow( $_ ) }
}
}
## PRIVATE
FUNCTION Push-Window {
[CmdletBinding()]
PARAM ([IntPtr]$Handle,[String]$ProcessName)
if(!$ProcessName) { $ProcessName = "--Unknown--" }
$Handles = Resolve-Window $Handle $ProcessName
$windows[$ProcessName].AddRange($Handles)
write-output $Handles
}
FUNCTION Resolve-Window {
[CmdletBinding()]
PARAM ([IntPtr]$Handle,[String]$ProcessName)
if(!$ProcessName) { $ProcessName = "--Unknown--" }
[IntPtr[]]$Handles = @($Handle)
if(!$Windows.ContainsKey($ProcessName)) {
$windows.Add($ProcessName, (New-Object $intPtrList))
}
if($Handle -eq [IntPtr]::Zero) {
[IntPtr[]]$Handles = @(Get-Process $ProcessName | % { $_.MainWindowHandle } )
}
return $Handles
}
## PRIVATE
FUNCTION Pop-Window {
[CmdletBinding()]
PARAM ([IntPtr]$Handle,[String]$ProcessName)
[IntPtr[]]$Handles = @($Handle)
if(!$ProcessName) { $ProcessName = "--Unknown--" }
if(($Handle -eq [IntPtr]::Zero) -and $windows[$ProcessName] ) {
write-output $windows[$ProcessName]
$Null = $windows[$ProcessName].Clear()
} elseif($Handle -ne [IntPtr]::Zero){
$Null = $windows[$ProcessName].Remove( $Handle )
}
write-output $Handles
}
Add-Type -Assembly System.Windows.Forms
function Wiggle-Mouse {
<#
.SYNOPSIS
Wiggle the mouse until you Ctrl+Break to stop the script.
.DESCRIPTION
Wiggle-Mouse randomly moves the mouse by a few pixels every few milliseconds until you stop the script.
.PARAMETER Variation
The maximum distance to move the mosue in any direction. Values that are too small aren't noticeable, and values that are too big make the user "loose" the mouse and they have no idea what happened.
.PARAMETER Name
The name of a running process whos windows you want to hide.
.EXAMPLE
Get-Process PowerShell | Hide-Window; Wiggle-Mouse -Duration 5; Get-Process PowerShell | Show-Window
Hides the PowerShell window and wiggle the mouse for five seconds ... :D
#>
[CmdletBinding()]
PARAM (
[Parameter(Position=0)][Int]$Variation=80,
[Parameter(Position=1)][Int]$Sleep=400,
[Parameter(Position=2)][Int]$Duration=0
)
if(!$Duration) { Write-Host "Ctrl+C to stop wiggling :)" }
$screen = [System.Windows.Forms.SystemInformation]::VirtualScreen
$random = new-object Random
$Duration *= -1000
While($Duration -le 0) {
[Windows.Forms.Cursor]::Position ="$(
$random.Next( [Math]::Max( $screen.Left, ([System.Windows.Forms.Cursor]::Position.X - $Variation) ),
[Math]::Min( $screen.Right, ([System.Windows.Forms.Cursor]::Position.X + $Variation) ) )
),$(
$random.Next( [Math]::Max( $screen.Top, ([System.Windows.Forms.Cursor]::Position.Y - $Variation) ),
[Math]::Min( $screen.Bottom, ([System.Windows.Forms.Cursor]::Position.Y + $Variation) ) )
)"
sleep -milli $Sleep
$Duration += $Sleep
}
}
[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)
}
}}
function Remove-AeroPeek {
PARAM(
[string]$Title="*",
[string]$Process="*"
)
PROCESS {
Foreach($window in Select-Window -Process $Process -Title $Title) {
[Tricks]::RemoveFromAeroPeek( $window.Handle )
}
}
}
function Restore-AeroPeek {
PARAM(
[string]$Title="*",
[string]$Process="*"
)
PROCESS {
Foreach($window in Select-Window -Process $Process -Title $Title) {
[Tricks]::RestoreToAeroPeek( $window.Handle )
}
}
}
# Remove-AeroPeek "Miranda IM"
# Remove-AeroPeek -Process Rainlendar2
Export-ModuleMember Select-Window, Show-Window, Hide-Window, Wiggle-Mouse, Set-GhostWindow, Remove-GhostWindow, Remove-AeroPeek
|
PowerShellCorpus/PoshCode/Set-PrimaryDnsSuffix.ps1
|
Set-PrimaryDnsSuffix.ps1
|
function Set-PrimaryDnsSuffix {
param ([string] $Suffix)
# http://msdn.microsoft.com/en-us/library/ms724224(v=vs.85).aspx
$ComputerNamePhysicalDnsDomain = 6
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
namespace ComputerSystem {
public class renamefull {
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
static extern bool SetComputerNameEx(int NameType, string lpBuffer);
public static bool SetPrimaryDnsSuffix(string suffix) {
try {
const int ComputerNamePhysicalDnsDomain = 6;
return SetComputerNameEx(ComputerNamePhysicalDnsDomain, suffix);
}
catch (Exception) {
return false;
}
}
}
}
"@
[ComputerSystem.Identification]::SetPrimaryDnsSuffix($Suffix)
}
|
PowerShellCorpus/PoshCode/Get-SQLFileSize.ps1
|
Get-SQLFileSize.ps1
|
Function Get-SQLFileSize {
<#
.SYNOPSIS
Retrieves the file size of a MDF or LDF file for a SQL Server
.DESCRIPTION
Retrieves the file size of a MDF or LDF file for a SQL Server
.PARAMETER Computer
Computer hosting a SQL Server
.NOTES
Name: Get-SQLFileSize
Author: Boe Prox
DateCreated: 17Feb2011
.EXAMPLE
Get-SQLFileSize -Computer Server1
Description
-----------
This command will return both the MDF and LDF file size for each database on Server1
.EXAMPLE
Get-SQLFileSize -Computer Server1 -LDF
Description
-----------
This command will return LDF file size for each database on Server1
Description
-----------
This command will return both the MDF and LDF file size for each database on Server1
.EXAMPLE
Get-SQLFileSize -Computer Server1 -MDF
Description
-----------
This command will return MDF file size for each database on Server1
#>
[cmdletbinding(
DefaultParameterSetName = 'Default',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = '',
ValueFromPipeline = $True)]
[string[]]$Computer,
[Parameter(
Mandatory = $False,
Position = 1,
ParameterSetName = '',
ValueFromPipeline = $False)]
[switch]$Mdf,
[Parameter(
Mandatory = $False,
Position = 2,
ParameterSetName = '',
ValueFromPipeline = $False)]
[switch]$Ldf
)
Begin {
If (!($PSBoundParameters.ContainsKey('Mdf')) -AND !($PSBoundParameters.ContainsKey('Ldf'))) {
Write-Verbose "MDF or LDF not selected, scanning for both file types"
$FileFlag = $True
$Flag = $False
}
#Create holder for data
Write-Verbose "Creating holder for data"
$report = @()
}
Process {
ForEach ($comp in $Computer) {
#Check for server connection
Write-Verbose "Testing server connection"
If (Test-Connection -count 1 -comp $comp -quiet) {
If ($PSBoundParameters.ContainsKey('Mdf') -OR $FileFlag) {
Write-Verbose "Looking for MDF file sizes"
Try {
Write-Verbose "Attempting to retrieve counters from server"
$DBDataFile = Get-Counter -Counter '\\SQLServer:Databases(*)\\Data File(s) Size (KB)' -MaxSamples 1 -comp $comp -ea stop
$DBDataFile.CounterSamples | % {
If ($_.InstanceName -ne "_total") {
$temp = "" | Select Computer, Database, FileType, Size_MB
$temp.Computer = $comp
$temp.Database = $_.InstanceName
$temp.FileType = 'MDF'
$temp.Size_MB = $_.CookedValue/1000
$report += $temp
}
}
}
Catch {
$Flag = $True
}
If ($Flag) {
Try {
Write-Verbose "Attempting to retrieve counters from server"
$DBDataFile = Get-Counter -Counter '\\MSSQL$MICROSOFT##SSEE:Databases(*)\\Data File(s) Size (KB)' -MaxSamples 1 -comp $comp -ea stop
$DBDataFile.CounterSamples | % {
If ($_.InstanceName -ne "_total") {
$temp = "" | Select Computer, Database, FileType, Size_MB
$temp.Computer = $comp
$temp.Database = $_.InstanceName
$temp.FileType = 'MDF'
$temp.Size_MB = $_.CookedValue/1000
$report += $temp
}
}
}
Catch {
Write-Warning "$($Comp): Unable to locate Database Counters or Database does not exist on this server"
Break
}
}
Else {
Write-Warning "$($Comp): Unable to locate Database Counters or Database does not exist on this server"
Break
}
}
If ($PSBoundParameters.ContainsKey('Ldf') -OR $FileFlag) {
Write-Verbose "Looking for LDF file sizes"
Try {
Write-Verbose "Attempting to retrieve counters from server"
$DBDataFile = Get-Counter -Counter '\\SQLServer:Databases(*)\\Log File(s) Size (KB)' -MaxSamples 1 -comp $comp -ea stop
$DBDataFile.CounterSamples | % {
If ($_.InstanceName -ne "_total") {
$temp = "" | Select Computer, Database, FileType, Size_MB
$temp.Computer = $comp
$temp.Database = $_.InstanceName
$temp.FileType = 'LDF'
$temp.Size_MB = $_.CookedValue/1000
$report += $temp
}
}
}
Catch {
$Flag = $True
}
If ($flag) {
Try {
Write-Verbose "Attempting to retrieve counters from server"
$DBDataFile = Get-Counter -Counter '\\MSSQL$MICROSOFT##SSEE:Databases(*)\\Log File(s) Size (KB)' -MaxSamples 1 -comp $comp -ea stop
$DBDataFile.CounterSamples | % {
If ($_.InstanceName -ne "_total") {
$temp = "" | Select Computer, Database, FileType, Size_MB
$temp.Computer = $comp
$temp.Database = $_.InstanceName
$temp.FileType = 'LDF'
$temp.Size_MB = $_.CookedValue/1000
$report += $temp
}
}
}
Catch {
Write-Warning "$($Comp): Unable to locate Database Counters or Database does not exist on this server"
Break
}
}
Else {
Write-Warning "$($Comp): Unable to locate Transaction Log Counters or Database does not exist on this server"
Break
}
}
}
Else {
Write-Warning "$($Comp) not found!"
}
}
}
End {
Write-Verbose "Displaying output"
$report
}
}
|
PowerShellCorpus/PoshCode/Convert-BounceToX_12.ps1
|
Convert-BounceToX_12.ps1
|
# $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $
# $Revision: 610 $
#.Synopsis
# Convert Bounce to X500
#.Description
# Convert URL Encoded address in a Bounce message to an X500 address
# that can be added as an alias to the mail-enabled object
#.Parameter bounceAddress
# URL Encoded bounce message address#
#.Example
# Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"
#.Example
# "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500
[CmdletBinding()]
PARAM (
[Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress
)
BEGIN
{
Add-Type -AssemblyName System.Web|Out-Null
}
PROCESS
{
if($_) {$bounceAddress = $_}
$bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+"
$bounceAddress = $bounceAddress -Replace "%3D","="
$bounceAddress = $bounceAddress -Replace "\\+","%"
$bounceAddress = $bounceAddress -Replace "_O=","/O="
$bounceAddress = $bounceAddress -Replace "_OU=","/OU="
$bounceAddress = $bounceAddress -Replace "_CN=","/CN="
if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]}
}
|
PowerShellCorpus/PoshCode/sudo.ps1
|
sudo.ps1
|
[CmdletBinding()]
Param(
[Parameter(ValueFromRemainingArguments=$true)]
$command=$(Read-Host "You must specify a command")
)
#requires -version 2.0
function global:Sudo {
## In order to use this, you have to
## Create a "Scheduled Task" named "Elevated powershell.exe" to run
## PowerShell -Command "exit"
## The scheduled task must be set to "Run with highest privileges"
## NOTE: THIS IS A SECURITY RISK.
## You should at least set it to run only when you're logged on
## I also do NOT set it to run "Hidden" so I always know.
######################################################################
##### You could create that with a script: http://poshcode.org/907
## New-ElevatedTask $((gcm PowerShell | ls).FullName) `
## '-Command "exit"' -TaskName "Elevated PowerShell"
######################################################################
[CmdletBinding()]
Param(
[Parameter(ValueFromRemainingArguments=$true)]
$command=$(Read-Host "You must specify a command")
)
$SchTasks = ls ([Environment]::GetFolderPath("System")) schtasks.exe
$SchTasks = $SchTasks.FullName
$TaskName = '"Elevated PowerShell"'
$AllProfile = Join-Path $(Split-Path $Profile) "Profile.ps1"
$OutputXml = Join-Path $(Split-Path $Profile) "SudoOutput.psxml"
$OutputErr = Join-Path $(Split-Path $Profile) "SudoOutput.err"
$command = $($command -join " ") + " 2> $OutputErr |
Export-CliXml $OutputXml"
$donecheck = {
Get-WinEvent -LogName Microsoft-Windows-TaskScheduler/Operational `
-FilterXPath "*[System[TimeCreated[timediff(@SystemTime) <= 2500]]
and EventData[@Name='TaskSuccessEvent'
and Data[@Name='TaskName']='\\Elevated PowerShell']]" `
-ErrorAction "SilentlyContinue"
}
## Append our command to the end of the profile script ...
## But make sure we remove any sig block at the end first
$script = gc $AllProfile
Set-Content $AllProfile @"
$(($script -notmatch "^\\s*#") -join "`n")
Remove-Item $OutputXml -ErrorAction "SilentlyContinue"
Write-Host "$Command" -Fore Cyan
$Command
"@
$result = &$SchTasks /Run /TN $TaskName
if($result -notmatch "^SUCCESS") {
Write-Error $result
} else {
while(!(&$donecheck)) { sleep 1 }
}
$ErrorActionPreference = "SilentlyContinue"
Import-CliXml $OutputXml
Write-Warning $(@(Get-Content $OutputErr) -join "`n")
Remove-Item $OutputXml
Remove-Item $OutputErr
Set-Content $AllProfile $script
}
Sudo $($command -join " ")
|
PowerShellCorpus/PoshCode/Brushes_1.ps1
|
Brushes_1.ps1
|
$frmMain_OnLoad= {
$m_BrushSize = New-Object Drawing.Rectangle(0, 0, $picDemo.Width, $picDemo.Height)
$wm = [Drawing.Drawing2D.WrapMode]
$cboWraM.Items.AddRange(@($wm::Clamp, $wm::Tile, $wm::TileFlipX, $wm::TileFlipY, $wm::TileFlipXY))
$cboWraM.SelectedIndex = 0
[int]$maxHatchStyle = 53
for ($i = [Convert]::ToInt32([Drawing.Drawing2D.HatchStyle]::Min); $i -lt $maxHatchStyle; $i++) {
$cboHatS.Items.Add([Drawing.Drawing2D.HatchStyle] $i)
}
$cboHatS.SelectedIndex = 0
$lgm = [Drawing.Drawing2D.LinearGradientMode]
$cboGraM.Items.AddRange(@($lgm::BackwardDiagonal, $lgm::ForwardDiagonal, `
$lgm::Horizontal, $lgm::Vertical))
$cboGraM.SelectedIndex = 0
}
$btnCol1_OnClick= {
$cdlg = New-Object Windows.Forms.ColorDialog
if ($cdlg.ShowDialog() -eq [Windows.Forms.Dialogresult]::OK) {
$col1 = $cdlg.Color
$txtCol1.Text = $cdlg.Color.ToString()
$txtCol1.BackColor = $cdlg.Color
}
}
$btnCol2_OnClick= {
$cdlg = New-Object Windows.Forms.ColorDialog
if ($cdlg.ShowDialog() -eq [Windows.Forms.Dialogresult]::OK) {
$col2 = $cdlg.Color
$txtCol2.Text = $cdlg.Color.ToString()
$txtCol2.BackColor = $cdlg.Color
}
}
$cboBruS_OnSelectedIndexChanged= {
switch ($cboBruS.Text) {
"Large" {
$m_BrushSize = New-Object Drawing.Rectangle(0, 0, $picDemo.Width, $picDemo.Height)
break
}
"Medium" {
$m_BrushSize = New-Object Drawing.Rectangle(0, 0, [Convert]::ToInt32($picDemo.Width / 2), `
[Convert]::ToInt32($picDemo.Height / 2))
break
}
"Small" {
$m_BrushSize = New-Object Drawing.Rectangle(0, 0, [Convert]::ToInt32($picDemo.Width / 4), `
[Convert]::ToInt32($picDemo.Height / 4))
break
}
}
RedrawPicture
}
function RedrawPicture {
$picDemo.CreateGraphics().Clear([Drawing.Color]::White)
$picDemo.Refresh()
switch ($cboBruT.Text) {
"Solid" {
$txtCol2.Enabled = $false
$btnCol2.Enabled = $false
$cboBruS.Enabled = $false
$cboWraM.Enabled = $false
$cboHatS.Enabled = $false
$nudRota.Enabled = $false
$nudGraB.Enabled = $false
$cboGraM.Enabled = $false
$brush = New-Object Drawing.SolidBrush $col1
break
}
"Hatch" {
$txtCol1.Enabled = $true
$btnCol1.Enabled = $true
$txtCol2.Enabled = $true
$btnCol2.Enabled = $true
$cboBruS.Enabled = $false
$cboWraM.Enabled = $false
$cboHatS.Enabled = $true
$nudRota.Enabled = $false
$nudGraB.Enabled = $false
$cboGraM.Enabled = $false
$brush = New-Object `
Drawing.Drawing2D.HatchBrush([Drawing.Drawing2D.HatchStyle]$cboHatS.SelectedItem, $col1, $col2)
break
}
"Texture" {
$txtCol1.Enabled = $false
$btnCol1.Enabled = $false
$txtCol2.Enabled = $false
$btnCol2.Enabled = $false
$cboBruS.Enabled = $true
$cboWraM.Enabled = $true
$cboHatS.Enabled = $false
$nudRota.Enabled = $true
$nudGraB.Enabled = $false
$cboGraM.Enabled = $false
#made this path correct, please, on you machine
$file = "$env:allusersprofile\\Documents\\My Drawings\\sunflower.jpg"
$pic = New-Object Drawing.Bitmap($file)
$brush = New-Object Drawing.TextureBrush($pic, $m_BrushSize)
$brush.WrapMode = [Drawing.Drawing2D.WrapMode]$cboWraM.SelectedItem
$brush.RotateTransform([Convert]::ToSingle($nudRota.Value))
break
}
"LinearGradient" {
$txtCol1.Enabled = $true
$btnCol1.Enabled = $true
$txtCol2.Enabled = $true
$btnCol2.Enabled = $true
$cboBruS.Enabled = $true
$cboWraM.Enabled = $false
$cboHatS.Enabled = $false
$nudGraB.Enabled = $true
$cboGraM.Enabled = $true
$brush = New-Object Drawing.Drawing2D.LinearGradientBrush($m_BrushSize, $col1, $col2, `
[Drawing.Drawing2D.LinearGradientMode]$cboGraM.SelectedItem)
$brush.RotateTransform([Convert]::ToSingle($nudRota.Value))
$brush.SetBlendTriangularShape([Convert]::ToSingle($nudGraB.Value))
break
}
}
$g = $picDemo.CreateGraphics()
switch ($cboDraw.Text) {
"Fill" {
$g.FillRectangle($brush, 0, 0, $picDemo.Width, $picDemo.Height)
break
}
"Ellipses" {
$g.FillEllipse($brush, $picDemo.Width / 10, $picDemo.Height / 10, `
$picDemo.Width / 2, $picDemo.Height / 2)
$g.FillEllipse($brush, $picDemo.Width / 3, $picDemo.Height / 3, `
$picDemo.Width / 2, $picDemo.Height / 2)
break
}
"Lines" {
$pen = New-Object Drawing.Pen($brush, 40)
$g.DrawLine($pen, 0, 0, $picDemo.Width, $picDemo.Height)
$g.DrawLine($pen, 0, 0, 0, $picDemo.Height)
$g.DrawLine($pen, 0, 0, $picDemo.Height, 0)
$g.DrawLine($pen, $picDemo.Width, 0, $picDemo.Width, $picDemo.Height)
$g.DrawLine($pen, 0, $picDemo.Height, $picDemo.Width, $picDemo.Height)
$g.DrawLine($pen, $picDemo.Width, 0, 0, $picDemo.Height)
break
}
}
}
function ShowMainWindow {
[void][Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void][Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[Windows.Forms.Application]::EnableVisualStyles()
$col1 = [Drawing.Color]::Blue
$col2 = [Drawing.Color]::White
$frmMain = New-Object Windows.Forms.Form
$mnuMain = New-Object Windows.Forms.MainMenu
$mnuFile = New-Object Windows.Forms.MenuItem
$mnuExit = New-Object Windows.Forms.MenuItem
$mnuHelp = New-Object Windows.Forms.MenuItem
$mnuInfo = New-Object Windows.Forms.MenuItem
$lblBruT = New-Object Windows.Forms.Label
$lblDraw = New-Object Windows.Forms.Label
$lblCol1 = New-Object Windows.Forms.Label
$lblCol2 = New-Object Windows.Forms.Label
$lblBruS = New-Object Windows.Forms.Label
$lblWraM = New-Object Windows.Forms.Label
$lblHatS = New-Object Windows.Forms.Label
$lblRota = New-Object Windows.Forms.Label
$lblGraB = New-Object Windows.Forms.Label
$lblGraM = New-Object Windows.Forms.Label
$cboBruT = New-Object Windows.Forms.ComboBox
$cboDraw = New-Object Windows.Forms.ComboBox
$txtCol1 = New-Object Windows.Forms.TextBox
$txtCol2 = New-Object Windows.Forms.TextBox
$btnCol1 = New-Object Windows.Forms.Button
$btnCol2 = New-Object Windows.Forms.Button
$cboBruS = New-Object Windows.Forms.ComboBox
$cboWraM = New-Object Windows.Forms.ComboBox
$cboHatS = New-Object Windows.Forms.ComboBox
$nudRota = New-Object Windows.Forms.NumericUpDown
$nudGraB = New-Object Windows.Forms.NumericUpDown
$cboGraM = New-Object Windows.Forms.ComboBox
$picDemo = New-Object Windows.Forms.PictureBox
#mnuMain
$mnuMain.MenuItems.AddRange(@($mnuFile, $mnuHelp))
#mnuFile
$mnuFile.MenuItems.AddRange(@($mnuExit))
$mnuFile.Text = "&File"
#mnuExit
$mnuExit.Shortcut = "CtrlX"
$mnuExit.Text = "E&xit"
$mnuExit.Add_Click( { $frmMain.Close() } )
#mnuHelp
$mnuHelp.MenuItems.AddRange(@($mnuInfo))
$mnuHelp.Text = "&Help"
#mnuInfo
$mnuInfo.Text = "About..."
$mnuInfo.Add_Click( { ShowAboutWindow } )
#lblBruT
$lblBruT.Location = New-Object Drawing.Point(8, 16)
$lblBruT.Size = New-Object Drawing.Size(96, 23)
$lblBruT.Text = "Brush Type:"
#lblDraw
$lblDraw.Location = New-Object Drawing.Point(8, 40)
$lblDraw.Size = New-Object Drawing.Size(96, 23)
$lblDraw.Text = "Drawing:"
#lblCol1
$lblCol1.Location = New-Object Drawing.Point(8, 80)
$lblCol1.Size = New-Object Drawing.Size(96, 23)
$lblCol1.Text = "Color 1:"
#lblCol2
$lblCol2.Location = New-Object Drawing.Point(8, 104)
$lblCol2.Size = New-Object Drawing.Size(96, 23)
$lblCol2.Text = "Color 2:"
#lblBruS
$lblBruS.Location = New-Object Drawing.Point(8, 152)
$lblBruS.Size = New-Object Drawing.Size(96, 23)
$lblBruS.Text = "Brush Size:"
#lblWraM
$lblWraM.Location = New-Object Drawing.Point(8, 184)
$lblWraM.Size = New-Object Drawing.Size(96, 23)
$lblWraM.Text = "Wrap Mode:"
#lblHatS
$lblHatS.Location = New-Object Drawing.Point(8, 216)
$lblHatS.Size = New-Object Drawing.Size(96, 23)
$lblHatS.Text = "Hatch Style:"
#lblRota
$lblRota.Location = New-Object Drawing.Point(8, 248)
$lblRota.Size = New-Object Drawing.Size(96, 23)
$lblRota.Text = "Rotation:"
#lblGraB
$lblGraB.Location = New-Object Drawing.Point(8, 280)
$lblGraB.Size = New-Object Drawing.Size(104, 23)
$lblGraB.Text = "Gradient Blend:"
#lblGraM
$lblGraM.Location = New-Object Drawing.Point(8, 312)
$lblGraM.Size = New-Object Drawing.Size(104, 23)
$lblGraM.Text = "Gradient Mode:"
#cboBruT
$cboBruT.Items.AddRange(@("Solid", "Hatch", "Texture", "LinearGradient"))
$cboBruT.Location = New-Object Drawing.Point(112, 13)
$cboBruT.SelectedItem = "Solid"
$cboBruT.Size = New-Object Drawing.Size(176, 24)
$cboBruT.Add_SelectedIndexChanged( { RedrawPicture } )
#cboDraw
$cboDraw.Items.AddRange(@("Fill", "Ellipses", "Lines"))
$cboDraw.Location = New-Object Drawing.Point(112, 40)
$cboDraw.SelectedItem = "Fill"
$cboDraw.Size = New-Object Drawing.Size(176, 24)
$cboDraw.Add_SelectedIndexChanged( { RedrawPicture } )
#txtCol1
$txtCol1.BackColor = "Blue"
$txtCol1.Location = New-Object Drawing.Point(112, 77)
$txtCol1.Size = New-Object Drawing.Size(144, 23)
$txtCol1.Text = "Color [Blue]"
$txtCol1.Add_TextChanged( { RedrawPicture } )
#txtCol2
$txtCol2.Location = New-Object Drawing.Point(112, 102)
$txtCol2.Size = New-Object Drawing.Size(144, 23)
$txtCol2.Text = "Color [White]"
$txtCol2.Add_TextChanged( { RedrawPicture } )
#btnCol1
$btnCol1.Location = New-Object Drawing.Point(256, 76)
$btnCol1.Size = New-Object Drawing.Size(32, 25)
$btnCol1.Text = "..."
$btnCol1.Add_Click($btnCol1_OnClick)
#btnCol2
$btnCol2.Location = New-Object Drawing.Point(256, 101)
$btnCol2.Size = New-Object Drawing.Size(32, 25)
$btnCol2.Text = "..."
$btnCol2.Add_Click($btnCol2_OnClick)
#cboBruS
$cboBruS.Items.AddRange(@("Large", "Medium", "Small"))
$cboBruS.Location = New-Object Drawing.Point(112, 149)
$cboBruS.SelectedItem = "Large"
$cboBruS.Size = New-Object Drawing.Size(176, 24)
$cboBruS.Add_SelectedIndexChanged($cboBruS_OnSelectedIndexChanged)
#cboWraM
$cboWraM.Location = New-Object Drawing.Point(112, 181)
$cboWraM.Size = New-Object Drawing.Size(176, 24)
$cboWraM.Add_SelectedIndexChanged( { RedrawPicture } )
#cboHatS
$cboHatS.Location = New-Object Drawing.Point(112, 213)
$cboHatS.Size = New-Object Drawing.Size(176, 24)
$cboHatS.Add_SelectedIndexChanged( { RedrawPicture } )
#nudRota
[decimal]$nudRota.Increment = [int[]](5, 0, 0, 0)
$nudRota.Location = New-Object Drawing.Point(112, 245)
[decimal]$nudRota.Maximum = [int[]](180, 0, 0, 0)
$nudRota.Size = New-Object Drawing.Size(176, 23)
$nudRota.Add_ValueChanged( { RedrawPicture } )
#nudGraB
$nudGraB.DecimalPlaces = 2;
[decimal]$nudGraB.Increment = [int[]](1, 0, 0, 65536)
$nudGraB.Location = New-Object Drawing.Point(112, 277)
[decimal]$nudGraB.Maximum = [int[]](1, 0, 0, 0)
$nudGraB.Size = New-Object Drawing.Size(176, 23)
[decimal]$nudGraB.Value = [int[]](1, 0, 0, 0)
$nudGraB.Add_ValueChanged( { RedrawPicture } )
#cboGraM
$cboGraM.Location = New-Object Drawing.Point(112, 309)
$cboGraM.Size = New-Object Drawing.Size(176, 24)
$cboGraM.Add_SelectedIndexChanged( { RedrawPicture } )
#picDemo
$picDemo.BorderStyle = "FixedSingle"
$picDemo.Location = New-Object Drawing.Point(304, 16)
$picDemo.Size = New-Object Drawing.Size(312, 320)
#frmMain
$frmMain.ClientSize = New-Object Drawing.Size(626, 371)
$frmMain.Controls.AddRange(@($lblBruT, $lblDraw, $lblCol1, $lblCol2, $lblBruS, $lblWraM, `
$lblHatS, $lblRota, $lblGraB, $lblGraM, $cboBruT, $cboDraw, `
$txtCol1, $txtCol2, $btnCol1, $btnCol2, $cboBruS, $cboWraM, `
$cboHatS, $nudRota, $nudGraB, $cboGraM, $picDemo))
$frmMain.Font = New-Object Drawing.Font("Microsoft Sans Serif", 10)
$frmMain.FormBorderStyle = "FixedSingle"
$frmMain.MaximizeBox = $false
$frmMain.Menu = $mnuMain
$frmMain.StartPosition = "CenterScreen"
$frmMain.Text = "Brushes"
$frmMain.Add_Load($frmMain_OnLoad)
[void]$frmMain.ShowDialog()
}
function ShowAboutWindow {
$frmMain = New-Object Windows.Forms.Form
$lblThis = New-Object Windows.Forms.Label
$btnExit = New-Object Windows.Forms.Button
#lblThis
$lblThis.Location = New-Object Drawing.Point(5, 29)
$lblThis.Size = New-Object Drawing.Size(330, 50)
$lblThis.Text = "(C) 2012 Grigori Zakharov `n
This is just an example that you can make better."
$lblThis.TextAlign = "MiddleCenter"
#btnExit
$btnExit.Location = New-Object Drawing.Point(132, 97)
$btnExit.Text = "Close"
$btnExit.Add_Click( { $frmMain.Close() } )
#frmMain
$frmMain.ClientSize = New-Object Drawing.Size(350, 137)
$frmMain.ControlBox = $false
$frmMain.Controls.AddRange(@($lblThis, $btnExit))
$frmMain.FormBorderStyle = "FixedSingle"
$frmMain.ShowInTaskbar = $false
$frmMain.StartPosition = "CenterScreen"
$frmMain.Text = "About..."
[void]$frmMain.ShowDialog()
}
ShowMainWindow
|
PowerShellCorpus/PoshCode/Copy files .ps1
|
Copy files .ps1
|
cls
<#
Writer: Ritesh P.
#>
# Core Declaration
$date = ((get-date).toString('MM-dd-yyyy'))
$time = ((Get-Date).toString('HH-mm-ss'))
#$what = "/COPYALL /S /B"
#$options = "/R:0 /W:0 /FP"
$NewDestinationPath = '\\\\'+'infra'+'\\c$\\data1\\'+$date+'-'+$time #
When I add $time to create Destination folder, Which protect
from folder duplication and also saved 8line of for loop code ;)
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++
$servers = 'infra'
foreach($Server in $Servers)
{
$sourceFolder = '\\\\'+$server+'\\c$\\data\\'
if (Test-Path $sourceFolder){
$desti=
$NewDestinationPath+'\\'+$Server
robocopy.exe
$sourceFolder $desti '*pub*.txt' /COPYALL /S /B /R:0 /W:0 /FP
/LOG:$date-$time-$server-'robocopy_log'.txt
#Write-output "Files
found:" on $sourceFolder __ | Out-File
$NewDestinationPath'\\'log_$date.txt -Append
}
else{
#"Files does not exist on $server " |
Out-File $NewDestinationPath'\\'Failed_BOS_$date.txt -Append
}
}
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++
# Email Declaration
#$file = c:\\scripts\\PublicFolderData\\log.txt
$smtpServer = “infra.al.com”
$msg = new-object Net.Mail.MailMessage
#$att = new-object Net.Mail.Attachment($file)
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = “BOS_Space_Report@al.com”
$msg.To.Add('riteshp@al.com')
$msg.Subject = “BOS Private Space Utilization Report”
#$msg.IsBodyHtml = $true
$msg.Body = "BOS Private Folder Utilization Space Report
Generated `n " + $desti
$msg.Body += "Log files located at
\\\\infra\\c$\\script\\publicfolderdata\\servername+date+robo_logfile.tx
t"
#$msg.Body = Get-Content "c:\\data\\body.txt"
#$msg.Attachments.Add($att)
$smtp.Send($msg)
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++
<#
"My pain may be the reason for
somebody's laugh
But my laugh must never be the
reason for somebody's pain"
-Charlie Chaplin
#>
|
PowerShellCorpus/PoshCode/BridgeBot 1.1.ps1
|
BridgeBot 1.1.ps1
|
## Depends on the PoshXmpp.dll from http://CodePlex.com/PowerXmpp
#requires -pssnapin PoshXmpp
## Requires System.Web for the RSS-feed option
[Reflection.Assembly]::LoadWithPartialName("System.Web") | Out-Null
##########################################################################################
# @Author: Joel Bennnett
# @Usage:
# Start-JabberMirror.ps1 User@JabberServer.com Password "groupchat@oneserver.com" "groupchat@anotherserver.com" "BridgeBot" "http://rssfeed"
##########################################################################################
param (
$JabberId = $(Read-Host "Jabber Login")
,$Password = $(Read-Host "Password")
,$IRC = "powershell%irc.freenode.net@irc.im.flosoft.biz" # $(Read-Host "First Jabber conference address")
,$JabberConf = "powershell@conference.im.flosoft.biz" # $(Read-Host "Second Jabber conference address")
,$ChatNick = "PowerBot" # $(Read-Host "The nickname you want to use")
[string[]]$AtomFeeds = @("http://groups.google.com/group/microsoft.public.windows.powershell/feed/atom_v1_0_topics.xml")
)
function Start-PowerBot {
$global:LastNewsCheck = $([DateTime]::Now.AddHours(-5))
$global:feedReader = new-object Xml.XmlDocument
$global:PoshXmppClient = PoshXmpp\\New-Client $JabberId $Password # http://im.flosoft.biz:5280/http-poll/
PoshXmpp\\Connect-Chat $IRC $ChatNick
PoshXmpp\\Connect-Chat $JabberConf $ChatNick
PoshXmpp\\Send-Message $IRC "Starting Mirror to $('{0}@{1}' -f $JabberConf.Split(@('%','@'),3))"
PoshXmpp\\Send-Message $JabberConf "Starting Mirror to $('{0}@{1}' -f $IRC.Split(@('%','@'),3))"
PoshXmpp\\Send-Message $IRC "/msg nickserv id Sup3rB0t"
}
function Process-Command($Chat, $Message) {
$split = $message.Body.Split(" |;")
$from = $Message.From.Bare.ToLower()
switch -regex ( $split[0] ) {
"!list" {
Write-Host "!LIST COMMAND. Send users of [$Chat] to [$($Message.From.Bare)]" -fore Magenta
PoshXmpp\\Send-Message $from (@($PoshXmppClient.ChatManager.GetUsers( $Chat ).Values) -join ", ")
}
"!gh|!get-help|!man" {
$help = get-help $split[1] | Select Synopsis,Syntax
$msgs = (get-help $split[1] | ... Synopsis Syntax | Out-String -w 1000 | split-string "`n" -count 4)[0,2];
PoshXmpp\\Send-Message $from $help.Synopsis;
PoshXmpp\\Send-Message $from ($help.Syntax | Out-String -w 1000 | split-string "`n" -count 4 -rem )[1]
}
}
}
# Max IRC Message Length http://www.faqs.org/rfcs/rfc1459.html
# PRIVMSG CHANNEL MSG
$IrcMaxLen = 510 - ("PRIVMSG :".Length + $IRC.Length + $JabberId.split('@')[0].Length)
function Get-Feeds([string[]]$JIDs,[string[]]$AtomFeeds) {
Write-Verbose "Checking feeds..."
foreach($feed in $AtomFeeds) {
$feedReader.Load($feed)
for($i = $feedReader.feed.entry.count - 1; $i -ge 0; $i--) {
$e = $feedReader.feed.entry[$i]
if([datetime]$e.updated -gt $global:LastNewsCheck) {
foreach($jid in $JIDs) {
$msg = ([System.Web.HttpUtility]::HtmlDecode($e.summary."#text") -replace "<br>", "").Trim()
$template = "{0} (Posted at {1:hh:mm} by {2}) {{0}} :: {3}" -f
$e.title."#text", [datetime]$e.updated, $e.author.name, $e.link.href
$len = [math]::Min($IrcMaxLen,($template.Length + $msg.Length)) - ($template.Length +3)
PoshXmpp\\Send-Message $jid $($template -f $msg.SubString(0,$len))
}
[Threading.Thread]::Sleep( 500 )
}
}
}
$global:LastNewsCheck = [DateTime]::Now
}
function Bridge {
PoshXmpp\\Receive-Message -All | foreach-object {
Write-Verbose ("MESSAGE: {0} {1} {2}" -f $_.From.Bare, $_.From.Resource, $_.Body)
if( $_.Type -eq "Error" ) {
Write-Error $_.Error
}
if( $_.From.Resource -ne $ChatNick ) {
$Chat = $null;
if( $_.From.Bare -eq $IRC )
{
$Chat = $JabberConf;
}
elseif( $_.From.Bare -eq $JabberConf )
{
$Chat = $IRC;
}
else
{
$_
}
if($Chat){
if(![String]::IsNullOrEmpty($_.Body) -and ($_.Body[0] -eq '!')) {
PoshXmpp\\Send-Message $Chat ("<{0}> {1}" -f $_.From.Resource, $_.Body)
Process-Command $Chat $_
}
elseif( ![String]::IsNullOrEmpty($_.Subject) )
{
$_.To = $Chat
# Send it directly using a method on the PoshXmppClient
$PoshXmppClient.Send($_)
}
else
{
PoshXmpp\\Send-Message $Chat ("<{0}> {1}" -f $_.From.Resource, $_.Body)
}
}
}
}
}
function Start-Bridge {
"PRESS ANY KEY TO STOP"
while(!$Host.UI.RawUI.KeyAvailable) {
Bridge
Get-Feeds @($IRC,$JabberConf) $AtomFeeds
$counter = 0
Write-Verbose "PRESS ANY KEY TO STOP" # we're going to wait 3 * 60 seconds
while(!$Host.UI.RawUI.KeyAvailable -and ($counter++ -lt 1800)) {
Bridge
[Threading.Thread]::Sleep( 100 )
}
}
}
function Stop-PowerBot {
PoshXmpp\\Disconnect-Chat $IRC $ChatNick
PoshXmpp\\Disconnect-Chat $JabberConf $ChatNick
$global:PoshXmppClient.Close();
}
|
PowerShellCorpus/PoshCode/CD.psm1.ps1
|
CD.psm1.ps1
|
PARAM ( $MaxEntryCount = 50)
<#
Author: Bartek Bielawski (@bielawb on Twitter)
Adds cd- functionality known in bash, an probably some other shells.
Version: 0.1
Any comments/ feedback welcome, ping me on twitter on via e-mail (bartb at aster dot pl)
#>
<#
We have to modify prompt function to handle changes in current location.
To prevent Remove-Module from deleting it we stored in private variable and restore from there OnRemove event.
#>
$oldPrompt = Get-Content function:\\prompt -ErrorAction SilentlyContinue
$MyPrompt = @"
# Added by cd module
Add-LocationToList
# Back to your original prompt
"@
Set-Content function:\\prompt -Force $($MyPrompt + $oldPrompt)
$MyInvocation.MyCommand.ScriptBlock.Module.OnRemove = {
# Remove-Module would actually remove Funtion:\\Prompt and we... would like to avoid it
Set-Content Function:\\prompt -Value $oldPrompt
}
function Add-LocationToList {
<#
.Synopsis
Adds directory to list of recent locations used by Set-PrevLocation function
.Description
This command will add string to collection of recent folders. It checks if string is a valid path.
It will ignore path if it's the last one added to collection.
By default it uses global $pwd variable as a parameter, so when launched without parameters will add current location to the list.
.Example
Add-LocationtoList
Adds current location (if not last one added) to collection of recent folders.
.Example
Add-LocationList C:\\temp\\foo\\bar
Adds c:\\temp\\foo\\bar (if it exists and is a container) to the list of recent folders.
#>
param (
[ValidateScript( { Test-Path -Path $_ -PathType Container })]
[string]$pwd = $global:pwd
)
if (!($Script:LocationList)) {
$Script:LocationList = New-Object System.Collections.Generic.List[string]
}
if ($Script:LocationList[0] -ne $pwd) {
$Script:LocationList.Insert(0,$pwd)
}
while ($Script:LocationList.Count -gt $MaxEntryCount) {
$Script:LocationList.RemoveAt($MaxEntryCount - 1)
}
}
function Set-PrevLocation {
<#
.Synopsis
Goes to folder that was previously visited/ added to the list of recent folders.
.Description
This function has 3 possible uses:
cd- => when used without parameters it will simply move to the folder that is first on the list. Usually that means last visited folder.
cd- -List => lists all folders available, with Level assigned to them.
cd- -Level X => changes location to folder with level equal to X
In order to work correctly requires that prompt function will not be overwritten after module was loaded.
.Example
cd c:\\
cd ~
cd-
If prompt function have not been overwritten:
This will change to root directory, than to home (OS/ user dependent path), and than back to root folder (last visited).
.Example
Set-PrevLocation -List
Lists all folders that are stored on the list of recent folders.
.example
cd c:\\
cd ~
cd hklm:
cd hkcu:
cd function:
cd alias:
cd- 5
If prompt function have not been overwritten:
Moves to each folder and than jumps back to the one that was visited 5 'jumps' ago.
#>
PARAM (
[int]$Level = 1,
[switch]$List
)
if ($List) {
if ( $Script:LocationList.Count -gt 1) {
for ($i = 1; $i -lt $LocationList.Count; $i ++) {
New-Object PSObject -Property @{Level = $I; Path = $LocationList[$i] }
}
} else {
"List is empty."
}
return
}
if ($script:LocationList.Count -gt $Level) {
Set-Location $script:LocationList[$Level];
for($RemoveAt = 0;$RemoveAt -lt $Level; $RemoveAt++) {
$Script:LocationList.RemoveAt(0)
# That will move others up so next one will always have '0' index. ;)
}
} else {
Write-Error "Value of Level parameter out of range. Try different value or check list of stored folders (-List)."
}
}
New-Alias -Name cd- -Value Set-PrevLocation -Force
Export-ModuleMember -Function Set-PrevLocation, Add-LocationToList -Alias cd-
|
PowerShellCorpus/PoshCode/Generate-Acronyms.ps1
|
Generate-Acronyms.ps1
|
param([String] $phrase)
$words = $phrase.Split()
$MaxLettersPerWord = 3
$output = @('')
$maxSize = [System.Math]::Pow($MaxLettersPerWord, $words.Count)
1..$words.Count | % {
$word, $words = $words
$output | % {
$oldWord = $_
1..$MaxLettersPerWord | % {
$output += $oldWord + $word.SubString(0,$_)
}
}
}
$output | Select-Object -Last $maxSize
|
PowerShellCorpus/PoshCode/sudo for Powershell_1.ps1
|
sudo for Powershell_1.ps1
|
# sudo.ps1
#
# Authors: pezhore, mrigns, This guy: http://tsukasa.jidder.de/blog/2008/03/15/scripting-sudo-with-powershell
# Other powershell peoples.
#
# Sources:
# http://tsukasa.jidder.de/blog/2008/03/15/scripting-sudo-with-powershell
# http://www.ainotenshi.org/%E2%80%98sudo%E2%80%99-for-powershell-sorta
#
# Version:
# 1.0 Initial version
# 1.1 added -ps flag, cleaned up passed $file/$script full path
# 1.2 Comments
# 1.3 Fixed passing working directory to powershell/auto closing
param(
[switch]$ps, # Switch for running args as powershell script
[string]$file, # Script/Program to run
[string]$arguments = $args # Arguments to program/script
)
# Find our powershell full path
$powershell = (get-command powershell).definition
# Get current directory
$dir = get-location
#If we're running this as a elevated powershell script
if ($ps){
# Script verification
if([System.IO.File]::Exists("$(get-location)\\$file")) {
# Set the $script to full path of the ps script
$script = (get-childitem $file).fullname
}
# Create a powershell process
$psi = new-object System.Diagnostics.ProcessStartInfo $powershell
$psi.WorkingDirectory = Get-Location
# Combine the script and its arguments
$sArgs = $script + " " + $arguments
# Set the arguments to be the ps script and it's arguments
$psi.Arguments = "-noexit -command set-location $dir; $sArgs"
# Magic to run as elevated
$psi.Verb = "runas";
}
# We're running something other than a powershells script
else {
# File verification
if([System.IO.File]::Exists("$(get-location)\\$file")) {
# Get full path
$file = (get-childitem $file).fullname
}
# Same as above, create proccess/working directory/arguments/runas
$psi = new-object System.Diagnostics.ProcessStartInfo $file
$psi.Arguments = $arguments
$psi.Verb = "runas"
}
# Start the process
[System.Diagnostics.Process]::Start($psi)
|
PowerShellCorpus/PoshCode/HttpRest 1.1.0.ps1
|
HttpRest 1.1.0.ps1
|
#requires -version 2.0
## HttpRest module
####################################################################################################
## Initial stages of changing HttpRest into a v2-only module
## Based on the REST api from MindTouch's Dream SDK
##
## INSTALL:
## You need mindtouch.dream.dll (mindtouch.core.dll, SgmlReaderDll.dll, log4net.dll) from the SDK
## Download DREAM from http`://sourceforge.net/project/showfiles.php?group_id=173074
## Unpack it, and you can find these dlls in the "dist" folder.
## Make sure to put them in the folder with this script module.
##
## For documentation of Dream: http`://wiki.developer.mindtouch.com/Dream
####################################################################################################
## Version History
## 1.0 First Release
## 1.0.1 Added Get-WebPageContent
## 1.0.2 Bug fix for Invoke-Http credential issues
## 1.1.0 First release of a PowerShell 2.0 (CTP3/Windows7) version....
####################################################################################################
## Usage:
## function Get-Google {
## Invoke-Http GET http`://www.google.com/search @{q=$args} |
## Receive-Http Xml "//h3[@class='r']/a" | Select href, InnerText
## }
## #########################################################################
## function Get-WebFile($url,$cred) {
## Invoke-Http GET $url -auth $cred | Receive-Http File
## }
## #########################################################################
## function Send-Paste {
## PARAM($PastebinURI="http`://posh.jaykul.com/p/",[IO.FileInfo]$file)
## PROCESS {
## if($_){[IO.FileInfo]$file=$_}
##
## if($file.Exists) {
## $ofs="`n"
## $result = Invoke-Http POST $PastebinURI @{
## format="posh" # PowerShell
## expiry="d" # (d)ay or (m)onth or (f)orever
## poster=$([Security.Principal.WindowsIdentity]::GetCurrent().Name.Split("\\")[-1])
## code2="$((gc $file) -replace "http`://","http``://")" # To get past the spam filter.
## paste="Send"
## } -Type FORM_URLENCODED -Wait
## $xml = $result.AsDocument().ToXml()
## write-output $xml.SelectSingleNode("//*[@class='highlight']/*").href
## } else { throw "File Not Found" }
## }}
##
####################################################################################################
if(!$PSScriptRoot){
Write-Debug $($MyInvocation.MyCommand | out-string)
$PSScriptRoot=(Split-Path $MyInvocation.MyCommand.Path -Parent)
}
# Write-Debug "Invocation: $($MyInvocation.MyCommand.Path)"
# Write-Debug "Invocation: $($MyInvocation.MyCommand)"
# Write-Debug "Invocation: $($MyInvocation)"
Write-Debug "PSScriptRoot: '$PSScriptRoot'"
# This Module depends on MindTouch.Dream
$null = [Reflection.Assembly]::LoadFrom( "$PSScriptRoot\\mindtouch.dream.dll" )
# MindTouch.Dream requires: mindtouch.dream.dll, mindtouch.core.dll, SgmlReaderDll.dll, and log4net.dll)
# This Module also depends on utility functions from System.Web
$null = [Reflection.Assembly]::LoadWithPartialName("System.Web")
## Some utility functions are defined at the bottom
[uri]$global:url = ""
[System.Management.Automation.PSCredential]$global:HttpRestCredential = $null
function Get-DreamMessage($Content,$Type) {
Write-Verbose "Content: $(if($Content){$Content.GetType()}else{"null"}) $($Content.Length) and Type: $(if($Type){$Type.GetType()}else{"null"})"
if(!$Content) {
Write-Verbose "No Content"
return [MindTouch.Dream.DreamMessage]::Ok()
}
if( $Content -is [System.Xml.XmlDocument]) {
Write-Verbose "Xml Content"
return [MindTouch.Dream.DreamMessage]::Ok( $Content )
}
if(Test-Path $Content -EA "SilentlyContinue") {
Write-Verbose "File Content"
return [MindTouch.Dream.DreamMessage]::FromFile((Convert-Path (Resolve-Path $Content)));
}
if($Type -is [String]) {
Write-Verbose "Specific Content: $([MindTouch.Dream.MimeType]::$Type)"
$Type = [MindTouch.Dream.MimeType]::$Type
}
if($Type -is [MindTouch.Dream.DreamMessage]) {
Write-Verbose "Specific Content: $([MindTouch.Dream.MimeType]::$Type)"
return [MindTouch.Dream.DreamMessage]::Ok( $Type, $Content )
} else {
Write-Verbose "Unspecified string content"
return [MindTouch.Dream.DreamMessage]::Ok( $([MindTouch.Dream.MimeType]::TEXT), $Content )
}
}
function Get-DreamPlug {
[CmdletBinding()]
PARAM ( $Url, [hashtable]$With )
if($Url -is [array]) {
Write-Verbose "URL is an array of parts"
if($Url[0] -is [hashtable]) {
Write-Verbose "URL is an array of hashtable parts"
$plug = [MindTouch.Dream.Plug]::New($global:url)
foreach($param in $url.GetEnumerator()) {
if($param.Value) {
$plug = $plug.At($param.Key,"=$(Encode-Twice $param.Value)")
} else {
$plug = $plug.At($param.Key)
}
}
}
else
{
[URI]$uri = Join-Url $global:url $url
$plug = [MindTouch.Dream.Plug]::New($uri)
}
}
elseif($url -is [string])
{
Write-Verbose "String URL"
trap { continue }
[URI]$uri = $url
if(!$uri.IsAbsoluteUri) {
$uri = Join-Url $global:url $url
Write-Verbose "Relative URL, appending to $($global:url) to get: $uri"
}
$plug = [MindTouch.Dream.Plug]::New($uri)
}
else {
Write-Verbose "No URL, using default $($global:url)"
$plug = [MindTouch.Dream.Plug]::New($global:url)
}
if($with) {
foreach($param in $with.GetEnumerator()) {
if($param.Value) {
$plug = $plug.With($param.Key,$param.Value)
}
}
Write-Verbose "Added 'with' params: $plug"
}
return $plug
}
#CMDLET Receive-Http {
Function Receive-Http {
PARAM(
# [Parameter(Position=1, Mandatory=$false)]
# [ValidateSet("Xml", "File", "Text","Bytes")]
# [Alias("As")]
$Output = "Xml"
,
# [Parameter(Position=2, Mandatory=$false)]
[string]$Path
,
# [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Result")]
# [Alias("IO")]
# [MindTouch.Dream.Result``1[[MindTouch.Dream.DreamMessage]]]
$InputObject
#,
# [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Response")]
# [MindTouch.Dream.DreamMessage]
# $response
)
BEGIN {
if($InputObject) {
Write-Output $inputObject | Receive-Http $Output $Path
} # else they'd better pass it in on the pipeline ...
}
PROCESS {
$response = $null
if($_ -is [MindTouch.Dream.Result``1[[MindTouch.Dream.DreamMessage]]]) {
$response = $_.Wait()
} elseif($_ -is [MindTouch.Dream.DreamMessage]) {
$response = $_
} elseif($_) {
throw "We can only pipeline [MindTouch.Dream.DreamMessage] objects, or [MindTouch.Dream.Result`1[DreamMessage]] objects"
}
if($response) {
Write-Debug $($response | Out-String)
if(!$response.IsSuccessful) {
Write-Error $($response | Out-String)
Write-Verbose $response.AsText()
throw "ERROR: '$($response.Status)' Response Status."
} else {
switch($Output) {
"File" {
## Joel's magic filename guesser ...
if(!$Path) {
[string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $response.Headers["Content-Disposition"] ).Groups[1].Value
$Path = $fileName.trim("\\/""'")
if(!$Path) {
$fileName = $response.ResponseUri.Segments[-1]
$Path = $fileName.trim("\\/")
if(!([IO.FileInfo]$Path).Extension) {
$Path = $Path + "." + $response.ContentType.Split(";")[0].Split("/")[1]
}
}
}
$File = Get-FileName $Path
[StreamUtil]::CopyToFile( $response.AsStream(), $response.ContentLength, $File )
Get-ChildItem $File
}
"XDoc" {
if($Path) {
$response.AsDocument()[$Path]
} else {
$response.AsDocument()#.ToXml()
}
}
"Xml" {
if($Path) {
$response.AsDocument().ToXml().SelectNodes($Path)
} else {
$response.AsDocument().ToXml()
}
}
"Text" {
if($Path) {
$response.AsDocument()[$Path] | % { $_.AsText }
} else {
$response.AsText()
}
}
"Bytes" {
$response.AsBytes()
}
}
}
}
}
}
## http`://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
## Nobody actually uses HEAD or OPTIONS, right?
## And nobody's even heard of TRACE or CONNECT ;)
# CMDLET Invoke-Http {
Function Invoke-Http {
[CmdletBinding()]
PARAM(
[Parameter(Position=0, Mandatory=$false)]
[ValidateSet("Post", "Get", "Put", "Delete", "Head", "Options")] ## There are other verbs, but we need a list to make sure you don't screw up
[string]$Verb = "Get"
,
[Parameter(Position=1, Mandatory=$true, ValueFromPipeline=$true)]
[string]
$Path
,
[Parameter(Position=2, Mandatory=$false)]
[hashtable]$with
,
[Parameter(Mandatory=$false)]
$Content
,
[Parameter(Mandatory=$false)]
$Type # Of Content
,
[Parameter(ParameterSetName="UseDefaultCredentials")]
$authenticate
,
[Parameter(ParameterSetName="ManualCredentials")]
$credentials
,
[switch]$waitForResponse
)
PROCESS {
$plug = Get-DreamPlug $Path $With
Write-Verbose "Content Type: $Type"
Write-Verbose "Content: $Content"
## Special Handling for FORM_URLENCODED
if($Type -like "Form*" -and !$Content) {
$dream = [MindTouch.Dream.DreamMessage]::Ok( $Plug.Uri )
$Plug = [MindTouch.Dream.Plug]::New( $Plug.Uri.SchemeHostPortPath )
Write-Verbose "RECREATED Plug: $($Plug.Uri.SchemeHostPortPath)"
} else {
$dream = Get-DreamMessage $Content $Type
Write-Verbose "Created Dream with Content: $($dream.Content)"
}
if(!$plug -or !$dream) {
throw "Can't come up with a request!"
}
Write-Verbose $("DREAM!",$dream | Out-String )
if($authenticate -or $credentials){
if($credentials -is [System.Management.Automation.PSCredential]) {
Write-Verbose "AUTHENTICATING AS $($credentials.GetNetworkCredential().UserName)"
$plug = $plug.WithCredentials($credentials.GetNetworkCredential())
} elseif($credentials -is [System.Net.ICredentials]) {
Write-Verbose "AUTHENTICATING AS $($credentials.GetNetworkCredential().UserName)"
$plug = $plug.WithCredentials($credentials.GetNetworkCredential())
} else {
if($credentials) {
Write-Error "Credential must be a PSCredential or a System.Net.ICredentials"
}
$null = Get-HttpCredential # Make sure they have global credentials
Write-Verbose "AUTHENTICATING AS $($global:HttpRestCredential.UserName)"
$plug = $plug.WithCredentials($global:HttpRestCredential.GetNetworkCredential())
}
}
Write-Verbose $plug.Uri
## DEBUG:
Write-Debug "URI: $($Plug.Uri)"
Write-Debug "Verb: $($Verb.ToUpper())"
Write-Debug $($dream | Out-String)
$result = $plug.InvokeAsync( $Verb.ToUpper(), $dream )
Write-Debug $($result | Out-String)
# if($DebugPreference -eq "Continue") {
# Write-Debug $($result.Wait() | Out-String)
# }
if($waitForResponse) {
$result = $result.Wait()
}
write-output $result
trap [MindTouch.Dream.DreamResponseException] {
Write-Error @"
TRAPPED DreamResponseException
$($_.Exception.Response | Out-String)
$($_.Exception.Response.Headers | Out-String)
"@
break;
}
}
}
function Get-WebPageContent {
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$true)]
[string]$url
,
[Parameter(Position=1,Mandatory=$false)]
[string]$xpath=""
,
[Parameter(Position=2,Mandatory=$false)]
[hashtable]$with=@{}
,
[Parameter(Mandatory=$false)]
[switch]$AsXml
,
[Parameter(Mandatory=$false)]
[switch]$Authenticate
)
BEGIN { $out = "Text"; if($AsXml) { $out="Xml" } }
PROCESS {
invoke-http get $url $with -Authenticate:$Authenticate | receive-http $out $xpath
}
}
new-alias gwpc Get-WebPageContent -EA "SilentlyContinue"
new-alias http Invoke-Http -EA "SilentlyContinue"
new-alias rcv Receive-Http -EA "SilentlyContinue"
# function Get-Http { return Invoke-Http "GET" @args }
# function New-Http { return Invoke-Http "PUT" @args }
# function Update-Http { return Invoke-Http "POST" @args }
# function Remove-Http { return Invoke-Http "DELETE" @args }
# new-alias Set-Http Update-Http
# new-alias Put-Http New-Http
# new-alias Post-Http Update-Http
# new-alias Delete-Http Remove-Http
function Set-HttpDefaultUrl {
PARAM ([uri]$baseUri=$(Read-Host "Please enter the base Uri for your RESTful web-service"))
$global:url = $baseUri
}
function Set-HttpCredential {
param($Credential=$(Get-CredentialBetter -Title "Http Authentication Request - $($global:url.Host)" `
-Message "Your login for $($global:url.Host)" `
-Domain $($global:url.Host)) )
if($Credential -is [System.Management.Automation.PSCredential]) {
$global:HttpRestCredential = $Credential
} elseif($Credential -is [System.Net.NetworkCredential]) {
$global:HttpRestCredential = new-object System.Management.Automation.PSCredential $Credential.UserName, $(ConvertTo-SecureString $credential.Password)
}
}
function Get-HttpCredential {
if(!$global:url) { Set-HttpDefaultUrl }
if(!$global:HttpRestCredential) { Set-HttpCredential }
if(!$Secure) {
return $global:HttpRestCredential.GetNetworkCredential();
} else {
return $global:HttpRestCredential
}
}
# function Authenticate-Http {
# PARAM($URL=@("users","authenticate"), $Credential = $(Get-HttpCredential))
# $plug = [MindTouch.Dream.Plug]::New( $global:url )
# $null = $plug.At("users", "authenticate").WithCredentials( $auth.UserName, $auth.Password ).Get()
# }
function ConvertTo-UrlDoubleEncode {
param([string]$text)
return [System.Web.HttpUtility]::UrlEncode( [System.Web.HttpUtility]::UrlEncode( $text ) )
}
New-Alias Encode-Twice ConvertTo-UrlDoubleEncode
function Join-Url ( [uri]$baseUri=$global:url ) {
$ofs="/";$BaseUrl = ""
if($BaseUri -and $baseUri.AbsoluteUri) {
$BaseUrl = "$($baseUri.AbsoluteUri.Trim('/'))/"
}
return [URI]"$BaseUrl$([string]::join("/",@($args)).TrimStart('/'))"
}
function ConvertTo-SecureString {
Param([string]$input)
$result = new-object System.Security.SecureString
foreach($c in $input.ToCharArray()) {
$result.AppendChar($c)
}
$result.MakeReadOnly()
return $result
}
## Unit-Test Get-FileName ## Should return TRUE
## (Get-FileName C:\\Windows\\System32\\Notepad.exe) -eq "C:\\Windows\\System32\\Notepad.exe" -and
## (Get-FileName C:\\Windows\\Notepad.exe C:\\Windows\\System32\\) -eq "C:\\Windows\\System32\\Notepad.exe" -and
## (Get-FileName WaitFor.exe C:\\Windows\\System32\\WaitForIt.exe) -eq "C:\\Windows\\System32\\WaitForIt.exe" -and
## (Get-FileName -Path C:\\Windows\\System32\\WaitForIt.exe) -eq "C:\\Windows\\System32\\WaitForIt.exe"
function Get-FileName {
param($fileName=$([IO.Path]::GetRandomFileName()), $path)
$fileName = $fileName.trim("\\/""'")
## if the $Path has a file name, and it's folder exists:
if($Path -and !(Test-Path $Path -Type Container) -and (Test-Path (Split-Path $path) -Type Container)) {
$path
## if the $Path is just a folder (and it exists)
} elseif($Path -and (Test-Path $path -Type Container)) {
$fileName = Split-Path $fileName -leaf
Join-Path $path $fileName
## If there's no valid $Path, and the $FileName has a folder...
} elseif((Split-Path $fileName) -and (Test-Path (Split-Path $fileName))) {
$fileName
} else {
Join-Path (Get-Location -PSProvider "FileSystem") (Split-Path $fileName -Leaf)
}
}
function Get-UtcTime {
Param($Format="yyyyMMddhhmmss")
[DateTime]::Now.ToUniversalTime().ToString($Format)
}
## Get-CredentialBetter
## An improvement over the default cmdlet which has no options ...
###################################################################################################
## History
## v 1.2 Refactor ShellIds key out to a variable, and wrap lines a bit
## v 1.1 Add -Console switch and set registry values accordingly (ouch)
## v 1.0 Add Title, Message, Domain, and UserName options to the Get-Credential cmdlet
###################################################################################################
function Get-CredentialBetter{
PARAM([string]$UserName, [string]$Title, [string]$Message, [string]$Domain, [switch]$Console)
$ShellIdKey = "HKLM:\\SOFTWARE\\Microsoft\\PowerShell\\1\\ShellIds"
## Carefully EA=SilentlyContinue because by default it's MISSING, not $False
$cp = (Get-ItemProperty $ShellIdKey ConsolePrompting -ea "SilentlyContinue")
## Compare to $True, because by default it's $null ...
$cp = $cp.ConsolePrompting -eq $True
if($Console -and !$cp) {
Set-ItemProperty $ShellIdKey ConsolePrompting $True
} elseif(!$Console -and $Console.IsPresent -and $cp) {
Set-ItemProperty $ShellIdKey ConsolePrompting $False
}
## Now call the Host.UI method ... if they don't have one, we'll die, yay.
$Host.UI.PromptForCredential($Title,$Message,$UserName,$Domain,"Generic","Default")
## BoyScouts: Leave everything better than you found it (I'm tempted to leave it = True)
Set-ItemProperty $ShellIdKey ConsolePrompting $cp -ea "SilentlyContinue"
}
Export-ModuleMember -Function * -Alias *
# Export-ModuleMember Invoke-Http, Receive-Http, Set-HttpCredential, Set-HttpDefaultUrl
# SIG # Begin signature block
# MIILCQYJKoZIhvcNAQcCoIIK+jCCCvYCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUoniyyA7pKrlhV2+dvfWyjfsv
# RvGgggbgMIIG3DCCBMSgAwIBAgIJALPpqDj9wp7xMA0GCSqGSIb3DQEBBQUAMIHj
# MQswCQYDVQQGEwJVUzERMA8GA1UECBMITmV3IFlvcmsxEjAQBgNVBAcTCVJvY2hl
# c3RlcjEhMB8GA1UEChMYaHR0cDovL0h1ZGRsZWRNYXNzZXMub3JnMSgwJgYDVQQL
# Ex9TY3JpcHRpbmcgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MTcwNQYDVQQDEy5odHRw
# Oi8vSHVkZGxlZE1hc3Nlcy5vcmcgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MScwJQYJ
# KoZIhvcNAQkBFhhKYXlrdWxASHVkZGxlZE1hc3Nlcy5vcmcwHhcNMDkwMzE1MTkx
# OTE5WhcNMTAwMzE1MTkxOTE5WjCBqzELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5l
# dyBZb3JrMRIwEAYDVQQHEwlSb2NoZXN0ZXIxITAfBgNVBAoTGGh0dHA6Ly9IdWRk
# bGVkTWFzc2VzLm9yZzESMBAGA1UECxMJU2NyaXB0aW5nMRUwEwYDVQQDEwxKb2Vs
# IEJlbm5ldHQxJzAlBgkqhkiG9w0BCQEWGEpheWt1bEBIdWRkbGVkTWFzc2VzLm9y
# ZzCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAPfqxOG9TQN+qZjZ6KfM
# +zBK0YpjeyPL/cFgiGBhiIdYWTBtkbZydFr3IiERKRsUJ0/SKFbhf0C3Bvd/neTJ
# qiZjH4D6xkrfdLlWMmmSXXqjSt48jZp+zfCAIaF8K84e9//7lMicdVFE6VcgoATZ
# /eMKQky4JvphJpzDHYPLxLJQrKd0pjDDwspjdX5RedWkzeZBG7VfBnebLWUzgnMX
# IxRQKfFCMryQDP8weceOnJjfJEf2FYmdpsEg5EKKKbuHsQCMVTxfteKdPvh1oh05
# 1GWyPsvEPh4auJUT8pAVvrdxq+/O9KW/UV01UxjRYM1vdklNw8g7mkJTrrHjSjl7
# tuugCnJjt5kN6v/OaUtRRMR68O85bSTVGOxJGCHUKlyuuTx9tnfIgy4siFYX1Ve8
# xwaAdN3haTon3UkWzncHOq3reCIVF0luwRZu7u+TnOAnz2BRlt+rcT0O73GN20Fx
# gyN2f5VGBbw1KuS7T8XZ0TFCspUdgwAcmTGuEVJKGhVcGAvNlLx+KPc5dba4qEfs
# VZ0MssC2rALC1z61qWuucb5psHYhuD2tw1SrztywuxihIirZD+1+yKE4LsjkM1zG
# fQwDO/DQJwkdByjfB2I64p6mk36OlZAFxVfRBpXSCzdzbgKpuPsbtjkb5lGvKjE1
# JFVls1SHLJ9q80jHz6yW7juBAgMBAAGjgcgwgcUwHQYDVR0OBBYEFO0wLZyg+qGH
# Z4WO8ucEGNIdU1T9MB8GA1UdIwQYMBaAFN2N42ZweJLF1mz0j70TMxePMcUHMAkG
# A1UdEwQCMAAwEQYJYIZIAYb4QgEBBAQDAgTwMCoGA1UdJQEB/wQgMB4GCCsGAQUF
# BwMBBggrBgEFBQcDAgYIKwYBBQUHAwMwCwYDVR0PBAQDAgTwMCwGCWCGSAGG+EIB
# DQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTANBgkqhkiG9w0BAQUF
# AAOCAgEAmKihxd6KYamLG0YLvs/unUTVJ+NW3jZP16R28PpmidY/kaBFOPhYyMl2
# bBGQABe7LA5rpHFAs0F56gYETNoFk0qREVvaoz9u18VfLb0Uwqtnq0P68L4c7p2q
# V3nKmWjeI6H7BAyFuogxmMH5TGDfiqrrVSuh1LtPbkV2Wtto0SAxP0Ndyts2J8Ha
# vu/2rt0Ic5AkyD+RblFPtzkCC/MLVwSNAiDSKGRPRrLaiGxntEzR59GRyf2vwhGg
# oAXUqcJ/CVeHCP6qdSTM39Ut3RmMZHXz5qY8bvLgNYL6MtcJAx+EeUhW497alzm1
# jInXdbikIh0d/peTSDyLbjS8CPFFtS6Z56TDGMf+ouTpEA16otcWIPA8Zfjq+7n7
# iBHjeuy7ONoJ2VDNgqn9B+ft8UWRwnJbyB85T83OAGf4vyhCPz3Kg8kWxY30Bhnp
# Fayc6zQKCpn5o5T0/a0BBHwAyMfr7Lhav+61GpzzG1KfAw58N2GV8KCPKNEd3Zdz
# y07aJadroVkW5R+35mSafKRJp5pz20GDRwZQllqGH1Y/UJFEiI0Bme9ecbl2vzNp
# JjHyl/jLVzNVrBI5Zwb0lCLsykApgNY0yrwEqaiqwcxq5nkXFDhDPQvbdulihSo0
# u33fJreCm2fFyGbTuvR61goSksAvLQhvijLAzcKqWKG+laOtYpAxggOTMIIDjwIB
# ATCB8TCB4zELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5ldyBZb3JrMRIwEAYDVQQH
# EwlSb2NoZXN0ZXIxITAfBgNVBAoTGGh0dHA6Ly9IdWRkbGVkTWFzc2VzLm9yZzEo
# MCYGA1UECxMfU2NyaXB0aW5nIENlcnRpZmljYXRlIEF1dGhvcml0eTE3MDUGA1UE
# AxMuaHR0cDovL0h1ZGRsZWRNYXNzZXMub3JnIENlcnRpZmljYXRlIEF1dGhvcml0
# eTEnMCUGCSqGSIb3DQEJARYYSmF5a3VsQEh1ZGRsZWRNYXNzZXMub3JnAgkAs+mo
# OP3CnvEwCQYFKw4DAhoFAKB4MBgGCisGAQQBgjcCAQwxCjAIoAKAAKECgAAwGQYJ
# KoZIhvcNAQkDMQwGCisGAQQBgjcCAQQwHAYKKwYBBAGCNwIBCzEOMAwGCisGAQQB
# gjcCARUwIwYJKoZIhvcNAQkEMRYEFPtIbR2Ib33ue+orAhek3JvLdPn7MA0GCSqG
# SIb3DQEBAQUABIICAJxGyC9H8QzR7pAW2U6p4ZwEN6ACNwdOg6etL8oKm6kHh/pr
# wVSKveDeErRQJ2I/ZU5sW147870fsUpQIoz7HmSd3iYWw9Ew7/pan+iXFtEJkWfZ
# QVAa1BAGsUFUQ0F+BoLD2EoRIHOBjt2qiJIiVUoHGTOo26DYSeCBeHXpSXCNcK6c
# R79WQ8QM6d4lsnrR01GOZI5XAUQPTVSMnQbkoQJCE/jFcrHmoLSwFO2LNGhFGhyV
# NO9OAGBD3WKCIoBpZfJ2xZS8byDUmk47h4NCG33gCwLsm4P138CZ7l0h+5LxvXOx
# 8BjcmmdwjIKny18EHb6X7qsfL6aYBwiXFzKdW1mc6l1oEtYpyeCbUMZDQA31nZ7Y
# Y3hRWP9SDxzdArVGH5uxo2RKgXY4Yqxq+rWRY9W4WYlWGbfe2SVnBBLnkeAyeLtR
# 2L59g+BuTqlCRuT1rKabW3AgquJHG9kuO1RsDefNlTjda/+NgwIciQONQDbfFHs+
# 23G3pEFGSmdgQtvZXlR+02xgzogQwLuSzDUzyVVe0ow1nQ26vTmMBlXVN+YlOoj/
# ZENATe2mDDh6G4zoWepr/GTeMH61d1Fwnq4VDd3O6m/jogNTUz5XQzqUvsABIccr
# mC3oC7NgymO55FZDX/ecU/Hkb8e55U3roHFsyWz+XZaonkFmgPVMIQGfG5lH
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Google Chromium Download.ps1
|
Google Chromium Download.ps1
|
<#
.Synopsis
Download Google Chromium if there is a later build.
.Description
Download Google Chromium if there is a later build.
#>
Set-StrictMode -Version Latest
Import-Module bitstransfer
# comment out when not debugging
$VerbosePreference = "Continue"
#$VerbosePreference = "SilentlyContinue"
$versionFile = "$Env:temp\\latestChromiumVersion.txt"
$installedChromiumVersion = 0
trap [Exception] {
write-host
write-error $("TRAPPED: " + $_.Exception.GetType().FullName);
write-error $("TRAPPED: " + $_.Exception.Message);
[string]($installedChromiumVersion) > $versionFile
exit;
}
if (Test-Path $versionFile)
{ $installedChromiumVersion = [int32] (cat $versionFile) }
$latestChromiumBuildURL ="http://build.chromium.org/f/chromium/snapshots/chromium-rel-xp"
Start-BitsTransfer "$latestChromiumBuildURL/LATEST" $versionFile
$latestChromiumVersion = [int32] (cat $versionFile)
if ($installedChromiumVersion -eq $latestChromiumVersion)
{
Write-Verbose "Exiting... Version $installedChromiumVersion is the latest."
return
}
$installerAppName = "mini_installer"
$installer = "$Env:temp\\$installerAppName.exe"
Write-Verbose "Initiating download of new version $latestChromiumVersion"
Start-BitsTransfer "$latestChromiumBuildURL/$latestChromiumVersion/mini_installer.exe" $installer
Write-Verbose "Installing new version of Chromium"
Invoke-Item $installer
$installerRunning = 1
while (!($installerRunning -eq $null))
{
sleep 5
$installerRunning = ( Get-Process | ? {$_.ProcessName -match "$installerAppName"} )
}
Write-Verbose "New Chromium Installed! Please restart the Chromium browser"
|
PowerShellCorpus/PoshCode/Findup_29.ps1
|
Findup_29.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"], "*.*", files, optionsbools["/recurse"], optionsbools["/xj"]);
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.WriteLine("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.ToLower()) == 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, List<FileInfo> returnList, Boolean recursiveFlag = true, Boolean xj = true)
{
foreach (string d in pathRec) { getFiles(d, searchPattern, returnList, recursiveFlag, xj); }
}
private static void getFiles(string[] pathRec, string searchPattern, List<FileInfo> returnList, Boolean recursiveFlag = true, Boolean xj = true)
{
foreach (string d in pathRec) { getFiles(d, searchPattern, returnList, recursiveFlag, xj); }
}
private static void getFiles(string pathRec, string searchPattern, List<FileInfo> returnList, Boolean recursiveFlag = true, Boolean xj = true)
{
string dirPart;
string filePart;
if (File.Exists(pathRec))
{
try
{
FileInfo addf = (new FileInfo(pathRec));
if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) || !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) || !xj)
foreach (FileInfo addf in (Dir.GetFiles(searchPattern)))
{
if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) || !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, returnList, recursiveFlag, !xj); }
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, returnList, recursiveFlag, xj);
return;
}
}
WriteErr("Invalid file path, directory path, file specification, or program option specified: " + pathRec);
}
}
}
}
|
PowerShellCorpus/PoshCode/finddupe_17.ps1
|
finddupe_17.ps1
|
# new version has more error handling, "-delete" and "-noprompt" options.
function Get-MD5([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]'))
{
$stream = $null;
$cryptoServiceProvider = [System.Security.Cryptography.MD5CryptoServiceProvider];
$hashAlgorithm = new-object $cryptoServiceProvider
$stream = $file.OpenRead();
$hashByteArray = $hashAlgorithm.ComputeHash($stream);
$stream.Close();
## We have to be sure that we close the file stream if any exceptions are thrown.
trap
{
if ($stream -ne $null)
{
$stream.Close();
}
break;
}
foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }}
return [string]$result;
}
$starttime=[datetime]::now
write-host "Usage: finddupe.ps1 <directory/file #1> <directory/file #2> ... <directory/file #N> [-delete] [-noprompt]"
$matches = 0 # initialize number of matches for summary.
$filesdeleted = 0 # number of files deleted.
$bytesrec = 0 # Number of bytes recovered.
$del = $false # delete duplicates
$noprompt = $false # delete without prompting toggle
$currentdir = $true # work on current directory by default
$args | ?{$_ -eq "-delete"} |%{$del=$true}
$args | ?{$_ -eq "-noprompt"} | %{$noprompt=$true}
$files=@(dir -ea 0 -recurse ($args | ?{$_ -ne "-delete" -and $_ -ne "-noprompt"} |?{if ((get-item -ea 0 $_) -eq $null){write-host "Error: " -f red -nonewline; write-host "$_ not found.";exit} else {$_}})|?{$_.psiscontainer -ne $true} )
if ($files.count -eq 0) {"No files found.`a";exit}
for ($i=0;$i -ne $files.count; $i++) # Cycle thru all files
{
if ($files[$i] -eq $null) {continue}
$filecheck = $files[$i]
$files[$i] = $null
for ($c=0;$c -ne $files.count; $c++)
{
if ($files[$c] -eq $null) {continue}
# write-host "Comparing $filecheck and $($files[$c]) `r" -nonewline
if ($filecheck.length -eq $files[$c].length)
{
#write-host "Comparing MD5 of $($filecheck.fullname) and $($files[$c].fullname) `r" -nonewline
if ($filecheck.md5 -eq $null)
{
$md5 = (get-md5 $filecheck.fullname)
$filecheck = $filecheck | %{add-member -inputobject $_ -name MD5 -membertype noteproperty -value $md5 -passthru}
}
if ($files[$c].md5 -eq $null)
{
$md5 = (get-md5 $files[$c].fullname)
$files[$c] = $files[$c] | %{add-member -inputobject $_ -name MD5 -membertype noteproperty -value $md5 -passthru}
}
if ($filecheck.md5 -eq $files[$c].md5)
{
write-host "Size and MD5 match: " -fore red -nonewline
write-host "`"$($filecheck.fullname)`"" -nonewline
write-host " and " -nonewline
write-host "`"$($files[$c].fullname)`""
$matches += 1
if ($del -eq $true)
{
if ($noprompt -eq $true)
{
del $files[$c].fullname
write-host "Deleted duplicate: " -f red -nonewline
write-host "$($files[$c].fullname)."
}
else
{
del $files[$c].fullname -confirm
}
if ((get-item -ea 0 $files[$c].fullname) -eq $null)
{
$filesdeleted += 1
$bytesrec += $files[$c].length
}
}
$files[$c] = $null
}
}
}
}
write-host ""
write-host "Number of Files checked: $($files.count)." # Display useful info; files checked and matches found.
write-host "Number of duplicates found: $matches."
Write-host "Number of duplicates deleted: $filesdeleted." # Display number of duplicate files deleted and bytes recovered.
write-host "$bytesrec bytes recovered."
write-host ""
write-host "Time to run: $(([datetime]::now)-$starttime|select hours, minutes, seconds, milliseconds)"
write-host ""
|
PowerShellCorpus/PoshCode/Get-LeaderBoard_2.ps1
|
Get-LeaderBoard_2.ps1
|
<#
.SYNOPSIS
Pulls down the leaderboards for the 2011 Scripting Games
.DESCRIPTION
Quick and dirty script to pull down the leaderboards for the 2011 scripting games.
Can choose either beginner or advanced via a command line switch. To see the output
in a table, you must pipe to "format-table -autosize" or "out-gridview"
.PARAMETER Level
The leaderboard to parse
.EXAMPLE
Get-LeaderBoard -Level Beginner
Retrieves the beginner leaderboard.
.EXAMPLE
Get-LeaderBoard -Level Advanced
Retrieves the advanced leaderboard
.EXAMPLE
Get-LeaderBoard Advanced | Format-Table -Autosize
Retrieves the advanced leaderboard and returns values in a table
.EXAMPLE
Get-LeaderBoard Advanced | Format-Table -Autosize
Retrieves the advanced leaderboard and displays a table.
.EXAMPLE
Get-LeaderBoard Advanced | where { $_.UserName -eq "My Name" }
Retrieves status for user "My Name"
.NOTES
NAME: Get-LeaderBoard
VERSION: 1.01
AUTHOR: Alex McFarland
LASTEDIT: 04/23/2011
-Added rankings to output. This unfortunately requires use of ft - auto to get
decent looking output.
-Incorporated regex changes to to issues points out by Scott Alvarino. Was
missing foreign language characters and periods.
#>
function Get-LeaderBoard
{
param(
[Parameter(
Position = 0,
Mandatory = $true,
HelpMessage = "Leaderboard to parse. Advanced, or Beginner")]
[ValidateSet("Advanced","Beginner")]
[String]$Level="Advanced"
)
# create a webclient
$WebClient = New-Object System.Net.WebClient
# download the page
$LeaderPage = $WebClient.DownloadString("http://2011sg.poshcode.org/Reports/TopUsers?filter=$Level")
# create a horrific looking regular expression
$RegEx = '<a href="/Scripts/By/\\d{1,3}">(?<UserName>[\\w\\s\\S]*)</a>\\s*</td>\\s*<td>\\s*(?<TotalPoints>\\d{1,2}\\.\\d{1,2})\\s*</td>\\s*<td>\\s*(?<ScriptsRated>\\d*)'
# initialize counter for ratings
$i = 1
# split the page into seperate objects so we can parse each invidual
$LeaderPage -split "<tr>" | ForEach {
# match the regex
$_ -match $RegEx | Out-Null
# create a new PSObject, supply a hashtable with the properties
if (-not $Matches.UserName -eq "")
{
New-Object PSObject -Property @{
"Ranking" = $i++
"UserName" = $Matches.UserName
"ScriptsRated" = $Matches.ScriptsRated
"TotalPoints" = $Matches.TotalPoints
"AverageRating" = if ($Matches.ScriptsRated -gt 0)
{
# get average round to two decimal places
"{0:N2}" -f ($Matches.TotalPoints / $Matches.ScriptsRated)
}
}
}
# clear matches
if ($Matches) { $Matches.Clear() }
# get our objects in a specific order.
} | select -Unique Ranking,UserName,ScriptsRated,AverageRating,TotalPoints
}
|
PowerShellCorpus/PoshCode/Backup-EventLogs_1.ps1
|
Backup-EventLogs_1.ps1
|
Function Backup-EventLogs
{
<#
.SYNOPSIS
Backup 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
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
)
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 $?
}
}
|
PowerShellCorpus/PoshCode/Reflection Module _1.1.ps1
|
Reflection Module _1.1.ps1
|
#requires -version 2.0
# ALSO REQUIRES Autoload for some functionality (Latest version: http://poshcode.org/3173)
# You should create a Reflection.psd1 with the contents:
# @{ ModuleToProcess="Reflection.psm1"; RequiredModules = @("Autoload"); GUID="64b5f609-970f-4e65-b02f-93ccf3e60cbb"; ModuleVersion="4.5.0.0" }
#History:
# 1.0 - First public release (March 19, 2010)
# 2.0 - Private Build
# - Included the Accelerator function inline
# - Added a few default aliases
# 3.0 - September 3, 2010
# - Included the New-ConstructorFunction feature (ripped from PowerBoots to serve a more generic and powerful purpose!)
# - New-ConstructorFunction and Import-ConstructorFunctions depend on the Autoload Module: http://poshcode.org/2312
# 3.5 - January 28, 2011
# - Fixed several bugs in Add-Assembly, Get-Assembly, Get-MemberSignature
# - Fixed alias exporting so aliases will show up now
# - Added New-ModuleManifestFromSnapin to create module manifests from snapin assemblies
# 3.6 - January 28, 2011
# - Added *basic* support for CustomPSSnapin to New-ModuleManifestFromSnapin
# 3.7 - February 1, 2001 - NOT RELEASED
# - Added [TransformAttribute] type
# 3.8 - May 4, 2011 - NOT RELEASED
# - Huge rewrite of Invoke-Generic (also published separately: http://poshcode.org/2649)
# 3.9 - May 25, 2011 - NOT RELEASED
# - Added "Interface" parameter to Get-Type
# 4.0 - Sept 27, 2011
# - Fix conflicts with PowerShell 3
# 4.1 - Oct 27, 2011
# - Fix PowerShell 3 changes so they don't break PowerShell 2 (huy!)
# 4.2 - Added Add-Enum and Add-Struct -- even though they're really more CodeGen than reflection
#
# 4.5 - March 2, 2013
# - Added Test-AssignableToGeneric and Get-ExtensionMethod
# - Updated Read-Choice from the standalone script I use.
Add-Type -TypeDefinition @"
using System;
using System.ComponentModel;
using System.Management.Automation;
using System.Collections.ObjectModel;
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class TransformAttribute : ArgumentTransformationAttribute {
private ScriptBlock _scriptblock;
private string _noOutputMessage = "Transform Script had no output.";
public override string ToString() {
return string.Format("[Transform(Script='{{{0}}}')]", Script);
}
public override Object Transform( EngineIntrinsics engine, Object inputData) {
try {
Collection<PSObject> output =
engine.InvokeCommand.InvokeScript( engine.SessionState, Script, inputData );
if(output.Count > 1) {
Object[] transformed = new Object[output.Count];
for(int i =0; i < output.Count;i++) {
transformed[i] = output[i].BaseObject;
}
return transformed;
} else if(output.Count == 1) {
return output[0].BaseObject;
} else {
throw new ArgumentTransformationMetadataException(NoOutputMessage);
}
} catch (ArgumentTransformationMetadataException) {
throw;
} catch (Exception e) {
throw new ArgumentTransformationMetadataException(string.Format("Transform Script threw an exception ('{0}'). See `$Error[0].Exception.InnerException.InnerException for more details.",e.Message), e);
}
}
public TransformAttribute() {
this.Script = ScriptBlock.Create("{`$args}");
}
public TransformAttribute( ScriptBlock Script ) {
this.Script = Script;
}
public ScriptBlock Script {
get { return _scriptblock; }
set { _scriptblock = value; }
}
public string NoOutputMessage {
get { return _noOutputMessage; }
set { _noOutputMessage = value; }
}
}
"@
function Get-Type {
<#
.Synopsis
Gets the types that are currenty loaded in .NET, or gets information about a specific type
.Description
Gets information about one or more loaded types, or gets the possible values for an enumerated type or value.
.Example
Get-Type
Gets all loaded types (takes a VERY long time to print out)
.Example
Get-Type -Assembly ([PSObject].Assembly)
Gets types from System.Management.Automation
.Example
[Threading.Thread]::CurrentThread.ApartmentState | Get-Type
Gets all of the possible values for the ApartmentState property
.Example
[Threading.ApartmentState] | Get-Type
Gets all of the possible values for an apartmentstate
#>
[CmdletBinding(DefaultParameterSetName="Assembly")]
param(
# The Assemblies to search for types.
# Can be an actual Assembly object or a regex to pass to Get-Assembly.
[Parameter(ValueFromPipeline=$true)]
[PsObject[]]$Assembly,
# The type name(s) to search for (wildcard patterns allowed).
[Parameter(Mandatory=$false,Position=0)]
[SupportsWildCards()]
[String[]]$TypeName,
# A namespace to restrict where we selsect types from (wildcard patterns allowed).
[Parameter(Mandatory=$false)]
[SupportsWildCards()]
[String[]]$Namespace,
# A Base type they should derive from (wildcard patterns allowed).
[Parameter(Mandatory=$false)]
[SupportsWildCards()]
[String[]]$BaseType,
# An interface they should implement (wildcard patterns allowed).
[Parameter(Mandatory=$false)]
[SupportsWildCards()]
[String[]]$Interface,
# An Custom Attribute which should decorate the class
[Parameter(Mandatory=$false)]
[SupportsWildCards()]
[String[]]$Attribute,
# The enumerated value to get all of the possible values of
[Parameter(ParameterSetName="Enum")]
[PSObject]$Enum,
# Causes Private types to be included
[Parameter()][Alias("Private","ShowPrivate")]
[Switch]$Force
)
process {
if($psCmdlet.ParameterSetName -eq 'Enum') {
if($Enum -is [Enum]) {
[Enum]::GetValues($enum.GetType())
} elseif($Enum -is [Type] -and $Enum.IsEnum) {
[Enum]::GetValues($enum)
} else {
throw "Specified Enum is neither an enum value nor an enumerable type"
}
}
else {
if($Assembly -as [Reflection.Assembly[]]) {
## This is what we expected, move along
} elseif($Assembly -as [String[]]) {
$Assembly = Get-Assembly $Assembly
} elseif(!$Assembly) {
$Assembly = [AppDomain]::CurrentDomain.GetAssemblies()
}
:asm foreach ($asm in $assembly) {
Write-Verbose "Testing Types from Assembly: $($asm.Location)"
if ($asm) {
trap {
if( $_.Exception.LoaderExceptions -and $_.Exception.LoaderExceptions[0] -is [System.IO.FileNotFoundException] ) {
$PSCmdlet.WriteWarning( "Unable to load some types from $($asm.Location), required assemblies were not found. Use -Debug to see more detail")
continue asm
}
Write-Error "Unable to load some types from $($asm.Location). Try with -Debug to see more detail"
Write-Debug $( $_.Exception.LoaderExceptions | Out-String )
continue asm
}
$asm.GetTypes() | Where {
( $Force -or $_.IsPublic ) -AND
( !$Namespace -or $( foreach($n in $Namespace) { $_.Namespace -like $n } ) ) -AND
( !$TypeName -or $( foreach($n in $TypeName) { $_.Name -like $n -or $_.FullName -like $n } ) -contains $True ) -AND
( !$Attribute -or $( foreach($n in $Attribute) { $_.CustomAttributes | ForEach { $_.AttributeType.Name -like $n -or $_.AttributeType.FullName -like $n } } ) -contains $True ) -AND
( !$BaseType -or $( foreach($n in $BaseType) { $_.BaseType -like $n } ) -contains $True ) -AND
( !$Interface -or @( foreach($n in $Interface) { $_.GetInterfaces() -like $n } ).Count -gt 0 )
}
}
}
}
}
}
function Add-Assembly {
#.Synopsis
# Load assemblies
#.Description
# Load assemblies from a folder
#.Parameter Path
# Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.).
#.Parameter Passthru
# Returns System.Runtime objects that represent the types that were added. By default, this cmdlet does not generate any output.
# Aliased to -Types
#.Parameter Recurse
# Gets the items in the specified locations and in all child items of the locations.
#
# Recurse works only when the path points to a container that has child items, such as C:\\Windows or C:\\Windows\\*, and not when it points to items that do not have child items, such as C:\\Windows\\*.dll
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true, Position=0)]
[Alias("PSPath")]
[string[]]$Path = ".",
[Alias("Types")]
[Switch]$Passthru,
[Switch]$Recurse
)
process {
foreach($file in Get-ChildItem $Path -Filter *.dll -Recurse:$Recurse) {
Add-Type -Path $file.FullName -Passthru:$Passthru | Where { $_.IsPublic }
}
}
}
function Get-Assembly {
<#
.Synopsis
Get a list of assemblies available in the runspace
.Description
Returns AssemblyInfo for all the assemblies available in the current AppDomain, optionally filtered by partial name match
.Parameter Name
A regex to filter the returned assemblies. This is matched against the .FullName or Location (path) of the assembly.
#>
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true, Position=0)]
[string[]]$Name = ''
)
process {
[appdomain]::CurrentDomain.GetAssemblies() | Where {
$Assembly = $_
if($Name){
$(
foreach($n in $Name){
if(Resolve-Path $n -ErrorAction 0) {
$n = [Regex]::Escape( (Resolve-Path $n).Path )
}
$Assembly.FullName -match $n -or $Assembly.Location -match $n -or ($Assembly.Location -and (Split-Path $Assembly.Location) -match $n)
}
) -contains $True
} else { $true }
}
}
}
function Update-PSBoundParameters {
#.Synopsis
# Ensure a parameter value is set
#.Description
# Update-PSBoundParameters takes the name of a parameter, a default value, and optionally a min and max value, and ensures that PSBoundParameters has a value for it.
#.Parameter Name
# The name (key) of the parameter you want to set in PSBoundParameters
#.Parameter Default
# A Default value for the parameter, in case it's not already set
#.Parameter Min
# The Minimum allowed value for the parameter
#.Parameter Max
# The Maximum allowed value for the parameter
#.Parameter PSBoundParameters
# The PSBoundParameters you want to affect (this picks the local PSBoundParameters object, so you shouldn't have to set it)
Param(
[Parameter(Mandatory=$true, Position=0)]
[String]$Name,
[Parameter(Mandatory=$false, Position=1)]
$Default,
[Parameter()]
$Min,
[Parameter()]
$Max,
[Parameter(Mandatory=$true, Position=99)]
$PSBoundParameters=$PSBoundParameters
)
end {
$outBuffer = $null
## If it's not set, and you passed a default, we set it to the default
if($Default) {
if (!$PSBoundParameters.TryGetValue($Name, [ref]$outBuffer))
{
$PSBoundParameters[$Name] = $Default
}
}
## If you passed a $max, and it's set greater than $max, we set it to $max
if($Max) {
if ($PSBoundParameters.TryGetValue($Name, [ref]$outBuffer) -and $outBuffer -gt $Max)
{
$PSBoundParameters[$Name] = $Max
}
}
## If you passed a $min, and it's set less than $min, we set it to $min
if($Min) {
if ($PSBoundParameters.TryGetValue($Name, [ref]$outBuffer) -and $outBuffer -lt $Min)
{
$PSBoundParameters[$Name] = $Min
}
}
$PSBoundParameters
}
}
function Get-Constructor {
<#
.Synopsis
Returns RuntimeConstructorInfo for the (public) constructor methods of the specified Type.
.Description
Get the RuntimeConstructorInfo for a type and add members "Syntax," "SimpleSyntax," and "Definition" to each one containing the syntax information that can use to call that constructor.
.Parameter Type
The type to get the constructor for
.Parameter Force
Force inclusion of Private and Static constructors which are hidden by default.
.Parameter NoWarn
Serves as the replacement for the broken -WarningAction. If specified, no warnings will be written for types without public constructors.
.Example
Get-Constructor System.IO.FileInfo
Description
-----------
Gets all the information about the single constructor for a FileInfo object.
.Example
Get-Type System.IO.*info mscorlib | Get-Constructor -NoWarn | Select Syntax
Description
-----------
Displays the constructor syntax for all of the *Info objects in the System.IO namespace.
Using -NoWarn supresses the warning about System.IO.FileSystemInfo not having constructors.
.Example
$path = $pwd
$driveName = $pwd.Drive
$fileName = "$Profile"
Get-Type System.IO.*info mscorlib | Get-Constructor -NoWarn | ForEach-Object { Invoke-Expression $_.Syntax }
Description
-----------
Finds and invokes the constructors for DirectoryInfo, DriveInfo, and FileInfo.
Note that we pre-set the parameters for the constructors, otherwise they would fail with null arguments, so this example isn't really very practical.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$true, Position=0)]
[Alias("ParameterType")]
[Type]$Type,
[Switch]$Force,
[Switch]$NoWarn
)
process {
$type.GetConstructors() | Where-Object { $Force -or $_.IsPublic -and -not $_.IsStatic } -OutVariable ctor
if(!$ctor -and !$NoWarn) { Write-Warning "There are no public constructors for $($type.FullName)" }
}
}
function Get-ExtensionMethod {
<#
.Synopsis
Finds Extension Methods which target the specified type
.Example
Get-ExtensionMethod String
Finds all extension methods which target strings
#>
[CmdletBinding()]
param(
# The type name to find Extension Methods for
[Parameter(Mandatory=$false,Position=0)]
[SupportsWildCards()]
[String[]]$TargetTypeName,
# A filter for the Extension Method name
[Parameter(Mandatory=$false)]
[SupportsWildCards()]
[String[]]$Name = "*",
# The type to search for Extension Methods (defaults to search all types)
[Parameter(Mandatory=$false,Position=99)]
[SupportsWildCards()]
[String[]]$TypeName = "*"
)
process {
Get-Type -TypeName $TypeName -Attribute ExtensionAttribute |
Get-Method -Name $Name -BindingFlags "Static,Public,NonPublic" -Attribute ExtensionAttribute |
ForEach-Object {
$Method = $_
$ParameterType = $_.GetParameters()[0].ParameterType
ForEach($T in $TargetTypeName) {
Write-Verbose "Is '$T' a '$ParameterType'?"
if($ParameterType.Name -like $T -or $ParameterType.FullName -like $T) {
Write-Verbose "The name '$T' matches '$ParameterType'"
Add-Member -Input $Method -Type NoteProperty -Name ParamBlock -Value (Get-MemberSignature $Method -ParamBlock) -Force
Write-Output $Method
continue
}
if($ParameterType.IsGenericType) {
$interface = $null
if(Test-AssignableToGeneric $T $ParameterType -interface ([ref]$interface)) {
# if([GenericHelper]::IsAssignableToGenericType( $T, $ParameterType )) {
Write-Verbose "'$T' is a generic that's assignable to '$ParameterType'"
Add-Member -Input $Method -Type NoteProperty -Name Extends -Value $interface.Value -Force
Add-Member -Input $Method -Type NoteProperty -Name ParamBlock -Value (Get-MemberSignature $Method -GenericArguments $interface.GetGenericArguments() -ParamBlock) -Force
Write-Output $Method
continue
}
} else {
if($ParameterType.IsAssignableFrom($T)) {
Write-Verbose "'$ParameterType' is assignable from '$T'"
Add-Member -Input $Method -Type NoteProperty -Name ParamBlock -Value (Get-MemberSignature $Method -ParamBlock) -Force
Write-Output $Method
continue
}
}
}
}
}
}
function Test-AssignableToGeneric {
<#
.Synopsis
Determine if a specific type can be cast to the given generic type
#>
param(
# The concrete type you want to test generics against
[Parameter(Position=0, Mandatory = $true)]
[Type]$type,
# A Generic Type to test
[Parameter(ValueFromPipeline=$true, Position=1, Mandatory = $true)]
[Type]$genericType,
# Check the GenericTypeDefinition of the GenericType (in case it's typed)
[Switch]$force,
# If the type is assignable because of an interface, return that interface here
[Parameter(Position=2)]
[ref]$interface = [ref]$null
)
process {
$interfaces = $type.GetInterfaces()
if($type.IsGenericType -and ($type.GetGenericTypeDefinition().equals($genericType))) {
return $true
}
foreach($i in $interfaces)
{
if($i.IsGenericType -and $i.GetGenericTypeDefinition().Equals($genericType)) {
$interface.Value = $i
return $true
}
if($i.IsGenericType -and $i.GetGenericTypeDefinition().Equals($genericType.GetGenericTypeDefinition())) {
$genericTypeArgs = @($genericType.GetGenericArguments())[0]
if(($genericTypeArgs.IsGenericParameter -and
$genericTypeArgs.BaseType.IsAssignableFrom( @($i.GetGenericArguments())[0] ) ) -or
$genericTypeArgs.IsAssignableFrom( @($i.GetGenericArguments())[0] )) {
$interface.Value = $i
return $true
}
}
}
if($force -and $genericType -ne $genericType.GetGenericTypeDefinition()) {
if(Test-AssignableToGeneric $type $genericType.GetGenericTypeDefinition()) {
return $true
}
}
$base = $type.BaseType
if(!$base) { return $false }
Test-AssignableToGeneric $base $genericType
}
}
function Get-Method {
<#
.Synopsis
Returns MethodInfo for the (public) methods of the specified Type.
.Description
Get the MethodInfo for a type and add members "Syntax," "SimpleSyntax," and "Definition" to each one containing the syntax information that can use to call that method.
.Parameter Type
.Parameter Name
.Parameter Force
#>
[CmdletBinding(DefaultParameterSetName="Type")]
param(
# The type to get methods from
[Parameter(ParameterSetName="Type", Mandatory=$true, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$true, Position=0)]
[Type]$Type,
# The name(s) of the method(s) you want to retrieve (Accepts Wildcard Patterns)
[Parameter(Mandatory=$false, Position=1)]
[SupportsWildCards()]
[PSDefaultValue(Help='*')]
[String[]]$Name ="*",
# Force inclusion of Private methods and property accessors which are hidden by default.
[Switch]$Force,
# The Binding Flags filter the output. defaults to returning all methods, static or instance
[PSDefaultValue(Help='Instance,Static,Public')]
[System.Reflection.BindingFlags]$BindingFlags = $(if($Force){"Instance,Static,Public,NonPublic"} else {"Instance,Static,Public"}),
# An Custom Attribute which should decorate the class
[Parameter(Mandatory=$false)]
[SupportsWildCards()]
[String[]]$Attribute
)
process {
Write-Verbose "[$($type.FullName)].GetMethods(`"$BindingFlags`")"
Write-Verbose "[$($type.FullName)].GetConstructors(`"$BindingFlags`")"
Write-Verbose "Filter by Name -like '$Name'"
$Type.GetMethods($BindingFlags) + $type.GetConstructors($BindingFlags) | Where-Object {
# Hide the Property accessor methods
($Force -or !$_.IsSpecialName -or $_.Name -notmatch "^get_|^set_") -AND
# And Filter by Name, if necessary
($Name -eq "*" -or ($( foreach($n in $Name) { $_.Name -like $n } ) -contains $True)) -AND
(!$Attribute -or $( foreach($n in $Attribute) { $_.CustomAttributes | ForEach { $_.AttributeType.Name -like $n -or $_.AttributeType.FullName -like $n } } ) -contains $True )
}
}
}
if(!($RMI = Get-TypeData System.Reflection.RuntimeMethodInfo) -or !$RMI.Members.ContainsKey("TypeName")) {
Update-TypeData -TypeName System.Reflection.RuntimeMethodInfo -MemberName "TypeName" -MemberType ScriptProperty -Value { $this.ReflectedType.FullName }
Update-TypeData -TypeName System.Reflection.RuntimeMethodInfo -MemberName "Definition" -MemberType ScriptProperty -Value { Get-MemberSignature $this -Simple }
Update-TypeData -TypeName System.Reflection.RuntimeMethodInfo -MemberName "Syntax" -MemberType AliasProperty -Value "Definition"
Update-TypeData -TypeName System.Reflection.RuntimeMethodInfo -MemberName "SafeSyntax" -MemberType ScriptProperty -Value { Get-MemberSignature $this }
}
function Get-MemberSignature {
<#
.Synopsis
Get the powershell signature for calling a member.
#>
[CmdletBinding(DefaultParameterSetName="CallSignature")]
param(
# The Method we're getting the signature for
[Parameter(ValueFromPipeline=$true,Mandatory=$true,Position=0)]
[System.Reflection.MethodBase]$MethodBase,
[Parameter(Mandatory=$false, Position=1)]
[Type[]]$GenericArguments,
# Return the simplified markup
[Parameter(ParameterSetName="CallSignature")]
[Switch]$Simple,
# Return a param block
[Parameter(ParameterSetName="ParamBlock")]
[Switch]$ParamBlock
)
process {
if($PSCmdlet.ParameterSetName -eq "ParamBlock") { $Simple = $true }
$parameters = $(
foreach($param in $MethodBase.GetParameters()) {
# Write-Host $param.ParameterType.FullName.TrimEnd('&'), $param.Name -fore cyan
# Write-Verbose "$($param.ParameterType.UnderlyingSystemType.FullName) - $($param.ParameterType)"
$paramType = $param.ParameterType
Write-Verbose "$(if($paramType.IsGenericType){'Generic: '})$($GenericArguments)"
if($paramType.IsGenericType -and $GenericArguments) {
try {
$paramType = $paramType.GetGenericTypeDefinition().MakeGenericType( $GenericArguments )
} catch { continue }
}
if($paramType.Name.EndsWith('&')) { $ref = '[ref]' } else { $ref = '' }
if($paramType.IsArray) { $array = ',' } else { $array = '' }
if($ParamBlock) {
'[Parameter(Mandatory=$true)]{0}[{1}]${2}' -f $ref, $paramType.ToString().TrimEnd('&'), $param.Name
} elseif($Simple) {
'[{0}] {2}' -f $paramType.ToString().TrimEnd('&'), $param.Name
} else {
'{0}({1}[{2}]${3})' -f $ref, $array, $paramType.ToString().TrimEnd('&'), $param.Name
}
}
)
if($PSCmdlet.ParameterSetName -eq "ParamBlock") {
$parameters -join ', '
} elseif($MethodBase.IsConstructor) {
"New-Object $($MethodBase.ReflectedType.FullName) $($parameters -join ', ')"
} elseif($Simple) {
"$($MethodBase.ReturnType.FullName) $($MethodBase.Name)($($parameters -join ', '))"
} elseif($MethodBase.IsStatic) {
"[$($MethodBase.ReturnType.FullName)] [$($MethodBase.ReflectedType.FullName)]::$($MethodBase.Name)($($parameters -join ', '))"
} else {
"[$($MethodBase.ReturnType.FullName)] `$$($MethodBase.ReflectedType.Name)Object.$($MethodBase.Name)($($parameters -join ', '))"
}
}
}
function Read-Choice {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, ValueFromRemainingArguments=$true)]
[hashtable[]]$Choices,
[Parameter(Mandatory=$False)]
[string]$Caption = "Please choose!",
[Parameter(Mandatory=$False)]
[string]$Message = "Choose one of the following options:",
[Parameter(Mandatory=$False)]
[int[]]$Default = 0,
[Switch]$MultipleChoice,
[Switch]$Passthru
)
begin {
[System.Collections.DictionaryEntry[]]$choices = $choices | % { $_.GetEnumerator() }
}
process {
$Descriptions = [System.Management.Automation.Host.ChoiceDescription[]]( $(
foreach($choice in $choices) {
New-Object System.Management.Automation.Host.ChoiceDescription $choice.Key,$choice.Value
}
) )
if(!$MultipleChoice) { [int]$Default = $Default[0] }
[int[]]$Answer = $Host.UI.PromptForChoice($Caption,$Message,$Descriptions,$Default)
if($Passthru) {
Write-Verbose "$Answer"
Write-Output $Descriptions[$Answer]
} else {
Write-Output $Answer
}
}
}
function Read-Choice {
<#
.Synopsis
Prompt the user for a choice, and return the (0-based) index of the selected item
.Parameter Message
This is the prompt that will be presented to the user. Basically, the question you're asking.
.Parameter Choices
An array of strings representing the choices (or menu items), with optional ampersands (&) in them to mark (unique) characters which can be used to select each item.
.Parameter ChoicesWithHelp
A Hashtable where the keys represent the choices (or menu items), with optional ampersands (&) in them to mark (unique) characters which can be used to select each item, and the values represent help text to be displayed to the user when they ask for help making their decision.
.Parameter Default
The (0-based) index of the menu item to select by default (defaults to zero).
.Parameter MultipleChoice
Prompt the user to select more than one option. This changes the prompt display for the default PowerShell.exe host to show the options in a column and allows them to choose multiple times.
Note: when you specify MultipleChoice you may also specify multiple options as the default!
.Parameter Caption
An additional caption that can be displayed (usually above the Message) as part of the prompt
.Parameter Passthru
Causes the Choices objects to be output instead of just the indexes
.Example
Read-Choice "WEBPAGE BUILDER MENU" "&Create Webpage","&View HTML code","&Publish Webpage","&Remove Webpage","E&xit"
.Example
[bool](Read-Choice "Do you really want to do this?" "&No","&Yes" -Default 1)
This example takes advantage of the 0-based index to convert No (0) to False, and Yes (1) to True. It also specifies YES as the default, since that's the norm in PowerShell.
.Example
Read-Choice "Do you really want to delete them all?" @{"&No"="Do not delete all files. You will be prompted to delete each file individually."; "&Yes"="Confirm that you want to delete all of the files"}
Note that with hashtables, order is not guaranteed, so "Yes" will probably be the first item in the prompt, and thus will output as index 0. Because of thise, when a hashtable is passed in, we default to Passthru output.
#>
[CmdletBinding(DefaultParameterSetName="HashtableWithHelp")]
param(
[Parameter(Mandatory=$true, Position = 10, ParameterSetName="HashtableWithHelp")]
[Hashtable]$ChoicesWithHelp
,
[Parameter(Mandatory=$true, Position = 10, ParameterSetName="StringArray")]
[String[]]$Choices
,
[Parameter(Mandatory=$False)]
[string]$Caption = "Please choose!"
,
[Parameter(Mandatory=$False, Position=0)]
[string]$Message = "Choose one of the following options:"
,
[Parameter(Mandatory=$False)]
[int[]]$Default = 0
,
[Switch]$MultipleChoice
,
[Switch]$Passthru
)
begin {
if($ChoicesWithHelp) {
[System.Collections.DictionaryEntry[]]$choices = $ChoicesWithHelp.GetEnumerator() | %{$_}
}
}
process {
$Descriptions = [System.Management.Automation.Host.ChoiceDescription[]]( $(
if($choices -is [String[]]) {
foreach($choice in $choices) {
New-Object System.Management.Automation.Host.ChoiceDescription $choice
}
} else {
foreach($choice in $choices) {
New-Object System.Management.Automation.Host.ChoiceDescription $choice.Key, $choice.Value
}
}
) )
# Passing an array as the $Default triggers multiple choice prompting.
if(!$MultipleChoice) { [int]$Default = $Default[0] }
[int[]]$Answer = $Host.UI.PromptForChoice($Caption,$Message,$Descriptions,$Default)
if($Passthru -or !($choices -is [String[]])) {
Write-Verbose "$Answer"
Write-Output $Descriptions[$Answer]
} else {
Write-Output $Answer
}
}
}
function Get-Argument {
param(
[Type]$Target,
[ref]$Method,
[Array]$Arguments
)
end {
trap {
write-error $_
break
}
$flags = [System.Reflection.BindingFlags]"public,ignorecase,invokemethod,instance"
[Type[]]$Types = @(
foreach($arg in $Arguments) {
if($arg -is [type]) {
$arg
}
else {
$arg.GetType()
}
}
)
try {
Write-Verbose "[$($Target.FullName)].GetMethod('$($Method.Value)', [$($Flags.GetType())]'$flags', `$null, ([Type[]]($(@($Types|%{$_.Name}) -join ','))), `$null)"
$MethodBase = $Target.GetMethod($($Method.Value), $flags, $null, $types, $null)
$Arguments
if($MethodBase) {
$Method.Value = $MethodBase.Name
}
} catch { }
if(!$MethodBase) {
Write-Verbose "Try again to get $($Method.Value) Method on $($Target.FullName):"
$MethodBase = Get-Method $target $($Method.Value)
if(@($MethodBase).Count -gt 1) {
$i = 0
$i = Read-Choice -Choices $(foreach($mb in $MethodBase) { @{ "$($mb.SafeSyntax) &$($i = $i+1;$i)`b`n" = $mb.SafeSyntax } }) -Default ($MethodBase.Count-1) -Caption "Choose a Method." -Message "Please choose which method overload to invoke:"
[System.Reflection.MethodBase]$MethodBase = $MethodBase[$i]
}
ForEach($parameter in $MethodBase.GetParameters()) {
$found = $false
For($a =0;$a -lt $Arguments.Count;$a++) {
if($argument[$a] -as $parameter.ParameterType) {
Write-Output $argument[$a]
if($a -gt 0 -and $a -lt $Arguments.Count) {
$Arguments = $Arguments | Select -First ($a-1) -Last ($Arguments.Count -$a)
} elseif($a -eq 0) {
$Arguments = $Arguments | Select -Last ($Arguments.Count - 1)
} else { # a -eq count
$Arguments = $Arguments | Select -First ($Arguments.Count - 1)
}
$found = $true
break
}
}
if(!$Found) {
$userInput = Read-Host "Please enter a [$($parameter.ParameterType.FullName)] value for $($parameter.Name)"
if($userInput -match '^{.*}$' -and !($userInput -as $parameter.ParameterType)) {
Write-Output ((Invoke-Expression $userInput) -as $parameter.ParameterType)
} else {
Write-Output ($userInput -as $parameter.ParameterType)
}
}
}
}
}
}
function Invoke-Member {
[CmdletBinding()]
param(
[parameter(position=10, valuefrompipeline=$true, mandatory=$true)]
[allowemptystring()]
$InputObject,
[parameter(position=0, mandatory=$true)]
[validatenotnullorempty()]
$Member,
[parameter(position=1, valuefromremainingarguments=$true)]
[allowemptycollection()]
$Arguments,
[parameter()]
[switch]$Static
)
# begin {
# if(!(get-member SafeSyntax -input $Member -type Property)){
# if(get-member Name -inpup $Member -Type Property) {
# $Member = Get-Method $InputObject $Member.Name
# } else {
# $Member = Get-Method $InputObject $Member
# }
# }
# $SafeSyntax = [ScriptBlock]::Create( $Member.SafeSyntax )
# }
process {
# if ($InputObject)
# {
# if ($InputObject | Get-Member $Member -static:$static)
# {
if ($InputObject -is [type]) {
$target = $InputObject
} else {
$target = $InputObject.GetType()
}
if(Get-Member $Member -InputObject $InputObject -Type Properties) {
$_.$Member
}
elseif($Member -match "ctor|constructor") {
$Member = ".ctor"
[System.Reflection.BindingFlags]$flags = "CreateInstance"
$InputObject = $Null
}
else {
[System.Reflection.BindingFlags]$flags = "IgnoreCase,Public,InvokeMethod"
if($Static) { $flags = "$Flags,Static" } else { $flags = "$Flags,Instance" }
}
[ref]$Member = $Member
[Object[]]$Parameters = Get-Argument $Target $Member $Arguments
[string]$Member = $Member.Value
Write-Verbose $(($Parameters | %{ '[' + $_.GetType().FullName + ']' + $_ }) -Join ", ")
try {
Write-Verbose "Invoking $Member on [$target]$InputObject with [$($Flags.GetType())]'$flags' and [$($Parameters.GetType())]($($Parameters -join ','))"
Write-Verbose "[$($target.FullName)].InvokeMember('$Member', [System.Reflection.BindingFlags]'$flags', `$null, '$InputObject', ([object[]]($(($Parameters | %{ '[' + $_.GetType().FullName + ']''' + $_ + ''''}) -join', '))))"
$target.InvokeMember($Member, [System.Reflection.BindingFlags]"$flags", $null, $InputObject, $Parameters)
} catch {
Write-Warning $_.Exception
if ($_.Exception.Innerexception -is [MissingMethodException]) {
write-warning "Method argument count (or type) mismatch."
}
}
# } else {
# write-warning "Method $Member not found."
# }
# }
}
}
function Invoke-Generic {
#.Synopsis
# Invoke Generic method definitions via reflection:
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[Alias('On')]
$InputObject,
[Parameter(Position=1,ValueFromPipelineByPropertyName=$true)]
[Alias('Named')]
[string]$MethodName,
[Parameter(Position=2)]
[Alias("Types")]
[Type[]]$ParameterTypes,
[Parameter(Position=4, ValueFromRemainingArguments=$true, ValueFromPipelineByPropertyName=$true)]
[Object[]]$WithArgs,
[Switch]$Static
)
begin {
if($Static) {
$BindingFlags = [System.Reflection.BindingFlags]"IgnoreCase,Public,Static"
} else {
$BindingFlags = [System.Reflection.BindingFlags]"IgnoreCase,Public,Instance"
}
}
process {
$Type = $InputObject -as [Type]
if(!$Type) { $Type = $InputObject.GetType() }
if($WithArgs -and -not $ParameterTypes) {
$ParameterTypes = $withArgs | % { $_.GetType() }
} elseif(!$ParameterTypes) {
$ParameterTypes = [Type]::EmptyTypes
}
trap { continue }
$MemberInfo = $Type.GetMethod($MethodName, $BindingFlags)
if(!$MemberInfo) {
$MemberInfo = $Type.GetMethod($MethodName, $BindingFlags, $null, $NonGenericArgumentTypes, $null)
}
if(!$MemberInfo) {
$MemberInfo = $Type.GetMethods($BindingFlags) | Where-Object {
$MI = $_
[bool]$Accept = $MI.Name -eq $MethodName
if($Accept){
Write-Verbose "$Accept = $($MI.Name) -eq $($MethodName)"
[Array]$GenericTypes = @($MI.GetGenericArguments() | Select -Expand Name)
[Array]$Parameters = @($MI.GetParameters() | Add-Member ScriptProperty -Name IsGeneric -Value {
$GenericTypes -Contains $this.ParameterType
} -Passthru)
$Accept = $ParameterTypes.Count -eq $Parameters.Count
Write-Verbose " $Accept = $($Parameters.Count) Arguments"
if($Accept) {
for($i=0;$i -lt $Parameters.Count;$i++) {
$Accept = $Accept -and ( $Parameters[$i].IsGeneric -or ($ParameterTypes[$i] -eq $Parameters[$i].ParameterType))
Write-Verbose " $Accept =$(if($Parameters[$i].IsGeneric){' GENERIC or'}) $($ParameterTypes[$i]) -eq $($Parameters[$i].ParameterType)"
}
}
}
return $Accept
} | Sort { @($_.GetGenericArguments()).Count } | Select -First 1
}
Write-Verbose "Time to make generic methods."
Write-Verbose $MemberInfo
[Type[]]$GenericParameters = @()
[Array]$ConcreteTypes = @($MemberInfo.GetParameters() | Select -Expand ParameterType)
for($i=0;$i -lt $ParameterTypes.Count;$i++){
Write-Verbose "$($ParameterTypes[$i]) ? $($ConcreteTypes[$i] -eq $ParameterTypes[$i])"
if($ConcreteTypes[$i] -ne $ParameterTypes[$i]) {
$GenericParameters += $ParameterTypes[$i]
}
$ParameterTypes[$i] = Add-Member -in $ParameterTypes[$i] -Type NoteProperty -Name IsGeneric -Value $($ConcreteTypes[$i] -ne $ParameterTypes[$i]) -Passthru
}
$ParameterTypes | Where-Object { $_.IsGeneric }
Write-Verbose "$($GenericParameters -join ', ') generic parameters"
$MemberInfo = $MemberInfo.MakeGenericMethod( $GenericParameters )
Write-Verbose $MemberInfo
if($WithArgs) {
[Object[]]$Arguments = $withArgs | %{ $_.PSObject.BaseObject }
Write-Verbose "Arguments: $(($Arguments | %{ $_.GetType().Name }) -Join ', ')"
$MemberInfo.Invoke( $InputObject, $Arguments )
} else {
$MemberInfo.Invoke( $InputObject )
}
}
}
# get a reference to the Type
$xlr8r = [psobject].assembly.gettype("System.Management.Automation.TypeAccelerators")
function Import-Namespace {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
[string]$Namespace,
[Switch]$Force
)
end {
Get-Type -Namespace $Namespace -Force:$Force | Add-Accelerator
}
}
function Add-Accelerator {
<#
.Synopsis
Add a type accelerator to the current session
.Description
The Add-Accelerator function allows you to add a simple type accelerator (like [regex]) for a longer type (like [System.Text.RegularExpressions.Regex]).
.Example
Add-Accelerator list System.Collections.Generic.List``1
$list = New-Object list[string]
Creates an accelerator for the generic List[T] collection type, and then creates a list of strings.
.Example
Add-Accelerator "List T", "GList" System.Collections.Generic.List``1
$list = New-Object "list t[string]"
Creates two accelerators for the Generic List[T] collection type.
.Parameter Accelerator
The short form accelerator should be just the name you want to use (without square brackets).
.Parameter Type
The type you want the accelerator to accelerate (without square brackets)
.Notes
When specifying multiple values for a parameter, use commas to separate the values.
For example, "-Accelerator string, regex".
PowerShell requires arguments that are "types" to NOT have the square bracket type notation, because of the way the parsing engine works. You can either just type in the type as System.Int64, or you can put parentheses around it to help the parser out: ([System.Int64])
Also see the help for Get-Accelerator and Remove-Accelerator
.Link
http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/
#>
[CmdletBinding()]
param(
[Parameter(Position=0,ValueFromPipelineByPropertyName=$true)]
[Alias("Key","Name")]
[string[]]$Accelerator,
[Parameter(Position=1,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[Alias("Value","FullName")]
[type]$Type
)
process {
# add a user-defined accelerator
foreach($a in $Accelerator) {
if($xlr8r::AddReplace) {
$xlr8r::AddReplace( $a, $Type)
} else {
$null = $xlr8r::Remove( $a )
$xlr8r::Add( $a, $Type)
}
trap [System.Management.Automation.MethodInvocationException] {
if($xlr8r::get.keys -contains $a) {
if($xlr8r::get[$a] -ne $Type) {
Write-Error "Cannot add accelerator [$a] for [$($Type.FullName)]`n [$a] is already defined as [$($xlr8r::get[$a].FullName)]"
}
Continue;
}
throw
}
}
}
}
function Get-Accelerator {
<#
.Synopsis
Get one or more type accelerator definitions
.Description
The Get-Accelerator function allows you to look up the type accelerators (like [regex]) defined on your system by their short form or by type
.Example
Get-Accelerator System.String
Returns the KeyValue pair for the [System.String] accelerator(s)
.Example
Get-Accelerator ps*,wmi*
Returns the KeyValue pairs for the matching accelerator definition(s)
.Parameter Accelerator
One or more short form accelerators to search for (Accept wildcard characters).
.Parameter Type
One or more types to search for.
.Notes
When specifying multiple values for a parameter, use commas to separate the values.
For example, "-Accelerator string, regex".
Also see the help for Add-Accelerator and Remove-Accelerator
.Link
http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/
#>
[CmdletBinding(DefaultParameterSetName="ByType")]
param(
[Parameter(Position=0, ParameterSetName="ByAccelerator", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("Key","Name")]
[string[]]$Accelerator,
[Parameter(Position=0, ParameterSetName="ByType", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("Value","FullName")]
[type[]]$Type
)
process {
# add a user-defined accelerator
switch($PSCmdlet.ParameterSetName) {
"ByAccelerator" {
$xlr8r::get.GetEnumerator() | % {
foreach($a in $Accelerator) {
if($_.Key -like $a) { $_ }
}
}
break
}
"ByType" {
if($Type -and $Type.Count) {
$xlr8r::get.GetEnumerator() | ? { $Type -contains $_.Value }
}
else {
$xlr8r::get.GetEnumerator() | %{ $_ }
}
break
}
}
}
}
function Remove-Accelerator {
<#
.Synopsis
Remove a type accelerator from the current session
.Description
The Remove-Accelerator function allows you to remove a simple type accelerator (like [regex]) from the current session. You can pass one or more accelerators, and even wildcards, but you should be aware that you can remove even the built-in accelerators.
.Example
Remove-Accelerator int
Add-Accelerator int Int64
Removes the "int" accelerator for Int32 and adds a new one for Int64. I can't recommend doing this, but it's pretty cool that it works:
So now, "$(([int]3.4).GetType().FullName)" would return "System.Int64"
.Example
Get-Accelerator System.Single | Remove-Accelerator
Removes both of the default accelerators for System.Single: [float] and [single]
.Example
Get-Accelerator System.Single | Remove-Accelerator -WhatIf
Demonstrates that Remove-Accelerator supports -Confirm and -Whatif. Will Print:
What if: Removes the alias [float] for type [System.Single]
What if: Removes the alias [single] for type [System.Single]
.Parameter Accelerator
The short form accelerator that you want to remove (Accept wildcard characters).
.Notes
When specifying multiple values for a parameter, use commas to separate the values.
For example, "-Accel string, regex".
Also see the help for Add-Accelerator and Get-Accelerator
.Link
http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/
#>
[CmdletBinding(SupportsShouldProcess=$true)]
param(
[Parameter(Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("Key","FullName")]
[string[]]$Accelerator
)
process {
foreach($a in $Accelerator) {
foreach($key in $xlr8r::Get.Keys -like $a) {
if($PSCmdlet.ShouldProcess( "Removes the alias [$($Key)] for type [$($xlr8r::Get[$key].FullName)]",
"Remove the alias [$($Key)] for type [$($xlr8r::Get[$key].FullName)]?",
"Removing Type Accelerator" )) {
# remove a user-defined accelerator
$xlr8r::remove($key)
}
}
}
}
}
###############################################################################
##### Imported from PowerBoots
$Script:CodeGenContentProperties = 'Content','Child','Children','Frames','Items','Pages','Blocks','Inlines','GradientStops','Source','DataPoints', 'Series', 'VisualTree'
$DependencyProperties = @{}
if(Test-Path $PSScriptRoot\\DependencyPropertyCache.xml) {
#$DependencyProperties = [System.Windows.Markup.XamlReader]::Parse( (gc $PSScriptRoot\\DependencyPropertyCache.xml) )
$DependencyProperties = Import-CliXml $PSScriptRoot\\DependencyPropertyCache.xml
}
function Get-ReflectionModule { $executioncontext.sessionstate.module }
function Set-ObjectProperties {
[CmdletBinding()]
param( $Parameters, [ref]$DObject )
if($DObject.Value -is [System.ComponentModel.ISupportInitialize]) { $DObject.Value.BeginInit() }
if($DebugPreference -ne "SilentlyContinue") { Write-Host; Write-Host ">>>> $($Dobject.Value.GetType().FullName)" -fore Black -back White }
foreach ($param in $Parameters) {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Processing Param: $($param|Out-String )" }
## INGORE DEPENDENCY PROPERTIES FOR NOW :)
if($param.Key -eq "DependencyProps") {
## HANDLE EVENTS ....
}
elseif ($param.Key.StartsWith("On_")) {
$EventName = $param.Key.SubString(3)
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Event handler $($param.Key) Type: $(@($param.Value)[0].GetType().FullName)" }
$sb = $param.Value -as [ScriptBlock]
if(!$sb) {
$sb = (Get-Command $param.Value -CommandType Function,ExternalScript).ScriptBlock
}
$Dobject.Value."Add_$EventName".Invoke( $sb );
# $Dobject.Value."Add_$EventName".Invoke( ($sb.GetNewClosure()) );
# $Dobject.Value."Add_$EventName".Invoke( $PSCmdlet.MyInvocation.MyCommand.Module.NewBoundScriptBlock( $sb.GetNewClosure() ) );
} ## HANDLE PROPERTIES ....
else {
try {
## TODO: File a BUG because Write-DEBUG and Write-VERBOSE die here.
if($DebugPreference -ne "SilentlyContinue") {
Write-Host "Setting $($param.Key) of $($Dobject.Value.GetType().Name) to $($param.Value.GetType().FullName): $($param.Value)" -fore Gray
}
if(@(foreach($sb in $param.Value) { $sb -is [ScriptBlock] }) -contains $true) {
$Values = @()
foreach($sb in $param.Value) {
$Values += & (Get-ReflectionModule) $sb
}
} else {
$Values = $param.Value
}
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject.Value )) -foreground green }
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( @($Values)[0] )) -foreground green }
Set-Property $Dobject $Param.Key $Values
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject.Value )) -foreground magenta }
if($DebugPreference -ne "SilentlyContinue") {
if( $Dobject.Value.$($param.Key) -ne $null ) {
Write-Host $Dobject.Value.$($param.Key).GetType().FullName -fore Green
}
}
}
catch [Exception]
{
Write-Host "COUGHT AN EXCEPTION" -fore Red
Write-Host $_ -fore Red
Write-Host $this -fore DarkRed
}
}
while($DependencyProps) {
$name, $value, $DependencyProps = $DependencyProps
$name = ([string]@($name)[0]).Trim("-")
if($name -and $value) {
Set-DependencyProperty -Element $Dobject.Value -Property $name -Value $Value
}
}
}
if($DebugPreference -ne "SilentlyContinue") { Write-Host "<<<< $($Dobject.Value.GetType().FullName)" -fore Black -back White; Write-Host }
if($DObject.Value -is [System.ComponentModel.ISupportInitialize]) { $DObject.Value.EndInit() }
}
function Set-Property {
PARAM([ref]$TheObject, $Name, $Values)
$DObject = $TheObject.Value
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $DObject )) -foreground DarkMagenta }
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( @($Values)[0] )) -foreground DarkMagenta }
$PropertyType = $DObject.GetType().GetProperty($Name).PropertyType
if('System.Windows.FrameworkElementFactory' -as [Type] -and $PropertyType -eq [System.Windows.FrameworkElementFactory] -and $DObject -is [System.Windows.FrameworkTemplate]) {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Loading a FrameworkElementFactory" -foreground Green}
# [Xml]$Template = [PoshWpf.XamlHelper]::ConvertToXaml( $DObject )
# [Xml]$Content = [PoshWpf.XamlHelper]::ConvertToXaml( (@($Values)[0]) )
# In .Net 3.5 the recommended way to programmatically create a template is to load XAML from a string or a memory stream using the Load method of the XamlReader class.
[Xml]$Template = [System.Windows.Markup.XamlWriter]::Save( $DObject )
[Xml]$Content = [System.Windows.Markup.XamlWriter]::Save( (@($Values)[0]) )
$Template.DocumentElement.PrependChild( $Template.ImportNode($Content.DocumentElement, $true) ) | Out-Null
$TheObject.Value = [System.Windows.Markup.XamlReader]::Parse( $Template.get_OuterXml() )
}
elseif('System.Windows.Data.Binding' -as [Type] -and @($Values)[0] -is [System.Windows.Data.Binding] -and !$PropertyType.IsAssignableFrom([System.Windows.Data.BindingBase])) {
$Binding = @($Values)[0];
if($DebugPreference -ne "SilentlyContinue") { Write-Host "$($DObject.GetType())::$Name is $PropertyType and the value is a Binding: $Binding" -fore Cyan}
if(!$Binding.Source -and !$Binding.ElementName) {
$Binding.Source = $DObject.DataContext
}
if($DependencyProperties.ContainsKey($Name)) {
$field = @($DependencyProperties.$Name.Keys | Where { $DObject -is $_ -and $PropertyType -eq ([type]$DependencyProperties.$Name.$_.PropertyType)})[0] # -or -like "*$Class" -and ($Param1.Value -as ([type]$_.PropertyType)
if($field) {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "$($field)" -fore Blue }
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Binding: ($field)::`"$($DependencyProperties.$Name.$field.Name)`" to $Binding" -fore Blue}
$DObject.SetBinding( ([type]$field)::"$($DependencyProperties.$Name.$field.Name)", $Binding ) | Out-Null
} else {
throw "Couldn't figure out $( @($DependencyProperties.$Name.Keys) -join ', ' )"
}
} else {
if($DebugPreference -ne "SilentlyContinue") {
Write-Host "But $($DObject.GetType())::${Name}Property is not a Dependency Property, so it probably can't be bound?" -fore Cyan
}
try {
$DObject.SetBinding( ($DObject.GetType()::"${Name}Property"), $Binding ) | Out-Null
if($DebugPreference -ne "SilentlyContinue") {
Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Dobject )) -foreground yellow
}
} catch {
Write-Host "Nope, was not able to set it." -fore Red
Write-Host $_ -fore Red
Write-Host $this -fore DarkRed
}
}
}
elseif($PropertyType -ne [Object] -and $PropertyType.IsAssignableFrom( [System.Collections.IEnumerable] ) -and ($DObject.$($Name) -eq $null)) {
if($Values -is [System.Collections.IEnumerable]) {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "$Name is $PropertyType which is IEnumerable, and the value is too!" -fore Cyan }
$DObject.$($Name) = $Values
} else {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "$Name is $PropertyType which is IEnumerable, but the value is not." -fore Cyan }
$DObject.$($Name) = new-object "System.Collections.ObjectModel.ObservableCollection[$(@($Values)[0].GetType().FullName)]"
$DObject.$($Name).Add($Values)
}
}
elseif($DObject.$($Name) -is [System.Collections.IList]) {
foreach ($value in @($Values)) {
try {
$null = $DObject.$($Name).Add($value)
}
catch
{
# Write-Host "CAUGHT array problem" -fore Red
if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") {
$null = $DObject.$($Name).Add( (New-System.Windows.Controls.TextBlock $value) )
} else {
Write-Error $_.Exception
throw
}
}
}
}
else {
## If they pass an array of 1 when we only want one, we just use the first value
if($Values -is [System.Collections.IList] -and $Values.Count -eq 1) {
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Value is an IList ($($Values.GetType().FullName))" -fore Cyan}
if($DebugPreference -ne "SilentlyContinue") { Write-Host "But we'll just use the first ($($Values[0].GetType().FullName))" -fore Cyan}
if($DebugPreference -ne "SilentlyContinue") { Write-Host ([System.Windows.Markup.XamlWriter]::Save( $Values[0] )) -foreground White}
try {
$DObject.$($Name) = $Values[0]
}
catch [Exception]
{
# Write-Host "CAUGHT collection value problem" -fore Red
if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") {
$null = $DObject.$($Name).Add( (TextBlock $Values[0]) )
}else {
throw
}
}
}
else ## If they pass an array when we only want one, we try to use it, and failing that, cast it to strings
{
if($DebugPreference -ne "SilentlyContinue") { Write-Host "Value is just $Values" -fore Cyan}
try {
$DObject.$($Name) = $Values
} catch [Exception]
{
# Write-Host "CAUGHT value problem" -fore Red
if($_.Exception.Message -match "Invalid cast from 'System.String' to 'System.Windows.UIElement'.") {
$null = $DObject.$($Name).Add( (TextBlock $values) )
}else {
throw
}
}
}
}
}
function Set-DependencyProperty {
[CmdletBinding()]
PARAM(
[Parameter(Position=0,Mandatory=$true)]
$Property,
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
$Element,
[Parameter()]
[Switch]$Passthru
)
DYNAMICPARAM {
$paramDictionary = new-object System.Management.Automation.RuntimeDefinedParameterDictionary
$Param1 = new-object System.Management.Automation.RuntimeDefinedParameter
$Param1.Name = "Value"
# $Param1.Attributes.Add( (New-ParameterAttribute -Position 1) )
$Param1.Attributes.Add( (New-Object System.Management.Automation.ParameterAttribute -Property @{ Position = 1 }) )
if( $Property ) {
if($Property.GetType() -eq ([System.Windows.DependencyProperty]) -or
$Property.GetType().IsSubclassOf(([System.Windows.DependencyProperty])))
{
$Param1.ParameterType = $Property.PropertyType
}
elseif($Property -is [string] -and $Property.Contains(".")) {
$Class,$Property = $Property.Split(".")
if($DependencyProperties.ContainsKey($Property)){
$type = $DependencyProperties.$Property.Keys -like "*$Class"
if($type) {
$Param1.ParameterType = [type]@($DependencyProperties.$Property.$type)[0].PropertyType
}
}
} elseif($DependencyProperties.ContainsKey($Property)){
if($Element) {
if($DependencyProperties.$Property.ContainsKey( $element.GetType().FullName )) {
$Param1.ParameterType = [type]$DependencyProperties.$Property.($element.GetType().FullName).PropertyType
}
} else {
$Param1.ParameterType = [type]$DependencyProperties.$Property.Values[0].PropertyType
}
}
else
{
$Param1.ParameterType = [PSObject]
}
}
else
{
$Param1.ParameterType = [PSObject]
}
$paramDictionary.Add("Value", $Param1)
return $paramDictionary
}
PROCESS {
trap {
Write-Host "ERROR Setting Dependency Property" -Fore Red
Write-Host "Trying to set $Property to $($Param1.Value)" -Fore Red
continue
}
if($Property.GetType() -eq ([System.Windows.DependencyProperty]) -or
$Property.GetType().IsSubclassOf(([System.Windows.DependencyProperty]))
){
trap {
Write-Host "ERROR Setting Dependency Property" -Fore Red
Write-Host "Trying to set $($Property.FullName) to $($Param1.Value)" -Fore Red
continue
}
$Element.SetValue($Property, ($Param1.Value -as $Property.PropertyType))
}
else {
if("$Property".Contains(".")) {
$Class,$Property = "$Property".Split(".")
}
if( $DependencyProperties.ContainsKey("$Property" ) ) {
$fields = @( $DependencyProperties.$Property.Keys -like "*$Class" | ? { $Param1.Value -as ([type]$DependencyProperties.$Property.$_.PropertyType) } )
if($fields.Count -eq 0 ) {
$fields = @($DependencyProperties.$Property.Keys -like "*$Class" )
}
if($fields.Count) {
$success = $false
foreach($field in $fields) {
trap {
Write-Host "ERROR Setting Dependency Property" -Fore Red
Write-Host "Trying to set $($field)::$($DependencyProperties.$Property.$field.Name) to $($Param1.Value) -as $($DependencyProperties.$Property.$field.PropertyType)" -Fore Red
continue
}
$Element.SetValue( ([type]$field)::"$($DependencyProperties.$Property.$field.Name)", ($Param1.Value -as ([type]$DependencyProperties.$Property.$field.PropertyType)))
if($?) { $success = $true; break }
}
if(!$success) {
throw "food"
}
} else {
Write-Host "Couldn't find the right property: $Class.$Property on $( $Element.GetType().Name ) of type $( $Param1.Value.GetType().FullName )" -Fore Red
}
}
else {
Write-Host "Unknown Dependency Property Key: $Property on $($Element.GetType().Name)" -Fore Red
}
}
if( $Passthru ) { $Element }
}
}
function Add-Struct {
#.Synopsis
# Creates Struct types from a list of types and properties
#.Description
# Add-Struct is a wrapper for Add-Type to create struct types.
#.Example
# New-Struct Song {
# [string]$Artist
# [string]$Album
# [string]$Name
# [TimeSpan]$Length
# } -CreateConstructorFunction
#
# Description
# -----------
# Creates a "Song" type with strongly typed Artist, Album, Name, and Length properties, with a simple constructor and a constructor function
#.Example
# New-Struct @{
# >> Product = { [string]$Name; [double]$Price; }
# >> Order = { [Guid]$Id; [Product]$Product; [int]$Quantity }
# >> Customer = {
# >> [string]$FirstName
# >> [string]$LastName
# >> [int]$Age
# >> [Order[]]$OrderHistory
# >> }
# >> }
# >>
#
# Description
# -----------
# To create a series of related struct types (where one type is a property of another type), you need to use the -Types hashtable parameter set. That way, all of the types will compiled together at once, so the compiler will be able to find them all.
#
[CmdletBinding(DefaultParameterSetName="Multiple")]
param(
# The name of the TYPE you are creating. Must be unique per PowerShell session.
[ValidateScript({
if($_ -notmatch '^[a-z][a-z1-9_]*$') {
throw "'$_' is invalid. A valid name identifier must start with a letter, and contain only alpha-numeric or the underscore (_)."
}
return $true
})]
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName = "Single")]
[string]$Name,
# A Scriptblock full of "[Type]$Name" definitions to show what properties you want on your Struct type
[Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName = "Single")]
[ScriptBlock]$Property,
# A Hashtable in the form @{Name={Properties}} with multiple
|
PowerShellCorpus/PoshCode/Test-UserCredential_3.ps1
|
Test-UserCredential_3.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) {
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 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.
.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.
#>
}
|
PowerShellCorpus/PoshCode/Test-Port.ps1
|
Test-Port.ps1
|
Param([string]$srv,$port=135,$timeout=3000,[switch]$verbose)
# Test-Port.ps1
# Does a TCP connection on specified port (135 by default)
$ErrorActionPreference = "SilentlyContinue"
# Create TCP Client
$tcpclient = new-Object system.Net.Sockets.TcpClient
# Tell TCP Client to connect to machine on Port
$iar = $tcpclient.BeginConnect($srv,$port,$null,$null)
# Set the wait time
$wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false)
# Check to see if the connection is done
if(!$wait)
{
# Close the connection and report timeout
$tcpclient.Close()
if($verbose){Write-Host "Connection Timeout"}
Return $false
}
else
{
# Close the connection and report the error if there is one
$error.Clear()
$tcpclient.EndConnect($iar) | out-Null
if(!$?){if($verbose){write-host $error[0]};$failed = $true}
$tcpclient.Close()
}
# Return $true if connection Establish else $False
if($failed){return $false}else{return $true}
|
PowerShellCorpus/PoshCode/Get-Credential++_1.ps1
|
Get-Credential++_1.ps1
|
## Get-Credential
## An improvement over the default cmdlet which has no options ...
###################################################################################################
## History
## v 2.0 Rewrite for v2 to replace the default Get-Credential
## v 1.2 Refactor ShellIds key out to a variable, and wrap lines a bit
## v 1.1 Add -Console switch and set registry values accordingly (ouch)
## v 1.0 Add Title, Message, Domain, and UserName options to the Get-Credential cmdlet
###################################################################################################
function Get-Credential {
## .Synopsis
## Gets a credential object based on a user name and password.
## .Description
## The Get-Credential function creates a credential object for a specified username and password, with an optional domain. You can use the credential object in security operations.
##
## The function accepts more parameters to customize the security prompt than the default Get-Credential cmdlet (including forcing the call through the console if you're in the native PowerShell.exe CMD console), but otherwise functions identically.
##
## .Parameter Credential
## For compatability reasons only, we accept a credential (and pass it right back out) the way the built-in Get-Credential does.
## .Parameter UserName
## A default user name for the credential prompt
## .Parameter Title
## Allows you to override the default window title of the credential dialog/prompt
##
## You should use this to allow users to differentiate one credential prompt from another. In particular, if you're prompting for, say, Twitter credentials, you should put "Twitter" in the title somewhere. If you're prompting for domain credentials. Being specific not only helps users differentiate and know what credentials to provide, but also allows tools like KeePass to automatically determine it.
## .Parameter Message
## Allows you to override the text displayed inside the credential dialog/prompt.
##
## You can use this for things like presenting an explanation of what you need the credentials for.
## .Parameter Domain
## Specifies the default domain to use if the user doesn't provide one (by default, this is null)
## .Parameter GenericCredentials
## The Get-Credential cmdlet forces you to always return DOMAIN credentials (so even if the user provides just a plain user name, it prepends "\\" to the user name). This switch allows you to override that behavior and allow generic credentials without any domain name or the leading "\\".
## .Parameter Inline
## Forces the credential prompt to occur inline in the console/host using Read-Host -AsSecureString (not implemented properly in PowerShell ISE)
##
[CmdletBinding(DefaultParameterSetName="Better")]
PARAM(
[Parameter(Position=1,Mandatory=$false)]
[Alias("Credential")]
[PSObject]$UserName=$null,
[Parameter(Position=2,Mandatory=$false)]
[string]$Title=$null,
[Parameter(Position=3,Mandatory=$false)]
[string]$Message=$null,
[Parameter(Position=4,Mandatory=$false)]
[string]$Domain=$null,
[Parameter(Mandatory=$false)]
[switch]$GenericCredentials,
[Parameter(Mandatory=$false)]
[switch]$Console
)
PROCESS {
if( $UserName -is [System.Management.Automation.PSCredential]) {
return $UserName
} elseif($UserName -ne $null) {
$UserName = $UserName.ToString()
}
if($Console) {
if($Title) { Write-Host $Title }
if($Message) { Write-Host $Message }
if($Domain) {
if($UserName -and $UserName -notmatch "[@\\\\]") {
$UserName = "${Domain}\\${UserName}"
}
}
if(!$UserName) {
$UserName = Read-Host "User"
if(($Domain -OR !$GenericCredentials) -and $UserName -notmatch "[@\\\\]") {
$UserName = "${Domain}\\${UserName}"
}
}
return New-Object System.Management.Automation.PSCredential $UserName,$(Read-Host "Password for user $UserName" -AsSecureString)
}
if($GenericCredentials) { $Credential = "Generic" } else { $Credential = "Domain" }
## Now call the Host.UI method ... if they don't have one, we'll die, yay.
## BugBug? PowerShell.exe disregards the last parameter
$Host.UI.PromptForCredential($Title, $Message, $UserName, $Domain, $Credential,"Default")
}
}
|
PowerShellCorpus/PoshCode/b87a3777-9def-4855-88ea-f9ae2610a469.ps1
|
b87a3777-9def-4855-88ea-f9ae2610a469.ps1
|
#alias,addnewemailaddress
import-csv .\\source.csv | foreach {
$user = Get-Mailbox $_.alias
$user.emailAddresses+= $_.addnewemailaddress
$user.primarysmtpaddress = $_.addnewemailaddress
Set-Mailbox $user -emailAddresses $user.emailAddresses
set-Mailbox $user -PrimarySmtpAddress $user.primarysmtpaddress
}
|
PowerShellCorpus/PoshCode/Test-Port_4.ps1
|
Test-Port_4.ps1
|
function Test-Port{
<#
.SYNOPSIS
Tests port on computer.
.DESCRIPTION
Tests port on computer.
.PARAMETER computer
Name of server to test the port connection on.
.PARAMETER port
Port to test
.PARAMETER tcp
Use tcp port
.PARAMETER udp
Use udp port
.PARAMETER UDPTimeOut
Sets a timeout for UDP port query. (In milliseconds, Default is 1000)
.PARAMETER TCPTimeOut
Sets a timeout for TCP port query. (In milliseconds, Default is 1000)
.NOTES
Name: Test-Port.ps1
Author: Boe Prox
DateCreated: 18Aug2010
List of Ports: http://www.iana.org/assignments/port-numbers
To Do:
Add capability to run background jobs for each host to shorten the time to scan.
.LINK
https://boeprox.wordpress.org
.EXAMPLE
Test-Port -computer 'server' -port 80
Checks port 80 on server 'server' to see if it is listening
.EXAMPLE
'server' | Test-Port -port 80
Checks port 80 on server 'server' to see if it is listening
.EXAMPLE
Test-Port -computer @("server1","server2") -port 80
Checks port 80 on server1 and server2 to see if it is listening
.EXAMPLE
@("server1","server2") | Test-Port -port 80
Checks port 80 on server1 and server2 to see if it is listening
.EXAMPLE
(Get-Content hosts.txt) | Test-Port -port 80
Checks port 80 on servers in host file to see if it is listening
.EXAMPLE
Test-Port -computer (Get-Content hosts.txt) -port 80
Checks port 80 on servers in host file to see if it is listening
.EXAMPLE
Test-Port -computer (Get-Content hosts.txt) -port @(1..59)
Checks a range of ports from 1-59 on all servers in the hosts.txt file
#>
[cmdletbinding(
DefaultParameterSetName = '',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = '',
ValueFromPipeline = $True)]
[array]$computer,
[Parameter(
Position = 1,
Mandatory = $True,
ParameterSetName = '')]
[array]$port,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[int]$TCPtimeout=1000,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[int]$UDPtimeout=1000,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[switch]$TCP,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[switch]$UDP
)
Begin {
If (!$tcp -AND !$udp) {$tcp = $True}
#Typically you never do this, but in this case I felt it was for the benefit of the function
#as any errors will be noted in the output of the report
$ErrorActionPreference = "SilentlyContinue"
$report = @()
}
Process {
ForEach ($c in $computer) {
ForEach ($p in $port) {
If ($tcp) {
#Create temporary holder
$temp = "" | Select Server, Port, TypePort, Open, Notes
#Create object for connecting to port on computer
$tcpobject = new-Object system.Net.Sockets.TcpClient
#Connect to remote machine's port
$connect = $tcpobject.BeginConnect($c,$p,$null,$null)
#Configure a timeout before quitting
$wait = $connect.AsyncWaitHandle.WaitOne($TCPtimeout,$false)
#If timeout
If(!$wait) {
#Close connection
$tcpobject.Close()
Write-Verbose "Connection Timeout"
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "TCP"
$temp.Open = "False"
$temp.Notes = "Connection to Port Timed Out"
}
Else {
$error.Clear()
$tcpobject.EndConnect($connect) | out-Null
#If error
If($error[0]){
#Begin making error more readable in report
[string]$string = ($error[0].exception).message
$message = (($string.split(":")[1]).replace('"',"")).TrimStart()
$failed = $true
}
#Close connection
$tcpobject.Close()
#If unable to query port to due failure
If($failed){
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "TCP"
$temp.Open = "False"
$temp.Notes = "$message"
}
#Successfully queried port
Else{
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "TCP"
$temp.Open = "True"
$temp.Notes = ""
}
}
#Reset failed value
$failed = $Null
#Merge temp array with report
$report += $temp
}
If ($udp) {
#Create temporary holder
$temp = "" | Select Server, Port, TypePort, Open, Notes
#Create object for connecting to port on computer
$udpobject = new-Object system.Net.Sockets.Udpclient($p)
#Set a timeout on receiving message
$udpobject.client.ReceiveTimeout = $UDPTimeout
#Connect to remote machine's port
Write-Verbose "Making UDP connection to remote server"
$udpobject.Connect("$c",$p)
#Sends a message to the host to which you have connected.
Write-Verbose "Sending message to remote host"
$a = new-object system.text.asciiencoding
$byte = $a.GetBytes("$(Get-Date)")
[void]$udpobject.Send($byte,$byte.length)
#IPEndPoint object will allow us to read datagrams sent from any source.
Write-Verbose "Creating remote endpoint"
$remoteendpoint = New-Object system.net.ipendpoint([system.net.ipaddress]::Any,0)
Try {
#Blocks until a message returns on this socket from a remote host.
Write-Verbose "Waiting for message return"
$receivebytes = $udpobject.Receive([ref]$remoteendpoint)
[string]$returndata = $a.GetString($receivebytes)
}
Catch {
If ($Error[0].ToString() -match "\\bRespond after a period of time\\b") {
#Close connection
$udpobject.Close()
#Make sure that the host is online and not a false positive that it is open
If (Test-Connection -comp $c -count 1 -quiet) {
Write-Verbose "Connection Open"
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "UDP"
$temp.Open = "True"
$temp.Notes = ""
}
Else {
<#
It is possible that the host is not online or that the host is online,
but ICMP is blocked by a firewall and this port is actually open.
#>
Write-Verbose "Host maybe unavailable"
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "UDP"
$temp.Open = "False"
$temp.Notes = "Unable to verify if port is open or if host is unavailable."
}
}
ElseIf ($Error[0].ToString() -match "forcibly closed by the remote host" ) {
#Close connection
$udpobject.Close()
Write-Verbose "Connection Timeout"
#Build report
$temp.Server = $c
$temp.Port = $p
$temp.TypePort = "UDP"
$temp.Open = "False"
$temp.Notes = "Connection to Port Timed Out"
}
Else {
$udpobject.close()
}
}
#Merge temp array with report
$report += $temp
}
}
}
}
End {
#Generate Report
$report
}
}
|
PowerShellCorpus/PoshCode/finddupe_9.ps1
|
finddupe_9.ps1
|
function Get-MD5([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]'))
{
$stream = $null;
$cryptoServiceProvider = [System.Security.Cryptography.MD5CryptoServiceProvider];
$hashAlgorithm = new-object $cryptoServiceProvider
$stream = $file.OpenRead();
$hashByteArray = $hashAlgorithm.ComputeHash($stream);
$stream.Close();
## We have to be sure that we close the file stream if any exceptions are thrown.
trap
{
if ($stream -ne $null)
{
$stream.Close();
}
break;
}
foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }}
return [string]$result;
}
write-host "Usage: finddupe.ps1 <directory/file #1> <directory/file #2> ... <directory/file #N> [-delete] [-noprompt]"
$matches = 0 # initialize number of matches for summary.
$files=@()
$del = $false # delete duplicates
$noprompt = $false # delete without prompting toggle
for ($i=0;$i -ne $args.count; $i++)
{
if ($args[$i] -eq "-delete")
{
$del=$true;continue
}
else
{
if ($args[$i] -eq "-noprompt")
{
$noprompt=$true;continue
}
else
{
$files+=(dir $args[$i] -recurse | ? {$_.psiscontainer -ne $true})
}
}
}
if ($files -eq $null) {write-host "No files found." -f red; exit}
for ($i=0;$i -ne $files.count; $i++) # Cycle thru all files
{
if ($files[$i] -eq $null) {continue}
$md5 = $null
$filecheck = $files[$i]
$files[$i] = $null
for ($c=0;$c -ne $files.count; $c++)
{
if ($files[$c] -eq $null) {continue}
# write-host "Comparing $filecheck and $($files[$c]) `r" -nonewline
if ($filecheck.length -eq $files[$c].length)
{
#write-host "Comparing MD5 of $($filecheck.fullname) and $($files[$c].fullname) `r" -nonewline
if ($md5 -eq $null) {$md5 = (get-md5 $filecheck)}
if ($md5 -eq (get-md5 $files[$c]))
{
write-host "Size and MD5 match: " -fore red -nonewline
"{0} and {1}" -f $filecheck.fullname, $files[$c].fullname
$matches++
if ($del -eq $true)
{
if ($noprompt -eq $true)
{
del $files[$c].fullname;write-host "$($files[$c].fullname) deleted." -f Red
}
else
{
del $files[$c].fullname -confirm
}
}
$files[$c] = $null
}
}
}
}
write-host ""
write-host "Number of Files checked: $($files.count)." # Display useful info; files checked and matches found.
write-host "Number of matches found: $($matches)."
write-host ""
|
PowerShellCorpus/PoshCode/ISE-Snippets variant.ps1
|
ISE-Snippets variant.ps1
|
#requires -version 2.0
## ISE-Snippets module v 1.0
## DEVELOPED FOR CTP3
## See comments for each function for changes ...
##############################################################################################################
## As a shortcut for every snippet would be to much, I created Add-Snippet which presents a menu.
## Feel free to add your own snippets to function Add-Snippet but please contribute your changes here
##############################################################################################################
## Provides Code Snippets for working with ISE
## Add-Snippet - Presents menu for snippet selection
## Add-SnippetToEditor - Adds a snippet at caret position
##############################################################################################################
## Add-Snippet
##############################################################################################################
## Presents menu for snippet selection
##############################################################################################################
function Add-Snippet
{
$snippets = @{
"region" = @( "#region", "#endregion" )
"function" = @( "function FUNCTION_NAME", "{", "}" )
"param" = @( "param ``", "(", ")" )
"if" = @( "if ( CONDITION )", "{", "}" )
"else" = @( "else", "{", "}" )
"elseif" = @( "elseif ( CONDITION )", "{", "}" )
"foreach" = @( "foreach ( ITEM in COLLECTION )", "{", "}" )
"for" = @( "foreach ( INIT; CONDITION; REPEAT )", "{", "}" )
"while" = @( "while ( CONDITION )", "{", "}" )
"dowhile" = @( "do" , "{", "}", "while ( CONDITION )" )
"dountil" = @( "do" , "{", "}", "until ( CONDITION )" )
"try" = @( "try", "{", "}" )
"catch" = @( "catch", "{", "}" )
"catch [<error type>] " = @( "catch [ERROR_TYPE]", "{", "}" )
"finaly" = @( "finaly", "{", "}" )
}
$editor = $psISE.CurrentOpenedFile.Editor
if ( $editor.SelectedText.length -eq 0) {
$caretLine = $editor.CaretLine
$caretColumn = $editor.CaretColumn
$text = $editor.Text.Split("`n")
$line = $text[$caretLine -1]
$LeftOfCarret = $line.substring(0, $caretColumn - 1)
$parts = $LeftOfCarret.split("")
$len = $parts[-1].length
$start = $caretColumn - $len
$editor.select($caretLine, $start, $caretLine, $caretColumn )
}
$snippetName = $editor.SelectedText
$editor.insertText('')
Add-SnippetToEditor $snippets[$snippetName]
}
## Add-SnippetToEditor
##############################################################################################################
## Adds a snippet at caret position
##############################################################################################################
function Add-SnippetToEditor
{
param `
(
[string[]] $snippet
)
$editor = $psISE.CurrentOpenedFile.Editor
$caretLine = $editor.CaretLine
$caretColumn = $editor.CaretColumn
$text = $editor.Text.Split("`n")
$newText = @()
if ( $caretLine -gt 1 )
{
$newText += $text[0..($caretLine -2)]
}
$curLine = $text[$caretLine -1]
$indent = $curline -replace "[^\\t ]", ""
foreach ( $snipLine in $snippet )
{
$newText += $indent + $snipLine
}
if ( $caretLine -ne $text.Count )
{
$newText += $text[$caretLine..($text.Count -1)]
}
$editor.Text = [String]::Join("`n", $newText)
$editor.SetCaretPosition($caretLine, $caretColumn)
}
#Export-ModuleMember Add-Snippet
##############################################################################################################
## Inserts command Add Snippet to custom menu
##############################################################################################################
if (-not( $psISE.CustomMenu.Submenus | where { $_.DisplayName -eq "_Snippet" } ) )
{
$null = $psISE.CustomMenu.Submenus.Add("_Snippet", {Add-Snippet}, "Ctrl+Alt+S")
}
|
PowerShellCorpus/PoshCode/0220791d-2756-4988-aca9-8cfa1366a66c.ps1
|
0220791d-2756-4988-aca9-8cfa1366a66c.ps1
|
param ([string]$recursePath= $(Throw "Du mň spesifisere ei mappe!"))
function build-word-docs($recursePath) {
# $dir = "C:\\Users\\bjorninge\\Documents\\My Dropbox\\mafo-bjorn\\bachelor-prosjekt\\Driftsdokumentasjon"
$oldDir = get-location
cd $recursePath
$files = ls -Recurse | where {$_.extension.endsWith(".docx")}
$word = new-object -com word.application
$word.Visible = $false
$word.Documents.Add() | out-null
$selection = $word.Selection
$i = 0
$count = $files.count
write-host "Totalt antall .docx-filer funnet: " $count
foreach($file in $files) {
$selection.InsertFile($file.fullname)
$selection.InsertBreak()
$i++
Write-Progress -activity "Filinnsetting" -status "Filer lagt til i Word-dokumentet : " -PercentComplete (($i / $count) * 100)
}
cd $oldDir
$word.Visible = $true
}
if( (test-path -literalpath $recursePath -pathtype container)) {
build-word-docs $recursePath
} else {
write-host "Innskrevet mappesti var ikke gyldig"
}
|
PowerShellCorpus/PoshCode/Movable button.ps1
|
Movable button.ps1
|
$btnMove_MouseDown= {
if ($_.Button -eq [Windows.Forms.MouseButtons]::Left) {
$bool = $true
$coor = [Drawing.Point]$_.Location
}
}
$btnMove_MouseMove= {
if ($bool) {
$btnMove.Location = New-Object Drawing.Point(
($btnMove.Left - $btnMove.X + $_.X), ($btnMove.Top - $btnMove.Y + $_.Y)
)
}
}
$btnMove_MouseUp= {
if ($_.Button -eq [Windows.Forms.MouseButtons]::Left) { $bool = $false }
}
function frmMain_Show {
Add-Type -AssemblyName System.Windows.Forms
[Windows.Forms.Application]::EnableVisualStyles()
$frmMain = New-Object Windows.Forms.Form
$btnMove = New-Object Windows.Forms.Button
#
#btnMove
#
$btnMove.Location = New-Object Drawing.Point(($frmMain.Width / 2 + 70), ($frmMain.Height / 2))
$btnMove.Size = New-Object Drawing.Size(110, 27)
$btnMove.Text = "Click and move"
$btnMove.Add_MouseDown($btnMove_MouseDown)
$btnMove.Add_MouseMove($btnMove_MouseMove)
$btnMove.Add_MouseUp($btnMove_MouseUp)
#
#frmMain
#
$frmMain.ClientSize = New-Object Drawing.Size(570, 370)
$frmMain.Controls.Add($btnMove)
$frmMain.FormBorderStyle = "FixedSingle"
$frmMain.MaximizeBox = $false
$frmMain.StartPosition = "CenterScreen"
$frmMain.Text = "Form1"
[void]$frmMain.ShowDialog()
}
frmMain_Show
|
PowerShellCorpus/PoshCode/vSphere Resultant Privs_2.ps1
|
vSphere Resultant Privs_2.ps1
|
# Need the Quest ActiveRoles cmdlets for this one.
Add-PSSnapin Quest.ActiveRoles* -ea SilentlyContinue
function Get-Groups {
param($principal)
# Start with this principal's base set of groups.
Write-Verbose "Checking principal $principal"
$groups = Get-QADUser $principal | Get-QADMemberOf
# Groups can be members of groups, so iterate until the list size remains fixed.
do {
$startLength = $groups.length
Write-Verbose ("Start length " + $startLength)
$groups += $groups | Get-QADMemberOf
$groups = $groups | Sort -Unique
$endLength = $groups.length
Write-Verbose ("End length " + $endLength)
} while ($endLength -ne $startLength)
Write-Output $groups
}
# Get the resultant privileges that a user has for a given object.
function Get-ResultantPrivileges {
param($principal, $viobject)
# Use the NT Account name.
$account = (Get-QADUser $principal).NTAccountName
if ($account -eq $null) {
throw "$principal not found, please check your spelling."
}
# Get the groups for this user.
$groups = Get-Groups -principal $account
$groupNames = $groups | Foreach { $_.Name }
# Get the full permission set for this object.
$perms = $viobject | Get-VIPermission
# Determine the list of roles that apply to this principal.
$relevantPerms = $perms | Where {
(($_.IsGroup -eq $true) -and ($groupNames -contains $_.Principal)) -or
($_.Principal -eq $account)
}
# Retrieve all these roles.
$roleNames = $relevantPerms | Foreach { $_.Role } | Sort -Unique
Write-Verbose "Rolenames are $roleNames"
$roleObjects = Get-VIRole $roleNames
$roleCount = ($roleObjects | Measure-Object).Count
# The resultant set is the intersection of the privileges within the role.
$roleObjects | Foreach { $_.PrivilegeList } | Group |
Where { $_.Count -eq $roleCount } |
Select Name
}
# Example:
# Get-ResultantPrivileges -principal "VMWORLD\\cshanklin" -viobject (Get-VM OpenFiler)
|
PowerShellCorpus/PoshCode/Get-Netstat _1.9.ps1
|
Get-Netstat _1.9.ps1
|
$null, $null, $null, $null, $netstat = netstat -a -n -o
[regex]$regex = '\\s+(?<Protocol>\\S+)\\s+(?<LocalAddress>\\S+)\\s+(?<RemoteAddress>\\S+)\\s+(?<State>\\S+)\\s+(?<PID>\\S+)'
$netstat | ForEach-Object {
if ( $_ -match $regex ) {
$process = "" | Select-Object Protocol, LocalAddress, RemoteAddress,
State, PID
$process.Protocol = $matches.Protocol
$process.LocalAddress = $matches.LocalAddress
$process.RemoteAddress = $matches.RemoteAddress
$process.State = $matches.State
$process.PID = $matches.PID
$process
}
}
|
PowerShellCorpus/PoshCode/Start-Cassini.ps1
|
Start-Cassini.ps1
|
function Start-Cassini([string]$physical_path=".", [int]$port=12372, [switch]$dontOpenBrowser) {
$serverLocation = Resolve-Path "C:\\Program Files (x86)\\Common Files\\Microsoft Shared\\DevServer\\10.0\\WebDev.WebServer40.EXE";
$full_app_path = Resolve-Path $physical_path
$url = "http://localhost:$port"
&($serverLocation.Path) /port:$port /path:"""$($full_app_path.Path)"""
Write-Host "Started $($full_app_path.Path) on $url"
Write-Host "Remember you can kill processes with kill -name WebDev*"
if($dontOpenBrowser -eq $false) {
[System.Diagnostics.Process]::Start($url)
}
}
|
PowerShellCorpus/PoshCode/Get-Command 2.0.ps1
|
Get-Command 2.0.ps1
|
## Which.ps1 - aka Get-Command
###################################################################################################
## This ought to be the same as Get-Command, except...
## This Which function will output the commands ...
## in the actual order they would be used by the shell
##################################################################################################
## Revision History
## 1.0 - initial release just sorted the Get-Command output by CommandType
## 2.0 - rewritten to take into account the order of commands in the PATH environment variable
##################################################################################################
function Get-Command([string]$command) {
begin { $Script:ErrorActionPreference = "SilentlyContinue" }
process {
if(!$_) { $_ = $command }
Microsoft.PowerShell.Core\\Get-Command $_ |
sort {
if($_.CommandType -match "ExternalScript|Application") {
1000 + [array]::IndexOf( (Get-Content Env:Path).Split(";"), [IO.Path]::GetDirectoryName($_.Definition) )
} else {
[int]$_.CommandType
}
}
}
}
|
PowerShellCorpus/PoshCode/Sendmail for PoSh 2 CTP3.ps1
|
Sendmail for PoSh 2 CTP3.ps1
|
#region vars
$script:maileditor = "C:\\Programme\\vim\\vim72\\vim.exe"
$script:encryption = "C:\\Programme\\GNU\\GnuPG\\gpg.exe"
$script:enckey = "s.patrick1982@gmail.com"
$script:tempmail = "C:\\temp\\psmail.txt"
$script:sigmail = "C:\\temp\\halten\\sig.txt"
$script:mailbody = ""
#endregion vars
#region initMail
function initHeader {
$script:mailTo = ($script:mailTo).Split(',') | % { $_.Trim() }
if (Test-Path $script:sigmail) {
(Get-Content $script:sigmail | Out-String) | Out-File $script:tempmail
}
& $script:maileditor $script:tempmail
}
function initMail {
$smtpserver = "smtpserver"
$myuser = "yoursmtp"
$mypass = "password"
$myAddress = "Patrick <s.patrick1982@gmail.com>"
$script:mail = New-Object System.Net.Mail.MailMessage
$script:srv = New-Object System.Net.Mail.SmtpClient
$script:srv.Host = $smtpserver
$script:srv.Credentials = New-Object System.Net.NetworkCredential($myuser, $mypass)
$script:mail.from = $myAddress
foreach ($rcpt in $script:mailTo) {
if ($rcpt -ne "") {
$script:mail.To.Add($rcpt)
}
}
$script:mail.subject = $script:subject
}
function initMailol {
$script:outlook = New-Object -ComObject Outlook.Application
$script:srv = New-Object -ComObject Redemption.SafeMailItem
$script:omail = $outlook.CreateItem("olMailItem")
$script:srv.Item = $script:omail
#region check
#User Input
foreach ($rcpt in $script:mailTo) {
$script:srv.Recipients.Add($rcpt) | Out-Null
}
#check recipients
$check = $script:srv.Recipients.ResolveAll()
if ($check -eq $False) {
for ($i=0; $i -gt $script:sitem.Recipients.Count;$i++) {
$script:srv.Recipients.Remove($i)
exit(-1)
}
}
#endregion
$script:srv.item.Subject = $script:subject
if ($script:debug -eq $true) {
Write-Host "Mail an - " $script:sitem.Recipients
Write-Host "Betreff - " $script:subject
}
}
#endregion initMail
#region sendmail
function sendmail {
Param (
[Parameter(Position=0,Mandatory=$True,HelpMessage="Sending Type (srv,ol)"]
[string]$script:client=$false,
[Parameter(Position=1,Mandatory=$True,Helpmessage="Mail To"]
[string]$script:mailTo=$false,
[Parameter(Position=2,Mandatory=$True,HelpMessage="Subject"]
[string]$script:subject=$false,
[Parameter(Position=3,Mandatory=$false,Helpmessage="Signed/Encrypted"]
[string]$script:mtype=$false
)
initheader($script:mailTo, $script:subject)
#region encrypt
switch ($script:mtype) {
s {
& $script:encryption -a -r $script:enckey --clearsign $script:tempmail
break;
}
e {
& $script:encryption -a -r $script:enckey --encrypt $script:tempmail
break;
}
}
#endregion encrypt
#body
if ($script:mtype -ne "") {
$script:mailbody = (Get-Content $script:tempmail".asc" | Out-String)
} else {
$script:mailbody = (Get-Content $script:tempmail | Out-String)
}
#cleaning
if (test-path $script:tempmail) { Remove-Item $script:tempmail -Confirm:$false }
if (test-path $script:tempmail".asc" ) { Remove-Item $script:tempmail".asc" -Confirm:$false }
switch ($script:client) {
srv {
initMail
$script:mail.Body = $script:mailbody
$script:srv.Send($script:mail)
break;
}
ol {
initMailol
$script:srv.Body = $script:mailbody
$script:srv.Send()
break;
}
}
}
|
PowerShellCorpus/PoshCode/Split-Job V 1.2.1.ps1
|
Split-Job V 1.2.1.ps1
|
#requires -version 2.0
<#
################################################################################
## Run commands in multiple concurrent pipelines
## by Arnoud Jansveld - www.jansveld.net/powershell
##
## Basic "drop in" usage examples:
## - Functions that accept pipelined input:
## Without Split-Job:
## Get-Content hosts.txt | MyFunction | Export-Csv results.csv
## With Split-Job:
## Get-Content hosts.txt | Split-Job {MyFunction} | Export-Csv results.csv
## - Functions that do not accept pipelined input (use foreach):
## Without Split-Job:
## Get-Content hosts.txt |% { .\\MyScript.ps1 -ComputerName $_ } | Export-Csv results.csv
## With Split-Job:
## Get-Content hosts.txt | Split-Job {%{ .\\MyScript.ps1 -ComputerName $_ }} | Export-Csv results.csv
##
## Example with an imported function:
## function Test-WebServer ($ComputerName) {
## $WebRequest = [System.Net.WebRequest]::Create("http://$ComputerName")
## $WebRequest.GetResponse()
## }
## Get-Content hosts.txt | Split-Job {%{Test-WebServer $_ }} -Function Test-WebServer | Export-Csv results.csv
##
## Example with importing a module
## Get-Content Clusters.txt | Split-Job { % { Get-Cluster -Name $_ } } -InitializeScript { Import-Module FailoverClusters }
##
##
## Version History
## 1.2 Changes by Stephen Mills - stephenmills at hotmail dot com
## Only works with PowerShell V2
## Modified error output to use ErrorRecord parameter of Write-Error - catches Category Info then.
## Works correctly in powershell_ise. Previous version would let pipelines continue if ESC was pressed. If Escape pressed, then it will do an async cancel of the pipelines and exit.
## Add seconds remaining to progress bar
## Parameters Added and related functionality:
## InitializeScript - allows to have custom scripts to initilize ( Import-Module ...), parameter might be renamed Begin in the future.
## MaxDuration - Cancel all pending and in process items in queue if the number of seconds is reached before all input is done.
## ProgressInfo - Allows you to add additional text to progress bar
## NoProgress - Hide Progress Bar
## DisplayInterval - frequency to update Progress bar in milliseconds
## InputObject - not yet used, planned to be used in future to support start processing the queue before pipeline isn't finished yet
## Added example for importing a module.
## 1.0 First version posted on poshcode.org
## Additional runspace error checking and cleanup
## 0.93 Improve error handling: errors originating in the Scriptblock now
## have more meaningful output
## Show additional info in the progress bar (thanks Stephen Mills)
## Add SnapIn parameter: imports (registered) PowerShell snapins
## Add Function parameter: imports functions
## Add SplitJobRunSpace variable; allows scripts to test if they are
## running in a runspace
## 0.92 Add UseProfile switch: imports the PS profile
## Add Variable parameter: imports variables
## Add Alias parameter: imports aliases
## Restart pipeline if it stops due to an error
## Set the current path in each runspace to that of the calling process
## 0.91 Revert to v 0.8 input syntax for the script block
## Add error handling for empty input queue
## 0.9 Add logic to distinguish between scriptblocks and cmdlets or scripts:
## if a ScriptBlock is specified, a foreach {} wrapper is added
## 0.8 Adds a progress bar
## 0.7 Stop adding runspaces if the queue is already empty
## 0.6 First version. Inspired by Gaurhoth's New-TaskPool script
################################################################################
#>
function Split-Job
{
param (
[Parameter(Position=0, Mandatory=$true)]$Scriptblock,
[Parameter()][int]$MaxPipelines=10,
[Parameter()][switch]$UseProfile,
[Parameter()][string[]]$Variable,
[Parameter()][string[]]$Function = @(),
[Parameter()][string[]]$Alias = @(),
[Parameter()][string[]]$SnapIn,
[Parameter()][float]$MaxDuration = $( [Int]::MaxValue ),
[Parameter()][string]$ProgressInfo ='',
[Parameter()][int]$ProgressID = 0,
[Parameter()][switch]$NoProgress,
[Parameter()][int]$DisplayInterval = 300,
[Parameter()][scriptblock]$InitializeScript,
[Parameter(ValueFromPipeline=$true)][object[]]$InputObject
)
begin
{
$StartTime = Get-Date
#$DisplayTime = $StartTime.AddMilliseconds( - $DisplayInterval )
$ExitForced = $false
function Init ($InputQueue){
# Create the shared thread-safe queue and fill it with the input objects
$Queue = [Collections.Queue]::Synchronized([Collections.Queue]@($InputQueue))
$QueueLength = $Queue.Count
# Do not create more runspaces than input objects
if ($MaxPipelines -gt $QueueLength) {$MaxPipelines = $QueueLength}
# Create the script to be run by each runspace
$Script = "Set-Location '$PWD'; "
$Script += {
$SplitJobQueue = $($Input)
& {
trap {continue}
while ($SplitJobQueue.Count) {$SplitJobQueue.Dequeue()}
@@ } }.ToString() + '|' + $Scriptblock
@@
# Create an array to keep track of the set of pipelines
$Pipelines = New-Object System.Collections.ArrayList
# Collect the functions and aliases to import
$ImportItems = ($Function -replace '^','Function:') +
($Alias -replace '^','Alias:') |
Get-Item | select PSPath, Definition
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
}
function Add-Pipeline {
# This creates a new runspace and starts an asynchronous pipeline with our script.
# It will automatically start processing objects from the shared queue.
$Runspace = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace($Host)
$Runspace.Open()
if (!$?) { throw "Could not open runspace!" }
$Runspace.SessionStateProxy.SetVariable('SplitJobRunSpace', $True)
function CreatePipeline
{
param ($Data, $Scriptblock)
$Pipeline = $Runspace.CreatePipeline($Scriptblock)
if ($Data)
{
$Null = $Pipeline.Input.Write($Data, $True)
$Pipeline.Input.Close()
}
$Null = $Pipeline.Invoke()
$Pipeline.Dispose()
}
# Optionally import profile, variables, functions and aliases from the main runspace
if ($UseProfile)
{
CreatePipeline -Script "`$PROFILE = '$PROFILE'; . `$PROFILE"
}
if ($Variable)
{
foreach ($var in (Get-Variable $Variable -Scope 2))
{
trap {continue}
$Runspace.SessionStateProxy.SetVariable($var.Name, $var.Value)
}
}
if ($ImportItems)
{
CreatePipeline $ImportItems {
foreach ($item in $Input) {New-Item -Path $item.PSPath -Value $item.Definition}
}
}
if ($SnapIn)
{
CreatePipeline (Get-PSSnapin $Snapin -Registered) {$Input | Add-PSSnapin}
}
#Custom Initialization Script for startup of Pipeline - needs to be after other other items added.
if ($InitializeScript -ne $null)
{
CreatePipeline -Scriptblock $InitializeScript
}
$Pipeline = $Runspace.CreatePipeline($Script)
$Null = $Pipeline.Input.Write($Queue)
$Pipeline.Input.Close()
$Pipeline.InvokeAsync()
$Null = $Pipelines.Add($Pipeline)
}
function Remove-Pipeline ($Pipeline)
{
# Remove a pipeline and runspace when it is done
$Pipeline.RunSpace.CloseAsync()
#Removed Dispose so that Split-Job can be quickly aborted even if currently running something waiting for a timeout.
#Added call to [System.GC]::Collect() at end of script to free up what memory it can.
#$Pipeline.Dispose()
$Pipelines.Remove($Pipeline)
}
}
end
{
# Main
# Initialize the queue from the pipeline
. Init $Input
# Start the pipelines
try
{
while ($Pipelines.Count -lt $MaxPipelines -and $Queue.Count) {Add-Pipeline}
# Loop through the pipelines and pass their output to the pipeline until they are finished
while ($Pipelines.Count)
{
# Only update the progress bar once per $DisplayInterval
if (-not $NoProgress -and $Stopwatch.ElapsedMilliseconds -ge $DisplayInterval)
{
$Completed = $QueueLength - $Queue.Count - $Pipelines.count
$Stopwatch.Reset()
$Stopwatch.Start()
#$LastUpdate = $stopwatch.ElapsedMilliseconds
$PercentComplete = (100 - [Int]($Queue.Count)/$QueueLength*100)
$Duration = (Get-Date) - $StartTime
$DurationString = [timespan]::FromSeconds( [Math]::Floor($Duration.TotalSeconds)).ToString()
$ItemsPerSecond = $Completed / $Duration.TotalSeconds
$SecondsRemaining = [math]::Round(($QueueLength - $Completed)/ ( .{ if ($ItemsPerSecond -eq 0 ) { 0.001 } else { $ItemsPerSecond}}))
Write-Progress -Activity "** Split-Job ** *Press Esc to exit* Next item: $(trap {continue}; if ($Queue.Count) {$Queue.Peek()})" `
-status "Queues: $($Pipelines.Count) QueueLength: $($QueueLength) StartTime: $($StartTime) $($ProgressInfo)" `
-currentOperation "$( . { if ($ExitForced) { 'Aborting Job! ' }})Completed: $($Completed) Pending: $($QueueLength- ($QueueLength-($Queue.Count + $Pipelines.Count))) RunTime: $($DurationString) ItemsPerSecond: $([math]::round($ItemsPerSecond, 3))"`
-PercentComplete $PercentComplete `
-Id $ProgressID `
-SecondsRemaining $SecondsRemaining
}
foreach ($Pipeline in @($Pipelines))
{
if ( -not $Pipeline.Output.EndOfPipeline -or -not $Pipeline.Error.EndOfPipeline)
{
$Pipeline.Output.NonBlockingRead()
$Pipeline.Error.NonBlockingRead() | % { Write-Error -ErrorRecord $_ }
} else
{
# Pipeline has stopped; if there was an error show info and restart it
if ($Pipeline.PipelineStateInfo.State -eq 'Failed')
{
Write-Error $Pipeline.PipelineStateInfo.Reason
# Restart the runspace
if ($Queue.Count -lt $QueueLength) {Add-Pipeline}
}
Remove-Pipeline $Pipeline
}
if ( ((Get-Date) - $StartTime).TotalSeconds -ge $MaxDuration -and -not $ExitForced)
{
Write-Warning "Aborting job! The MaxDuration of $MaxDuration seconds has been reached. Inputs that have not been processed will be skipped."
$ExitForced=$true
}
if ($ExitForced) { $Pipeline.StopAsync(); Remove-Pipeline $Pipeline }
}
while ($Host.UI.RawUI.KeyAvailable)
{
if ($Host.ui.RawUI.ReadKey('NoEcho,IncludeKeyDown,IncludeKeyUp').VirtualKeyCode -eq 27 -and !$ExitForced)
{
$Queue.Clear();
Write-Warning 'Aborting job! Escape pressed! Inputs that have not been processed will be skipped.'
$ExitForced = $true;
#foreach ($Pipeline in @($Pipelines))
#{
# $Pipeline.StopAsync()
#}
}
}
if ($Pipelines.Count) {Start-Sleep -Milliseconds 50}
}
#Clear the Progress bar so other apps don't have to keep seeing it.
Write-Progress -Completed -Activity "`0" -Status "`0"
# Since reference to Dispose was removed. I added this to try to help with releasing resources as possible.
# This might be a bad idea, but I'm leaving it in for now. (Stephen Mills)
[GC]::Collect()
}
finally
{
foreach ($Pipeline in @($Pipelines))
{
if ( -not $Pipeline.Output.EndOfPipeline -or -not $Pipeline.Error.EndOfPipeline)
{
Write-Warning 'Pipeline still runinng. Stopping Async.'
$Pipeline.StopAsync()
Remove-Pipeline $Pipeline
}
}
}
}
}
|
PowerShellCorpus/PoshCode/VMWare Quick Migration_5.ps1
|
VMWare Quick Migration_5.ps1
|
#########################################
#Name: VMWare Quick Migration Function
#Author: Justin Grote <jgrote NOSPAMAT enpointe DOT com>
#Credit: Inspired by Mike DiPetrillo's Quick Migration Script: http://www.mikedipetrillo.com/mikedvirtualization/2008/10/quick-migration-for-vmware-the-power-of-powershell.html
#Version: 0.1
#Last Revised: 31 July 2009
#
#Description: Performs the fucntional equivalent of a Hyper-V Quick Migration by suspending a VM,
# moving it to a new host, and resuming it. This does not require vMotion licensing.
# it works by providing required VM objects via the pipeline or the second argument,
# and specifying the Destination host in the first argument.
# The commeand accepts both text strings and VMHost objects for the VMHost Parameter
#
#Prerequisites:
# Powershell v1
# VMWare PowerCLI 4.0 (May work with earlier version but not tested)
# VMWare Foundation Edition or Better (for API support). May work with VMWare Server 2 but not tested.
#
#Instructions to Install: Save this script and import into your session with, for example, . C:\\temp\\quickmigrate.ps1
# You can also include it in your PowerCLI profile to have it automatically included.
#Command Usage: get-vm MyTestVM | Quick-MigrateVM "MyTestHost2"
#########################################
function QuickMigrate-VM {
PARAM(
$NewVMHost = ""
, [VMware.VimAutomation.Client20.VirtualMachineImpl]$VMsToMigrate = $null
)
BEGIN {
if (!$NewVMHost){
Write-Error "No Destination VMHost Specified. You must specify a host to migrate to. `n Example: Get-VM `"Test`" | QuickMigrate-VM `"Host1`""
break
}
elseif ($VMsToMigrate) {
Write-Output $InputObject | &($MyInvocation.InvocationName) -NewVMHost $newVMHost
}
else {
#If NewVMHost was provided as a String, convert it into a VMHost Object.
if ($NewVMHost.GetType().Name -eq "String") {
set-variable -name destinationVMHost -value (get-vmhost $NewVMHost) -scope 1
}
#Make sure that we have a VMHost object to work with.
if (! $destinationVMHost -or (! $destinationVMHost.GetType().Name -eq "VMHostImpl")) {
write-error "Destination VM Host was not found or you provided the wrong object type. Please provide a VMHostImpl object or specify the fully qualified name of a VM Host"
break
}
write-host -fore white "===Begin Quick Migration==="
}
}
PROCESS {
$step = 0
$skip = $false
#In the Event of an error, output the error, and skip the rest of the current item.
#This is a workaround for the fact that "continue" doesn't work in a function process loop.
trap {
write-host -fore yellow "`tSKIPPED: "$_.Exception.Message
set-variable -name skip -value ($true) -scope 1
continue
}
$vmToMigrate = $_
### Validation Checks
if($_ -is [VMware.VimAutomation.Client20.VirtualMachineImpl]) {
write-host -fore white "Quick Migrating $($vmToMigrate.Name) to $NewVMHost..."
}
else {
throw "Object Passed was not a Virtual Machine object. Object must be of type VMware.VimAutomation.Client20.VirtualMachineImpl."
}
# Check for connected devices
if (! $skip -and (get-cddrive $vmToMigrate).ConnectionState.Connected -ieq "TRUE") {
throw "Connected CD Drive. Please disconnect and try again."
}
if (! $skip -and (get-floppydrive $vmToMigrate).ConnectionState.Connected -ieq "TRUE") {
throw "Connected Floppy Drive. Please disconnect and try again."
}
# Make sure the current VM Host and the Destination Host are different.
$sourceVMHost = get-vmhost -vm $vmToMigrate
if (! $skip -and ($sourceVMHost.Name -eq $destinationVMHost.Name)) {
throw "Source and Destination Hosts are the same."
}
###Validation Complete, begin Migration
if (! $skip) {
$step++
write-host -fore cyan "`t($step). Suspending" $vmToMigrate.Name"..."
$suspend = Suspend-VM -VM $vmToMigrate -confirm:$false
}
if (! $skip) {
$step++
write-host -fore cyan "`t($step). Moving" $vmToMigrate.Name "to" $destinationVMHost.Name"..."
$migrate = Get-VM $vmToMigrate | Move-VM -Destination $destinationVMHost
}
if (! $skip) {
$step++
write-host -fore cyan "`t($step). Resuming" $vmToMigrate.Name"..."
$resume = Start-VM -VM $vmToMigrate
}
write-host -fore green "`tCOMPLETED"
}
END { write-host -fore white "===END Quick Migration===" }
}
|
PowerShellCorpus/PoshCode/New-ODataServiceProxy_3.ps1
|
New-ODataServiceProxy_3.ps1
|
function New-ODataServiceProxy {
#.Synopsis
# Creates a proxy class for an odata web service and assigns it to the specified variable.
# DOES NOT output the proxy on the pipleline, and you should not do so either!
#.Description
# Uses the data service client utility (DataSvcUtil.exe) to generate a proxy class (and types for all objects) for an OData web service.
# WARNING: Outputting this object to the PowerShell host will result in queriying all the object collections on the service.
# NOPTE: kb982307 is required to use this with .Net 3.5, see links/notes
#.Parameter URI
# The URI for the web service
#.Parameter Name
# The name of the global variable to store the OData WebService proxy object in (defaults to "ODataServiceProxy")
#.Parameter Passthru
# Causes the method to output all of the types defined by the service metadata
#.Example
# New-ODataServiceProxy http://odata.netflix.com/Catalog/
# $AdventuresInOdyssey = $ODataServiceProxy.Titles.AddQueryOption('$filter',"substringof('Adventures in Odyssey',Name)")
# $AdventuresInOdyssey | Format-List Name, ReleaseYear, Url, Synopsis
#.Example
# function Get-Films {
# param($Name)
# New-ODataServiceProxy http://odata.netflix.com/Catalog/ -Name NetFlix
# if($Name -match "\\*") {
# $sName = $Name -replace "\\*"
# # Note the substring PLUS a Where -like filter to pull off wildcard matching which isn't supported by NetFlix
# $Global:Films = $proxy.Titles.AddQueryOption('$filter',"substringof('$sName',Name)") | Where { $_.Name -like $Name }
# } else {
# $Global:Films = $proxy.Titles.AddQueryOption('$filter',"'$Name' eq Name")
# }
# $Films | Format-List Name, ReleaseYear, AverageRating, Url, Synopsis
# Write-Host "NOTE: This data is cached in `$Films" -Fore Yellow
# }
#
# C:\\PS>Get-Films Salt
#
#.Example
# New-ODataServiceProxy http://packages.nuget.org/v1/FeedService.svc/ NuGet
# $NuGet.Packages.AddQueryOption('$filter',"startswith(Title,'O') eq true") | Format-Table Id, Version, Authors, Description -Wrap -Auto
#
#.Link
# Data Services Update for .Net 3.5 SP1: http://support.microsoft.com/kb/982307
# ADO.NET Data Service Client Utility: http://msdn.microsoft.com/en-us/library/ee383989.aspx
# AddQueryOption: http://msdn.microsoft.com/en-us/library/cc646860.aspx
# NetFlix Catalog Documentation: http://developer.netflix.com/docs/oData_Catalog
#.Notes
# I can't stress enough that you should not output the proxy object, or any property that returns a System.Data.Services.Client.DataServiceQuery[T] without a filter unless you're sure that's what you want.
# A kb patch is required for .Net 3.5 SP1 to get the Data Services to 2.0 so you can use most of the OData services you will see on the web: http://support.microsoft.com/kb/982307
#
# VERSION HISTORY:
# v1.0 - 2010 Aug 02 - First Version http://poshcode.org/2039
# v1.1 - 2010 Aug 03 - Simple Caching http://poshcode.org/2040
# - Added a type cache to make it easier to find proxies you've already compiled (because we can't recompile them)
# v1.2 - 2010 Aug 03 - Examples
# - Added additional examples
# v1.3 - 2010 Aug 03 - Language fix
# - Removed the Language parameter from Add-Type when on .Net4 (setting it explicitly results in downgrading to 3, and having multiple assembly references!?)
# v1.4 - 2011 Jan 17 - Stop output
# - Changed output to just be the variable that gets set, so it's properties don't all get called resulting in huge web service calls.
# v1.5 - 2011 Jan 17 - Clean up examples
# - Add Example for calling NuGet service
# - Clean up Links, Re-document that you need the DataServices update for .Net 3.5
param(
[Parameter(Mandatory=$true)]
[Alias("Uri","WSU")]
[String]$WebServiceUri = "http://odata.netflix.com/Catalog/",
[Alias("Name","VN")]
[String]$VariableName = "ODataServiceProxy",
[switch]$Passthru
)
if(!(Test-Path Variable::Global:ODataServices)){
## You can only use this on .Net 4 or .Net 3.5 SP1
## For .Net 3.5 SP1 you need to download http://support.microsoft.com/kb/982307
## If you don't have it, this won't succeed
[Reflection.Assembly]::Load("System.Data.Services.Client, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") | Out-Null
$global:ODataServices = @{}
}
$normalized = ([uri]$WebServiceUri).AbsoluteUri.TrimEnd("/")
if($global:ODataServices.ContainsKey($normalized)) {
New-Object $global:ODataServices.$normalized.ContextType $WebServiceUri
if($Passthru) {
$global:ODataServices.$normalized.OtherTypes
}
return
}
## Find the right DataSvcUtil for this version of .Net
switch($PSVersionTable.ClrVersion.Major) {
4 { # PoshConsole and modded .Net4 PowerShell_ISE etc.
Set-Alias Get-ODataServiceDefinition (Get-ChildItem ([System.Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory()) DataSvcUtil.exe)
break
}
2 { # PowerShell.exe and everyone else
$FrameworkPath = [System.Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory() | Split-Path
Set-Alias Get-ODataServiceDefinition (Get-ChildItem $FrameworkPath\\v3.5\\DataSvcUtil.exe)
break
}
default { throw "This script is out of date, please fix it and upload a new one to PoshCode!" }
}
## Get the service definition into a string via a temp file
$temp = [IO.Path]::GetTempFileName()
Get-ODataServiceDefinition -out:$temp -uri:$WebServiceUri -nologo | tee -var output | out-null
if(!$?) {
Write-Error ($output -join "`n")
return
}
$code = @(Get-Content $temp) -join "`n" # -Delim ([char]0)
Remove-Item $temp
switch($PSVersionTable.ClrVersion.Major) {
4 {
$Types = Add-Type $code -Reference "System.Data.Services.Client, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Core" -Passthru
}
2 {
$Types = Add-Type $code -Reference "System.Data.Services.Client, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" -Passthru -Language CSharpVersion3
}
default { throw "This script is out of date, please fix it and upload a new one to PoshCode!" }
}
if(!$Types) { return }
$ContextType = $Types | Where-Object { $_.BaseType -eq [System.Data.Services.Client.DataServiceContext] }
$global:ODataServices.$normalized = New-Object PSObject -Property @{ContextType=$ContextType; OtherTypes=$([Type[]]($Types|Where-Object{$_.BaseType -ne [System.Data.Services.Client.DataServiceContext]}))}
$ctx = new-object $ContextType $WebServiceUri
$VariableName = $VariableName.Split(":")[-1]
if(Test-Path Variable:$VariableName) { Remove-Variable $VariableName -Force }
Set-Variable -Name "Global:$VariableName" -Value $ctx -Description "An OData WebService Proxy to $WebServiceUri" -Option ReadOnly, AllScope -Passthru
if($Passthru) { Write-Output $types }
}
|
PowerShellCorpus/PoshCode/Send-SmtpMessage.ps1
|
Send-SmtpMessage.ps1
|
## Send-SmtpMessage -- a special implementation to show how to send via GMail
## GMail is a bit more complicated than most....
###################################################################################################
## Examples:
## Send-SmtpMessage "receiver@gmail.com" "Hello there" "This is an important email"
## sends a message after prompting you for your login credentials...
## notice this will use your login as the FROM email (gmail will force that anyway)
##
## Send-SmtpMessage "receiver@gmail.com" "Hello there" "This is an important email" `
## $(New-Object Net.NetworkCredential "Username","Password") `
## "Sender@Server.com" "smtp.Server.com" $null
## sends a message without prompting, and specifies the sender and server address...
###################################################################################################
## Revision History
## 1.2 - Works for gmail now
## 1.0 - Works for me
###################################################################################################
param (
[Net.Mail.MailAddress]$to = $(Read-Host "Email address to send to (eg: receiver@hotmail.com)")
,[string]$Subject = $(Read-Host "Email Subject")
,[string]$Body = $(Read-Host "Main Email Body")
## Note your login name for gmail is: user@gmail.com
,[Net.NetworkCredential]$credentials = $(Get-Credential)
,[Net.Mail.MailAddress]$from = $null
,[string]$Server="smtp.gmail.com" # Change this to your server address
,[int]$Port=587 # Does anyone other than gmail use this port?
)
## Fix up the credentials for Gmail
## (gmail requires user@gmail.com in the username, and NOTHING in the domain)
$credentials.UserName += "@" + $credentials.Domain
$credentials.Domain = ""
if(!$from) {
$from = $credentials.UserName
}
## Most (not gmail) servers will not need to specify a port
if($Port) {
$mail = new-object Net.Mail.SmtpClient $Server,$Port
} else {
$mail = new-object Net.Mail.SmtpClient $Server
}
$mail.Credentials = $credentials
## Gmail _requires_ Ssl -- most others seem to have it as an option, nowadays
$mail.EnableSsl = $true
## And finally ....
$mail.Send($From,$To,$Subject,$Body)
|
PowerShellCorpus/PoshCode/Highlight-Syntax 2.0.ps1
|
Highlight-Syntax 2.0.ps1
|
#requires -version 2.0
# Highlight-Syntax.ps1
# version 2.0
# by Jeff Hillman
#
# this script uses the System.Management.Automation.PsParser class
# to highlight PowerShell syntax with HTML.
param( [string] $code, [switch] $LineNumbers )
if ( Test-Path $code -ErrorAction SilentlyContinue )
{
$code = Get-Content $code | Out-String
}
$backgroundColor = "#DDDDDD"
$foregroundColor = "#000000"
$lineNumberColor = "#404040"
$PSTokenType = [System.Management.Automation.PSTokenType]
$colorHash = @{
# $PSTokenType::Unknown = $foregroundColor;
$PSTokenType::Command = "#C86400";
# $PSTokenType::CommandParameter = $foregroundColor;
# $PSTokenType::CommandArgument = $foregroundColor;
$PSTokenType::Number = "#800000";
$PSTokenType::String = "#800000";
$PSTokenType::Variable = "#000080";
# $PSTokenType::Member = $foregroundColor;
# $PSTokenType::LoopLabel = $foregroundColor;
# $PSTokenType::Attribute = $foregroundColor;
$PSTokenType::Type = "#404040";
$PSTokenType::Operator = "#C86400";
# $PSTokenType::GroupStart = $foregroundColor;
# $PSTokenType::GroupEnd = $foregroundColor;
$PSTokenType::Keyword = "#C86400";
$PSTokenType::Comment = "#008000";
$PSTokenType::StatementSeparator = "#C86400";
# $PSTokenType::NewLine = $foregroundColor;
$PSTokenType::LineContinuation = "#C86400";
# $PSTokenType::Position = $foregroundColor;
}
filter Html-Encode
{
$_ = $_ -replace "&", "&"
$_ = $_ -replace " ", " "
$_ = $_ -replace "<", "<"
$_ = $_ -replace ">", ">"
$_
}
# replace the tabs with spaces
$code = $code -replace "\\t", ( " " * 4 )
if ( $LineNumbers )
{
$highlightedCode = "<li style='color: $lineNumberColor; padding-left: 5px'>"
}
else
{
$highlightedCode = ""
}
$parser = [System.Management.Automation.PsParser]
$lastColumn = 1
$lineCount = 1
foreach ( $token in $parser::Tokenize( $code, [ref] $null ) | Sort-Object StartLine, StartColumn )
{
# get the color based on the type of the token
$color = $colorHash[ $token.Type ]
if ( $color -eq $null )
{
$color = $foregroundColor
}
# add whitespace
if ( $lastColumn -lt $token.StartColumn )
{
$highlightedCode += ( " " * ( $token.StartColumn - $lastColumn ) )
}
switch ( $token.Type )
{
$PSTokenType::String {
$string = "<span style='color: {0}'>{1}</span>" -f $color,
( $code.SubString( $token.Start, $token.Length ) | Html-Encode )
# we have to highlight each piece of multi-line strings
if ( $string -match "\\r\\n" )
{
# highlight any line continuation characters as operators
$string = $string -replace "(``)(?=\\r\\n)",
( "<span style='color: {0}'>``</span>" -f $colorHash[ $PSTokenType::Operator ] )
$stringHtml = "</span><br />`r`n"
if ( $LineNumbers )
{
$stringHtml += "<li style='color: $lineNumberColor; padding-left: 5px'>"
}
$stringHtml += "<span style='color: $color'>"
$string = $string -replace "\\r\\n", $stringHtml
}
$highlightedCode += $string
break
}
$PSTokenType::NewLine {
$highlightedCode += "<br />`r`n"
if ( $LineNumbers )
{
$highlightedCode += "<li style='color: $lineNumberColor; padding-left: 5px'>"
}
$lastColumn = 1
++$lineCount
break
}
default {
if ( $token.Type -eq $PSTokenType::LineContinuation )
{
$lastColumn = 1
++$lineCount
}
$highlightedCode += "<span style='color: {0}'>{1}</span>" -f $color,
( $code.SubString( $token.Start, $token.Length ) | Html-Encode )
}
}
$lastColumn = $token.EndColumn
}
# put the highlighted code in the pipeline
"<div style='width: 100%; " +
"/*height: 100%;*/ " +
"overflow: auto; " +
"font-family: Consolas, `"Courier New`", Courier, mono; " +
"font-size: 12px; " +
"background-color: $backgroundColor; " +
"color: $foregroundColor; " +
"padding: 2px 2px 2px 2px; white-space: nowrap'>"
if ( $LineNumbers )
{
$digitCount = $lineCount.ToString().Length
"<ol start='1' style='border-left: " +
"solid 1px $lineNumberColor; " +
"margin-left: $( ( $digitCount * 10 ) + 15 )px; " +
"padding: 0px;'>"
}
$highlightedCode
if ( $LineNumbers )
{
"</ol>"
}
"</div>"
|
PowerShellCorpus/PoshCode/ConvertFrom-Hashtable_2.ps1
|
ConvertFrom-Hashtable_2.ps1
|
# function ConvertFrom-Hashtable {
PARAM([HashTable]$hashtable,[switch]$combine)
BEGIN { $output = New-Object PSObject }
PROCESS {
if($_) {
$hashtable = $_;
if(!$combine) {
$output = New-Object PSObject
}
}
$hashtable.GetEnumerator() |
ForEach-Object { Add-Member -inputObject $output `
-memberType NoteProperty -name $_.Name -value $_.Value }
$output
}
#}
|
PowerShellCorpus/PoshCode/USB Script backup_4.ps1
|
USB Script backup_4.ps1
|
<#
.SYNOPSIS
Backup-ToUSB.ps1 (Version 3.1, 19 Jan 2012)
.DESCRIPTION
This script will backup recently changed *.ps1,*.psm1,*.psd1 files from any
selected folder (default is $pwd) to any number of inserted USB devices, on
which an archive folder 'PSarchive' will be created if it does not already
exist.
Any USB Hard Disk will appear as a local system disk (DeviceType 3) so the
default 'Exclude' pattern is set to drives C:\\ and D:\\ which can be changed
to suit.
.EXAMPLE
Invoke-Expression ".\\Backup-ToUsb.ps1 -exclude cd $args"
Add this in a function in $profile and it will exclude drives C and D from
the backup devices used.
.EXAMPLE
.\\Backup-ToUSB.ps1 ps* -exclude cde -v
Backup all ps* files and exclude drives C,D,E and show Verbose output.
.EXAMPLE
.\\Backup-ToUSB.ps1 -type ps1 -v
Select *.ps1 files to be archived. 'Verbose' will display the name of each
file processed and the size (in Kb) on disk. Using the '-Debug' switch shows
the time difference that has tagged any file for archive.
.NOTES
If the message 'WARNING: Error on drive X:\\ - restart.' keeps appearing,
manually enter 'Test-Path X:\\' before resubmitting, which seems to cure it!
The author may be contacted via www.SeaStarDevelopment.Bravehost.com
#>
param ([String]$types = 'ps1',
[String]$folder = $pwd,
[String]$exclude = 'cd',
[Switch]$debug,
[Switch]$verbose)
if ($verbose) {
$verbosePreference = 'Continue'
}
if ($debug) {
$debugPreference = 'Continue'
}
$drive = '-<BLANK>-'
if ($types -notmatch '^ps1|psd1|psm1|ps\\*$') { #Adjust to suit.
Write-Warning "Invalid filetype ($types): ps1, psm1, psd1 only."
exit 1
}
if (!(Test-path $folder -pathType Container )) {
[System.Media.SystemSounds]::Hand.Play()
Write-Warning "$folder is not a directory - resubmit."
exit 3
}
function copyFile ([string]$value, [String]$value1) {
Copy-Item -Path $value -Destination $newFolder -Force
Write-Verbose "--> Archiving file: (Size $value1) $value"
$SCRIPT:files++
}
$exclude = "[$exclude]:"
Get-WMIObject Win32_LogicalDisk -filter 'DriveType = 2 OR DriveType = 3' |
Select-Object VolumeName, FreeSpace, DeviceID |
Where-Object {($_.VolumeName -ne $null) -and
($_.DeviceID -notmatch $exclude)} |
foreach {
$vol = $_.VolumeName
$drive = $_.DeviceID + '\\'
[int]$free = $_.FreeSpace / 1MB
Write-Verbose "Scanning USB devices - Drive = [$drive] Name = $vol, Free = $free Mb"
if (!(Test-Path $drive)) {
Write-Warning "Error on drive $drive - restart."
[System.Media.SystemSounds]::Hand.Play() #Sometimes gives an error.
exit 4
}
[int]$SCRIPT:files = 0 #Reset counter for each new drive.
$newFolder = $drive + "PSarchive" #Check if folder exists.
if (!(Test-Path $newFolder)) {
New-Item -path ($drive) -name PSarchive -type directory | Out-Null
}
(Get-ChildItem $folder -filter "*.$types") |
foreach {
$checkFile = Join-Path ($drive + 'PSArchive') $_
$fsize = "{0:0000}" -f ($_.Length /1kb)
if ($fsize -eq '0000') {
$fsize = '<1kb'
}
if (Test-path $checkFile) {
$lwtHdd = $_.LastWriteTime #HDD time last written.
$lwtUsb = (Get-Item $checkFile).LastWriteTime
if ($lwtHdd -gt $lwtUsb) {
Write-Debug "(HDD) $lwtHdd (USB) $LwtUsb $_"
copyFile $_ $fSize
}
}
else { #New file, so archive it anyway.
Write-Debug "(HDD) $($_.LastWriteTime) (USB Archiving new file) $_"
copyFile $_ $fsize
}
}
$print = "Backup to USB drive [{0}] (Volume = {2}) completed; {1} files copied." -f $drive, $SCRIPT:files, $vol
Write-Host "--> $print"
}
if ($drive -eq '-<BLANK>-') {
[System.Media.SystemSounds]::Asterisk.Play()
Write-Warning "No USB drive detected - Insert a device and resubmit."
}
|
PowerShellCorpus/PoshCode/Get-DefragAnalysis_1.ps1
|
Get-DefragAnalysis_1.ps1
|
# defrag_analysis.ps1
#
# Displays Defrag Analysis Info for a remote server.
#
# Author: tojo2000@tojo2000.com
Set-PSDebug -Strict`
trap [Exception] {
continue
}
function GenerateForm {
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
$form1 = New-Object System.Windows.Forms.Form
$richTextBox1 = New-Object System.Windows.Forms.RichTextBox
$textBox1 = New-Object System.Windows.Forms.TextBox
$button1 = New-Object System.Windows.Forms.Button
$handler_button1_Click = {
$richTextBox1.Text = ''
$volumes = @(gwmi Win32_Volume -ComputerName $textBox1.Text `
-Filter 'DriveType = 3')
foreach ($volume in $volumes) {
$analysis = $volume.DefragAnalysis().DefragAnalysis
Write-TextBox "Drive : $($volume.DriveLetter)"
Write-TextBox "Volume Name : $($analysis.VolumeName)"
Write-TextBox ("Volume Size : " +
"{0:0.00}GB" -f ($analysis.VolumeSize/1GB))
Write-TextBox "Total Fragmentation : $($analysis.TotalPercentFragmentation)%"
Write-TextBox ""
Write-TextBox "Free Space : $($analysis.FreeSpacePercent)%"
Write-TextBox ("Free Space Frag. : " +
"$($analysis.FreeSpacePercentFragmentation)%")
Write-TextBox ""
Write-TextBox "Files : $($analysis.TotalFiles)"
Write-TextBox "Fragmented Files : $($analysis.TotalFragmentedFiles)"
Write-TextBox "File Fragmentation : $($analysis.FilePercentFragmentation)%"
Write-TextBox ""
Write-TextBox "Folders : $($analysis.TotalFolders)"
Write-TextBox "Fragmented Folders : $($analysis.FragmentedFolders)"
Write-TextBox ""
Write-TextBox "MFT Usage : $($analysis.MFTPercentInUse)%"
Write-TextBox "MFT Fragments : $($analysis.TotalMFTFragments)"
Write-TextBox "MFT Records : $($analysis.MFTRecordCount)"
Write-TextBox ""
Write-TextBox ("PageFile Size : " +
"{0:0.00}GB" -f ($analysis.PageFileSize/1GB))
Write-TextBox "PageFile Fragments : $($analysis.TotalPageFileFragments)"
Write-TextBox ""
Write-TextBox "----------------------------"
}
}
$handler_form1_Load = {
$textBox1.Select()
}
$form1.Name = 'form1'
$form1.Text = 'Defrag Info 1.0'
$form1.BackColor = [System.Drawing.Color]::FromArgb(255,227,227,227)
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 428
$System_Drawing_Size.Height = 404
$form1.ClientSize = $System_Drawing_Size
$form1.add_Load($handler_form1_Load)
$richTextBox1.Text = ''
$richTextBox1.TabIndex = 2
$richTextBox1.Name = 'richTextBox1'
$richTextBox1.Font = New-Object System.Drawing.Font("Courier New",10,0,3,0)
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 343
$System_Drawing_Size.Height = 315
$richTextBox1.Size = $System_Drawing_Size
$richTextBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 40
$System_Drawing_Point.Y = 61
$richTextBox1.Location = $System_Drawing_Point
$form1.Controls.Add($richTextBox1)
$textBox1.Text = '<Enter Server Name>'
$textBox1.Name = 'textBox1'
$textBox1.TabIndex = 1
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 250
$System_Drawing_Size.Height = 20
$textBox1.Size = $System_Drawing_Size
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 40
$System_Drawing_Point.Y = 21
$textBox1.Location = $System_Drawing_Point
$textBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$form1.Controls.Add($textBox1)
$button1.UseVisualStyleBackColor = $True
$button1.Text = 'Analyze'
$button1.DataBindings.DefaultDataSourceUpdateMode = 0
$button1.TabIndex = 0
$button1.Name = 'button1'
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 75
$System_Drawing_Size.Height = 23
$button1.Size = $System_Drawing_Size
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 308
$System_Drawing_Point.Y = 19
$button1.Location = $System_Drawing_Point
$button1.add_Click($handler_button1_Click)
$form1.Controls.Add($button1)
$form1.ShowDialog()| Out-Null
}
function Write-TextBox {
param([string]$text)
$richTextBox1.Text += "$text`n"
}
# Launch the form
GenerateForm
|
PowerShellCorpus/PoshCode/d1c44eb5-e148-4345-a712-661f0b8e3e08.ps1
|
d1c44eb5-e148-4345-a712-661f0b8e3e08.ps1
|
#
# simple example using a hash to parse CAS Connect Logs
#
# after using the get-CASConnectLogEntries.ps1 to collect the log information
# this script runs thru those files and counts Cached vs Classic
#
#
# the directory where you keep these "cas connect logs" - change to fit your needs
$Script:CasLogUNCDir ='\\\\<server>\\<drv>\\Web\\Data\\CASConnectLogs'
# Hast Table to hold results : LegacyExchangeDN-Clientversion, Mode
$Cleints = @{}
foreach ($Line in (gci $Script:CasLogUNCDir | gc) ) {
#legacyExchangeDN
$LEDN = $Line.Split(",")[3]
#Outlook version
$OLVER = $Line.Split(",")[6]
#ClientMode
$Mode = $Line.Split(",")[7]
if(-not ($Clients.ContainsKey($LEDN+'-'+$OLVer))) {
$Clients.Add($($LEDN+'-'+$OLVer),$MODE)
}
}
"Total Clients [ {0} ]; Cached [ {1} ]; Classic [ {2} ]"-f ($Clients.Count),(($Clients.getenumerator() | ?{$_.value-match'Cached'}).Count),(($Clients.getenumerator() | ?{$_.value-notmatch'Cached'}).Count)
|
PowerShellCorpus/PoshCode/vmware guests subnet.ps1
|
vmware guests subnet.ps1
|
$snapins = "vmware.vimautomation.core"
foreach ($snapin in $snapins){if (!(Get-PSSnapin $snapin -ErrorAction SilentlyContinue)){Add-PSSnapin $snapin}}
$vserver = "vmware vCenter Server"
$vNetwork = "General_Services"
$logfile = "d:\\Scripts\\log\\vm.log"
$subnet = "255.255.255.128"
connect-viserver -Server $vserver
$vms = Get-VM
foreach ($vm in $vms){
$nw = $vm|Get-NetworkAdapter
if (($nw.networkname) -like $vNetwork){
$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration -ComputerName $vm.name| where{$_.IPEnabled -eq “TRUE”}
Foreach($NIC in $NICs) {
try{
$NIC.EnableStatic($nic.ipaddress, $subnet)
$string = "$vm is adapted"
$string
$string|Out-File -FilePath $logfile -Append -Encoding OEM
}
Catch{
$string = "$vm is not adapted"
$string
$string|Out-File -FilePath $logfile -Append -Encoding OEM
}
}
}
}
|
PowerShellCorpus/PoshCode/SharePoint Site Owners.ps1
|
SharePoint Site Owners.ps1
|
Get-SPWebApplication | Get-SPSite -Limit ALL |
ForEach-Object {
$content = "";
$rootSite = New-Object Microsoft.SharePoint.SPSite($_.Url)
$subSites = $rootSite.AllWebs;
if($subSites.Count -le 0)
{
@@ This occurs when a Site Collection does not contains any subsite (not even the root site)
Write-Host "The Site Collection" $siteUrl "does not contains any site."
}
else
{
foreach($subsite in $subSites)
{
$siteOwners = $subsite.AssociatedOwnerGroup
if($siteOwners)
{
foreach ($owner in $subsite.Users)
{
if($subsite.ParentWeb)
{
$content += "$($subsite.ParentWeb.Url),$($owner.Name),Site Owner`n"
}
else
{
$content += "$($subsite.Url),$($owner.Name),Site Owner`n"
}
}
}
else
{
$content += "Could not find an AssociatedGroupOwner in the site with the Url: $($subsite.Url) `n"
}
$subsite.Dispose()
$rootSite.Dispose()
}
@@ Set the patch to the CSV files
$FilePath = "C:\\Owners\\" + $_.Url.Replace("http://","").Replace("/","-").Replace(":","-") + ".csv";
out-file -filepath $FilePath -inputobject $content
}
}
|
PowerShellCorpus/PoshCode/Script logging.ps1
|
Script logging.ps1
|
#region Log File Management
$ScriptName = $MyInvocation.mycommand.name
$LocalAppDir = "$(gc env:LOCALAPPDATA)\\PS_Data"
$LogName = $ScriptName.replace(".ps1", ".log")
$MaxLogFileSizeMB = 5 # After a log file reaches this size it will archive the existing and create a new one
trap
[Exception] {
sendl
"error: $($_.Exception.GetType().Name) - $($_.Exception.Message)"
}
function LogFileCheck
{
if (!(Test-Path $LocalAppDir)) # Check if log file directory exists - if not, create and then create log file for this script.
{
mkdir $LocalAppDir
New-Item "$LocalAppDir\\$LogName" -type file
break
}
if
(Test-Path "$LocalAppDir\\$LogName") # {
if (((gci "$LocalAppDir\\$LogName").length/1MB) -gt $MaxLogFileSizeMB) # Check size of log file - to stop unweildy size, archive existing file if over limit and create fresh.
{
$NewLogFile = $LogName.replace(".log", " ARCHIVED $(Get-Date -Format dd-MM-yyy-hh-mm-ss).log")
ren "$LocalAppDir\\$LogName" "$LocalAppDir\\$NewLogFile"
}
}
}
function sendl ([string]$message) # Send to log file
{
$toOutput
= "$(get-date) > $message " | Out-File "$LocalAppDir\\$LogName" -append -NoClobber
}
LogFileCheck
#endregion Log File Management
|
PowerShellCorpus/PoshCode/Binary Clock_1.ps1
|
Binary Clock_1.ps1
|
function get-binary($number,$words=1+(1*[int]($number -gt 255))) {
# Takes the passed numerical value and converts to a Binary word.
# Pads 0 to the left to make it a proper set of 8 or 16
#
# If you use this function outside of the clock, it is automatically
# designed to generate a 16 bit output padded if the value is greater
# than 255
return [convert]::tostring($number,2).padleft(8*$words,"0")
}
Clear-Host
Do {
# Get the Current Date/Time
$Current=GET-DATE
#Build a String with the Hours, Minutes and Seconds in Binary
$output=(Get-Binary $current.hour)+":"+(get-binary $Current.minute)+":"+(Get-Binary $Current.Second)
# Remember our location
$location=$Host.UI.RawUI.CursorPosition
# Send output to the screen
Write-Host $output
# The Position back
$Host.UI.RawUI.CursorPosition=$location
# Take a nap for a second
Start-sleep 1
} until ($FALSE) # Do it over and over and over since $FALSE will never be $TRUE
|
PowerShellCorpus/PoshCode/Get-TwitterReply.ps1
|
Get-TwitterReply.ps1
|
# Its a modification from the version in http://blogs.technet.com/jamesone/archive/2009/02/16/how-to-drive-twitter-or-other-web-tools-with-powershell.aspx
# usees https and gets all replies
Function Get-TwitterReply {
param ($username, $password)
if ($WebClient -eq $null) {$Global:WebClient=new-object System.Net.WebClient }
$WebClient.Credentials = (New-Object System.Net.NetworkCredential -argumentList $username, $password)
$page = 0
$ret = @()
do { $Page ++
$replies = ([xml]$webClient.DownloadString("https://twitter.com/statuses/replies.xml?page=$Page") ).statuses.status
$ret += $replies
Write-host $replies.count
} while ($replies.count -gt 0 ) # sometimes I get less than 20
$ret
write-host $ret.count
# Returns the 20 most recent @replies for the authenticating user.
#page: Optional. Retrieves the 20 next most recent replies
#since. Optional. Narrows the returned results to just those replies created after the specified HTTP-formatted date, up to 24 hours old.
#since_id. Optional. Returns only statuses with an ID greater than (that is, more recent than) the specified ID. Ex: http://twitter.com/statuses/replies.xml?since_id=12345
}
|
PowerShellCorpus/PoshCode/New-ArgsTestExe.ps1
|
New-ArgsTestExe.ps1
|
Add-Type -Type @"
using System;
internal class ArgsTest
{
private static void Main(string[] args)
{
Console.WriteLine();
/*
I've commented this out because (at least in C#)
it is the same as Environment.GetCommandLineArgs()
Except that GetCommandLineArgs shows parameter 0 as the executable path
*/
// Console.WriteLine("Using args:");
// Console.WriteLine();
// for (int i = 0; i < args.Length; i++)
// {
// Console.WriteLine(" Arg {0} is: {1}", i, args[i]);
// }
// Console.WriteLine();
// Console.WriteLine();
Console.WriteLine("CommandLine:");
Console.WriteLine();
Console.WriteLine(" " + Environment.CommandLine);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("CommandLineArgs:");
Console.WriteLine();
string[] arguments = Environment.GetCommandLineArgs();
for (int i = 0; i < arguments.Length; i++)
{
Console.WriteLine(" Arg {0} is: {1}", i, arguments[i]);
}
Console.WriteLine();
Console.WriteLine();
System.Threading.Thread.Sleep(10000);
}
}
"@ -OutputAssembly ArgsTest.exe -OutputType ConsoleApplication
|
PowerShellCorpus/PoshCode/Out-DataTable.ps1
|
Out-DataTable.ps1
|
#######################
<#
.SYNOPSIS
Creates a DataTable for an object
.DESCRIPTION
Creates a DataTable based on an objects properties.
.INPUTS
Object
Any object can be piped to Out-DataTable
.OUTPUTS
System.Data.DataTable
.EXAMPLE
$dt = Get-Alias | Out-DataTable
This example creates a DataTable from the properties of Get-Alias and assigns output to $dt variable
.NOTES
Adapted from script by Marc van Orsouw see link
Version History
v1.0 - Chad Miller - Initial Release
.LINK
http://thepowershellguy.com/blogs/posh/archive/2007/01/21/powershell-gui-scripblock-monitor-script.aspx
#>
function Out-DataTable
{
[CmdletBinding()]
param([Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)] [PSObject[]]$InputObject)
Begin
{
$dt = new-object Data.datatable
$First = $true
}
Process
{
foreach ($object in $InputObject)
{
$DR = $DT.NewRow()
$object.PsObject.get_properties() | foreach
{
if ($first)
{
$Col = new-object Data.DataColumn
$Col.ColumnName = $_.Name.ToString()
$DT.Columns.Add($Col)
}
if ($_.IsArray)
{ $DR.Item($_.Name) =$_.value | ConvertTo-XML -AS String -NoTypeInformation -Depth 1 }
else { $DR.Item($_.Name) = $_.value }
}
$DT.Rows.Add($DR)
$First = $false
}
}
End
{
Write-Output @(,($dt))
}
} #Out-DataTable
|
PowerShellCorpus/PoshCode/ASPX Mailbox (5 of 6).ps1
|
ASPX Mailbox (5 of 6).ps1
|
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MailboxTaskResults.aspx.cs" Inherits="MailboxTaskResults" %>
<%@ Reference Page="~/MailboxConfirm.aspx" %>
<%@ PreviousPageType VirtualPath="~/MailboxConfirm.aspx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title> Domain Mailbox Task Results</title>
</head>
<body>
<form id="frmMailboxTaskResults" runat="server"></form>
</body>
</html>
|
PowerShellCorpus/PoshCode/VMware guest information.ps1
|
VMware guest information.ps1
|
# vminfo.ps1
#
# Give this a VMware guest and it will attempt to dump all the information available.
#
# Example: .\\vminfo.ps1 "guestname"
#
# This scripts assumes that you have already connected to a VirtualCenter server.
#
# This was developed and tested using VMware vSphere PowerCLI version 4.1.1.2816
# on an ESXi 4.1 build 381591 cluster
Param($guest)
####################################################################
# ProcessObject - This recursive function does the bulk of the work.
#
#Input Parameters
#
# $xobj - Object to dump info on
# $pref - Prefix to use on print lines
#
# When an object is encountered then we recursively call ourselves to
# process that object after first updating the prefix.
#
# Snapshot objects can point to both a parent and a child. Dumping both
# Parent and Child objects results in an endless loop. Therefore dump only
# Child objects.
function ProcessObject ($xobj, $pref){
$plen = $pref.length
$pad = $width - $plen
If ($pad -lt 0){$pad = 0}
# Get information on all of the members of this object because what is done with a member is
# dependent on whether the member is an object or is a data item and if it is a data item
# what kind of data item is it
$xom = $xobj | get-member -membertype property
foreach ($ent in $xom){
$xnam = $ent.name
#write-host ">>>>>>>Processing entry" $ent.name
$xnlen = $xnam.length
$strs = $ent.Definition.split(" ")
# process 1st level simple things like strings and numbers including simple arrays
# There are some fields in a VMware guest "Get-View" description we will ignore
# because they are obsolete and have either had their descriptive names changed
# or a new cmdlet is now available and it is the preferred method for finding
# out about the object.
#
# The following "objects" may be encountered but will be ignored. These are legacy objects
# from ESX 3.5 but were promoted to having their own cmdlets in ESX 4. Therefore we will
# ignore them when found as members of some other object prefering to examine them using the
# new cmdlets.
#
# legacy guest objects
#
# CDDrives == Get-CDDrives
# FloppyDrives == Get-FloppyDrive
# HardDisk == Get-HardDisk
# NetworkAdapters == Get-NetworkAdapter
# UsbDevices == Get-UsbDevice
#
# legacy host objects
#
# ConsoleNic == Get-VMHostNetworkAdapter
# PhysicalNic == Get-VMHostNetworkAdapter
# VirtualNic == Get-VMHostNetworkAdapter
# VirtualSwitch == Get-VirtualSwitch
# ScsiLun == Get-ScsiLun
#
#
if ($xnam -match "^(CDDrives|FloppyDrives|HardDisks|NetworkAdapters|UsbDevices)$" ){
"{0,-$plen}{1,-1}{2,-$pad}{3,-2}{4,-30}" -f $pref, ".", $xnam, ":", "== skipping legacy device object ==" #| Out-File -FilePath $reportfile -Append
}
elseif ($xnam -match "^(ConsoleNic|PhysicalNic|ScsiLun|VirtualNic|VirtualSwitch)$" ){
#Write-Host "****** skipping legacy Network Adapter object- $xnam"
"{0,-$plen}{1,-1}{2,-$pad}{3,-2}{4,-30}" -f $pref, ".", $xnam, ":", "== skipping legacy Network Adapter object ==" #| Out-File -FilePath $reportfile -Append
}
# The following are obsolete identifiers in ESX 3.5 that have new names as of ESX version 4.x
# We will ignore all old identifiers and only display the new identifiers.
#
# Description - replaced by Notes
# Host is replaced by VMHost
# HostId is replaced by VMHostId
# State == ConnectionState
# VirtualMachineId == VMId
elseif ($xnam -match "^(Description|Host|HostId|State|VirtualMachineId)$" ){
"{0,-$plen}{1,-1}{2,-$pad}{3,-2}{4,-30}" -f $pref, ".", $xnam, ":", "== skipping obsolete identifier ==" #| Out-File -FilePath $reportfile -Append
}
# Examining the following will result in recursive loops threrfore we will skip them.
#
# Parent
# VM
# VMHost
elseif ($xnam -match "^(VMHost)$" ){
"{0,-$plen}{1,-1}{2,-$pad}{3,-2}{4,-30}" -f $pref, ".", $xnam, ":", "== skipping object to avoid infinite loop ==" #| Out-File -FilePath $reportfile -Append
}
elseif ($strs[0] -match "^System.String\\[\\]" ){
if (!$xobj.$xnam.count) {
$res = $xobj.$xnam
#Write-Host "=== single entry array name =" $xnam "result" $res
"{0,-$plen}{1,-1}{2,-$pad}{3,-2}{4,-30}" -f $pref, ".", $xnam, ":", $xobj.$xnam #| Out-File -FilePath $reportfile -Append
}
else {
$count = $xobj.$xnam.count
for ($i=0; $i -lt $count; $i++){
$namlen = $xnam.length
$ipad = $pad - 2 - $namlen
If ($i -gt 9){$ipad--}
If ($ipad -lt 1){$ipad = 1}
"{0,-$plen}{1,-1}{2,-$namlen}{3,1}{4,1}{5,-$ipad}{6,-2}{7,-30}" -f $pref, ".", $xnam, "[", $i, "]", ":", $xobj.$xnam[$i] #| Out-File -FilePath $reportfile -Append
}
}
}
elseif ($strs[0] -match "^System.(String|Int|Nullable|Boolean|DateTime|Double)" ){
# If this is a "value__" then show the number and the symbolic name
if ($xnam -eq "value__"){
$vpad = $pad + 3
"{0,-$plen}{1,$vpad}{2,-2}{3,-2}{4,-30}" -f $pref, ": ", $xobj.$xnam, "-", $xobj #| Out-File -FilePath $reportfile -Append
}
else {
"{0,-$plen}{1,-1}{2,-$pad}{3,-2}{4,-30}" -f $pref, ".", $xnam, ":", $xobj.$xnam #| Out-File -FilePath $reportfile -Append
}
}
elseif ($strs[0] -match "^VMware.Vim(.|Automation.Types|Automation.ViCore)"){
# Hack to avoid closed loop when crawling snapshot structures
# Each child points back to its parent and each parent points to its children
# hence and endless loop. Therefore do not process parents
if ($xnam -match "^(Parent|ParentSnapshot|VM)$"){
$pad = $width-$plen
If ($pad -lt 0){$pad = 0}
"{0,-$plen}{1,-1}{2,-$pad}{3,-2}" -f $pref, ".", $xnam, ": == skipping $xnam to avoid infinite loop ==" #| Out-File -FilePath $reportfile -Append
}
else {
$pad = $width-$plen
If ($pad -lt 0){$pad = 0}
$yobj = $xobj.$xnam
$newp = $pref + "." + $xnam
if (!$yobj){
"{0,-$plen}{1,-1}{2,-$pad}{3,-2}" -f $pref, ".", $xnam, ": =undefined=" #| Out-File -FilePath $reportfile -Append
}
else{
if (!$yobj.count){
ProcessObject $yobj $newp
}
else {
$lc = $yobj.count
for ($z = 0; $z -lt $lc; $z++){
$zobj = $yobj[$z]
$zperf = $newp + "[" + $z + "]"
ProcessObject $zobj $zperf
}
}
}
}
}
elseif ($strs[0] -match "^System.(Collections)" ){
Foreach ($entry in $xobj.$xnam){
$newpref = $pref + "." + $xnam
$cpad = $pad - $xnam.length - 1
If ($cpad -lt 0){$cpad = 0}
"{0,-$plen}{1,-1}{2,-$Cpad}{3,-2}{4,-30}" -f $newpref, ".", $entry.Key, ":", $entry.value #$strs[0] #| Out-File -FilePath $reportfile -Append
}
}
else {
"{0,-$plen}{1,-1}{2,-$pad}{3,-2}{4,-30}" -f $pref, ".", $xnam, ":", $ent.Definition #$strs[0] #| Out-File -FilePath $reportfile -Append
}
}
}
function POLauncher ($xobj, $pref){
if (!$xobj.count){
ProcessObject $xobj $pref
}
else {
$lc = $xobj.count
for ($z = 0; $z -lt $lc; $z++){
$zobj = $xobj[$z]
$zperf = $pref + "[" + $z + "]"
ProcessObject $zobj $zperf
}
}
}
# end function ProcessObject
$reportfile = "vminfo-rpt.txt"
$first = 20
$width = 70
$xvm = get-vm -name $guest
$prefix = $xvm.name + " Get-VM"
POLauncher $xvm $prefix
# Display information about virtual devices attached to the guest
# Process devices CDDrives|Harddisk|FloppyDrives|NetworkAdapters|UsbDevices
$dvm = get-HardDisk -vm $xvm
$prefix = $xvm.name + " Get-HardDisk"
POLauncher $dvm $prefix
$cdvm = get-CDDrive -vm $xvm
$prefix = $xvm.name + " Get-CDDrive"
POLauncher $cdvm $prefix
$flpvm = get-FloppyDrive -vm $xvm
$prefix = $xvm.name + " Get-FloppyDrive"
POLauncher $flpvm $prefix
$netvm = get-NetworkAdapter -vm $xvm
$prefix = $xvm.name + " Get-NetworkAdapter"
POLauncher $netvm $prefix
$usbvm = get-UsbDevice -vm $xvm
$prefix = $xvm.name + " Get-UsbDevice"
POLauncher usbvm $prefix
#Get-View return more information than Get-Vm
$xview = $xvm | get-view
$prefix = $xvm.name + " Get-View"
POLauncher $xview $prefix
# Return information about any snapshots.
$snap = get-snapshot $xvm
if ($snap){
$prefix = $xvm.name + " Get-Snapshot"
POLauncher $snap $prefix
}
#Tell ua about the host we are running on
$vmhost = $xvm.VMHost
$prefix = $vmhost.name + " Get-VMHost"
POLauncher $vmhost $prefix
# probably don't want to do this one unless you want to be buried in data
#$vmhostv = Get-View $vmhost
#$prefix = $vmhostv.name + " Get-View"
#POLauncher $vmhostv $prefix
#Dump information about the Host's devices
$nics = Get-VMHostNetworkAdapter $vmhost
foreach ($nic in $nics){
$prefix = $vmhost.name + " " + $nic.Name
POLauncher $nic $prefix
}
$vmguest = get-vmguest $xvm
$prefix = $xvm.name + " Get-VMGuest"
#POLauncher $vmguest $prefix
$vmdatastore = get-datastore -vm $xvm
$prefix = $xvm.name + " Get-Datastore"
POLauncher $vmdatastore $prefix
$dc = Get-Datacenter -vm $xvm
$prefix = $xvm.name + " Get-Datacenter"
#POLauncher $dc $prefix
|
PowerShellCorpus/PoshCode/WPFDiskSpace.ps1
|
WPFDiskSpace.ps1
|
#Usage: Get-WmiObject -computername Z002 Win32_LogicalDisk -filter "DriveType=3" | ./WPFDiskSpace.ps1
#Note: Requires .NET 3.5, Visifire Charts (tested on v2.1.0), Powerboots (tested on v0.1)
$libraryDir = Convert-Path (Resolve-Path "$ProfileDir\\Libraries")
[Void][Reflection.Assembly]::LoadFrom( (Convert-Path (Resolve-Path "$libraryDir\\WPFVisifire.Charts.dll")) )
if (!(Get-PSSnapin | ?{$_.name -eq 'PoshWpf'}))
{ Add-PsSnapin PoshWpf }
New-BootsWindow -Async {
$chart = New-Object Visifire.Charts.Chart
$chart.Height = 500
$chart.Width = 800
$chart.watermark = $false
$chart.Theme = "Theme2"
$chart.View3D = $true
$chart.BorderBrush = [System.Windows.Media.Brush]"Gray"
$chart.CornerRadius = [System.Windows.CornerRadius]5
$chart.BorderThickness = [System.Windows.Thickness]0.5
$chart.AnimationEnabled = $false
$ds1 = New-Object Visifire.Charts.DataSeries
$ds1.RenderAs = [Visifire.Charts.RenderAs]"StackedBar"
$ds1.LegendText = "UsedSpace"
$ds1.LabelEnabled = $true
#$ds1.LabelText = "#YValue"
$ds2 = New-Object Visifire.Charts.DataSeries
$ds2.RenderAs = [Visifire.Charts.RenderAs]"StackedBar"
$ds2.LegendText = "FreeSpace"
$ds2.LabelEnabled = $true
#$ds2.LabelText = "#YValue"
$ds2.RadiusX = 5
$ds2.RadiusY = 5
foreach ($disk in $input)
{
$pFree = $([int](([double]$disk.FreeSpace/[double]$disk.Size) * 100))
$pUsed = $([int]((([double]$disk.Size - [double]$disk.FreeSpace)/[double]$disk.Size) * 100))
$dp1 = new-object Visifire.Charts.DataPoint
$dp1.AxisXLabel = ($disk.Name)
$dp1.YValue = ([math]::round((([double]$disk.Size - [double]$disk.FreeSpace)/1GB),2))
$dp1.LabelText = "$pUsed"
$ds1.DataPoints.Add($dp1)
$dp2 = new-object Visifire.Charts.DataPoint
$dp2.YValue = ([math]::round(($disk.FreeSpace/1GB),2))
$dp2.LabelText = "$pFree"
$ds2.DataPoints.Add($dp2)
}
$chart.Series.Add($ds1)
$chart.Series.Add($ds2)
$chart
} -Title "Disk Space"
|
PowerShellCorpus/PoshCode/AD attributes.ps1
|
AD attributes.ps1
|
<%@ Language=VBScript %>
<% StartTime = Timer %>
<!--#include file = "global.inc"-->
<html>
<head><title><%=strCompany%> - Search List</title>
</head>
<body>
<!--#include file="default.htm"-->
<link rel="stylesheet" href="/server/default.css" TYPE="text/css" media="screen">
<%
Dim MyVariable
MyVariable=Request.Form("name")
MyVariable =Replace(MyVariable,"'","''")
'the request.form gets the info within the boxes of the form actioned
'from the previous HTML/ASP
gotname = Request.form("name")
%>
<%
Dim objRootDSE, objConnection, objRecordSet, objCommand
Dim strDomainLDAP, intPage, i, j, strTRbgColor, strTemp
Const ADS_SCOPE_SUBTREE = 2
Set objRootDSE = GetObject("GC://RootDSE")
strDomainLDAP = objRootDSE.Get("DefaultNamingContext")
Set objRootDSE = Nothing
response.write("Display Name that was searched for: <h3>" & gotname)
Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = Server.CreateObject("ADODB.Recordset")
Set objCommand = Server.CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection
objCommand.Properties("Page Size") = 10000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
objCommand.Properties("Size Limit") = 10000
objCommand.CommandText = "SELECT mail, l, title, Displayname, msds-PrincipalName" & _
" FROM 'GC://windows2008DC' WHERE objectCategory='user' AND homemdb='*' AND UserAccountControl='512' AND objectclass='User' AND displayname= '*" & myvariable & "*' ORDER BY Name"
objRecordSet.Open objCommand.CommandText, objConnection,1,1
objRecordSet.PageSize = Cint(RowsPerPage)
If Request.QueryString("page") = "" Then
intPage = 1
Else
intPage = Request.QueryString("page")
End If
If objRecordSet.EOF Then
Response.Write "<h3>No search term entered or search term not found</h3>" & vbCrLf
Response.End
Else
Response.Write "<center><h3>" & strCompany & " - Searchlist </h3>" & vbCrLf
objRecordSet.AbsolutePage = intPage
Response.Write "<table align=center border=1>" & vbNewLine
Response.Write " <tr align=center>" & vbNewLine
For i = 0 To objRecordSet.Fields.Count - 1
Response.Write " <th>" & objRecordSet.Fields(i).Name & "</th>" & vbNewLine
Next
Response.Write " </tr>" & vbNewLine
rem Response.Write objRecordSet.RecordCount
For j = 1 To objRecordSet.RecordCount
rem objRecordSet.PageSize
Response.Write " <tr bgColor='"
strTRbgColor = RowOddColor
If j Mod 2 = 0 Then strTRbgColor = RowEvenColor
Response.Write strTRbgColor
If RowMoveColor <> "" Then
Response.Write "' onmouseover=this.bgColor='" & RowMoveColor & "' onmouseout=this.bgColor='" & strTRbgColor
End If
Response.Write "'>" & vbCrLf
If objRecordSet.Fields(0).Value <> "" Then strTemp = objRecordSet.Fields(0).Value
Response.Write " <td>winnt://" & strTemp & "</td>" & vbNewLine
For i = 1 To objRecordSet.Fields.Count - 1
strTemp = "<font color=" & strTRbgColor & ">-</font>"
If objRecordSet.Fields(i).Value <> "" Then strTemp = objRecordSet.Fields(i).Value
Response.Write " <td>" & strTemp & "</td>" & vbNewLine
Next
Response.Write " </tr>" & vbNewLine
objRecordSet.MoveNext
Next
Response.Write "</table>" & vbNewLine
Response.Write "<br><br>" & vbNewLine
objRecordSet.Close
Set objRecordSet = Nothing
Set objConnection = Nothing
End If
%>
</body>
</html>
<%
Private Function TrimServerVariable(strString)
Dim temp 'As String
If inStr(strString,"&") <> 0 Then
arr = Split(strString, "&")
strString = ""
For i = 0 To UBound(arr) - 1
temp = Left(arr(i), InStr(arr(i), "="))
If InStr(strString, temp) = 0 Then
strString = strString & arr(i) & "&"
End If
Next
strString = Left(strString, Len(strString) - 1)
End If
TrimServerVariable = strString
End Function
%>
<%
EndTime = Timer
Response.Write "<!-- Page rendered in " & (EndTime-StartTime) & " -->" & vbNewLine
%>
|
PowerShellCorpus/PoshCode/SearchZIP_3.psm1 .ps1
|
SearchZIP_3.psm1 .ps1
|
function SearchZIPfiles {
<#
.SYNOPSIS
Search for (filename) strings inside compressed ZIP or RAR files (V2.4).
.DESCRIPTION
In any directory containing a large number of ZIP/RAR compressed Web Page files
this procedure will search each individual file name for simple text strings,
listing both the source RAR/ZIP file and the individual file name containing
the string. The relevant RAR/ZIP can then be subsequently opened in the usual
way.
Using the '-Table' (or alias '-GridView') switch will show the results with the
Out-GridView display.
.EXAMPLE
extract -find 'library' -path d:\\scripts
Searching for 'library' - please wait... (Use CTRL+C to quit)
[Editor.zip] File: Windows 7 Library Procedures.mht
[Editor.rar] File: My Library collection from 1974 Idi Amin.html
[Test2.rar] File: Playlists from library - Windows 7 Forums.mht
[Test3.rar] File: Module library functions UserGroup.pdf
Folder 'D:\\Scripts' contains 4 matches for 'library' in 4 file(s).
.EXAMPLE
extract -find 'backup' -path desktop
Searching for 'backup' - please wait... (Use CTRL+C to quit)
[Web.zip] File: How To Backup User and System Files.mht
[Pages.rar] File: Create an Image Backup.pdf
Folder 'D:\\Scripts' contains 2 matches for 'backup' in 2 file(s).
.EXAMPLE
extract pdf desk
Searching for 'pdf' - please wait... (Use CTRL+C to quit)
[Test1.rar] File: VirtualBox_ Guest Additions package.pdf
[Test2.rar] File: W8 How to Install Windows 8 in VirtualBox.pdf
[Test2.rar] File: W8 Install Windows 8 As a VM with VirtualBox.pdf
Folder 'C:\\Users\\Sam\\desktop' contains 3 matches for 'pdf' in 2 file(s).
This example uses the 'extract' alias to find all 'pdf' files on the desktop.
.NOTES
The first step will find any lines containing the selected pattern (which can
be anywhere in the line). Each of these lines will then be split into 2
headings: Source and Filename.
Note that there may be the odd occasion where a 'non-readable' character in the
returned string slips through the net!
.LINK
Web Address Http://www.SeaStarDevelopment.BraveHost.com
#>
[CmdletBinding()]
param([string][string][Parameter(Mandatory=$true)]$Find,
[string][ValidateNotNullOrEmpty()]$path = $pwd,
[switch][alias("GRIDVIEW")]$table)
Set-StrictMode -Version 2
[int]$count = 0
if ($path -like 'desk*') {
$path = Join-Path $home 'desktop\\*'
}
else {
$xpath = Join-Path $path '*' -ea 0
if (!($?) -or !(Test-Path $path)) {
Write-Warning "Path '$path' is invalid - resubmit"
return
}
$path = $xpath
}
Get-ChildItem $path -include '*.rar','*.zip' |
Select-String -SimpleMatch -Pattern $find |
foreach-Object `
-begin {
$container = @{}
$folder = $path.Replace('*','')
$lines = @{}
$regex = '(?s)^(?<zip>.+?\\.(?:zip|rar)):(?:\\d+):.*\\\\(?<file>.*\\.(mht|html?|pdf))(.*)$'
Write-Host "Searching for '$find' - please wait... (Use CTRL+C to quit)"
} `
-process {
$_ = $_ -replace '/','\\'
if ( $_ -match $regex ) {
if ($container.keys -contains $matches.zip) {
$container[$matches.zip] +=1 #Record the number in each.
}
else {
$container[$matches.zip] = 1
}
$source = $matches.zip -replace [regex]::Escape($folder)
$file = $matches.file
$file = $file -replace '\\p{S}|\\p{Cc}',' ' #Some 'Dingbats'.
$file = $file -replace '\\s+',' ' #Single space words.
if ($table) {
$key = "{0:D4}" -f $count
$lines["$key $source"] = $file #Create a unique key.
}
else {
Write-Host "[$source] File: $file"
}
$count++
}
} `
-end {
$total = "in $($container.count) file(s)."
$title = "Folder '$($path.Replace('\\*',''))' contains $($count) matches for '$find' $total"
if ($table -and $count -gt 0) {
$lines.GetEnumerator() |
Select-Object @{name = 'Source';expression = {$_.Key.SubString(5)}},
@{name = 'File' ;expression = {$_.Value}} |
Sort-Object File |
Out-GridView -Title $title
}
else {
if ($count -eq 0) {
$title = "Folder '$($path.Replace('\\*',''))' contains no matches for '$find'."
}
Write-Host $title
}
}
} #End function.
New-Alias extract SearchZIPfiles -Description 'Find Web files inside ZIP/RAR'
Export-ModuleMember -Function SearchZIPfiles -Alias Extract
|
PowerShellCorpus/PoshCode/Test-TCPPort_2.ps1
|
Test-TCPPort_2.ps1
|
function Test-TCPPort {
param (
[parameter(Mandatory=$true)]
[string] $ComputerName,
[parameter(Mandatory=$true)]
[string] $Port
)
try {
$TimeOut = 5000
$IsConnected = $false
$Addresses = [System.Net.Dns]::GetHostAddresses($ComputerName) | ? {$_.AddressFamily -eq 'InterNetwork'}
$Address = [System.Net.IPAddress]::Parse($Addresses)
$Socket = New-Object System.Net.Sockets.TCPClient
$Connect = $Socket.BeginConnect($Address, $Port, $null, $null)
$Wait = $Connect.AsyncWaitHandle.WaitOne($TimeOut, $false)
if ( $Socket.Connected ) {
$IsConnected = $true
$Socket.Close()
} else {
$IsConnected = $false
}
} catch {
Write-Debug $_
$IsConnected = $false
} finally {
return $IsConnected
}
}
|
PowerShellCorpus/PoshCode/Dumping COM.ps1
|
Dumping COM.ps1
|
$arr = @()
$key = "HKLM:\\SOFTWARE\\Classes\\CLSID"
foreach ($i in (gci $key)) {
$des = $key + "\\" + $i.PSChildName + "\\ProgID"
Write-Progress "Dumping. Please, standby..." $des
foreach ($a in (gp -ea 0 $des)."(default)") {
$arr += $a
}
}
[array]::Sort([array]$arr)
$arr | Out-File -file C:\\logs\\COMnames.txt -enc UTF8
|
PowerShellCorpus/PoshCode/Get-DiskUsage_4.ps1
|
Get-DiskUsage_4.ps1
|
Function Get-DiskUsage {
<#
.SYNOPSIS
A tribute to the excellent Unix command DU.
.DESCRIPTION
This command will output the full path and the size of any object
and it's subobjects. Using just the Get-DiskUsage command without
any parameters will result in an output of the directory you are
currently placed in and it's subfolders.
.PARAMETER Path
If desired a path can be specified with the Path parameter. In no path
is specified $PWD will be used.
.PARAMETER h
the -h paramater is the same as -h in Unix. It will list the folders
and subfolders in the most appropriate unit depending on the size
(i.e. Human Readable).
.PARAMETER l
The -l paramater will add the largest file to the end of the output.
.PARAMETER Sort
Allows you to sort by Folder or Size. If none i specified the default
of Folder will be used.
.PARAMETER Depth
Depth will allow you to specify a maximum recursion depth. A depth
of 1 would return the immediate subfolders under the root.
.PARAMETER Force
Works the same way as Get-ChildItem -force.
.PARAMETER Descending
Works the same way as Sort-Object -descending.
.LINK
http://www.donthaveasite.nu
.NOTES
Author: Jonas Hallqvist
Developed with Powershell v3
#>
[CmdletBinding(
SupportsShouldProcess=$True
)]
param (
[String]$Path=$PWD,
[Switch]$h,
[Switch]$l,
[String]$Sort="Folder",
[Int]$Depth,
[Switch]$Force,
[Switch]$Descending
)
$ErrorActionPreference = "silentlycontinue"
function HumanReadable {
param ($size)
switch ($size) {
{$_ -ge 1PB}{"{0:#'P'}" -f ($size / 1PB); break}
{$_ -ge 1TB}{"{0:#'T'}" -f ($size / 1TB); break}
{$_ -ge 1GB}{"{0:#'G'}" -f ($size / 1GB); break}
{$_ -ge 1MB}{"{0:#'M'}" -f ($size / 1MB); break}
{$_ -ge 1KB}{"{0:#'K'}" -f ($size / 1KB); break}
default {"{0}" -f ($size) + "B"}
}
}
function LargestFolder {
if ($h) {
$large = ($results | Sort-Object -Property Size -Descending)[0] | Format-Table @{Label="Size";Expression={HumanReadable $_.Size};Align="Right"},Folder -AutoSize -HideTableHeaders
Write-host "Largest Folder is:" -NoNewline
$large
}
else {
$large = ($results | Sort-Object -Property Size -Descending)[0] | Format-Table @{Label="Size";Expression={"$($_.Size)B"};Align="Right"},Folder -AutoSize -HideTableHeaders
Write-host "Largest Folder is:" -NoNewline
$large
}
}
function Max-Depth {
param(
[String]$Path = '.',
[String]$Filter = '*',
[Int]$Level = 0,
[Switch]$Force,
[Switch]$Descending,
[int]$i=0
)
$results=@()
$root = (Resolve-Path $Path).Path
if ($root -notmatch '\\\\$') {$root += '\\'}
if (Test-Path $root -PathType Container) {
do {
[String[]]$_path += $root + "$Filter"
$Filter = '*\\' + $Filter
$i++
}
until ($i -eq $Level)
$dirs=Get-ChildItem -directory $_path -Force:$Force
foreach ($dir in $dirs) {
$size = 0
$size += (gci $dir.Fullname -recurse | Measure-Object -Property Length -Sum).Sum
$results += New-Object psobject -Property @{Folder=$dir.fullname;Size=$size}
}
if ($h) {
$results | Sort-Object $Sort -Descending:$Descending | Format-Table @{Label="Size";Expression={HumanReadable $_.Size};Align="Right"},Folder -AutoSize
}
if ($l) {
LargestFolder
}
if (($h -eq $false) -and ($l -eq $false)) {
$results | Sort-Object $Sort -Descending:$Descending | Format-Table @{Label="Size";Expression={"$($_.Size)B"};Align="Right"},Folder -AutoSize
}
}
}
if ($Depth) {
Max-Depth -Path $Path -Level $Depth -Force:$Force -Descending:$Descending
}
else {
$results = @()
$dirs=Get-ChildItem -directory $Path -Force:$Force -Recurse
foreach ($dir in $dirs) {
$size = 0
$size += (gci $dir.FullName -Recurse | Measure-Object -Property Length -Sum).Sum
$results+= New-Object psobject -Property @{Folder=$dir.FullName;Size=$size}
}
if ($h) {
$results | Sort-Object $Sort -Descending:$Descending | Format-Table @{Label="Size";Expression={HumanReadable $_.Size};Align="Right"},Folder -AutoSize
}
if ($l) {
LargestFolder
}
if (($h -eq $false) -and ($l -eq $false)) {
$results | Sort-Object $Sort -Descending:$Descending | Format-Table @{Label="Size";Expression={"$($_.Size)B"};Align="Right"},Folder -AutoSize
}
}
}
<#
Copyright (c) 2013, Jonas Hallqvist
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#>
|
PowerShellCorpus/PoshCode/egg_timer_1.ps1
|
egg_timer_1.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/Export-HTML.ps1
|
Export-HTML.ps1
|
#Requires -Version 2.0
<#
Export-Html behaves exactly like native ConvertTo-HTML
However it has one optional parameter -Path
Which lets you specify the output file: e.g.
Get-Process | Export-Html C:\\temp\\processes.html
(c) Dmitry Sotnikov
http://dmitrysotnikov.wordpress.com
Proxy generated using PowerGUI Script Editor code snippets:
http://poshoholic.com/2009/08/28/learn-powershell-v2-features-using-powershell-code-snippets/
All changes to the proxy commented
This sample from Kirk used for inspiration:
http://poshoholic.com/2009/09/18/powershell-3-0-why-wait-importing-typed-objects-with-typed-properties-from-a-csv-file/
#>
function Export-Html {
[CmdletBinding(DefaultParameterSetName='Page')]
param(
[Parameter(ValueFromPipeline=$true)]
[System.Management.Automation.PSObject]
${InputObject},
# Adding Path parameter
# (made it Position 0, and incremented Position for others)
[Parameter(Position=0)]
[Alias('PSPath', 'FilePath')]
[ValidateNotNullOrEmpty()]
[System.String]
${Path},
[Parameter(Position=1)]
[ValidateNotNullOrEmpty()]
[System.Object[]]
${Property},
[Parameter(ParameterSetName='Page', Position=4)]
[ValidateNotNullOrEmpty()]
[System.String[]]
${Body},
[Parameter(ParameterSetName='Page', Position=2)]
[ValidateNotNullOrEmpty()]
[System.String[]]
${Head},
[Parameter(ParameterSetName='Page', Position=3)]
[ValidateNotNullOrEmpty()]
[System.String]
${Title},
[ValidateSet('Table','List')]
[ValidateNotNullOrEmpty()]
[System.String]
${As},
[Parameter(ParameterSetName='Page')]
[Alias('cu','uri')]
[ValidateNotNullOrEmpty()]
[System.Uri]
${CssUri},
[Parameter(ParameterSetName='Fragment')]
[ValidateNotNullOrEmpty()]
[Switch]
${Fragment},
[ValidateNotNullOrEmpty()]
[System.String[]]
${PostContent},
[ValidateNotNullOrEmpty()]
[System.String[]]
${PreContent})
begin
{
try {
$outBuffer = $null
if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
{
$PSBoundParameters['OutBuffer'] = 1
}
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('ConvertTo-Html',
[System.Management.Automation.CommandTypes]::Cmdlet)
# define string variable to become the target command line
#region Initialize helper variable to create command
$scriptCmdPipeline = ''
#endregion
# add new parameter handling
#region Process and remove the Path parameter if it is present
if ($Path) {
$PSBoundParameters.Remove('Path') | Out-Null
$scriptCmdPipeline += " | Out-File -FilePath $Path"
}
#endregion
$scriptCmd = {& $wrappedCmd @PSBoundParameters}
# redefine command invocation
#region Append our pipeline command to the end of the wrapped command script block.
$scriptCmd = $ExecutionContext.InvokeCommand.NewScriptBlock(
[string]$scriptCmd + $scriptCmdPipeline
)
#endregion
$steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
$steppablePipeline.Begin($PSCmdlet)
} catch {
throw
}
}
process
{
try {
$steppablePipeline.Process($_)
} catch {
throw
}
}
end
{
try {
$steppablePipeline.End()
} catch {
throw
}
}
<#
.ForwardHelpTargetName ConvertTo-Html
.ForwardHelpCategory Cmdlet
#>}
|
PowerShellCorpus/PoshCode/337d4ddf-c2e9-4243-8681-ea4303a40040.ps1
|
337d4ddf-c2e9-4243-8681-ea4303a40040.ps1
|
None
|
PowerShellCorpus/PoshCode/Convert-SchemaGUID.ps1
|
Convert-SchemaGUID.ps1
|
# List of Guids not properly defined in AD but used
# Used to initialize GuidCache.
New-Variable -Name GuidCache -Force -Option AllScope -Scope Script -Description "Cached GUIDs from AD. :: [redtoo]"
$Script:GuidCache = @{
"a05b8cc2-17bc-4802-a710-e7c15ab866a2" = "Autoenroll"
"00000000-0000-0000-0000-000000000000" = "All"
}
$Script:GuidObjects = @{}
function Convert-SchemaGUIDtoLDAPDisplayName {
<#
.Synopsis
Convert-SchemaGUIDtoLDAPDisplayName converts a schema GUId to the LDAP Display Name
.DESCRIPTION
Convert-SchemaGUIDtoLDAPDisplayName converts a schema GUId to the LDAP Display Name
.PARAMETER guid
The schema guid to lookup
.EXAMPLE
PS C:\\> Convert-SchemaGUIDtoLDAPDisplayName "bf96793f-0de6-11d0-a285-00aa003049e2"
.INPUTS
System.String
.OUTPUTS
System.String
.NOTES
NAME: Convert-SchemaGUIDtoLDAPDisplayName
AUTHOR: Patrick Sczepanski
VERSION 20120105
#Requires -Version 2.0
.LINK
http://PoshCode.org/embed/3788
#>
[Cmdletbinding()]
Param(
[Parameter(Mandatory=$true,Position=0)]
[GUID]$guid
)
$ThisFunctionName = $MyInvocation.MyCommand.Name
if ( $GuidCache.Contains($guid.Tostring()) ) {
Write-Verbose "[$ThisFunctionName] :: Found in script cache."
return $GuidCache.($guid.Tostring())
}
$RootDSE = [DirectoryServices.DirectoryEntry]"LDAP://RootDSE"
$escapedGuid = "\\" + ((([GUID]$guid).ToByteArray() |% {"{0:x}" -f $_}) -join '\\')
$Filter = "(&(|(objectcategory=classschema)(objectcategory=attributeschema)(objectcategory=controlAccessRight))" +
"(|(schemaIdGuid=$escapedGuid)(rightsGuid=$guid)))"
Write-Verbose "[$ThisFunctionName] :: Query Schema and configuration"
Write-Verbose "[$ThisFunctionName] :: Base $($RootDSE.configurationNamingContext)"
Write-Verbose "[$ThisFunctionName] :: Filter $Filter"
Write-Verbose "[$ThisFunctionName] :: Attr ldapdisplayname"
$SearchResult = Search-AD -Searchbase $RootDSE.configurationNamingContext `
-Filter $Filter `
-Attributes ("distinguishedname","name","ldapdisplayname","displayname") `
-Scope Subtree `
-FindOne `
-ReferralChasing Subordinate `
-PageSize 0
if ( $SearchResult.properties.distinguishedname[0] -like "*Schema*" ) {
$GuidCache.($guid.Tostring()) = $SearchResult.properties.ldapdisplayname[0]
Write-Verbose "[$ThisFunctionName] :: Found in schema, added to cache."
Write-Output $SearchResult.properties.ldapdisplayname[0]
} elseif ( $SearchResult.properties.distinguishedname[0] -like "*Configuration*" ) {
$GuidCache.($guid.Tostring()) = $SearchResult.properties.displayname[0]
Write-Verbose "[$ThisFunctionName] :: Found in configuration context, added to cache."
Write-Output $SearchResult.properties.displayname[0]
} else {
Write-Verbose "[$ThisFunctionName] :: Not found return GUID, added 'unknown'."
Write-Output $guid.ToString()
}
}
#endregion Convert-Schema
|
PowerShellCorpus/PoshCode/Map a Network Drive.ps1
|
Map a Network Drive.ps1
|
function MapNetDrive
{
param(
#Non-Boolean parameters (Values)
#
[Parameter(Position=0,Mandatory=$true)]
[string]$DriveLetter="Z:",
[Parameter(Position=1,Mandatory=$true)]
[string]$Path,
#Boolean switches (On/Off)
#
[Parameter(Position=2,Mandatory=$false)]
[switch]$Credentials,
[Parameter(Position=3,Mandatory=$false)]
[switch]$Stay,
[Parameter(Position=4,Mandatory=$false)]
[switch]$Force
)
#Creates new WScript.Network object called "$map" and allows it to access MapNetworkDrive(), EnumNetworkDrives(),
#and RemoveNetworkDrive() methods.
#
$map=New-Object -ComObject WScript.Network
#Uses EnumNetworkDrives() and "-contains" operator to determine if specified drive already exists. If so, and "$Force"
#parameter is not present to force an override, it outputs a message to the user. Then uses "Try/Catch" statement to
#catch any other general errors that might prevent removal of drive.
#
if($map.EnumNetworkDrives() -contains $DriveLetter)
{
if(!$Force)
{throw "Can't map $driveLetter because it's already mapped. Use -Force to override."}
try
{$map.RemoveNetworkDrive($DriveLetter,$Force.ToBool(),$Stay.ToBool())}
catch
{
Write-Error -Exception $_.Exception.InnerException -Message "Error removing '$driveLetter'
$($_.Exception.InnerException.InnerException.Message)"
}
}
#Maps new network drive, checking first if "$Credentials" parameter is passed. If so, a System.Management.Automation.PSCredential object
#called "$creds" is created and instantiated to result value of "Get-Credential" Cmdlet. Because of its type, "$creds" has access to the
#individual "UserName" and "Password" property values when the user submits them at the prompt.
#
#"$Stay" is placeholder for "bUpdateProfile" argument of the MapNetworkDrive() method, which determines whether the new
#drive is saved as part of the user's profile. It's value here is determined by the presence of the "$Stay" switch.
#
if($Credentials)
{
[System.Management.Automation.PSCredential]$creds=$(Get-Credential) #-Credential $($(Get-WmiObject -Class Win32_ComputerSystem).UserName)
$map.MapNetworkDrive($DriveLetter,$Path,$Stay.ToBool(),$creds.UserName,$creds.GetNetworkCredential().Password)
}
else {$map.MapNetworkDrive($DriveLetter,$Path,$Stay.ToBool())}
#Opens newly created drive letter in Windows Explorer
#
$explore=New-Object -ComObject Shell.Application
$explore.Open($DriveLetter)
}
|
PowerShellCorpus/PoshCode/Start-BootsTimer_2.ps1
|
Start-BootsTimer_2.ps1
|
function Start-BootsTimer {
#.Syntax
# Creates a stay-on-top countdown timer
#.Description
# A WPF borderless count-down timer, with audio/voice alarms and visual countdown + colored progress indication
#.Parameter EndMessage
# The message to be spoken by a voice when the time is up...
#.Parameter StartMessage
# A message to be spoken at start up (just to let you know, audibly, what's up).
#.Parameter Minutes
# Some minutes to add to the timer
#.Parameter Seconds
# Some seconds to add to the timer
#.Parameter Hours
# Some hours to add to the timer
#.Parameter SoundFile
# A .wav file to play as the alarm
#.Parameter FontSize
# The size of the timer text
#.Parameter SingleAlarm
# Only sound the alarm once
#.Example
# Start-BootsTimer 180 "The three minute egg is ready!"
#
# Starts a three minute timer with the specified voice alert at the end
#
#.Example
# Start-BootsTimer -End "The three minute egg is ready!" -Minute 3
#
# Starts a three minute timer with the specified voice alert at the end
#
#.Example
# Start-BootsTimer "Your turn is over!" -Minutes 10 -Single -FontSize 18
#
# Starts a 10 minute timer that only plays the alert once at the end, and has a small font, which would fit over the task bar or a window title bar...
[CmdletBinding(DefaultParameterSetName="Times")]
PARAM(
[Parameter(Position=2,ParameterSetName="Times",Mandatory=$false)]
[Parameter(Position=1,ParameterSetName="Reasons", Mandatory=$true)]
[string]$EndMessage
,
[Parameter(Position=2,ParameterSetName="Reasons", Mandatory=$false)]
[string]$StartMessage
,
[Parameter(Position=3,ParameterSetName="Reasons", Mandatory=$false)]
[int]$minutes = 0
,
[Parameter(Position=4,ParameterSetName="Reasons", Mandatory=$false)]
[Parameter(Position=1,ParameterSetName="Times", Mandatory=$true)]
[int]$seconds = 0
,
[Parameter()]
[int]$hours = 0
,
[Parameter()]
$SoundFile = "$env:SystemRoot\\Media\\notify.wav"
,
[Parameter()]
$FontSize = 125
,
[Parameter()]
[Switch]$SingleAlarm
)
# Default to 10 seconds ... without adding 5 seconds when people specify minutes
if(($seconds + $Minutes + $hours) -eq 0) { $seconds = 10 }
$start = [DateTime]::Now
## We have to store all this stuff, because the powerboots window lasts longer than the script
$TimerStuff = @{}
$TimerStuff["seconds"] = [Math]::Abs($seconds) + [Math]::Abs([int]($minutes*60)) + [Math]::Abs([int]($hours*60*60))
$TimerStuff["TimerEnd"] = $start.AddSeconds( $TimerStuff["seconds"] )
$TimerStuff["SingleAlarm"] = $SingleAlarm
## Take care of as much overhead as we can before we need it...
if(Test-Path $soundFile) {
$TimerStuff["Sound"] = new-Object System.Media.SoundPlayer
$TimerStuff["Sound"].SoundLocation=$SoundFile
}
if($EndMessage -or $StartMessage) {
$TimerStuff["Voice"] = new-object -com SAPI.SpVoice
}
## Create and store a scriptblock to figure out the remaining time and format it
$TimerStuff["NowFunction"] = {
$diff = $BootsTimer.Tag["TimerEnd"] - [DateTime]::Now;
$diff.TotalSeconds
if($diff.Ticks -ge 0) {
([DateTime]$diff.Ticks).ToString(" HH:mm.ss")
} else {
([DateTime][Math]::Abs($diff.Ticks)).ToString("-HH:mm.ss")
}
}
## Create and store a scriptblock to sound the alarm
$TimerStuff["AlarmFunction"] = {
if($BootsTimer.Tag["Sound"]) {
$BootsTimer.Tag["Sound"].Play()
} else {
[System.Media.SystemSounds]::Exclamation.Play()
}
if($BootsTimer.Tag["EndMessage"]) {
$null = $BootsTimer.Tag["Voice"].Speak( $BootsTimer.Tag["EndMessage"], 1 )
}
}
## Store the "EndMessage" message
if($EndMessage) {
$TimerStuff["EndMessage"] = $EndMessage
}
## If they provided a second status message, read it out loud
if($StartMessage) {
$null = $TimerStuff["Voice"].Speak( $StartMessage, 1 )
}
$TimerStuff["FontSize"] = $FontSize
## Make the window ...
$Global:BootsTimer = boots -WindowStyle None -AllowsTransparency -Topmost {
TextBlock "" -FontSize $BootsParameters.FontSize -FontFamily Impact -margin 20 `
-BitmapEffect $(OuterGlowBitmapEffect -GlowColor White -GlowSize 15) `
-Foreground $(LinearGradientBrush -Start "1,1" -End "0,1" {
GradientStop -Color Black -Offset 0.0
GradientStop -Color Black -Offset 0.95
GradientStop -Color Red -Offset 1.0
GradientStop -Color Red -Offset 1.0
}) # -TextDecorations ([System.Windows.TextDecorations]::Underline)
} -On_MouseDown {
if($_.ChangedButton -eq "Left") { $this.DragMove() }
} -On_Close {
$this.Tag["Timer"].Stop()
Remove-BootsWindow $this
} -Async -Passthru -Background Transparent -ShowInTaskbar:$False -Tag $TimerStuff
## Now we need to call that scriptblock on a timer. That's easy, but it
## must be done on the window's thread, so we use Invoke-BootsWindow.
## Notice the first argument is the window we want to run the script in
Invoke-BootsWindow $Global:BootsTimer {
## We'll create a timer
$Global:BootsTimer.Tag["Timer"] = new-object System.Windows.Threading.DispatcherTimer
$BootsTimer.Tag["Timer"].Interval = [TimeSpan]"0:0:0.05"
## And will invoke the $updateBlock
$BootsTimer.Tag["Timer"].Add_Tick( {
trap {
write-host "Error: $_" -fore Red
write-host $($_.Exception.StackTrace | Out-String) -fore Red
}
$remain, $BootsTimer.Content.Text = & $BootsTimer.Tag["NowFunction"]
$remain = $remain / $BootsTimer.Tag["seconds"]
## Move the gradient a little bit each time.
$BootsTimer.Content.Foreground.GradientStops[2].Offset = [Math]::Max(0.0, $remain)
$BootsTimer.Content.Foreground.GradientStops[1].Offset = [Math]::Max(0.0, $remain - 0.05)
## When we get to the end ... make a few changes
if($remain -le 0) {
## The first time we hit the end, we want to add a mouse click handler...
if($this.Interval.Seconds -eq 0) {
## Which will now only fire every few seconds
## So it's easier to close the window ;)
$this.Interval = [TimeSpan]"0:0:2"
## If you click on the finished window, it just goes away
$BootsTimer.Add_MouseDown( { $BootsTimer.Close() } )
## But if they chose -SingleAlarm, they don't neeto bother
if($BootsTimer.Tag["SingleAlarm"]) { $BootsTimer.Close() }
}
& $BootsTimer.Tag["AlarmFunction"]
}
} )
## Now start the timer running
$BootsTimer.Tag["Timer"].Start()
}
}
|
PowerShellCorpus/PoshCode/Appscanner v0.10.ps1
|
Appscanner v0.10.ps1
|
#######################
#Appscanner V0.10
#Author Adam Liquorish
#Creation Date 08/11/11
#Change log:
# 14/11/11 Removed unrequired step
# 02/12/11 Created input choice for domain.local,cached rather than auto determine
# 02/12/11 Added all supported filetypes for applockers ".bat",".cmd",".dll",".exe",".js",".msi",".msp","ocx",".psq",".vbs"
# 09/12/11 Implemented try/catch to capture file not found or access denied errors for outputting files
#
#Syntax
#appscanner -path <path> -user <user> -applockerpolicy <local/path> -outputpath <path> -userstatus <domain,local,cached> -logdirectory <path>
#
#Example
#appscanner -path "C:\\Program Files" -user "adam" -applockerpolicy "local" -outputpath "c:\\temp\\output.html" -userstatus "local" -logdirectory "c:\\temp\\"
#######################
######Define Parameters
param(
[Parameter(Mandatory=$true,
HelpMessage="Enter Path to be processed.")]
[ValidateNotNullOrEmpty()]
[string]$path,
[Parameter(Mandatory=$true,
HelpMessage="Enter User to be processed, as either builtin\\<user> or <domain>\\<user>.")]
[ValidateNotNullOrEmpty()]
[string]$user=$(Read-Host -prompt "User"),
#Uncomment when in production version.
[Parameter(Mandatory=$true,
HelpMessage="Enter Applocker XML to be utilised ie c:\\applocker.xml, or type local to use effective policy for workstation")]
[ValidateNotNullOrEmpty()]
[string]$applockerpolicy=$(Read-Host -prompt "Path to applocker policy xml file, or type local to use effective policy for workstation"),
[Parameter(Mandatory=$true,
HelpMessage="Enter Path for ouput ie c:\\Temp\\output.html.")]
[ValidateNotNullOrEmpty()]
[string]$outputpath=$(Read-Host -prompt "Path for Output"),
[Parameter(Mandatory=$true,
HelpMessage="Is the user a Domain/Local/Cached User.[Domain,Local,Cached]")]
[ValidateNotNullOrEmpty()]
[ValidateSet("Domain","Local","Cached")]
[string]$UserStatus=$(Read-Host -prompt "Is the user a Domain/Local/Cached User.[Domain,Local,Cached]"),
[Parameter(Mandatory=$true,
HelpMessage="Enter Log Directory for ouput ie c:\\Temp\\")]
[ValidateNotNullOrEmpty()]
[string]$logdirectory=$(Read-Host -prompt "Log Directory")
)
######END DEFINE PARAMETERS
######Define Logger
$logfilename="$(get-date -format yyyy-MM-dd-hh-mm-ss).txt"
$logfile=$logdirectory+$logfilename
if ($host.name -match 'ise')
{
write-host "Warning: Running in Windows Powershell ISE, Transcript logging will not be running" -foregroundcolor red
$null
}
else
{
write-host "Running in Powershell Console, Transcript logging will now start" -foregroundcolor blue
try{
start-transcript -path $logfile
}
#catch for if path not found
catch [System.IO.DirectoryNotFoundException]{
write-host "Critical: Parent Path to save $logfile not found." -foregroundcolor red
read-host "Press enter to exit"
}
#catch for path access denied
catch [System.Management.Automation.RuntimeException]{
write-host "Critical: Write access to $logfile is denied unable to save log file." -foregroundcolor red
read-host "Press enter key to exit"
}
}
###### END Logger
######Define Variables
$ticksymbol=[char]10004
$errorsymbol=[char]10008
$asterisksymbol=[char]10033
$dict=@{}
$t=$null
$hashtable=$null
$u=$null
$Pathvalid=test-path $path
$Pathvalidpolicy=test-path $applockerpolicy
$direct=$null
$inherited=$null
######END DEFINE VARIABLEs
######Define HTML Output
$a="<style>"
$a=$a +"TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a=$a +"TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:thistle}"
$a=$a +"TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;}"
$a=$a +"</style>"
$header= "<h1>List of Processed Files</h1>"
######END DEFINE HTML OUTPUT
######Testing Privileges
#$currentprincipal=new-object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
#& {
# if ($currentprincipal.isinrole( [Security.principal.windowsbuiltinrole]::Administrator))
# {
# write-host "$ticksymbol Running with administrative privilages" -foregroundcolor blue
# }
# else
# {
# write-host "$errorsymbol Script is currently not running with administrative privileges, please run as admin" -foregroundcolor red
# read-host "Press enter to exit" -foregroundcolor red
# exit
# }
# }
######END TESTING PRIV
######Importing Required Modules
try
{
if((get-wmiobject -cl win32_operatingsystem).version -gt "6")
{
write-host "$ticksymbol Win Vista or higher detected, Importing Applocker Module" -foregroundcolor blue
if((get-module -listavailable|foreach-object {$_.name}) -contains "applocker")
{
import-module applocker
write-host "Successfully imported applocker module" -foregroundcolor blue
}
else
{
write-host "Critical: Applocker module cannot be found try logging in as administrator" -foregroundcolor red
read-host "Press enter to quit"
exit
}
}
else
{
"Critical: $errorsymbol Exiting....An operating system lower that Windows Vista has been detected. Script can only be run on Vista or higher."
read-host "Press Enter key to exit"
Exit
}
}
catch
{
write-host "Critical: Error encountered loading applocker module" -foregroundcolor red
read-host "Press Enter key to exit"
Exit
}
######END IMPORT MODULES
######MAIN
if ($Pathvalid -eq "True")
#If Path Valid
{
if ($applockerpolicy -eq "local")
#Output effective local applied applocker policy
{
#Determine whether an applocker policy is in effect on workstation
if((get-applockerpolicy -effective -xml ) -like "*Rule*")
{
write-host "$ticksymbol A valid Applocker Policy is currently applied to this workstation" -foregroundcolor blue
write-host "Warning: A path is required to save local applied applocker policy for usage" -foregroundcolor red
$applockerpolicy=read-host "Enter path, ie c:\\temp\\applockerpolicy.xml"
write-host "$asterisksymbol Effective applied Applocker Policy for this workstation has been selected, policy will be output to $applockerpolicy" -foregroundcolor blue
#Effective Applocker policy output
try{
get-applockerpolicy -effective -xml >$applockerpolicy
}
#catch for if path not found
catch [System.IO.DirectoryNotFoundException]{
write-host "Critical: Parent Path to save $applockerpolicy not found." -foregroundcolor red
read-host "Press enter to exit"
}
#catch for path access denied
catch [System.Management.Automation.RuntimeException]{
write-host "Critical: Write access to $applockerpolicy is denied unable to export policy." -foregroundcolor red
read-host "Press enter key to exit"
}
}
else
{
write-host "Critical: $errorsymbol Exiting....An applocker policy has not been applied to this workstation" -foregroundcolor red
read-host "Press Enter key to exit"
exit
}
}
elseif ($Pathvalidpolicy -eq "True")
{
write-host "$ticksymbol Valid XML file supplied for Applocker Policy" -foregroundcolor blue
}
else
{
write-host "Critical: $errorsymbol Exiting....Invalid path for applocker policy xml file, File Doesn't exist!" -foreground red
read-host "Press Enter key to exit"
exit
}
#Stage 1 Find group membership for user
$starttime=get-date
"Stage 1 of 7, Enumerating Groups User is a member of, including inherited groups"
#Load .Net Assembler
add-type -AssemblyName System.DirectoryServices.AccountManagement
$domain = (Get-wmiobject Win32_ComputerSystem).Domain
$ping=new-object system.net.networkinformation.ping
#Function for finding group membership for only local or domain not a cached user!!!
function groupfind
{
#Create objects to filter based on group name and ContextType--Domain or Machine
$principal = new-object System.DirectoryServices.AccountManagement.PrincipalContext $ctype,$domain
$idtype = [System.DirectoryServices.AccountManagement.IdentityType]::SamAccountName
$groupPrincipal = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($principal, $idtype, $user)
#Recursively find what groups the user is a member of
#Also assigns groups found to a global variable called groupout
set-variable -name groupout -value $groupprincipal.GetAuthorizationGroups() -scope global
}
#END FUNCTION
#Determine if workstation is part of a domain or just local.
If($userstatus -eq "Domain")
{
try {
$domainName = [System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain() | select -ExpandProperty Name
$isDomain = $domainName -match $domain
$domain =$domainname
write-host "Workstation is part of a domain" -foregroundcolor blue
#Determine if domain controller is contactable if not contactable treat workstation as local and use local account information
if ($ping.send(([System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain()).pdcroleowner.name).status -eq "Success")
{
$ctype = [System.DirectoryServices.AccountManagement.ContextType]::Domain
write-host "Successfully contacted Domain controller, using Domain account information." -foregroundcolor blue
#calls function groupfind
groupfind
}
else
{
write-host "Critical: Domain Controller not contactable!" -foregroundcolor red
read-host "Press Enter key to exit"
exit
}
}
catch {
write-host "Critical: Computer is not part of a domain" -foregroundcolor red
read-host "Press Enter key to exit"
exit
}
}
elseif($userstatus -eq "Local")
{
#Build list of local users
$computername="$env:computername"
$computer=[ADSI]"WinNT://$computername,computer"
$localuserlist=$computer.psbase.children|where-object {$_.psbase.schemaclassname -eq 'user'}
$localuserlistfilt=foreach($useritem in $localuserlist){$useritem.name}
#Check queried user against list to see whether user is local
if($localuserlistfilt -contains $user)
{
write-host "Verified user is a part of local SAM database" -foregroundcolor blue
$domain=(Get-wmiobject Win32_ComputerSystem).Name
$ctype = [System.DirectoryServices.AccountManagement.ContextType]::Machine
#Calls function groupfind
groupfind
}
else
{
write-host "Critical: User is not a local user" -foregroundcolor red
read-host "Press Enter key to exit"
exit
}
}
elseif($userstatus -eq "Cached")
{
try {
#Build list of local users
$computername="$env:computername"
$computer=[ADSI]"WinNT://$computername,computer"
$localuserlist=$computer.psbase.children|where-object {$_.psbase.schemaclassname -eq 'user'}
$localuserlistfilt=foreach($useritem in $localuserlist){$useritem.name}
#Check queried user against list to see whether user is local
if($localuserlistfilt -contains $user)
{
write-host "Critical: User is a part of local SAM database, therefore user is not cached." -foregroundcolor red
read-host "Press Enter key to exit"
exit
}
else
{
#Check queried user matches logged on user"
if((gwmi win32_computersystem).username -like "*$user")
{
write-host "Verified user is a cached user" -foregroundcolor blue
$groupout=[system.security.principal.windowsidentity]::getcurrent().groups|foreach-object {$_.translate([system.security.principal.ntaccount])}
}
else
{
write-host "Critical: Logged on user doesn't match queried user, therefore User is not a cached user" -foregroundcolor red
read-host "Press Enter key to exit"
exit
}
}
}
catch {
write-host "Critical: User is not cached" -foregroundcolor red
read-host "Press Enter key to exit"
exit
}
}
else
{
write-host "Critical: Please use Local,Domain or Cached" -foregroundcolor red
read-host "Press Enter key to exit"
exit
}
"Stage 1 of 7, Finished Scanning Group Membership"
"Stage 1 of 7, Outputting Group Membership hierarchy"
#Add user to variable
$groupfilter=@($user)
#Filter group properties down to name string
$groupfilter+=foreach($groupname in $groupout){$groupname.name}
#Determine direct membership
$domaincut=$domain -match "\\w+[A-Za-z0-9-]+"
$domaincutvalue=$matches.values
$query="ASSOCIATORS OF {Win32_Account.Name='$user',Domain='$domaincutvalue'} WHERE ResultRole=GroupComponent ResultClass=Win32_Account"
$directmembership=get-wmiobject -query $query
$directmembershipresults=foreach($directmember in $directmembership){$directmember.name}
$directmembershipresultsfiltered=$directmembershipresults|select-object -unique
"#####################################################"
write-host "#Green is for the username," -foregroundcolor darkgreen -nonewline; write-host "Red is for direct group membership," -foregroundcolor red -nonewline; write-host "Blue is for the inherited group membership" -foregroundcolor blue
"#User $user group structure looks like the following;"
foreach ($group in $groupfilter){
if($directmembershipresultsfiltered -contains $group){
$direct+=@($group)}
elseif($group -eq $user){
$null}
else{$inherited+=@($group)}
}
#Display user
write-host "-$user" -foregroundcolor darkgreen
#Display direct membership
foreach($member in $direct){
write-host "->$member" -foregroundcolor red
}
foreach($member in $inherited){
write-host "-->$member" -foregroundcolor blue
}
"#####################################################"
"Stage 1 of 7 Complete"
#End Stage 1
#Stage 2 Recurse found items to variable
$count=0
"Stage 2 of 7 $path is populating a variable "
Get-Childitem $path -recurse -outvariable objects|where-object{write-progress "Stage 2 of 7 Recursing items to variable, Examining $($_.fullname)...." "Found $count items";"$($_.fullname)"}|foreach-object {$count++}
"Stage 2 of 7 $path has been populated into a variable"
#End Stage 2
#Stage 3 FILTERACL
"Stage 3 of 7 Processing ACL on files to index"
$max=$objects.length
#filter variable
$filteracl ={$groupfilter -like $_.IdentityReference.value.split("\\")[1] -and ($_.FileSystemRights -band 131241 -or $_.FileSystemRights -band 278)}
#Filter and add to new property
foreach ($i in $objects)
{
$dict[$i.fullname]=@{user="";Permission=""}
$t++
$i.GetAccessControl().Access |Where $filteracl|foreach {$dict.($i.Fullname).User+=($_.IdentityReference,",");$dict.($i.Fullname).Permission=$_.FileSystemRights}
Write-Progress -activity "Stage 3 of 7 Processing File Permissions to index" -status "$t of $max" -PercentComplete (($t/$objects.count)*100) -CurrentOperation $i.fullname
}
"Stage 3 of 7 Complete"
#END STAGE 3
#Stage 4 Remove Duplicate identities
"Stage 4 of 7 Removing duplicate identities"
#Zeroise write-progress counter
$t=$null
#Remove duplicate identities due to listing of inherited groups in ACL
foreach ($i in $objects)
{
$t++
$identarray=$dict[$i.fullname].user;$dict[$i.fullname].user=$null;$splitidentarray=$identarray -split ",";$uniqueidentarray=$splitidentarray|sort-object -unique;$uniqueidentarray -join ","|foreach {$dict.($i.fullname).User+=($_)}
Write-Progress -activity "Stage 4 of 7 Removing Username/Group Duplicates" -status "$t of $max" -PercentComplete (($t/$objects.count)*100) -CurrentOperation $i.fullname
}
"Stage 4 of 7 Complete"
#END STAGE 4
#Stage 5 APPLOCKER
"Stage 5 of 7 Processing Applocker policy on files"
#Applocker file extensions list
$Applockerfileextlist=".bat",".cmd",".dll",".exe",".js",".msi",".msp","ocx",".psq",".vbs"
$userpol=$objects|where {$Applockerfileextlist -contains $_.Extension}|convert-path|test-applockerpolicy $applockerpolicy -User $user
$userobjpol = $userpol|select-object PolicyDecision,FilePath,MatchingRule
$userobjpolcount=0
$userobjpol|foreach {
$userobjpolcount++
$dict[$_.FilePath] += @{ PolicyDecision = $_.PolicyDecision;MatchingRule= $_.MatchingRule}
Write-progress -activity "Stage 5 of 7 Processing AppLockers results:" -status "$userobjpolcount of $($userobjpol.count)" -PercentComplete (($userobjpolcount/$userobjpol.count)*100) -CurrentOperation $_
}
"Stage 5 of 7 Complete"
#END STAGE 5
#Stage 6
"Stage 6 0f 7 Preparing format of results for html Report"
$max2=$dict.count
$hashtable=foreach($j in $dict.keys){
$u++
New-Object -TypeName PSObject -Property @{Path=$j
User=$dict.$j.user
Permission=$dict.$j.Permission
MatchingRule=$dict.$j.MatchingRule
PolicyDecision=$dict.$j.PolicyDecision
}
Write-Progress -activity "Stage 6 of 7 Processing Dictionary to properties" -status "$u of $max2" -PercentComplete (($u/$max2)*100) -CurrentOperation $_}
"Stage 6 of 7 Complete, $u files scanned of $max for Applocker scan"
#END STAGE 6
#####END MAIN
#####RESULTS
#OUTPUT RESULTS TO FILE
"Stage 7 of 7 Outputting to file $outputpath"
try{
$hashtable|sort-object Path|ConvertTo-Html -head $header -title "ACL List" -body $a|Set-Content $outputpath
}
#catch for if path not found
catch [System.IO.DirectoryNotFoundException]{
write-host "Critical: Parent Path to save $outputpath not found." -foregroundcolor red
read-host "Press enter to exit"
}
#catch for path access denied
catch [System.Management.Automation.RuntimeException]{
write-host "Critical: Write access to $outputpath is denied unable to export results." -foregroundcolor red
read-host "Press enter key to exit"
}
#Display results
$endtime=get-date
$totaltime=$endtime-$starttime
$totaltimehours=$totaltime.hours
$totaltimeminutes=$totaltime.minutes
$outputsize=get-item "$outputpath"|foreach {echo($_.length/1mb).tostring("0.00 MB")}
"Stage 7 of 7, Scanned $max files of $path is complete in $totaltimehours hours and $totaltimeminutes minutes, $outputpath is $outputsize."
#####END RESULTS
#####Zeroise variables and unrequired files
#Stop Logging
if ($host.name -match 'ise')
{
$null
}
else
{
"Running Log output to $logfile"
stop-transcript >$null
}
#Prompt delete applocker policy
$delete=read-host -prompt "Would you like the Applocker policy file $applockerpolicy deleted,YES/NO"
if($delete -eq "yes")
{
del $applockerpolicy
}
else
{
write-host "Warning: $asterisksymbol You chose not to delete file $applockerpolicy, Application will now exit....." -foregroundcolor red
read-host "Press Enter key to exit"
}
}
#If Path invalid
else
{
write-host "Critical: $errorsymbol Exiting...Invalid path supplied for processing" -foregroundcolor red
read-host "Press Enter key to exit"
exit
}
|
PowerShellCorpus/PoshCode/divide integer.ps1
|
divide integer.ps1
|
function divide-integer ([int]$dividend , [int]$divisor ){ [int]$local:remainder = $Null;return [Math]::DivRem($dividend,$divisor,[ref]$local:remainder);}
set-alias i/ divide-integer
i/ 10 3
function divide-integerpipe ([int]$divisor )
{ begin { [int]$local:remainder = $Null}
process { [Math]::DivRem($_ ,$divisor,[ref]$local:remainder); }
}
set-alias i\\ divide-integerpipe
10 | i\\ 3
1..10 | i\\ 3
|
PowerShellCorpus/PoshCode/Get-GPOSettings.ps1
|
Get-GPOSettings.ps1
|
<#
.SYNOPSIS
Get-GPOSettings
.DESCRIPTION
This script gets a list of all Group Policy Objects in the domain filtered on the value
of GPOSettingName. For each GPO if the Extension Name matches GPOSettingName the Extensions
are then reported back.
.PARAMETER GPOSettingName
The name of the GPO Setting you want to filter on. This can be viewed by using the
GPO search function of the GPMC.
.PARAMETER GPOSettingGuid
The GUID of the GPOSettingName, the only way to determine this is to enable GPMC
logging in the registry, and then grep the log file for the GPO Setting Name.
.PARAMETER GPOComputerContext
Any value other than $true will switch the script to evaluate the user policies.
.EXAMPLE
.\\Get-GPOSettings.ps1
Description
-----------
The default syntax returns a list of Deployed Printer connections.
.NOTES
ScriptName: Get-GPOSettings.ps1
Created By: Jeff Patton
Date Coded: August 18, 2011
ScriptName is used to register events for this script
LogName is used to determine which classic log to write to
This script relies on the Get-ADObject and Get-GPO cmdlet that are provided from
the ActiveDirectory and GroupPolicy modules.
.LINK
http://scripts.patton-tech.com/wiki/PowerShell/Production/Get-GPOSettings
.LINK
http://www.ldap389.info/en/2010/09/17/powershell-search-settings-gpo-parameter-configuration-gpmc/
.LINK
http://technet.microsoft.com/en-us/library/ee617198.aspx
.LINK
http://technet.microsoft.com/en-us/library/ee461059.aspx
#>
Param
(
$GPOSettingName = "Deployed Printer Connections Policy",
$GPOSettingGuid = "{8A28E2C5-8D06-49A4-A08C-632DAA493E17}",
$GPOComputerContext = $true
)
Begin
{
$ScriptName = $MyInvocation.MyCommand.ToString()
$LogName = "Application"
$ScriptPath = $MyInvocation.MyCommand.Path
$Username = $env:USERDOMAIN + "\\" + $env:USERNAME
New-EventLog -Source $ScriptName -LogName $LogName -ErrorAction SilentlyContinue
$Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nStarted: " + (Get-Date).toString()
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message
$GPOSettingGuid = "*$($GPOSettingGuid)*"
$ErrorActionPreference = "Stop"
# Dotsource in the functions you need.
Try
{
Import-Module GroupPolicy
Import-Module ActiveDirectory
}
Catch
{
Write-Warning "Must have the Active Directory and Group Policy cmdlets installed."
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "101" -EntryType "Error" -Message "RSAT installed?"
Break
}
Switch ($GPOComputerContext)
{
$true
{
$GPOs = Get-ADObject -Filter {(ObjectClass -eq "groupPolicyContainer") -and (gPCMachineExtensionNames -like $GPOSettingGuid)}
}
Default
{
$GPOs = Get-ADObject -Filter {(ObjectClass -eq "groupPolicyContainer") -and (gPCUserExtensionNames -like $GPOSettingGuid)}
}
}
}
Process
{
If ($GPOs -ne $null)
{
$Report = @()
foreach ($GPO in $GPOs)
{
[XML]$GPOReport = Get-GPOReport -Guid $GPO.Name -ReportType XML
Try
{
Switch ($GPOComputerContext)
{
$true
{
foreach ($Extension in $GPOReport.GPO.Computer.ExtensionData)
{
if ($Extension.Name -eq $GPOSettingName)
{
$Settings = $Extension.Extension.ChildNodes
}
}
If ($Settings -ne $null)
{
foreach ($Setting in $Settings)
{
$ReportItem = New-Object -TypeName PSObject -Property @{
Name = $GPOReport.GPO.Name
GUID = $GPO.Name
Setting = $Setting.InnerText
}
$Report += $ReportItem
}
}
}
Default
{
foreach ($Extension in $GPOReport.GPO.User.ExtensionData)
{
if ($Extension.Name -eq $GPOSettingName)
{
$Settings = $Extension.Extension.ChildNodes
}
}
If ($Settings -ne $null)
{
foreach ($Setting in $Settings)
{
$ReportItem = New-Object -TypeName PSObject -Property @{
Name = $GPOReport.GPO.Name
GUID = $GPO.Name
Setting = $Setting.InnerText
}
$Report += $ReportItem
}
}
}
}
}
Catch
{
Write-Error $Error[0].Exception.InnerException.Message.ToString().Trim()
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Error[0]
}
}
}
}
End
{
$Message = "Script: " + $ScriptPath + "`nScript User: " + $Username + "`nFinished: " + (Get-Date).toString()
Write-EventLog -LogName $LogName -Source $ScriptName -EventID "100" -EntryType "Information" -Message $Message
Return $Report
}
|
PowerShellCorpus/PoshCode/FTP download.ps1
|
FTP download.ps1
|
$File = "D:\\Dev\\somefilename.zip"
$ftp = "ftp://username:password@example.com/pub/incoming/somefilename.zip"
"ftp url: $ftp"
$webclient = New-Object System.Net.WebClient
$uri = New-Object System.Uri($ftp)
"Uploading $File..."
$webclient.UploadFile($uri, $File)
|
PowerShellCorpus/PoshCode/Get-WebPage_1.ps1
|
Get-WebPage_1.ps1
|
function Get-WebPage {
<#
.SYNOPSIS
Downloads web page from site.
.DESCRIPTION
Downloads web page from site and displays source code or displays total bytes of webpage downloaded
.PARAMETER Url
URL of the website to test access to.
.PARAMETER UseDefaultCredentials
Use the currently authenticated user's credentials
.PARAMETER Proxy
Used to connect via a proxy
.PARAMETER Credential
Provide alternate credentials
.PARAMETER ShowSize
Displays the size of the downloaded page in Kilobytes
.NOTES
Name: Get-WebPage
Author: Boe Prox
DateCreated: 08Feb2011
.EXAMPLE
Get-WebPage -url "http://www.bing.com"
Description
------------
Returns information about Bing.Com to include StatusCode and type of web server being used to host the site.
#>
[cmdletbinding(
DefaultParameterSetName = 'url',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = '',
ValueFromPipeline = $True)]
[string][ValidatePattern("^(http|https)\\://*")]$Url,
[Parameter(
Position = 1,
Mandatory = $False,
ParameterSetName = 'defaultcred')]
[switch]$UseDefaultCredentials,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[string]$Proxy,
[Parameter(
Mandatory = $False,
ParameterSetName = 'altcred')]
[switch]$Credential,
[Parameter(
Mandatory = $False,
ParameterSetName = '')]
[switch]$ShowSize
)
Begin {
$psBoundParameters.GetEnumerator() | % {
Write-Verbose "Parameter: $_"
}
#Create the initial WebClient object
Write-Verbose "Creating web client object"
$wc = New-Object Net.WebClient
#Use Proxy address if specified
If ($PSBoundParameters.ContainsKey('Proxy')) {
#Create Proxy Address for Web Request
Write-Verbose "Creating proxy address and adding into Web Request"
$wc.Proxy = New-Object -TypeName Net.WebProxy($proxy,$True)
}
#Determine if using Default Credentials
If ($PSBoundParameters.ContainsKey('UseDefaultCredentials')) {
#Set to True, otherwise remains False
Write-Verbose "Using Default Credentials"
$webrequest.UseDefaultCredentials = $True
}
#Determine if using Alternate Credentials
If ($PSBoundParameters.ContainsKey('Credentials')) {
#Prompt for alternate credentals
Write-Verbose "Prompt for alternate credentials"
$wc.Credential = (Get-Credential).GetNetworkCredential()
}
}
Process {
Try {
If ($ShowSize) {
#Get the size of the webpage
Write-Verbose "Downloading web page and determining size"
"{0:N0}" -f ($wr.DownloadString($url) | Out-String).length -as [INT]
}
Else {
#Get the contents of the webpage
Write-Verbose "Downloading web page and displaying source code"
$wc.DownloadString($url)
}
}
Catch {
Write-Warning "$($Error[0])"
}
}
}
|
PowerShellCorpus/PoshCode/Set-Blur.ps1
|
Set-Blur.ps1
|
Add-Type -Type @"
using System;
using System.Runtime.InteropServices;
namespace Huddled {
public class Dwm {
[DllImport("user32.dll")]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll", SetLastError=true)]
public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
public static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags);
[DllImport("dwmapi.dll", PreserveSig = false)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DwmIsCompositionEnabled();
[DllImport("dwmapi.dll")]
public static extern void DwmEnableBlurBehindWindow(IntPtr hwnd, ref BlurSettings blurBehind);
[DllImport("dwmapi.dll", PreserveSig = true)]
public static extern int DwmExtendFrameIntoClientArea(IntPtr hwnd, ref Margins margins);
[StructLayout(LayoutKind.Sequential)]
public struct Margins
{
public int leftWidth;
public int rightWidth;
public int topHeight;
public int bottomHeight;
}
[StructLayout(LayoutKind.Sequential)]
public struct BlurSettings
{
public int dwFlags;
public bool fEnable;
public IntPtr hRgnBlur;
public bool fTransitionOnMaximized;
public BlurSettings(bool enable) {
dwFlags = 5; // enable
fEnable = enable;
hRgnBlur = IntPtr.Zero;
fTransitionOnMaximized = true;
}
public BlurSettings(bool enable, bool maximizeTransition) {
dwFlags = 5; // enable
fEnable = enable;
fTransitionOnMaximized = maximizeTransition;
hRgnBlur = IntPtr.Zero;
}
}
[StructLayout(LayoutKind.Sequential)]
public struct ColorRef
{
public uint ColorDWORD;
public ColorRef(System.Drawing.Color color)
{
ColorDWORD = (uint)color.R + (((uint)color.G) << 8) + (((uint)color.B) << 16);
}
public System.Drawing.Color Color {
get
{
return System.Drawing.Color.FromArgb((int)(0x000000FFU & ColorDWORD),
(int)(0x0000FF00U & ColorDWORD) >> 8, (int)(0x00FF0000U & ColorDWORD) >> 16);
}
set
{
ColorDWORD = (uint)value.R + (((uint)value.G) << 8) + (((uint)value.B) << 16);
}
}
}
}
}
"@ -Ref System.Drawing
function global:Set-Blur {
#.Synopsis
# Mess with the transparency and blur of the PowerShell window
#.Parameter color
# The color to treat as transparent (you can set this to your foreground or background for best effect, but you must pass an actual [Drawing.Color]
#.Parameter opacity
# On a scale of 0 to 255, how opaque to make the window (255 is no transparency, 0 is invisible)
#.Parameter blur
# If set, -blur turns on the DWM Blur-Behind, otherwise turns it off
#.Parameter Opaque
# If set, turns off the color and opacity settings
#.Parameter Handle
# The handle of the window to act on. Defaults to the current PowerShell window
#.Example
# Set-Blur -Color ([System.Drawing.Color]::FromArgb( 0xff, 1, 36, 86 )) -Blur
#
# Makes the PowerShell Blue color transparent, and applies the window blur
#.Example
# Set-Blur -Color ([System.Drawing.Color]::FromArgb( 0xff, 1, 36, 86 ))
#
# Makes the PowerShell Blue color completely transparent
#.Example
# Set-Blur -Opacity 200
#
# Sets the window partly transparent
param([System.Drawing.Color]$color, [byte]$opacity, [switch]$Blur, [switch]$Opaque, [IntPtr]$handle = (ps -Id $pid).MainWindowHandle)
if($opaque) {
$style = [Huddled.Dwm]::GetWindowLong($handle, -20) -bor 0x80000 -bxor 0x80000
} else {
$style = [Huddled.Dwm]::GetWindowLong($handle, -20) -bor 0x80000
}
$style = [Huddled.Dwm]::SetWindowLong($Handle, -20, $style);
$flag = 0
if($color) { $flag += 1 } else { $color = [System.Drawing.Color]::Black }
if($opacity) { $flag += 2 } else { $opacity = 255 }
## This is why I wanted to console color ... you want to set this to your actual console background color
$colorRef = (New-Object Huddled.DWM+ColorRef $color).ColorDWORD
$null = [Huddled.Dwm]::SetLayeredWindowAttributes($handle, $colorRef, $opacity, $flag)
if([Huddled.Dwm]::DwmIsCompositionEnabled()) {
$blurSettings = New-Object Huddled.Dwm+BlurSettings $blur
$null = [Huddled.Dwm]::DwmEnableBlurBehindWindow($handle, [ref]$blurSettings);
}
}
|
PowerShellCorpus/PoshCode/Get-WebFile 3.5.ps1
|
Get-WebFile 3.5.ps1
|
## Get-WebFile.ps1 (aka wget for PowerShell)
##############################################################################################################
## Downloads a file or page from the web
## History:
## v3.5 - Add -Quiet switch to turn off the progress reports ...
## v3.4 - Add progress report for files which don't report size
## v3.3 - Add progress report for files which report their size
## v3.2 - Use the pure Stream object because StreamWriter is based on TextWriter:
## it was messing up binary files, and making mistakes with extended characters in text
## v3.1 - Unwrap the filename when it has quotes around it
## v3 - rewritten completely using HttpWebRequest + HttpWebResponse to figure out the file name, if possible
## v2 - adds a ton of parsing to make the output pretty
## added measuring the scripts involved in the command, (uses Tokenizer)
##############################################################################################################
#function wget {
param(
$url = (Read-Host "The URL to download"),
$fileName,
[switch]$quiet
)
$req = [System.Net.HttpWebRequest]::Create($url);
$res = $req.GetResponse();
if($fileName -and !(Split-Path $fileName)) {
$fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName
}
elseif(($fileName -eq $null) -or (Test-Path -PathType "Container" $fileName))
{
# if( -and !((Test-Path -PathType "Leaf" $fileName) -or ((Test-Path -PathType "Container" (Split-Path $fileName)) -and -not )))
[string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $res.Headers["Content-Disposition"] ).Groups[1].Value
$fileName = $fileName.trim("\\/""'")
if(!$fileName) {
$fileName = $res.ResponseUri.Segments[-1]
$fileName = $fileName.trim("\\/")
if(!$fileName) {
$fileName = Read-Host "Please provide a file name"
}
$fileName = $fileName.trim("\\/")
if(!([IO.FileInfo]$fileName).Extension) {
$fileName = $fileName + "." + $res.ContentType.Split(";")[0].Split("/")[1]
}
}
$fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName
}
if($res.StatusCode -eq 200) {
[int]$goal = $res.ContentLength
$reader = $res.GetResponseStream()
$writer = new-object System.IO.FileStream $fileName, "Create"
[byte[]]$buffer = new-object byte[] 4096
[int]$total = [int]$count = 0
do
{
$count = $reader.Read($buffer, 0, $buffer.Length);
$writer.Write($buffer, 0, $count);
if(!$quiet) {
$total += $count
if($goal -gt 0) {
Write-Progress "Downloading $url" "Saving $total of $goal" -id 0 -percentComplete (($total/$goal)*100)
} else {
Write-Progress "Downloading $url" "Saving $total bytes..." -id 0
}
}
} while ($count -gt 0)
$writer.Flush()
$reader.Close()
$writer.Close()
}
$res.Close();
ls $fileName
#}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.