full_path
stringlengths 31
232
| filename
stringlengths 4
167
| content
stringlengths 0
48.3M
|
|---|---|---|
PowerShellCorpus/PoshCode/d62dc55e-3050-4347-8836-eb27971623ff.ps1
|
d62dc55e-3050-4347-8836-eb27971623ff.ps1
|
####### Log deletions in all sites in a web application ######
############# http://iLoveSharePoint.com ##################
############## by Christian Glessner ######################
################ begin config #################
# Url of the web application to audit. Don't forget to activate the delete audit log on sites you want to log.
$targetWebAppUrl = "http://localhost:100"
# Url of the web that contains the list to log (list must contains the following columns: "Title" (text), "Event Url" (Url), "Item Type" (text), "Event" (text), "Occurred" (DateTime), "User" (text)"
$logWebUrl = "http://localhost:100"
# Title of the log list
$logListTitle ="Audit"
################# end config ##################
$lastRunPropName = "_iLSP_lastAuditTimestamp"
[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SharePoint')
$logSite = New-Object Microsoft.SharePoint.SPSite($logWebUrl)
$logWeb = $logSite.OpenWeb()
$logList = $logWeb.Lists[$logListTitle]
$targetWebApp = [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup($(New-Object Uri($targetWebAppUrl)))
if($targetWebApp.Properties.ContainsKey($lastRunPropName) -eq $false)
{
$targetWebApp.Properties[$lastRunPropName] = [DateTime]::MinValue
$targetWebApp.Update()
}
$lastRun = [DateTime]::Parse($targetWebApp.Properties[$lastRunPropName].ToString())
$newRun = [DateTime]::Now.ToUniversalTime()
foreach($site in $targetWebApp.Sites)
{
$query = New-Object Microsoft.SharePoint.SPAuditQuery($site)
$query.AddEventRestriction([Microsoft.SharePoint.SPAuditEventType]::Delete)
$query.SetRangeStart($lastRun)
$query.SetRangeEnd($newRun.AddDays(1))
$result = $site.Audit.GetEntries($query)
if($result.Count -gt 0)
{
foreach($entry in $result)
{
$eventUrl = $site.Url + "/" + $entry.DocLocation
$item = $logList.Items.Add()
$item[[Microsoft.SharePoint.SPBuiltInFieldId]::Title] = $entry.DocLocation
$item["Event Url"] = $eventUrl
$item["Item Type"] = $entry.ItemType
$item["Event"] = $entry.Event
$item["Occurred"] = $entry.Occurred.ToLocalTime()
$item["User"] = $logWeb.SiteUsers.GetByID($entry.UserId).LoginName
$item.Update()
}
}
$site.Dispose()
}
$targetWebApp.Properties[$lastRunPropName] = $newRun
$targetWebApp.Update()
$logWeb.Dispose()
$logSite.Dispose()
|
PowerShellCorpus/PoshCode/get windows product key_2.ps1
|
get windows product key_2.ps1
|
function get-windowsproductkey([Parameter(ValueFromPipeline=$true)][string[]]$computer)
{
PROCESS{
foreach($comp in $computer) {
$Reg = [WMIClass] ("\\\\" + $comp + "\\root\\default:StdRegProv")
$values = [byte[]]($reg.getbinaryvalue(2147483650,"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion","DigitalProductId").uvalue)
$lookup = [char[]]("B","C","D","F","G","H","J","K","M","P","Q","R","T","V","W","X","Y","2","3","4","6","7","8","9")
$keyStartIndex = [int]52;
$keyEndIndex = [int]($keyStartIndex + 15);
$decodeLength = [int]29
$decodeStringLength = [int]15
$decodedChars = new-object char[] $decodeLength
$hexPid = new-object System.Collections.ArrayList
for ($i = $keyStartIndex; $i -le $keyEndIndex; $i++){ [void]$hexPid.Add($values[$i]) }
for ( $i = $decodeLength - 1; $i -ge 0; $i--)
{
if (($i + 1) % 6 -eq 0){$decodedChars[$i] = '-'}
else
{
$digitMapIndex = [int]0
for ($j = $decodeStringLength - 1; $j -ge 0; $j--)
{
$byteValue = [int](($digitMapIndex * [int]256) -bor [byte]$hexPid[$j]);
$hexPid[$j] = [byte] ([math]::Floor($byteValue / 24));
$digitMapIndex = $byteValue % 24;
$decodedChars[$i] = $lookup[$digitMapIndex];
}
}
}
$STR = ''
$decodedChars | % { $str+=$_}
$STR
}}}
get-windowsproductkey .
|
PowerShellCorpus/PoshCode/VMtoolsUpgrade-disable_1.ps1
|
VMtoolsUpgrade-disable_1.ps1
|
#####################################################################
# TIAA-CREF VMWare Standard Scripts - PowerCLI
#
# Purpose: "Check and upgrade Tools during power cycling"
# Author: David Chung
# Support: IT Infrastructure
# Docs: N/A
#
# Instruction: 1. Create CSV file with list of servers
# 2. Execute script from PowerCLI
# 3. Enter virtual server name
#
#####################################################################
$viserver = read-host "Please enter vCenter Server:"
connect-viserver $viserver
$vms = Import-Csv c:\\server.csv
foreach ($vm.name in $vms)
{
Write-Host $vm.name " - Disabling VMTools Update at Power Cycle"
$vmConfig = New-Object VMware.Vim.VirtualMachineConfigSpec
$vmConfig.Tools = New-Object VMware.Vim.ToolsConfigInfo
$vmConfig.Tools.ToolsUpgradePolicy = "Manual"
Get-VM $vm.name | where {$_.Extensiondata.ReconfigVM($vmconfig)}
}
|
PowerShellCorpus/PoshCode/Get-ChilditemsRecursive.ps1
|
Get-ChilditemsRecursive.ps1
|
function Get-ChildItem2 ($path)
{
# path can either be absolut or relative, I only tried filesystem
# perhaps to named Get-ChildItemsRecursive
$root = gi $path
$PathLength = $root.FullName.length
# it would be nice if Split-Path could do the trick, I didn't grok it
gci $path -rec | % {
Add-Member -InputObject $_ -MemberType NoteProperty -Name RelativePath -Value $_.FullName.substring($PathLength+1)
$_
}
}
# Try for example:
# Get-ChildItem2 $pshome | % {$_.RelativePath }
# Now generate demo data
cd f:
md tmp
md tmp\\gcir\\dir1
md tmp\\gcir\\dir2
"file1" > tmp\\gcir\\dir1\\file1.txt
"file2" > tmp\\gcir\\dir1\\file2.txt
copy-Item tmp\\gcir\\dir1\\file1.txt tmp\\gcir\\dir2\\file1.txt # both file1 have same length and LastWriteTime
"file2changed" > tmp\\gcir\\dir2\\file2.txt # different length forced by different contents
# now we get pathnames relative to the starting path
Get-ChildItem2 tmp | % {$_.RelativePath }
<#
gcir
gcir\\dir1
gcir\\dir2
gcir\\dir1\\file1.txt
gcir\\dir1\\file2.txt
gcir\\dir2\\file1.txt
gcir\\dir2\\file2.txt
#>
# and it is easy to compare two trees of files
Compare-Object (Get-ChildItem2 tmp\\gcir\\dir1) (Get-ChildItem2 tmp\\gcir\\dir2) -prop RelativePath, LastWriteTime, Length -includeEqual
<#
RelativePath LastWriteTime Length SideIndicator
------------ ------------- ------ -------------
file1.txt 05.04.2009 10:45:03 16 ==
file2.txt 05.04.2009 10:45:03 30 =>
file2.txt 05.04.2009 10:45:03 16 <=
#>
# well we look only for the different files
Compare-Object (Get-ChildItem2 tmp\\gcir\\dir1) (Get-ChildItem2 tmp\\gcir\\dir2) -prop RelativePath, LastWriteTime, Length
# add some fiddeling to the newest file only
$last = $null
Compare-Object (Get-ChildItem2 tmp\\gcir\\dir1) (Get-ChildItem2 tmp\\gcir\\dir2) -prop RelativePath, LastWriteTime, Length |
Sort RelativePath, LastWriteTime -desc | % {
if ($last -ne $_.RelativePath)
{ $_ }
$last = $_.RelativePath
} | sort RelativePath
<#
RelativePath LastWriteTime Length SideIndicator
------------ ------------- ------ -------------
file2.txt 05.04.2009 10:45:03 30 =>
#>
|
PowerShellCorpus/PoshCode/Script permissions_1.ps1
|
Script permissions_1.ps1
|
<#
.SYNOPSIS
Applies permissions and roles to vSphere vApps
.DESCRIPTION
Applies permissions and roles to vSphere vApps
-VIServer (Optional, defaults to Development) {FQDN of VCentre Server}
-AppName (Required) {VApp Label}
-ADGroup (Optional) {Domain\\Group_Object}
-Role (Optional) {vSphere Role, ReadOnly, Owner-Managed, Supplier-Managed}
.EXAMPLE
Grants the Owner-Managed vSphere role to MYDOM\\MYGroup on the "Test VApp".
Create-Permissions -AppName "Test VApp" -ADGroup "MYDOM\\MYGroup" -Role "Owner-Managed"
#>
#Author: Ant B 2012
Param(
[String]$VIServer = "<Default VC>",
[parameter(Mandatory=$true)][String]$AppName,
[parameter(Mandatory=$true)][string]$ADGroup,
[parameter(Mandatory=$true)][string]$Role
)
#Check for the VMware Snapin, load if it isn't already there.
if ( (Get-PSSnapin -Name VMware.VimAutomation.Core -ErrorAction SilentlyContinue) -eq $null )
{
Add-PsSnapin VMware.VimAutomation.Core
}
#Connect to VCentre
Connect-VIServer $VIServer
$authmgr = Get-View AuthorizationManager
$perm = New-Object Vmware.VIM.Permission
$perm.principal = $ADGroup
$perm.group = $true
$perm.propagate = $true
$perm.roleid = ($authmgr.Rolelist | where{$_.Name -eq $Role}).Roleid
$target = get-vapp | select name, Id | where{$_.Name -eq $AppName}
$authmgr.SetEntityPermissions($target.Id, $perm)
#Close our connection to VCentre
Disconnect-VIServer -Server * -Force -Confirm:$False
|
PowerShellCorpus/PoshCode/disabled AD accounts.ps1
|
disabled AD accounts.ps1
|
#Get Domain List
$objForest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
$DomainList = @($objForest.Domains | Select-Object Name)
$Domains = $DomainList | foreach {$_.Name}
#get users list
$users = Get-Content U:\\EMCU15FI3_USER.txt
$total = $users.count
"SAMaccountname;DisplayName;HomeDir;Domain" | Out-File -FilePath test.txt
foreach($Domain in $Domains){
$i=0
foreach($user in $users) {
# serializevalue parameter is used to inly get the properties needed so variable doesn't use too much RAM.
$b = Get-QADUser -SamAccountName $user -SizeLimit 0 -Disabled -DontUseDefaultIncludedProperties -IncludedProperties NTAccountName, DisplayName, HomeDirectory, userprincipalname -SerializeValues
$storing = $b.sAMAccountName + ";" + $b.displayName + ";" + $b.homeDirectory + ";" +$domain
if ($storing.StartsWith(";")) {
}
else{
$storing | Out-File -FilePath test.txt -append
}
$storing=$null
$b=$null
#free up the garbage collect (empties unused variables)
[System.GC]::Collect()
$i++;
Write-Progress -Activity "Searching disabled accounts in $domain" -Status "Progress:" -PercentComplete $($i*100/$total)
}
}
|
PowerShellCorpus/PoshCode/Get-ServiceAccounts_1.ps1
|
Get-ServiceAccounts_1.ps1
|
#requires -pssnapin PSCX
#Author: Glenn Sizemore glnsize@get-admin.com
#Purpose: Scan a remote system for any services running under a non standard account.
# Standard accounts would be considered, NT AUTHORITY\\NetworkService,
# NT AUTHORITY\\LocalService, LocalSystem, or .\\ASPNET
#
#Usage: PS > Get-ServiceAccounts [-Target <string>] [-Path <string>] [-verbose] [-Credential <PSCredential Object> ]
#
# -Target(optional)
# can be either a string or an array of strings.
# -Path(optional)
# Path to an item containing a list of Targets
# -Verbose(optional)
# turns on verbose logging to the console
# -Credential(optional)
# should only be used with V2, uses alternate credentials when
# querying target for services.
#
#Returns: PSCustom Object
#
#Example: Get-ServiceAccounts -Target "host1","host2","host3" -Path "C:\\temp\\otherhosts.txt" -verbose
#
# this command will combined the targets: host1, host2, and host3 with all targets located in
# the file otherhost.txt, and scan all of them for unique service accounts.
#
param($target,
[string]$Path,
[switch]$verbose,
[System.Management.Automation.PSCredential]$credential = ($null)
)
begin
{
# Create an empty object to hold all service accounts found.
$SvcAccounts = @()
#Save the current $ErrorActionPreference so we can restore it.
$ErrActionSave = $ErrorActionPreference
$Verbosesave = $VerbosePreference
$warningSave = $WarningPreference
#If a PSCredential is supplied then wmi query will be ran under that account.
if ($credential)
{
Write-Host "there is a known bug using -credential in V1..."
$gwmiquery = {Get-WmiObject -Class Win32_Service -ComputerName $computer -Credential $credential `
-property name, startname, caption, StartMode `
-filter 'NOT Startname LIKE "%NT AUTHORITY%" AND NOT Startname LIKE "LocalSystem" AND NOT Startname LIKE "ASPNET"'}
}
else
{
$gwmiquery = {Get-WmiObject -Class Win32_Service -ComputerName $computer -property name, startname, caption, StartMode `
-filter 'NOT Startname LIKE "%NT AUTHORITY%" AND NOT Startname LIKE "LocalSystem" AND NOT Startname LIKE "ASPNET"'}
}
if ($Verbose) {$VerbosePreference = "Continue"; $WarningPreference = "Continue"}
#Workhorse...
function ProcessTarget ($computer)
{
$obj = @()
#Set ErrorAction to silent... we'll handle the error's ourselves.
$ErrorActionPreference = "SilentlyContinue"
Write-Verbose "querying $computer ..."
#call the Query from above.
$services = &$gwmiquery
#set erroraction back there sould be no error's from here on out.
$ErrorActionPreference = $ErrActionSave
Write-Verbose " $($services.count) services located on $computer using "
foreach ($service in $Services)
{
# If there was an error while attempting the gwmi call, there will be only one error.
# We check that error to help annotate why we were unsuccessful.
switch -regex ($Error[0].Exception)
{
"The RPC server is unavailable"
{
Write-warning "RPC Unavailable on $computer"
$obj += "" | Select @{e={$computer};n='Target'},@{e={"RPC_Unavalable"};n='SvcName'}
continue
}
#vista
"Access denied"
{
Write-warning "Access Denied on $computer"
$obj += "" | Select @{e={$computer};n='Target'},@{e={"Access_Denied"};n='SvcName'}
continue
}
#XP/Server 2k3
"Access is denied"
{
Write-warning "Access Denied on $computer"
$obj += "" | Select @{e={$computer};n='Target'},@{e={"Access_Denied"};n='SvcName'}
continue
}
$null
{
$obj += "" | Select @{e={$computer};n='Target'},
@{e={$service.name };n='SvcName'},
@{e={$service.startname };n='SvcAcccount'},
@{e={$service.caption };n='SvcDes'},
@{e={$service.StartMode };n='StartMode'}
}
}
$Error.clear()
}
return $obj
}
}
process
{
$Targets = @()
if ($Path){$Targets = Get-Content $Path}
if ($Target){$Targets += $target}
foreach ($computer in $Targets)
{
ping-host -HostName $computer -Count 1 -Quiet -Timeout 1| Where-Object { $_.loss -ne 100} | `
ForEach-Object {$SvcAccounts += ProcessTarget $_.host}
}
}
End
{
$ErrorActionPreference = $ErrActionSave
$VerbosePreference = $Verbosesave
$WarningPreference = $warningSave
Write-Output $SvcAccounts
}
|
PowerShellCorpus/PoshCode/PowerShell script config.ps1
|
PowerShell script config.ps1
|
#################################################
# Sample code showing how to save/load PowerShell script
# configuration to disk
#
# (c) Dmitry Sotnikov
# http://dmitrysotnikov.wordpress.com/2010/05/07/storing-powergui-add-on-configuration
#################################################
# Assign unique folder and config names
# This would sore data in
# C:\\Users\\username\\AppData\\Roaming\\MyPowerGUIAddOn\\MyAddOn.Config.xml
$FolderName = "MyPowerGUIAddOn"
$ConfigName = "MyAddOn.Config.xml"
# keep all add-on parameters in a map
$parameters = @{}
# read parameters
if ( Test-Path -Path "$($env:AppData)\\$FolderName\\$ConfigName") {
$parameters = Import-Clixml -Path "$($env:AppData)\\$FolderName\\$ConfigName"
# now you can use them, e.g.
$parameters['A']
$parameters['B']
} else {
# Config does not exist yet - set defaults
$parameters['A'] = 5
$parameters['B'] = "Qwerty"
}
# store parameters
if ( -not (Test-Path -Path "$($env:AppData)\\$FolderName")) {
mkdir "$($env:AppData)\\$FolderName"
}
$parameters | Export-Clixml -Path "$($env:AppData)\\$FolderName\\$ConfigName"
|
PowerShellCorpus/PoshCode/Get-LocalGroupAllMembers.ps1
|
Get-LocalGroupAllMembers.ps1
|
# #############################################################################
# NAME: FUNCTION-Get-LocalGroupAllMembers.ps1
#
# AUTHOR: Francois-Xavier Cat
# DATE: 2012/12/27
# EMAIL: fxcat@lazywinadmin.com
# WEBSITE: LazyWinAdmin.com
# TWiTTER: @lazywinadm
#
# COMMENT: The following functions will gather all the local and domain members (direct or nested)
# By Default the function will query the Localhost and the Group Administrators.
# REQUIRE: Quest Active Directory
# USAGE: Get-LocalGroupAllMembers -ComputerName SERVER01 -GroupName "Administrators"
#
# VERSION HISTORY
# 1.0 2012.12.27 Initial Version.
#
# #############################################################################
# Function to get LOCAL Group Member(s)
# Members can be from the Local Machine or from the Domain.
# Also, this function does not look for nested membership on local group(local group member of another local group)
# since it is not supported by Microsoft (even if you can do it via net.exe, the permission won't work)
# http://technet.microsoft.com/en-us/library/ee681621(v=ws.10).aspx
Function global:Get-LocalGroupMembership {
[Cmdletbinding()]
Param (
[Parameter(ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
[string]$ComputerName = $env:COMPUTERNAME,
[string]$GroupName = "Administrators"
)
# Create the array that will contains all the output of this function
$Output = @()
# Get the members for the group and computer specified
$Group = [ADSI]"WinNT://$ComputerName/$GroupName"
$Members = @($group.psbase.Invoke("Members"))
# Format the Output
$Members | foreach {
$name = $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)
$class = $_.GetType().InvokeMember("Class", 'GetProperty', $null, $_, $null)
$path = $_.GetType().InvokeMember("ADsPath", 'GetProperty', $null, $_, $null)
# Find out if this is a local or domain object
if ($path -like "*/$ComputerName/*"){
$Type = "Local"
}
else {$Type = "Domain"
}
$Details = "" | Select ComputerName,Account,Class,Group,Path,Type
$Details.ComputerName = $ComputerName
$Details.Account = $name
$Details.Class = $class
$Details.Group = $GroupName
$details.Path = $path
$details.Type = $type
# Send the current result to the $output variable
$output = $output + $Details
}
# Finally show the Output to the user.
$output
}
# Function to get DOMAIN Group Member(s)
# This function allow to dig into Active Directory to get all the members (direct or nested)
# Members can only be from the Domain.
function global:Get-DomainGroupMembership {
param ($GroupName,$ComputerName)
#$ComputerName parameter here is only used for information purpose, to show in the output
# Create the array that will contains all the output of this function
$Output = @()
# Check the current members of $GroupName
$Members = $GroupName | Get-QADGroupMember
# Check the Count of $members
$MembersCount = $Members.count
# If there is at least 1 member, do the following
if ($MembersCount -gt 0){
foreach ($member in $Members){
switch ($Member.type){
"user"{
# Return the user information
$Details = "" | Select ComputerName,Account,Class,Group,Domain,type,path
$Details.ComputerName = $ComputerName
$Details.Account = $member.name
$Details.Class = $Member.type
$Details.Group = $GroupName
$details.domain = $member.domain.name
$details.type = "Domain"
$Details.path = $Member.CanonicalName
$output = $output + $Details
}#Switch user
"group"{
# Return the group object information
$Details = "" | Select ComputerName,Account,Class,Group,Domain,type,path
$Details.ComputerName = $ComputerName
$Details.Account = $member.name
$Details.Class = $Member.type
$Details.Group = $GroupName
$details.domain = $member.domain.name
$details.type = "Domain"
$Details.path = $Member.CanonicalName
$output = $output + $Details
# Return the members of the current group
Get-DomainGroupMembership -GroupName $Member.name -ComputerName $ComputerName
}#Switch group
}#switch ($Member.type)
}#foreach ($member in $Members)
}#if ($MembersCount -gt 0)
#Finally show the output
$Output
}#end function Get-DomainGroupMembership
# Function to Get LOCAL and DOMAIN member(s) information
# LOCAL Group Membership information is handled by the function Get-LocalGroupMembership
# DOMAIN Group Membership information is handled by the function Get-DomainGroupMembership
function global:Get-LocalGroupAllMembers {
param (
[parameter(ValueFromPipeline=$true)]
[string]$ComputerName = "$env:computername",
[string]$GroupName = "Administrators"
)
# Create the array that will contains all the output of this function
$Output = @()
# Get the local administrators for the current ComputerName using the function declared
# earlier: Get-LocalGroupMembership
$LocalAdministrators = Get-LocalGroupMembership -ComputerName $ComputerName -GroupName $GroupName
# Let's now get information about each members, and members of members, etc...
foreach ($admin in $LocalAdministrators){
# L O C A L #
# Local User
if (($admin.Type -like "Local") -and ($admin.class -like "User")){
$Details = "" | Select ComputerName,Account,Class,Group,Type,Path
$Details.ComputerName = $admin.ComputerName
$Details.Account = $admin.account
$Details.Class = $admin.class
$Details.Group = $admin.group
$Details.Type = $admin.type
$Details.Path = $admin.path
$output = $output + $Details
}
# Local Group
if (($admin.type -like "Local") -and ($admin.class -like "group")){
# Return the local group information before checking its members
$Details = "" | Select ComputerName,Account,Group,Domain
$Details.ComputerName = $admin.ComputerName
$Details.Account = $admin.account
$Details.Class = $admin.class
$Details.Group = $admin.group
$Details.type = $admin.type
$Details.path = $admin.path
$output = $output + $Details
# Return the members of the current Local Group
$localgroup = Get-LocalGroupMembership -GroupName $admin.account -ComputerName $ComputerName
# If There is at least 1 member, do the following
if ($localgroup.count -gt 0) {
foreach ($localMember in $localgroup){
$Details = "" | Select ComputerName,Account,Class,Group,Type,Path
$Details.Account = $localMember.account
$Details.Group = $admin.account # Here we are taking the name of the parent group
$Details.ComputerName = $localMember.ComputerName
$Details.Class = $localMember.class
$Details.type = $localMember.type
$Details.path = $localMember.path
$output = $output + $Details
}#foreach
}#if
}#if (Get-LocalGroupMember -group $admin.account -ComputerName $ComputerName)
# D O M A I N #
if ($admin.type -like "Domain"){
# Get information about this object in the domain
# Here we just want to know if it is an User or Group.
$ADObject = Get-QADObject $admin.account
Switch ($ADObject.type) {
# Domain User
"user" {
# Return the User information
$Details = "" | Select ComputerName,Account,Class,Group,Domain,type,path
$Details.ComputerName = $ComputerName
$Details.Account = $ADObject.name
$Details.Class = $ADObject.type
$Details.Group = $admin.group
$Details.domain = $ADObject.domain.name
$Details.Type = $admin.type
$Details.path = $ADObject.CanonicalName
$output = $output + $Details
}#user (switch)
# Domain Group
"group"{
# Return the Group information
$Details = "" | Select ComputerName,Account,Class,Group,Domain,type,path
$Details.ComputerName = $ComputerName
$Details.Account = $ADObject.name
$details.Class = $ADObject.type
$Details.Group = $admin.group
$Details.domain = $ADObject.domain.name
$Details.Type = $admin.type
$Details.path = $ADObject.CanonicalName
$output = $output + $Details
# Checking if the group has members, call the function declared ealier
# Get-DomainGroupMembership
Get-DomainGroupMembership -GroupName $ADObject.name -ComputerName $ComputerName
}#group (switch)
}#switch
}#if ($admin.domain -notlike "$ComputerName"){
}#foreach ($admin in $LocalAdministrators){
$output
}#function global:Get-LocalGroupAllMembers
|
PowerShellCorpus/PoshCode/Get Twitter RSS Feed.ps1
|
Get Twitter RSS Feed.ps1
|
param ([String] $ScreenName)
$client = New-Object System.Net.WebClient
$idUrl = "https://api.twitter.com/1/users/show.json?screen_name=$ScreenName"
$data = $client.DownloadString($idUrl)
$start = 0
$findStr = '"id":'
do {
$start = $data.IndexOf($findStr, $start + 1)
if ($start -gt 0) {
$start += $findStr.Length
$end = $data.IndexOf(',', $start)
$userId = $data.SubString($start, $end-$start)
}
} while ($start -le $data.Length -and $start -gt 0)
$feed = "http://twitter.com/statuses/user_timeline/$userId.rss"
$feed
|
PowerShellCorpus/PoshCode/New-Zip_2.ps1
|
New-Zip_2.ps1
|
Function New-Zip
{
<#
.SYNOPSIS
Create a Zip File from any files piped in.
.DESCRIPTION
Requires that you have the SharpZipLib installed, which is available from
http://www.icsharpcode.net/OpenSource/SharpZipLib/
.NOTES
File Name : PowerZip.psm1
Author : Christophe CREMON (uxone) - http://powershell.codeplex.com
Requires : PowerShell V2
.PARAMETER Source
Set the name of the source to zip (file or directory)
.PARAMETER ZipFile
Set the name of the zip file to create
.PARAMETER Recurse
Browse the source recursively
.PARAMETER Include
Include only items you specify
.PARAMETER Exclude
Exclude items you specify
.PARAMETER AbsolutePaths
Preserve the absolute path name of each item in the zip container
.PARAMETER DeleteAfterZip
Delete source items after successful zip
.EXAMPLE
New-Zip -Source C:\\Temp -ZipFile C:\\Archive\\Scripts.zip -Include *.ps1 -DeleteAfterZip
Copies all PS1 files from the C:\\Temp directory to C:\\Archive\\Scripts.zip and delete them after successful ZIP
#>
param (
[ValidateNotNullOrEmpty()]
[Parameter(
Mandatory = $true)
]
[string] $Source,
[Parameter(
Mandatory = $true)
]
[string] $ZipFile,
[switch] $Recurse,
[array] $Include,
[array] $Exclude,
[switch] $AbsolutePaths,
[switch] $DeleteAfterZip )
[int] $ExitCode = 1
$LoadAssembly = [System.Reflection.Assembly]::LoadWithPartialName("ICSharpCode.SharpZipLib")
if ( -not $LoadAssembly ) { throw "! Assembly not found {ICSharpCode.SharpZipLib}" }
$RootPath = ( Resolve-Path -Path $Source -ErrorAction SilentlyContinue ).Path
if ( -not $RootPath ) { throw "! Source not found {$Source}" }
if ( $ZipFile -notmatch "\\.zip$" ) { $ZipFile = $ZipFile -replace "$",".zip" }
if ( $Recurse -eq $true ) { $RecurseArgument = "-Recurse" }
if ( $AbsolutePaths -eq $true ) { $AbsolutePathsArgument = "-AbsolutePaths" }
if ( $DeleteAfterZip -eq $true ) { $DeleteAfterZipArgument = "-DeleteAfterZip" }
if ( $Include )
{
$Include = $Include -join ","
$IncludeArgument = "-Include $Include"
$Source = $Source+"\\*"
}
if ( $Exclude )
{
$Exclude = $Exclude -join ","
$ExcludeArgument = "-Exclude $Exclude"
}
$GetCommand = "Get-ChildItem -Path '$Source' $RecurseArgument $IncludeArgument $ExcludeArgument -Force"
$ItemsToZip = Invoke-Expression -Command $GetCommand
$SizeBeforeZip = ( $ItemsToZip | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue ).Sum
$SizeBeforeZipInMB = $SizeBeforeZip | ForEach-Object { "{0:N2}" -f ($_ / 1MB) }
if ( -not $SizeBeforeZip )
{
Write-Output "NOTHING TO ZIP"
break
}
$StartTime = Get-Date
Write-Output "`n===================================`n=> Start Time : $($StartTime.ToString(""dd/MM/yyyy-HH:mm:ss""))`n"
Write-Output "TOTAL SIZE BEFORE ZIP : {$SizeBeforeZipInMB MB}`n"
Write-Output "Initializing ZIP File {$ZipFile} ...`n"
$CreateZIPContainer = New-Item -ItemType File -Path $ZipFile -Force -ErrorAction SilentlyContinue
if ( -not $CreateZIPContainer ) { throw "! Unable to create ZIP container {$ZipFile}" }
$oZipOutputStream = New-Object -TypeName ICSharpCode.SharpZipLib.Zip.ZipOutputStream([System.IO.File]::Create($ZipFile))
[byte[]] $Buffer = New-Object Byte[] 4096
foreach ( $Item in $ItemsToZip )
{
if ( $Item.FullName -ne $ZipFile )
{
if ( Test-Path ( $Item.FullName ) -ErrorAction SilentlyContinue )
{
$ZipEntry = $Item.FullName
if ( -not $AbsolutePaths )
{
$ReplacePath = [Regex]::Escape( $RootPath+"\\" )
$ZipEntry = $Item.FullName -replace $ReplacePath,""
}
if ( $Item.psIsContainer -eq $true )
{
if ( $Recurse -eq $true )
{
Write-Output "Processing ZIP of Directory {$($Item.FullName)} ..."
$OldErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
$oZipEntry = New-Object -TypeName ICSharpCode.SharpZipLib.Zip.ZipEntry("$ZipEntry/")
$oZipOutputStream.PutNextEntry($oZipEntry)
if ( $? -ne $true )
{
$ItemsNotZipped += @($Item.FullName)
$ErrorsArray += @("! Unable to ZIP Directory {$($Item.FullName)}")
}
$ErrorActionPreference = $OldErrorActionPreference
}
}
else
{
Write-Output "Processing ZIP of File {$($Item.FullName)} ..."
$OldErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
$FileStream = [IO.File]::OpenRead($Item.FullName)
$oZipEntry = New-Object -TypeName ICSharpCode.SharpZipLib.Zip.ZipEntry("$ZipEntry")
$oZipOutputStream.PutNextEntry($oZipEntry)
[ICSharpCode.SharpZipLib.Core.StreamUtils]::Copy($FileStream,$oZipOutputStream,$Buffer)
if ( $? -ne $true )
{
$ItemsNotZipped += @($Item.FullName)
$ErrorsArray += @("! Unable to ZIP File {$($Item.FullName)}")
}
$FileStream.Close()
}
}
}
}
$oZipOutputStream.Finish()
$oZipOutputStream.Close()
if ( $? -eq $true )
{
$ErrorActionPreference = $OldErrorActionPreference
if ( $DeleteAfterZip )
{
$ItemsToZip | Where-Object { $ItemsNotZipped -notcontains $_.FullName } | ForEach-Object {
if ( $_.psIsContainer -ne $true )
{
if ( Test-Path ( $_.FullName ) -ErrorAction SilentlyContinue )
{
Write-Output "Processing Delete of File {$($_.FullName)} ..."
$RemoveItem = Remove-Item -Path $_.FullName -Force -ErrorAction SilentlyContinue
if ( $? -ne $true )
{
$ErrorsArray += @("! Unable to Delete File {$($_.FullName)}")
}
}
}
}
if ( $Recurse )
{
$ItemsToZip | Where-Object { $ItemsNotZipped -notcontains ( Split-Path -Parent $_.FullName ) } | ForEach-Object {
if ( $_.psIsContainer -eq $true )
{
if ( Test-Path ( $_.FullName ) -ErrorAction SilentlyContinue )
{
Write-Output "Processing Delete of Directory {$($_.FullName)} ..."
$RemoveItem = Remove-Item -Path $_.FullName -Force -Recurse -ErrorAction SilentlyContinue
if ( $? -ne $true )
{
$ErrorsArray += @("! Unable to Delete Directory {$($_.FullName)}")
}
}
}
}
}
}
Write-Output "`nZIP File Created {$ZipFile} ...`n"
$ExitCode = 0
}
else
{
$ErrorActionPreference = $OldErrorActionPreference
$ErrorsArray += @("! ZIP Archive {$ZipFile} Creation Failed`n")
}
if ( $ErrorsArray )
{
Write-Output "`n[ ERRORS OCCURED ]"
$ErrorsArray
$ExitCode = 1
}
else
{
$SizeAfterZip = ( Get-Item -Path $ZipFile -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue ).Sum
$SizeAfterZipInMB = $SizeAfterZip | ForEach-Object { "{0:N2}" -f ($_ / 1MB) }
Write-Output "`nTOTAL SIZE AFTER ZIP : {$SizeAfterZipInMB MB}`n"
$Gain = ( $SizeBeforeZip - $SizeAfterZip )
$GainInMB = $Gain | ForEach-Object { "{0:N2}" -f ($_ / 1MB) }
if ( $Gain -gt 0 )
{
$GainInPercent = (($SizeBeforeZip - $SizeAfterZip) / $SizeBeforeZip) * 100 | ForEach-Object { "{0:N2}" -f $_ }
Write-Output "GAIN : {$GainInMB MB} ($GainInPercent %)`n"
}
}
$EndTime = Get-Date
$ExecutionTime = ($EndTime-$StartTime)
Write-Output "`nExecution Time : $ExecutionTime`n"
Write-Output "=> End Time : $($EndTime.ToString(""dd/MM/yyyy-HH:mm:ss""))`n=================================`n"
exit $ExitCode
}
Export-ModuleMember -Function New-Zip
|
PowerShellCorpus/PoshCode/Set-Domain.ps1
|
Set-Domain.ps1
|
function Set-Domain {
param( [switch]$help,
[string]$domain=$(read-host "Please specify the domain to join"),
[System.Management.Automation.PSCredential]$credential = $(Get-Credential)
)
$usage = "`$cred = get-credential `n"
$usage += "Set-AvaDomain -domain corp.avanade.org -credential `$cred`n"
if ($help) {Write-Host $usage;exit}
$username = $credential.GetNetworkCredential().UserName
$password = $credential.GetNetworkCredential().Password
$computer = Get-WmiObject Win32_ComputerSystem
$computer.JoinDomainOrWorkGroup($domain ,$password, $username, $null, 3)
}
|
PowerShellCorpus/PoshCode/Get-SiSReport_1.ps1
|
Get-SiSReport_1.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 = $ThisDisk.Used
Free = $ThisDisk.Free
CommonStoreFiles = ($SisResult[($SisResult.Count)-4]).TrimStart("Common store files:")
LinkFiles = ($SisResult[($SisResult.Count)-3]).TrimStart("Link files:")
InaccessibleLinkFiles = ($SisResult[($SisResult.Count)-2]).TrimStart("Inaccessible link files:")
SpaceSaved = ($SisResult[($SisResult.Count)-1]).TrimStart("Space saved:")
}
}
}
End
{
Return $SisReport
}
}
|
PowerShellCorpus/PoshCode/Set-Wallpaper (CTP3)_1.ps1
|
Set-Wallpaper (CTP3)_1.ps1
|
#requires -version 2.0
## Set-Wallpaper - set your windows desktop wallpaper
###################################################################################################
## Usage:
## Set-Wallpaper "C:\\Users\\Joel\\Pictures\\Wallpaper\\Dual Monitor\\mandolux-tiger.jpg" "Tile"
## ls *.jpg | get-random | Set-Wallpaper
## ls *.jpg | get-random | Set-Wallpaper -Style "Stretch"
###################################################################################################
## History:
## v0.5 First release (on #PowerShell@irc.freenode.net)
## v1.0 Public release (http://www.poshcode.org/488)
## - Added Style: Tile|Center|Stretch
## v1.1 (http://poshcode.org/491)
## - Added "NoChange" style to just use the style setting already set
## - Made the Style parameter to the cmdlet optional
## v2.0 This Release
## - Updated for CTP3, and made it run as a script instead of a function.
###################################################################################################
[CmdletBinding()]
Param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[string]
$Path
,
[Parameter(Position=1, Mandatory=$false)]
$Style = "NoChange"
)
BEGIN {
try {
$WP = [Wallpaper.Setter]
} catch {
$WP = add-type @"
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32;
namespace Wallpaper
{
public enum Style : int
{
Tile, Center, Stretch, NoChange
}
public class Setter {
public const int SetDesktopWallpaper = 20;
public const int UpdateIniFile = 0x01;
public const int SendWinIniChange = 0x02;
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int SystemParametersInfo (int uAction, int uParam, string lpvParam, int fuWinIni);
public static void SetWallpaper ( string path, Wallpaper.Style style ) {
SystemParametersInfo( SetDesktopWallpaper, 0, path, UpdateIniFile | SendWinIniChange );
RegistryKey key = Registry.CurrentUser.OpenSubKey("Control Panel\\\\Desktop", true);
switch( style )
{
case Style.Stretch :
key.SetValue(@"WallpaperStyle", "2") ;
key.SetValue(@"TileWallpaper", "0") ;
break;
case Style.Center :
key.SetValue(@"WallpaperStyle", "1") ;
key.SetValue(@"TileWallpaper", "0") ;
break;
case Style.Tile :
key.SetValue(@"WallpaperStyle", "1") ;
key.SetValue(@"TileWallpaper", "1") ;
break;
case Style.NoChange :
break;
}
key.Close();
}
}
}
"@ -Passthru
}
}
PROCESS {
Write-Verbose "Setting Wallpaper ($Style) to $(Convert-Path $Path)"
$WP::SetWallpaper( (Convert-Path $Path), $Style )
}
|
PowerShellCorpus/PoshCode/Split.ps1
|
Split.ps1
|
function Split {
<#
.Synopsis
Splits up a file into smaller files.
.Description
This function takes a file as input and splits it into files by a set number of
lines.
.Parameter filename
The name of the file to be used as an input.
This value can be piped to the function (see examples)
.Parameter lines
The number of lines per file.
.Parameter prefix
A prefix for the output filenames. Defaults to 'split.'
.Parameter extension
The file extension to use for output files.
.Example
# Simple split of a file.
Split -filename mybigfile.txt -lines 100
.Example
# Pass a number of files by pipeline, filtering out directories
ls | ?{-not $_.PSIsContainer} | %{$_.FullName} | Split -lines 100
#>
param([Parameter(Mandatory=$true,
ValueFromPipeLine=$true)]
[string]$filename,
[Parameter(Mandatory=$true)]
[int]$lines,
[Parameter(Mandatory=$false)]
[string]$prefix = 'split.',
[Parameter(Mandatory=$false)]
[string]$extension = 'txt')
if (-not (Test-Path $file)) {
Write-Host "$file not found!"
break
}
$increment = 0
$line = 0
Get-Content $file |
%{
$line += 1
if (-not ($lines % $line)) {
$increment += 1
}
$_ >> "$file.$increment.$extension"
}
}
|
PowerShellCorpus/PoshCode/Highlight-Syntax _3.0.ps1
|
Highlight-Syntax _3.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 ) )
}
@@ $lastColumn = $token.EndColumn
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/Add-PrinterDriver.ps1
|
Add-PrinterDriver.ps1
|
#requires -version 2
function Add-PrinterDriver {
<#
.SYNOPSIS
Adds printer drivers to the local computer from a specified print server.
.DESCRIPTION
Adds printer drivers to the local computer from a specified print server. The function collects all shared printer objects from the specified print server and installs them on the local computer if not already installed. One mandatory parameter: PrintServer
.PARAMETER PrintServer
The name of the print server to add printer drivers from
.PARAMETER Clean
Switch parameter which deletes all network printer connections for the current user.
.EXAMPLE
Add-PrinterDriver -PrintServer srv01.domain.local
Add printer drivers from the specified print server
.EXAMPLE
Add-PrinterDriver -PrintServer srv01.domain.local -Clean
Add printer drivers from the specified print server, then removes all network printer connections for the current user.
.EXAMPLE
Add-PrinterDriver -PrintServer srv01.domain.local -Verbose
Add printer drivers from the specified print server with the -Verbose switch parameter
.NOTES
AUTHOR: Jan Egil Ring
BLOG: http://blog.powershell.no
LASTEDIT: 03.07.2011
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.
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[string] $PrintServer,
[switch] $Clean
)
#Collecting all shared printer objects from the specified print server
$allprinters = @(Get-WmiObject win32_printer -ComputerName $PrintServer -Filter 'shared=true')
#Defining all unique printer drivers from the specified print server
$drivers = @($allprinters | Select-Object drivername -Unique)
#Defining a collection containing the first printer object using a unique printer driver
$printers = @()
foreach ($item in $drivers){
$printers += @($allprinters | Where-Object {$_.drivername -eq $item.drivername})[0]
}
#Collecting locally installed drivers
$localdrivers = @()
foreach ($driver in (Get-WmiObject Win32_PrinterDriver)){
$localdrivers += @(($driver.name -split ",")[0])
}
#Initializing the CurrentPrinter variable for use with Write-Progress
$CurrentPrinter = 1
#Looping through the printer objects collection, installing those who are not already installed on the local computer
foreach ($printer in $printers) {
Write-Progress -Activity "Installing printers..." -Status "Current printer: $($printer.name)" -Id 1 -PercentComplete (($CurrentPrinter/$printers.count) * 100)
#Create hash-table for output object
$outputobject = @{}
$outputobject.drivername = $printer.drivername
$locallyinstalled = $localdrivers | Where-Object {$_ -eq $printer.drivername}
if (-not $locallyinstalled) {
Write-Verbose "$($printer.drivername) is not installed locally"
$AddPrinterConnection = Invoke-WmiMethod -Path Win32_Printer -Name AddPrinterConnection -ArgumentList ([string]::Concat('\\\\', $printer.__SERVER, '\\', $printer.ShareName)) -EnableAllPrivileges
$outputobject.returncode = $AddPrinterConnection.ReturnValue
}
else
{
Write-Verbose "$($printer.drivername) is already installed locally"
$outputobject.returncode = "Already installed"
}
#Create a new object for each driver, based on the outputobject hash-table
New-Object -TypeName PSObject -Property $outputobject
$CurrentPrinter ++
}
#Deletes all printer connections for the current user
if ($clean) {
$printers = Get-WmiObject Win32_Printer -EnableAllPrivileges -Filter network=true
if ($printers) {
foreach ($printer in $printers) {
$printer.Delete()
}
}
}
}
|
PowerShellCorpus/PoshCode/Find sharable storage_1.ps1
|
Find sharable storage_1.ps1
|
# This function returns all datastores that can be shared amongst ESX hosts.
function Get-ShareableDatastore {
# Get all datastores.
$datastores = Get-Datastore
# Load the HostStorageSystems of all hosts.
$hosts = Get-VMHost | Get-View -property ConfigManager
$storageSystems = @()
foreach ($h in $hosts) {
$sdi = Get-View $h.ConfigManager.StorageSystem -Property StorageDeviceInfo
Write-Debug ("GSD: SDI for host $h is " + $sdi)
$storageSystems += $sdi
}
foreach ($dso in $datastores) {
$ds = $dso | Get-View -Property Info
# Check if this datastore is NFS.
$dsInfo = $ds.Info
Write-Debug ("GSD: Is it NFS? " + $dsInfo.getType())
if ($dsInfo -is [VMware.Vim.NasDatastoreInfo]) {
Write-Output $dso
continue
}
# Get the first extent of the datastore.
$firstExtent = $dsInfo.Vmfs.Extent[0]
Write-Debug ("GSD: first extent: " + $firstExtent.DiskName)
# Find a host that maps this LUN.
foreach ($hss in $storageSystems) {
$lun = $hss.StorageDeviceInfo.ScsiLun | Where { $_.CanonicalName -eq $firstExtent.DiskName }
if ($lun) {
Write-Debug ("GSD: found " + $lun.DeviceName + " on " + $hss.MoRef.Value)
Write-Debug ("GSD: LUN details: Name:" + $lun.DisplayName + ", Type:" + $lun.DeviceType + ", Vendor:" + $lun.Vendor + ", Model:" + $lun.Model)
# Search the adapter topology of this host, looking for the LUN.
$adapterTopology = $hss.StorageDeviceInfo.ScsiTopology.Adapter |
Where { $_.Target |
Where { $_.Lun |
Where { $_.ScsiLun -eq $lun.key }
}
} | Select -First 1
# We've found a host that has this LUN. Find how it maps to an adapter.
$adapter = $hss.StorageDeviceInfo.HostBusAdapter | Where { $_.Key -eq $adapterTopology.Adapter }
Write-Debug ("GSD: HBA type is: " + $adapter.getType())
# It's shared if it's Fibre Channel or iSCSI (we checked for NFS earlier)
if ($adapter -is [VMware.Vim.HostFibreChannelHba] -or $adapter -is [VMware.Vim.HostInternetScsiHba]) {
Write-Debug "GSO: $dso is sharable"
Write-Output $dso
}
# Otherwise it's not shared and we quit walking through hosts.
break
}
}
}
}
|
PowerShellCorpus/PoshCode/where-in.ps1
|
where-in.ps1
|
function where-in {
[cmdletbinding()]
param (
[parameter(mandatory = $true,position = 1)]
[system.Collections.IEnumerable]$collection,
[parameter(position = 2)]
[scriptblock]$predicate ,
[parameter(valuefrompipeline = $true)]
$pipelineobject
)
process {
if ($predicate) {
foreach ($__ in $collection) {
if(&$predicate) {
write-Output $pipelineobject
break;
}
}
}
else {
if ($collection -contains $pipelineobject) {
write-Output $pipelineobject }
}
}
}
set-alias ?in where-in
$a = (1..10) , (1..10) | % { $_ }
$a | Where-in (3,4,8)
gps | where-in ("power","s") { $_.processname.startswith($__) }
function where-propertyin {
[cmdletbinding()]
param (
[parameter(mandatory = $true,position = 1)]
[system.Collections.IEnumerable]$collection,
[parameter(mandatory = $true,position = 2)]
[string] $propertyname,
[parameter(position = 3)]
[scriptblock]$predicate ,
[parameter(valuefrompipeline = $true)]
$pipelineobject
)
process {
if ($predicate) {
foreach ($__ in $collection) {
$_ = $pipelineobject.$propertyname
if(&$predicate) {
write-Output $pipelineobject
break;
}
}
}
else {
if ($collection -contains $pipelineobject.$propertyname) {
write-Output $pipelineobject }
}
}
}
set-alias ?.in where-propertyin
gps | where-propertyin ("powershell","svchost") processname
gps | where-propertyin ("power","s") processname { $_.startswith($__) }
|
PowerShellCorpus/PoshCode/Get-MailboxesOverSizeLim.ps1
|
Get-MailboxesOverSizeLim.ps1
|
# -------------------------------------------------------------------------------
# Script: Get-MailboxesOverSizeLimit.ps1
# Author: Chris Brown
# Date: 04/04/2011 10:41:00
# Keywords:
# comments:
#
# Versioning
# 04/04/2011 CJB Initial Script
#
# -------------------------------------------------------------------------------
# ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠
# ~ ~ ~ Variables ~ ~ ~
# ~~ Mail Server Details ~~
$SmtpServer = "mailserver.yourdomain.local"
$FromAddress = "alerts@yourdomain.com"
$ToAddress = "HelpDesk@yourdomain.com"
$Subject = "[Exchange] Mailboxes over size limits"
#
#
# ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠ ♥ ♦ ♣ ♠
if ( (Get-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.E2010 -ErrorAction SilentlyContinue) -eq $null) {
Write-Verbose "Exchange 2010 snapin is not loaded. Loading it now."
try { Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010; Write-Verbose "Loaded Exchange 2010 snapin" }
catch { Write-Error "Could not load Exchange 2010 snapins!"; }
}
$overLimit = Get-Mailbox | Get-MailboxStatistics -WarningAction SilentlyContinue | Where {"ProhibitSend","MailboxDisabled" -contains $_.StorageLimitStatus}
if ($overLimit.Count -gt 0) {
$mailBody = $overLimit | ft DisplayName,TotalItemSize,StorageLimitStatus | Out-String
Send-MailMessage -Body $mailBody.ToString() -From $FromAddress -SmtpServer $SmtpServer -Subject $Subject -To $toAddress
} else {
"No results"
}
|
PowerShellCorpus/PoshCode/Connect-LabManager.ps1
|
Connect-LabManager.ps1
|
function Ignore-SslErrors {
# Create a compilation environment
$Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
$Compiler=$Provider.CreateCompiler()
$Params=New-Object System.CodeDom.Compiler.CompilerParameters
$Params.GenerateExecutable=$False
$Params.GenerateInMemory=$True
$Params.IncludeDebugInformation=$False
$Params.ReferencedAssemblies.Add("System.DLL") > $null
$TASource=@'
namespace Local.ToolkitExtensions.Net.CertificatePolicy {
public class TrustAll : System.Net.ICertificatePolicy {
public TrustAll() {
}
public bool CheckValidationResult(System.Net.ServicePoint sp,
System.Security.Cryptography.X509Certificates.X509Certificate cert,
System.Net.WebRequest req, int problem) {
return true;
}
}
}
'@
$TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
$TAAssembly=$TAResults.CompiledAssembly
## We now create an instance of the TrustAll and attach it to the ServicePointManager
$TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
[System.Net.ServicePointManager]::CertificatePolicy=$TrustAll
}
function New-ObjectFromProxy {
param($proxy, $proxyAttributeName, $typeName)
# Locate the assembly for $proxy
$attribute = $proxy | gm | where { $_.Name -eq $proxyAttributeName }
$str = "`$assembly = [" + $attribute.TypeName + "].assembly"
invoke-expression $str
# Instantiate an AuthenticationHeaderValue object.
$type = $assembly.getTypes() | where { $_.Name -eq $typeName }
return $assembly.CreateInstance($type)
}
function Connect-LabManager {
param($server, $credential)
# Log in to Lab Manager's web service.
$server = "https://" + $server + "/"
$endpoint = $server + "LabManager/SOAP/LabManager.asmx"
$proxy = new-webserviceproxy -uri $endpoint -cred $credential
# Before continuing we need to add an Authentication Header to $proxy.
$authHeader = New-ObjectFromProxy -proxy $proxy -proxyAttributeName "AuthenticationHeaderValue" -typeName "AuthenticationHeader"
$authHeader.username = $credential.GetNetworkCredential().UserName
$authHeader.password = $credential.GetNetworkCredential().Password
$proxy.AuthenticationHeaderValue = $authHeader
return $proxy
}
# Examples:
# Run this command if your Lab Manager's certificate is untrusted but you want to connect.
# Ignore-SslErrors
# Connect to Lab Manager.
# $labManager = Connect-LabManager -server "demo.eng.vmware.com" -credential (get-credential)
# Find out what operations there are.
# $labManager | gm | where { $_.MemberType -eq "Method" }
# See http://www.vmware.com/pdf/lm30_soap_api_guide.pdf for help on arguments.
# List all library configurations.
# $labManager.ListConfigurations(1)
# Find all machines deployed from any library configuration.
# $labManager.ListConfigurations(1) | foreach { write-host ("For Configuration " + $_.id + ":"); $labManager.ListMachines($_.id) }
|
PowerShellCorpus/PoshCode/Edit-File in Notepad++.ps1
|
Edit-File in Notepad++.ps1
|
<#
.Synopsis
Open a file for editing in notepad++
.Description
Opens one or more files in Notepad++, passing all the switches each time. Accepts filenames on the pipeline
.Notes
I took the "no" off the parameters, because in PowerShell you only need to enter just enough of the parameter name to differentiate ... this way each one is differentiatable by the first letter.
.Link
http://notepad-plus.sourceforge.net/uk/cmdLine-HOWTO.php
.Link
http://notepad-plus.sourceforge.net/
.Link
http://poshcode.org/notepad++lexer/
.Example
Edit-File $Profile -MultiInstance -SessionOff -TabBarOff -PluginsOff
Open your Profile in a new Notepad++ window in a "notepad" like mode: multi-session, no tab bars, no previous files, no plugins.
.Example
ls *.ps1 | Edit-File -SessionOff
Open all the ps1 scripts in Notepad++ without restoring previous files.
.Example
Edit-File -language xml ~\\Projects\\Project1\\Project1.csproj
Open the file Project1.csproj as a xml file, even though its extension is not recognized as xml...
.Parameter File
The absolute or relative path of file(s) you want to open, accepts wildcards
.Parameter MultiInstance
Notepad++ is unique instance by default. This option allows you to launch several instances of Notepad++.
.Parameter PluginsOff
Use this parameter to launch Notepad++ without loading the plugins. This parameter is useful when you want to determinate where the bad behaviour or crash come from (from the plugins or from Notepad++ itself).
.Parameter Language
This option applies the specified Language to the filesToOpen to open, allowing you to specify XML for csproj files, for example.
Valid Languages are : c, cpp, java, cs, objc, rc, html, javascript, php, vb, sql, xml, asp, perl, pascal, python, css, lua, batch, ini, nfo, tex, fortran, bash, actionscript and nsis.
.Parameter Number
Cause Notepad++ to go to the LineNumber you want after opening the file
.Parameter SessionOff
Launch Notepad++ without loading the previous session (the files opened in Notepad++ last time).
.Parameter ReadOnly
Open files in read only mode. (Alias: RO)
.Parameter TabBarOff
Turn off the tab interface. Useful if you want a minimalist session ...
#>
[CmdletBinding()]
Param(
[Parameter(ValueFromPipelineByPropertyName=$true,Position=1)]
[Alias("FullName","LiteralPath","Path")]
[string[]]
$File
,
[Parameter()]
[switch]$MultiInstance
,
[Parameter()]
[switch]$PluginsOff
,
[Parameter()]
[string]$Language
,
[Parameter(Position=2)]
[int]$Number
,
[Parameter()]
[switch]$SessionOff
,
[Parameter()]
[Alias("RO")]
[Switch]$ReadOnly
,
[Parameter()]
[Switch]$TabBarOff
)
BEGIN {
$npp = "C:\\Programs\\DevTools\\Notepad++\\notepad++.exe"
$param = @(
if($MultiInstance) { "-multiInst" }
if($PluginsOff) { "-noPlugin" }
if($Language) { "-l$Language" }
if($Number) { "-n$Number" }
if($SessionOff) { "-nosession" }
if($ReadOnly) { "-ro" }
if($TabBarOff) { "-notabbar" }
" "
) -join " "
}
PROCESS {
foreach($path in $File) {
foreach($f in Convert-Path (Resolve-Path $path)) {
$parameters = $param + """" + + """"
write-verbose "$npp $parameters"
[Diagnostics.Process]::Start($npp,$parameters).WaitForInputIdle(500)
}
}
}
|
PowerShellCorpus/PoshCode/LoadModuleConfig_2.ps1
|
LoadModuleConfig_2.ps1
|
################################################################################
## Script Name: LoadModuleConfig
## Created On: 01/21/2010
## Author: Thell Fowler
## File: LoadModuleConfig.ps1
## Usage: Called from the NestedModules value from a module manifest.
## Version: 1.0.1.0
## Purpose: Provides automated loading of local configuration data.
##
## Requirements: PowerShell Version 2
## Last Updated: 01/23/2010
## History:
## 1.0.1.0 01/21/2010 - TBF - Made Add-Member calls forceful.
## 1.0.0.0 01/21/2010 - TBF - Initial implementation.
##
##
################################################################################
<#
To make use of this script use new-modulemanifest to create a manifest named
the with the same name as the manifest you are loading data for but with an
extension of 'config.psd1'
Enter LoadModuleConfig.ps1 in the NestedModules field.
After creating the manifest open it in your editor and edit the PrivateData
field to include hashes for LocalUser and Settings. After the Settings key
add values as you see fit.
Here is an example, as used in the FuncGuard module.
# Private data to pass to the module specified in ModuleToProcess
PrivateData = @{
"LocalUser" = @{
"Settings"=@{
"ActiveConfiguration" = "PSUnit"
"Configurations"=@{
"PSUnit" =@{
"Name"="PSUnit";
"Path"=$(join-path -Path $Env:Temp -ChildPath "FuncGuard.PSUnit");
"Prefix"="PSUNIT"
}
}
}
}
}
After loading the module a global variable will be available with a name
convention of $($ModuleName)Settings and the values can be accessed using
normal hash retrieval.
$config = $FuncGuardSettings["Configurations"].$($FuncGuardSettings["ActiveConfiguration"])
$Path = $config.Path
#>
#requires -version 2.0
Set-StrictMode -Version 2
$Module = $ExecutionContext.SessionState.Module
if (! $Module) {
throw ( New-Object System.Management.Automation.SessionStateException `
"An active module was not found! LoadModuleConfig must be run from a module manifest's NestedModules field.")
}
$ModuleName = $Module.Name.Replace(".config",$null)
$AppData = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::LocalApplicationData)
$ModuleConfigPath = join-path -Path $AppData `
-ChildPath "WindowsPowerShell\\Modules\\$ModuleName\\$ModuleName.config.xml"
$configurations = $null
if ( Test-Path $ModuleConfigPath -PathType Leaf ) {
$configurations = Import-Clixml -Path $ModuleConfigPath
} else {
# Generate new default config file.
$configurations = $Module.PrivateData.LocalUser.Settings
$configurations.add("InitializeConfigurations", $true)
Export-Clixml -InputObject $configurations -Path $ModuleConfigPath
}
if ($configurations) {
Add-Member -InputObject $configurations -Name ModuleName -MemberType NoteProperty -force `
-Value $ModuleName
Add-Member -InputObject $configurations -Name Export -MemberType ScriptMethod -force `
-Value {
$AppData = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::LocalApplicationData)
$ModuleConfigPath = join-path -Path $AppData `
-ChildPath "WindowsPowerShell\\Modules\\$ModuleName\\$($this.ModuleName).config.xml"
Export-Clixml -InputObject $this -Path $ModuleConfigPath
}
Set-Variable -Name "$($ModuleName)Settings" -Value $($configurations) -Scope Global `
-Description "$($ModuleName) module configuration settings."
}
|
PowerShellCorpus/PoshCode/Move-Template_1.ps1
|
Move-Template_1.ps1
|
Function Move-Template{
<#
.Synopsis
Move a VM template
.Description
Move a VM template either to a new host via vmotion or to a new datastore via svmotion
.Parameter Name
Name of the VM to be migrated
.Parameter VIObject
Template to be migrated
.Parameter VMHost
VMHost to vmotion the template to
.Parameter Datastore
Datastore to svmotion template to
.Example
Move-Template -Name W2k8R201 -VMHost (Get-VMHost ESX1)
VMotion W2k8R201 template to the ESX1 host.
.Example
Move-Template -Name W2k8R201 -Datastore (Get-Datastore NFS2)
sVMotion W2k8R201 template to the NFS2 Datastore.
.Example
Get-Template | Move-Template -Datastore (Get-Datastore NFS2)
sVMotion all templates onto the NFS2 Datastore
.Example
Get-Template CentOS_5_2_x64 | Move-Template -Datastore (Get-Datastore NFS2) -VMHost (Get-VMHost ESX03)
sVMotion the CentOS_5_2_x64 templates onto the NFS2 Datastore, and then vmotion said template onto ESX03
.link
Get-Template
New-Template
Remove-Template
Set-Template
#>
[CmdletBinding(SupportsShouldProcess=$true,SupportsTransactions=$False,ConfirmImpact="low",DefaultParameterSetName="")]
param(
[Parameter(Mandatory=$true,Position=0,HelpMessage="Name of template to move", ParameterSetName="ByName")]
[STRING]
$Name,
[Parameter(Mandatory=$true,ValueFromPipeline=$true, HelpMessage="Managed object of the template to be migrated", ParameterSetName="ByObject")]
[VMware.VimAutomation.Client20.TemplateImpl[]]
$Template,
[Parameter(Mandatory=$false,ValueFromPipeline=$true, HelpMessage="VMHost to vmotion the template to", ParameterSetName="ByObject")]
[Parameter(Mandatory=$false,ValueFromPipeline=$true, HelpMessage="VMHost to vmotion the template to", ParameterSetName="ByName")]
[VMware.VimAutomation.Client20.VMHostImpl]
$VMHost,
[Parameter(Mandatory=$false,ValueFromPipeline=$true, HelpMessage="Datastore to svmotion the template to", ParameterSetName="ByObject")]
[Parameter(Mandatory=$false,ValueFromPipeline=$true, HelpMessage="Datastore to svmotion the template to", ParameterSetName="ByName")]
[VMware.VimAutomation.Client20.DatastoreImpl]
$Datastore
)
Process{
switch ($pscmdlet.parametersetname) {
"ByName"
{
if ($pscmdlet.ShouldProcess($Name,"vmotion Template to $($VMHost.name) and svmotion to $($Datastore.name)")){
$template = Get-Template -Name $Name -verbose:$False
$vm = Set-Template -Template $template -ToVM -verbose:$False -confirm:$False
switch ($VM) {
{$Datastore} {Move-VM -VM $VM -Datastore $Datastore -verbose:$False -Confirm:$false}
{$VMHost} {Move-VM -VM $VM -Destination $VMHost -verbose:$False -Confirm:$false}
}
(Get-View -VIObject $VM -verbose:$False).MarkAsTemplate()
}
}
"ByObject"
{
Foreach ($tmp in $Template) {
if ($pscmdlet.ShouldProcess($tmp.Name,"vmotion Template to $($VMHost.name) and svmotion to $($Datastore.name)")){
$vm = Set-Template -Template $tmp -ToVM -verbose:$False -confirm:$False
switch ($VM) {
{$Datastore} {Move-VM -VM $VM -Datastore $Datastore -verbose:$False -Confirm:$false}
{$VMHost} {Move-VM -VM $VM -Destination $VMHost -verbose:$False -Confirm:$false}
}
(Get-View -VIObject $VM -verbose:$False).MarkAsTemplate()
}
}
}
}
}
}
|
PowerShellCorpus/PoshCode/Test-TCPPort.ps1
|
Test-TCPPort.ps1
|
# http://powershell.codeplex.com
Function Test-TCPPort
{
param ( [ValidateNotNullOrEmpty()]
[string] $EndPoint = $(throw "Please specify an EndPoint (Host or IP Address)"),
[string] $Port = $(throw "Please specify a Port") )
$TimeOut = 1000
$IP = [System.Net.Dns]::GetHostAddresses($EndPoint)
$Address = [System.Net.IPAddress]::Parse($IP)
$Socket = New-Object System.Net.Sockets.TCPClient
$Connect = $Socket.BeginConnect($Address,$Port,$null,$null)
if ( $Connect.IsCompleted )
{
$Wait = $Connect.AsyncWaitHandle.WaitOne($TimeOut,$false)
if(!$Wait)
{
$Socket.Close()
return $false
}
else
{
$Socket.EndConnect($Connect)
$Socket.Close()
return $true
}
}
else
{
return $false
}
}
|
PowerShellCorpus/PoshCode/Get-DiskUsage_2.ps1
|
Get-DiskUsage_2.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}
#{$_ -eq $null}{"0B"}
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
}
}
}
|
PowerShellCorpus/PoshCode/Run-Query (SharePoint).ps1
|
Run-Query (SharePoint).ps1
|
function Run-Query($siteUrl, $queryText)
{
[reflection.assembly]::loadwithpartialname("microsoft.sharePOint") | out-null
[reflection.assembly]::loadwithpartialname("microsoft.office.server") | out-null
[reflection.assembly]::loadwithpartialname("microsoft.office.server.search") | out-null
$s = [microsoft.sharepoint.spsite]$siteUrl
$q = new-object microsoft.office.server.search.query.fulltextsqlquery -arg $s
$q.querytext = $queryText
$q.RowLimit = 100
$q.ResultTypes = "RelevantResults"
$dt = $q.Execute()
$r = $dt["RelevantResults"]
$output = @()
while ($r.Read()) {
$o = new-object PSObject
0..($r.FieldCount-1) | foreach {
add-member -inputObject $o -memberType "NoteProperty" -name $r.GetName($_) -value $r[$_].ToString()
}
$output += $o
}
return $output
}
#Sample usage:
#Run-Query -siteUrl "http://dev/" -queryText "SELECT PreferredName, WorkPhone FROM S"
|
PowerShellCorpus/PoshCode/Script-Object_3.ps1
|
Script-Object_3.ps1
|
#Copyright (c) 2011 Justin Dearing
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in
#all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#THE SOFTWARE.
# The authoritative version is https://github.com/justaprogrammer/PowerShellScripts/blob/master/Script-Object.ps1.
# If you have a change I'd love to know about it to consider merging it into github.
param(
[Parameter(Mandatory=$true, HelpMessage='The name of the database object we wish to script')]
[string] $ObjectName,
[string] $Path = "$($ObjectName).sql",
[string] $ConnectionString = 'Data Source=.\\sqlexpress2k8R2;Initial Catalog=master;Integrated Security=SSPI;',
[string] $AtlantisSchemaEngineBaseDir = 'F:\\src\\Atlantis.SchemaEngine\\' # Adjust for your environment
);
Add-Type -Path "$($AtlantisSchemaEngineBaseDir)\\Atlantis.SchemaEngine\\bin\\Debug\\Atlantis.SchemaEngine.dll"
$schemaReader = [Atlantis.SchemaEngine.Container.SQLServer.SQLServerSchemaReaderFactory]::GetSpecificSQLServerSchemaReader($ConnectionString, [Atlantis.SchemaEngine.Enumerations.ContainerMode]::Navigation)
$dbObjects = $schemaReader.ReadObjects() | Where-Object { $_.ObjectName,$_.ObjectDesriptiveName,$_.ObjectQualifiedName -contains $ObjectName };
if ($dbObjects -eq $null) {
Throw New-Object System.ArgumentException "Object `"$($ObjectName)`" not found.",'-ObjectName';
}
$dbObjects.Script([Atlantis.SchemaEngine.Enumerations.ScriptGenerationType]::Create, (New-Object Atlantis.SchemaEngine.Configuration.GenerationOptions)).Scripts
|
PowerShellCorpus/PoshCode/Get-InstalledProgram_v_3.ps1
|
Get-InstalledProgram_v_3.ps1
|
function Get-InstalledProgram() {
param (
[String[]]$Computer,
$User
)
#############################################################################################
if ($User) {$Connection = Get-Credential -Credential $User}
#############################################################################################
if (!$Connection){
foreach ($Comp in $Computer){
$Install_soft = gwmi win32_product -ComputerName $Comp | where {$_.vendor -notlike "*Microsoft*" -and $_.vendor -notlike "*PGP*" -and $_.vendor -notlike "*Intel*" -and $_.vendor -notlike "*Corel*" -and $_.vendor -notlike "*Adobe*" -and $_.vendor -notlike "*ABBYY*" -and $_.vendor -notlike "*Sun*" -and $_.vendor -ne "SAP" -and $_.vendor -ne "Marvell" -and $_.vendor -ne "Hewlett-Packard"} | Format-List __SERVER,Name,Version,InstallDate
$Install_soft
}
}
else {
foreach ($Comp in $Computer){
$Install_soft = gwmi win32_product -ComputerName $Comp -Credential $Connection | where {$_.vendor -notlike "*Microsoft*" -and $_.vendor -notlike "*PGP*" -and $_.vendor -notlike "*Intel*" -and $_.vendor -notlike "*Corel*" -and $_.vendor -notlike "*Adobe*" -and $_.vendor -notlike "*ABBYY*" -and $_.vendor -notlike "*Sun*" -and $_.vendor -ne "SAP" -and $_.vendor -ne "Marvell" -and $_.vendor -ne "Hewlett-Packard"} | Format-List __SERVER,Name,Version,InstallDate
$Install_soft
}
}
}
|
PowerShellCorpus/PoshCode/Set Active Sync DevideID.ps1
|
Set Active Sync DevideID.ps1
|
# Requires a connection to Exchange Server, or Exchange Management Shell
$s = New-PSSession -ConfigurationName Microsoft.Exchange -Name ExchMgmt -ConnectionUri http://ex14.domain.local/PowerShell/ -Authentication Kerberos
Import-PSSession $s
# Get all Client Access Server properties for all mailboxes with an ActiveSync Device Partnership
$Mailboxes = Get-CASMailbox -Filter {HasActivesyncDevicePartnership -eq $true} -ResultSize Unlimited
# Get DeviceID for all mailboxes
$EASMailboxes = $Mailboxes | Select-Object PrimarySmtpAddress,@{N='DeviceID';E={Get-ActiveSyncDeviceStatistics -Mailbox $_.Identity | Select-Object –ExpandProperty DeviceID}}
# Set the ActiveSyncAllowedDeviceIDs attribute of all Mailboxes
$EASMailboxes | foreach {Set-CASMailbox $_.PrimarySmtpAddress -ActiveSyncAllowedDeviceIDs $_.DeviceID}
|
PowerShellCorpus/PoshCode/Ping Alert Script_1.ps1
|
Ping Alert Script_1.ps1
|
#Email Alert Parameters
$to = "user@mydomain.com"
$from = "unreachable@mydomain.com"
$smtpserver = "my_exchange_server"
#Array of computers to test
$Computers = ("comp1" , "comp2" , "comp3" , "comp4")
#Variable to hold INT value 0
$zero = 0
Foreach ($Computer in $Computers)
{
if
(
#Checks for a file with the host computers name in the Reports folder and if it doesn't exist creates it with content 0
Test-Path $("C:\\Reports\\" + $Computer + ".txt")
)
{
}
else
{
$zero > $("C:\\Reports\\" + $Computer + ".txt")
}
#Reads the content of the file and saves to variable as text
$FailedPings = Get-Content $("C:\\Reports\\" + $Computer + ".txt")
#Converts the value to INT
$INT_FailedPings = [INT]$FailedPings
#Actually runs the ping test
$PingTest = Test-Connection -ComputerName $Computer -count 1
if
(
#If ping is unsuccessful
$PingTest.StatusCode -ne "0"
)
{
if
(
#If previous failed pings value is less or equal to 3
$INT_FailedPings -le 3
)
{
#Increment the value by 1
$INT_FailedPings++
#Write the value out to the reports folder file for this host
$INT_FailedPings > $("C:\\Reports\\" + $Computer + ".txt")
#Send an alert of failed ping
Send-MailMessage -to $to -subject "Warning, Host $Computer is down. You will only receive 4 of these messages!" -from $from -body "Ping to $Computer failed, you will only receive 3 of these messages!" -smtpserver $smtpserver
}
}
elseif
(
#If previous checks have failed the value will be non zero, as checks are now working sets the value back to zero and alerts that host is back up
$INT_FailedPings -ne 0
)
{
$zero > $("C:\\Reports\\" + $Computer + ".txt")
Send-MailMessage -to $to -subject "Host $Computer is back up" -from $from -body "Panic over" -smtpserver $smtpserver
}
else
#If ping is successful and past pings were successful do nothing
{
}
}
|
PowerShellCorpus/PoshCode/Show-Fonts.ps1
|
Show-Fonts.ps1
|
ipmo PowerBoots # Require PowerBoots
## More readable:
New-BootsWindow {
ScrollViewer {
StackPanel {
ForEach($font in (New-Object Drawing.Text.InstalledFontCollection).Families | Select -Expand Name) {
TextBlock "$font -- The brown fox (quickly) jumps over the ""lazy"" dog, 123456789" -FontFamily $font -FontSize 16 -Tooltip $font
}
}
}
} -Width 800 -Height 900
return
## One-liner:
New-BootsWindow { (New-Object Drawing.Text.InstalledFontCollection).Families | %{ Label "$($_.Name) -- The brown fox (quickly) jumps over the ""lazy"" dog, 123456789" -FontFamily $_.Name -FontSize 16 -Tooltip $_.Name } | StackPanel | ScrollViewer } -Width 800 -Height 900
|
PowerShellCorpus/PoshCode/New-Zip_4.ps1
|
New-Zip_4.ps1
|
Function New-Zip
{
<#
.SYNOPSIS
Create a Zip File from any files piped in.
.DESCRIPTION
Requires that you have the SharpZipLib installed, which is available from
http://www.icsharpcode.net/OpenSource/SharpZipLib/
.NOTES
File Name : PowerZip.psm1
Author : Christophe CREMON (uxone) - http://powershell.codeplex.com
Requires : PowerShell V2
.PARAMETER Source
Set the name of the source to zip (file or directory)
.PARAMETER ZipFile
Set the name of the zip file to create
.PARAMETER Recurse
Browse the source recursively
.PARAMETER Include
Include only items you specify
.PARAMETER Exclude
Exclude items you specify
.PARAMETER AbsolutePaths
Preserve the absolute path name of each item in the zip container
.PARAMETER DeleteAfterZip
Delete source items after successful zip
.EXAMPLE
New-Zip -Source C:\\Temp -ZipFile C:\\Archive\\Scripts.zip -Include *.ps1 -DeleteAfterZip
Copies all PS1 files from the C:\\Temp directory to C:\\Archive\\Scripts.zip and delete them after successful ZIP
#>
param (
[ValidateNotNullOrEmpty()]
[Parameter(
Mandatory = $true)
]
[string] $Source,
[Parameter(
Mandatory = $true)
]
[string] $ZipFile,
[switch] $Recurse,
[array] $Include,
[array] $Exclude,
[switch] $AbsolutePaths,
[switch] $DeleteAfterZip )
$LoadAssembly = [System.Reflection.Assembly]::LoadWithPartialName("ICSharpCode.SharpZipLib")
if ( -not $LoadAssembly ) { throw "! Assembly not found {ICSharpCode.SharpZipLib}" }
if ( $Source -match "\\*" )
{
throw "! Please use -Recurse with -Include instead of ""*"""
}
$Source = $Source -replace "\\\\$|\\/$",""
$CheckSource = Get-Item -Path $Source -ErrorAction SilentlyContinue
if ( -not $CheckSource ) { throw "! Source not found {$Source}" }
else
{
if ( $CheckSource.psIsContainer )
{
$RootPath = ( Resolve-Path -Path $Source -ErrorAction SilentlyContinue ).Path
}
else
{
$RootPath = ( Resolve-Path -Path $Source -ErrorAction SilentlyContinue ).Path
if ( $RootPath )
{
$RootPath = Split-Path -Path $RootPath -ErrorAction SilentlyContinue
}
}
}
if ( $ZipFile -notmatch "\\.zip$" ) { $ZipFile = $ZipFile -replace "$",".zip" }
if ( $ZipFile -match "\\*" )
{
throw "! Incorrect zip file name {$ZipFile}"
}
if ( $Recurse -eq $true ) { $RecurseArgument = "-Recurse" }
if ( $AbsolutePaths -eq $true ) { $AbsolutePathsArgument = "-AbsolutePaths" }
if ( $DeleteAfterZip -eq $true ) { $DeleteAfterZipArgument = "-DeleteAfterZip" }
if ( $Include )
{
$Include = $Include -join ","
$IncludeArgument = "-Include $Include"
$Source = $Source+"\\*"
}
if ( $Exclude )
{
$Exclude = $Exclude -join ","
$ExcludeArgument = "-Exclude $Exclude"
}
$GetCommand = "Get-ChildItem -Path '$Source' $RecurseArgument $IncludeArgument $ExcludeArgument -Force"
$ItemsToZip = Invoke-Expression -Command $GetCommand
$SizeBeforeZip = ( $ItemsToZip | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue ).Sum
$SizeBeforeZipInMB = $SizeBeforeZip | ForEach-Object { "{0:N2}" -f ($_ / 1MB) }
if ( -not $SizeBeforeZip )
{
Write-Output "NOTHING TO ZIP"
return $true
break
}
$CreateZIPContainer = New-Item -ItemType File -Path $ZipFile -Force -ErrorAction SilentlyContinue
if ( -not $CreateZIPContainer ) { throw "! Unable to create ZIP container {$ZipFile}" }
else { $ZipFile = ( Resolve-Path -Path $ZipFile -ErrorAction SilentlyContinue ).Path }
$oZipOutputStream = New-Object -TypeName ICSharpCode.SharpZipLib.Zip.ZipOutputStream([System.IO.File]::Create($ZipFile))
[byte[]] $Buffer = New-Object Byte[] 4096
$StartTime = Get-Date
Write-Output "`n===================================`n=> Start Time : $($StartTime.ToString(""dd/MM/yyyy-HH:mm:ss""))`n"
Write-Output "TOTAL SIZE BEFORE ZIP : {$SizeBeforeZipInMB MB}`n"
foreach ( $Item in $ItemsToZip )
{
if ( $Item.FullName -ne $ZipFile )
{
if ( Test-Path ( $Item.FullName ) -ErrorAction SilentlyContinue )
{
$ZipEntry = $Item.FullName
if ( -not $AbsolutePaths )
{
$ReplacePath = [Regex]::Escape( $RootPath+"\\" )
$ZipEntry = $Item.FullName -replace $ReplacePath,""
}
if ( $Item.psIsContainer -eq $true )
{
if ( $Recurse -eq $true )
{
Write-Output "Processing ZIP of Directory {$($Item.FullName)} ..."
$OldErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
$oZipEntry = New-Object -TypeName ICSharpCode.SharpZipLib.Zip.ZipEntry("$ZipEntry/")
$oZipOutputStream.PutNextEntry($oZipEntry)
if ( $? -ne $true )
{
$ItemsNotZipped += @($Item.FullName)
$ErrorsArray += @("! Unable to ZIP Directory {$($Item.FullName)}")
}
$ErrorActionPreference = $OldErrorActionPreference
}
}
else
{
Write-Output "Processing ZIP of File {$($Item.FullName)} ..."
$OldErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
$FileStream = [IO.File]::OpenRead($Item.FullName)
$oZipEntry = New-Object -TypeName ICSharpCode.SharpZipLib.Zip.ZipEntry("$ZipEntry")
$oZipOutputStream.PutNextEntry($oZipEntry)
[ICSharpCode.SharpZipLib.Core.StreamUtils]::Copy($FileStream,$oZipOutputStream,$Buffer)
if ( $? -ne $true )
{
$ItemsNotZipped += @($Item.FullName)
$ErrorsArray += @("! Unable to ZIP File {$($Item.FullName)}")
}
$FileStream.Close()
}
}
}
}
$oZipOutputStream.Finish()
$oZipOutputStream.Close()
if ( $? -eq $true )
{
$ErrorActionPreference = $OldErrorActionPreference
if ( $DeleteAfterZip )
{
$ItemsToZip | Where-Object { $ItemsNotZipped -notcontains $_.FullName } | ForEach-Object {
if ( $_.psIsContainer -ne $true )
{
if ( Test-Path ( $_.FullName ) -ErrorAction SilentlyContinue )
{
Write-Output "Processing Delete of File {$($_.FullName)} ..."
$RemoveItem = Remove-Item -Path $_.FullName -Force -ErrorAction SilentlyContinue
if ( $? -ne $true )
{
$ErrorsArray += @("! Unable to Delete File {$($_.FullName)}")
}
}
}
}
if ( $Recurse )
{
$ItemsToZip | Where-Object { $ItemsNotZipped -notcontains ( Split-Path -Parent $_.FullName ) } | ForEach-Object {
if ( $_.psIsContainer -eq $true )
{
if ( Test-Path ( $_.FullName ) -ErrorAction SilentlyContinue )
{
Write-Output "Processing Delete of Directory {$($_.FullName)} ..."
$RemoveItem = Remove-Item -Path $_.FullName -Force -Recurse -ErrorAction SilentlyContinue
if ( $? -ne $true )
{
$ErrorsArray += @("! Unable to Delete Directory {$($_.FullName)}")
}
}
}
}
}
}
Write-Output "`nZIP File Created {$ZipFile} ...`n"
}
else
{
$ErrorActionPreference = $OldErrorActionPreference
$ErrorsArray += @("! ZIP Archive {$ZipFile} Creation Failed`n")
}
$EndTime = Get-Date
$ExecutionTime = ($EndTime-$StartTime)
Write-Output "`nExecution Time : $ExecutionTime`n"
Write-Output "=> End Time : $($EndTime.ToString(""dd/MM/yyyy-HH:mm:ss""))`n=================================`n"
if ( $ErrorsArray )
{
Write-Output "`n[ ERRORS OCCURED ]"
$ErrorsArray
return $false
}
else
{
$SizeAfterZip = ( Get-Item -Path $ZipFile -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue ).Sum
$SizeAfterZipInMB = $SizeAfterZip | ForEach-Object { "{0:N2}" -f ($_ / 1MB) }
Write-Output "`nTOTAL SIZE AFTER ZIP : {$SizeAfterZipInMB MB}`n"
$Gain = ( $SizeBeforeZip - $SizeAfterZip )
$GainInMB = $Gain | ForEach-Object { "{0:N2}" -f ($_ / 1MB) }
if ( $Gain -gt 0 )
{
$GainInPercent = (($SizeBeforeZip - $SizeAfterZip) / $SizeBeforeZip) * 100 | ForEach-Object { "{0:N2}" -f $_ }
Write-Output "GAIN : {$GainInMB MB} ($GainInPercent %)`n"
}
return $true
}
}
Export-ModuleMember -Function New-Zip
|
PowerShellCorpus/PoshCode/Wizard template.ps1
|
Wizard template.ps1
|
#######################################################################################################################
# File: wizard_template.ps1 #
# Author: Alexander Petrovskiy #
# Publisher: Alexander Petrovskiy, PowerShellDevTools.WordPress.Com #
# Copyright: © 2010-2011 Alexander Petrovskiy, PowerShellDevTools.WordPress.Com. All rights reserved. #
# Usage: To run this example no preparations needed. #
# There also are the following settings you may be intersted in: #
# 1. the wizard caption #
# 2. default size of the wizard #
# 3. default size of the wizard's buttons #
# 4. button labels #
# 5. right-to-left layout #
# All the settings mentioned are placed inside the 'adjustable settings' region #
# Please provide feedback in the PowerShellDevTools.WordPress.Com blog. #
#######################################################################################################################
cls
Set-StrictMode -Version 2
#region host preparations
if ($Host.Name -eq 'ConsoleHost')
{
Add-Type -AssemblyName System.Windows.Forms;
Add-Type -AssemblyName System.Drawing;
}
#endregion host preparations
#region the resulting wizard
#region adjustable settings
#region controls settings
# Form size and caption
[string]$script:constWizardInitialCaption = `
'This is a sample wizard';
[int]$script:constWizardWidth = `
[System.Windows.Forms.SystemInformation]::VirtualScreen.Width / 2;
[int]$script:constWizardHeight = `
[System.Windows.Forms.SystemInformation]::VirtualScreen.Height / 2;
# Buttons Next, Back, Cancel, Finish
[int]$script:constButtonHeight = 23;
[int]$script:constButtonWidth = 75;
[int]$script:constButtonAreaHeight = `
$script:constButtonHeight * 2;
[string]$script:constButtonNextName = '&Next';
[string]$script:constButtonBackName = '&Back';
[string]$script:constButtonFinishName = '&Finish';
[string]$script:constButtonCancelName = '&Cancel';
# Step display name and description
[int]$script:constLabelStepDisplayNameLeft = 5;
[int]$script:constLabelStepDisplayNameTop = 0;
[float]$script:constLabelStepDisplayNameFontSize = 16;
[int]$script:constLabelStepDescriptionLeft = 5;
[int]$script:constLabelStepDescriptionTop = 30;
# Form properties
[bool]$script:constWizardRigthToLeft = $false;
# Initial step number
[int]$script:currentStep = 0;
#endregion controls settings
#endregion adjustable settings
#region mandatory settings
#region Initialization of the SplitContainer controls
# The outer split container
[System.Windows.Forms.SplitContainer]$script:splitOuter = `
New-Object System.Windows.Forms.SplitContainer;
$script:splitOuter.Dock = [System.Windows.Forms.DockStyle]::Fill;
$script:splitOuter.IsSplitterFixed = $true;
$script:splitOuter.Orientation = `
[System.Windows.Forms.Orientation]::Horizontal;
$script:splitOuter.SplitterWidth = 5;
# The inner split container
[System.Windows.Forms.SplitContainer]$script:splitInner = `
New-Object System.Windows.Forms.SplitContainer;
$script:splitInner.Dock = [System.Windows.Forms.DockStyle]::Fill;
$script:splitInner.IsSplitterFixed = $true;
$script:splitInner.Orientation = `
[System.Windows.Forms.Orientation]::Horizontal;
$script:splitInner.SplitterWidth = 5;
$script:splitOuter.Panel1.Controls.Add($script:splitInner);
# The labels for the curent step name and description
[System.Windows.Forms.Label]$script:lblStepDisplayName = `
New-Object System.Windows.Forms.Label;
$script:lblStepDisplayName.Left = `
$script:constLabelStepDisplayNameLeft;
$script:lblStepDisplayName.Top = `
$script:constLabelStepDisplayNameTop;
[System.Drawing.Font]$private:font = `
$script:lblStepDisplayName.Font;
$private:font = `
New-Object System.Drawing.Font($private:font.Name, `
$script:constLabelStepDisplayNameFontsize, `
$private:font.Style, $private:font.Unit, `
$private:font.GdiCharSet, $private:font.GdiVerticalFont );
$script:lblStepDisplayName.Font = $private:font;
[System.Windows.Forms.Label]$script:lblStepDescription = `
New-Object System.Windows.Forms.Label;
$script:lblStepDescription.Left = `
$script:constLabelStepDescriptionLeft;
$script:lblStepDescription.Top = `
$script:constLabelStepDescriptionTop;
$script:splitInner.Panel1.Controls.AddRange(($script:lblStepDisplayName, `
$script:lblStepDescription));
#endregion Initialization of the SplitContainer controls
#region buttons functions
function Enable-FinishButton
{
$script:btnNext.Enabled = $false;
$script:btnNext.Visible = $false;
$script:btnFinish.Enabled = $true;
$script:btnFinish.Visible = $true;
}
function Enable-NextButton
{
$script:btnNext.Enabled = $true;
$script:btnNext.Visible = $true;
$script:btnFinish.Enabled = $false;
$script:btnFinish.Visible = $false;
}
function Enable-BackButton
{
$script:btnBack.Enabled = $true;
$script:btnBack.Visible = $true;
$script:btnCancel.Enabled = $false;
$script:btnCancel.Visible = $false;
}
function Enable-CancelButton
{
$script:btnBack.Enabled = $false;
$script:btnBack.Visible = $false;
$script:btnCancel.Enabled = $true;
$script:btnCancel.Visible = $true;
}
#endregion buttons functions
#region the Next and Back buttons
[System.Windows.Forms.Button]$script:btnNext = `
New-Object System.Windows.Forms.Button;
$script:btnNext.Anchor = [System.Windows.Forms.AnchorStyles]::Bottom -bor `
[System.Windows.Forms.AnchorStyles]::Right -bor `
[System.Windows.Forms.AnchorStyles]::Top;
$script:btnNext.Text = $script:constButtonNextName;
[System.Windows.Forms.Button]$script:btnBack = `
New-Object System.Windows.Forms.Button;
$script:btnBack.Anchor = [System.Windows.Forms.AnchorStyles]::Bottom -bor `
[System.Windows.Forms.AnchorStyles]::Right -bor `
[System.Windows.Forms.AnchorStyles]::Top;
$script:btnBack.Text = $script:constButtonBackName;
$script:splitOuter.Panel2.Controls.AddRange(($script:btnBack, $script:btnNext));
#endregion the Next and Back buttons
#region the Finish and the Cancel buttons
[System.Windows.Forms.Button]$script:btnFinish = `
New-Object System.Windows.Forms.Button;
$script:btnFinish.Anchor = [System.Windows.Forms.AnchorStyles]::Bottom -bor `
[System.Windows.Forms.AnchorStyles]::Right -bor `
[System.Windows.Forms.AnchorStyles]::Top;
$script:btnFinish.Text = $script:constButtonFinishName;
[System.Windows.Forms.Button]$script:btnCancel = `
New-Object System.Windows.Forms.Button;
$script:btnCancel.Anchor = [System.Windows.Forms.AnchorStyles]::Bottom -bor `
[System.Windows.Forms.AnchorStyles]::Right -bor `
[System.Windows.Forms.AnchorStyles]::Top;
$script:btnCancel.Text = $script:constButtonCancelName;
Enable-CancelButton;
Enable-NextButton;
$script:splitOuter.Panel2.Controls.AddRange(($script:btnCancel, $script:btnFinish));
#endregion the Finish and the Cancel buttons
#region Initialization of the main form
$script:frmWizard = $null;
[System.Windows.Forms.Form]$script:frmWizard = `
New-Object System.Windows.Forms.Form;
$script:frmWizard.Controls.Add($script:splitOuter);
# left-to-right and right-to-left
if ($script:constWizardRigthToLeft)
{
$script:frmWizard.RightToLeft = `
[System.Windows.Forms.RightToLeft]::Yes;
$script:frmWizard.RightToLeftLayout = $true;
}
else
{
$script:frmWizard.RightToLeft = `
[System.Windows.Forms.RightToLeft]::No;
$script:frmWizard.RightToLeftLayout = $false;
}
$script:frmWizard.Text = $script:constWizardInitialCaption;
#endregion Initialization of the main form
#endregion mandatory settings
#region the Wizard steps
[System.Collections.ArrayList]$script:wzdSteps = `
New-Object System.Collections.ArrayList;
# Here we create an 'enumeration' (PSObject)
# and begin filling ArrayList $script:wzdSteps with Panel controls
[System.EventHandler]$script:hndlRunControlsAdd = `
{try{$script:splitInner.Panel2.Controls.Add($script:wzdSteps[$script:currentStep]);}
catch{Write-Debug $Error[0]; Write-Debug $global:Error[0];}};
#region function New-WizardStep
function New-WizardStep
{
param(
[string]$StepName,
[string]$StepDisplayName,
[string]$StepDescription = ''
)
# Storing parameters in step arrays
Add-Member -InputObject $script:steps -MemberType NoteProperty `
-Name $StepName -Value $script:wzdSteps.Count;
$null = $script:stepDisplayNames.Add($StepDisplayName);
$null = $script:stepDescriptions.Add($StepDescription);
# Adding a fake scriptblock to keep counters
$null = $script:stepscriptblocks.Add({});
# Create and add the new step's panel to the array
[System.Windows.Forms.Panel]$private:panel = `
New-Object System.Windows.Forms.Panel;
$null = $script:wzdSteps.Add($private:panel);
$script:currentStep = $script:wzdSteps.Count - 1;
$script:splitInner.Panel2.Controls.Add($script:wzdSteps[$script:currentStep]);
$script:wzdSteps[$script:currentStep].Dock = `
[System.Windows.Forms.DockStyle]::Fill;
# To restore initial state for this code running before the user accesses the wizard.
$script:currentStep = 0;
}
#endregion function New-WizardStep
#region function Add-ControlToStep
function Add-ControlToStep
# Adds a control of selected type to a wizard step
{
param(
[Parameter(Mandatory=$true)]
[string]$StepNumber,
[Parameter(Mandatory=$true)]
[string]$ControlType,
[Parameter(Mandatory=$true)]
[string]$ControlName,
[int]$ControlTop,
[int]$ControlLeft,
[int]$ControlHeight,
[int]$ControlWidth,
[string]$ControlData
)
$private:ctrl = $null;
try{
$private:ctrl = New-Object $ControlType;
}catch{Write-Error "Unable to create a control of $($ControlType) type";}
try{
$private:ctrl.Name = $ControlName;
}catch{Write-Error "Unable to set the Name property with value $($ControlName) to a control of the $($ControlType) type";}
try{
$private:ctrl.Top = $ControlTop;
}catch{Write-Error "Unable to set the Top property with value $($ControlTop) to a control of the $($ControlType) type";}
try{
$private:ctrl.Left = $ControlLeft;
}catch{Write-Error "Unable to set the Left property with value $($ControlLeft) to a control of the $($ControlType) type";}
try{
$private:ctrl.Height = $ControlHeight;
}catch{Write-Error "Unable to set the Height property with value $($ControlHeight) to a control of the $($ControlType) type";}
try{
$private:ctrl.Width = $ControlWidth;
}catch{Write-Error "Unable to set the Width property with value $($ControlWidth) to a control of the $($ControlType) type";}
try{
$private:ctrl.Text = $ControlData;
}catch{Write-Error "Unable to set the Text property with value $($ControlData) to a control of the $($ControlType) type";}
try{
$wzdSteps[$StepNumber].Controls.Add($private:ctrl);
}catch{Write-Error "Unable to add a control of $($ControlType) type to the step $($StepNumber)";}
}
#endregion function Add-ControlToStep
#region function Add-CodeToStep
function Add-CodeToStep
# Adds a scriptblock to a wizard step
{
param(
[Parameter(Mandatory=$true)]
[string]$StepNumber,
[Parameter(Mandatory=$true)]
[scriptblock]$StepCode
)
$script:stepScriptblocks[$StepNumber] = $StepCode;
}
#endregion function Add-CodeToStep
#region Step data arrays
[psobject]$script:steps = New-Object psobject;
[System.Collections.ArrayList]$script:stepDisplayNames = `
New-Object System.Collections.ArrayList;
[System.Collections.ArrayList]$script:stepDescriptions = `
New-Object System.Collections.ArrayList;
[System.Collections.ArrayList]$script:stepScriptblocks = `
New-Object System.Collections.ArrayList;
#endregion Step data arrays
#endregion the Wizard steps
#region events of the wizard controls
#region resizing
#region button sizes
function Set-NextButtonLeft
{
param([int]$Left)
$script:btnNext.Left = $Left;
$script:btnFinish.Left = $Left;
}
function Set-NextButtonTop
{
param([int]$Top)
$script:btnNext.Top = $Top;
$script:btnFinish.Top = $Top;
}
function Set-BackButtonLeft
{
param([int]$Left)
$script:btnBack.Left = $Left;
$script:btnCancel.Left = $Left;
}
function Set-BackButtonTop
{
param([int]$Top)
$script:btnBack.Top = $Top;
$script:btnCancel.Top = $Top;
}
#endregion button sizes
#region function Initialize-WizardControls
function Initialize-WizardControls
<#
.SYNOPSIS
The Initialize-WizardControls function sets the wizard common controls to predefined positions.
.DESCRIPTION
The Initialize-WizardControls function does the following:
- sets Top, Left, Width and Height properties of the wizard buttons
- positions of the step labels
- sets the SplitterDistance property of both Splitcontainer controls
.EXAMPLE
PS C:\\> Initialize-WizardControls
This example shows how to step the wizard forward.
.INPUTS
No input
.OUTPUTS
No output
#>
{
# Set sizes of buttons
$script:btnNext.Height = $script:constButtonHeight;
$script:btnNext.Width = $script:constButtonWidth;
$script:btnBack.Height = $script:constButtonHeight;
$script:btnBack.Width = $script:constButtonWidth;
$script:btnFinish.Height = $script:btnNext.Height;
$script:btnFinish.Width = $script:btnNext.Width;
$script:btnCancel.Height = $script:btnBack.Height;
$script:btnCancel.Width = $script:btnBack.Width;
# SplitterDistance of the outer split container
# in other words, the area where Next and Back buttons are placed
$script:splitOuter.SplitterDistance = `
$script:splitOuter.Height - `
$script:constButtonAreaHeight;
# Placements of the buttons
if ($script:constWizardRigthToLeft)
{
Set-NextButtonLeft 10;
Set-BackButtonLeft ($script:constButtonWidth + 20);
}
else
{
Set-NextButtonLeft ($script:splitOuter.Width - `
$script:constButtonWidth - 10);
Set-BackButtonLeft ($script:splitOuter.Width - `
$script:constButtonWidth - `
$script:constButtonWidth - 20);
}
Set-NextButtonTop (($script:constButtonAreaHeight - $script:constButtonHeight) / 2);
Set-BackButtonTop (($script:constButtonAreaHeight - $script:constButtonHeight) / 2);
# SplitterDistance of the inner split container
# this is the place where step name is placed
$script:splitInner.SplitterDistance = `
$script:constButtonAreaHeight * 1.5;
# Step Display Name and Description labels
$script:lblStepDisplayName.Width = `
$script:splitInner.Panel1.Width - `
$script:constLabelStepDisplayNameLeft * 2;
$script:lblStepDescription.Width = `
$script:splitInner.Panel1.Width - `
$script:constLabelStepDescriptionLeft * 2;
# Refresh after we have changed placements of the controls
[System.Windows.Forms.Application]::DoEvents();
}
#endregion function Initialize-WizardControls
[System.EventHandler]$script:hndlFormResize = {Initialize-WizardControls;}
[System.EventHandler]$script:hndlFormLoad = {Initialize-WizardControls;}
#[System.Windows.Forms.MouseEventHandler]$script:hndlSplitMouseMove = `
# {Initialize-WizardControls;}
# Initial arrange on Load form.
$script:frmWizard.add_Load($script:hndlFormLoad);
#$script:frmWizard.add_Resize($script:hndlFormResize);
$script:splitOuter.add_Resize($script:hndlFormResize);
#endregion resizing
#region steps
#region function Invoke-WizardStep
function Invoke-WizardStep
<#
.SYNOPSIS
The Invoke-WizardStep function sets active panel on the wizard form.
.DESCRIPTION
The Invoke-WizardStep function does the following:
- changes internal variable $script:currentStep
- sets/resets .Enabled property of btnNext and btnBack
- changes .Dock and .Left properties of every panel
.PARAMETER Forward
The optional parameter Forward is used to point out the direction the wizard goes.
.EXAMPLE
PS C:\\> Invoke-WizardStep -Forward $true
This example shows how to step the wizard forward.
.INPUTS
System.Boolean
.OUTPUTS
No output
#>
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$false)]
[bool]$Forward = $true
)
Begin{}
Process{
# run the step code
try{
$script:stepScriptblocks[$script:currentStep].Invoke();
} catch {return;} #Cancel step
if ($Forward)
{
Enable-BackButton;
if ($script:currentStep -lt ($script:wzdSteps.Count - 1))
{$script:currentStep++;}
if ($script:currentStep -lt ($script:wzdSteps.Count - 1))
{
# step forward but not the last step
Enable-NextButton;
}
else
{
# the last step
Enable-FinishButton;
}
}
else
{
# go backward
Enable-NextButton;
if ($script:currentStep -gt 0)
{$script:currentStep--;}
if ($script:currentStep -gt 0)
{
# step backward but not the first one
Enable-BackButton;
}
else
{
# the first step
Enable-CancelButton;
}
}
for($private:i = 0; $private:i -lt $script:wzdSteps.Count;
$private:i++)
{
if ($private:i -ne $script:currentStep)
{
$script:wzdSteps[$private:i].Dock = `
[System.Windows.Forms.DockStyle]::None;
$script:wzdSteps[$private:i].Left = 10000;
}
else
{
$script:wzdSteps[$private:i].Dock = `
[System.Windows.Forms.DockStyle]::Fill;
$script:wzdSteps[$private:i].Left = 0;
}
}
$script:lblStepDisplayName.Text = `
$script:stepDisplayNames[$script:currentStep];
$script:lblStepDescription.Text = `
$script:stepDescriptions[$script:currentStep];
}
End{}
}
#endregion function Invoke-WizardStep
#region function Initialize-WizardStep
function Initialize-WizardStep
# This is the selfsufficient function doing all the necessary
# calculations for controls on each panel.
# Also from the code can be seen how to address the panel you are interesting in
# using the 'enumeration' created earlier
# for example, $script:wzdSteps[$script:steps.Welcome]
{
$script:lblStepDisplayName.Text = `
$script:stepDisplayNames[$script:currentStep];
$script:lblStepDescription.Text = `
$script:stepDescriptions[$script:currentStep];
}
#endregion function Initialize-WizardStep
#region $hndlStepForward
[System.EventHandler]$hndlStepForward = {
# serve controls' data
Initialize-WizardStep;
# switch panels
Invoke-WizardStep $true;
}
#endregion $hndlStepForward
#region $hndlStepBack
[System.EventHandler]$hndlStepBack = {
# switch panels
Invoke-WizardStep $false;
}
#endregion $hndlStepBack
#region $hndlFinish
[System.EventHandler]$hndlFinish = {
# ask for exit
[System.Windows.Forms.DialogResult]$private:res = `
[System.Windows.Forms.MessageBox]::Show("Are you sure?", `
"Question on exit", `
[System.Windows.Forms.MessageBoxButtons]::YesNo);
if ($res -eq [System.Windows.Forms.DialogResult]::Yes){
# close the wizard
$frmWizard.Close();
}
}
#endregion $hndlFinish
#region $hndlCancel
[System.EventHandler]$hndlCancel = {
# close the wizard
$frmWizard.Close();
}
#endregion $hndlCancel
#region wizard buttons' clicks
$script:btnNext.add_Click($script:hndlStepForward);
$script:btnBack.add_Click($script:hndlStepBack);
$script:btnFinish.add_Click($script:hndlFinish);
$script:btnCancel.add_Click($script:hndlCancel);
#endregion wizard buttons' clicks
#endregion steps
#endregion events of the wizard controls
#region wizard initialization
#region function Initialize-Wizard
function Initialize-Wizard
# This is one more selfsufficient function written to make
# the latest preparations for the form run
{
#region control settings
$script:frmWizard.Width = $script:constWizardWidth;
$script:frmWizard.Height = $script:constWizardHeight;
#endregion control settings
Initialize-WizardStep;
}
#endregion function Initialize-Wizard
#endregion wizard initialization
#endregion the resulting wizard
# Step 1: Welcome
New-WizardStep 'Welcome' `
'This is the first step' `
'Welcome to the PowerShell Wizard, the our dear customer!';
# Add a label
# Please note that we can use the enumeration $steps which is being created runtime
# on a call of the New-WizardStep function
Add-ControlToStep $steps.Welcome `
System.Windows.Forms.Label `
'lblWelcome' 20 10 50 300 `
'This Wizard carries you through the steps you need to collect the files from a given path';
# Step 2
New-WizardStep 'Input' `
'Step Two' `
'Here you type some in controls, plz';
# Add a label
Add-ControlToStep $steps.Input `
System.Windows.Forms.Label `
'lblInput' 20 10 20 300 `
'Please type the path to a catalog';
# Add a text box
Add-ControlToStep $steps.Input `
System.Windows.Forms.TextBox `
'txtInput' 40 10 20 300
# Add the code which requires that text box was not empty
Add-CodeToStep $steps.Input `
-StepCode {
[string]$private:path = `
$wzdSteps[$steps.Input].Controls['txtInput'].Text;
if ($private:path.Length -eq 0)
{
# stop the step
throw;
}
if (-not [System.IO.Directory]::Exists($private:path))
{
# stop the step
throw;
}
}
# Step 3
New-WizardStep 'Progress' `
'The third one' `
'Wait, please. Sip a coffee' ;
# Add a progress bar
Add-ControlToStep $steps.Progress `
'System.Windows.Forms.ProgressBar' `
'pbDir' 200 50 100 400
Add-CodeToStep $steps.Progress `
-StepCode {
# set progress bar maximum
$wzdSteps[$steps.Progress].Controls['pbDir'].Minimum = 0;
$wzdSteps[$steps.Progress].Controls['pbDir'].Value = 0;
$wzdSteps[$steps.Progress].Controls['pbDir'].Maximum = `
(Get-ChildItem $wzdSteps[$steps.Input].Controls['txtInput'].Text).Length;
# clear the list box (from the next step)
$wzdSteps[$steps.Output].Controls['lbxFiles'].Items.Clear();
# add file names to the list box
Get-ChildItem $wzdSteps[$steps.Input].Controls['txtInput'].Text | %{
$wzdSteps[$steps.Progress].Controls['pbDir'].Value++;
$wzdSteps[$steps.Output].Controls['lbxFiles'].Items.Add($_.Name);
}
}
# Step 4
New-WizardStep 'Output' 'Fourth' `
'Now awake and read the output';
# Add a list box
Add-ControlToStep $steps.Output `
System.Windows.Forms.ListBox `
lbxFiles 50 50 300 400
# Step 5: Finish
New-WizardStep 'Finish' 'Finish!' 'Bye!';
Initialize-Wizard;
# Set the second step as active
Invoke-WizardStep -Forward $true;
$script:frmWizard.ShowDialog() | Out-Null;
|
PowerShellCorpus/PoshCode/PS2WCF_4.ps1
|
PS2WCF_4.ps1
|
<#
.SYNOPSIS
Functions to call WCF Services With PowerShell.
.NOTES
Version 1.1 10.02.2012
Requires Powershell v2 and .NET 3.5
Original version by Christian Glessner
Blog: http://www.iLoveSharePoint.com
Twitter: http://twitter.com/cglessner
Codeplex: http://codeplex.com/iLoveSharePoint
PowerShell v2.0 modification by Justin Dearing
Blog: http://justaprogrammer.net
Twitter: http://twitter.com/zippy1981
.LINK
Blog describing original version: http://www.ilovesharepoint.com/2008/12/call-wcf-services-with-powershell.html
Posted to PoshCode.org http://poshcode.org/?lang=&q=PS2WCF
#>
# load WCF assemblies
Add-Type -AssemblyName "System.ServiceModel"
Add-Type -AssemblyName "System.Runtime.Serialization"
<#
.SYNOPSIS
Get metadata of a service
.DESCRIPTION
Parses a wsdl or mex and generates a WsdlImporter object from it.
.EXAMPLE
Get-WsdlImporter 'http://localhost.fiddler:14232/EchoService.svc/mex'
.EXAMPLE
Get-WsdlImporter 'http://localhost.fiddler:14232/EchoService.svc' -HttpGet
.EXAMPLE
Get-WsdlImporter 'http://localhost.fiddler:14232/EchoService.svc?wsdl' -HttpGet
#>
function global:Get-WsdlImporter([Parameter(Mandatory=$true, ValueFromPipeline=$true)][string]$wsdlUrl, [switch]$httpGet)
{
if($httpGet -eq $true)
{
$local:mode = [System.ServiceModel.Description.MetadataExchangeClientMode]::HttpGet
}
else
{
$local:mode = [System.ServiceModel.Description.MetadataExchangeClientMode]::MetadataExchange
}
$mexClient = New-Object System.ServiceModel.Description.MetadataExchangeClient((New-Object System.Uri($wsdlUrl)),$mode)
$mexClient.MaximumResolvedReferences = [System.Int32]::MaxValue
$metadataSet = $mexClient.GetMetadata()
$wsdlImporter = New-Object System.ServiceModel.Description.WsdlImporter($metadataSet)
return $wsdlImporter
}
<#
.SYNOPSIS
Generate wcf proxy types
.DESCRIPTION
Examines a web services meta data (wsdl or mex) and generates the types for the client proxy,
as well as request and response contracts.
.EXAMPLE
$proxyType = Get-WcfProxyType $wsdlImporter
$endpoints = $wsdlImporter.ImportAllEndpoints();
$proxy = New-Object $proxyType($endpoints[0].Binding, $endpoints[0].Address);
#>
function global:Get-WcfProxyType(
[Parameter(ParameterSetName='WsdlImporter', Position=0, Mandatory=$true, ValueFromPipeline=$true)][ServiceModel.Description.WsdlImporter] $wsdlImporter,
[Parameter(ParameterSetName='WsdlUrl', Position=0, Mandatory=$true, ValueFromPipeline=$true)][string] $wsdlUrl,
[string] $proxyPath
) {
switch ($PsCmdlet.ParameterSetName)
{
"WsdlUrl" {
$wsdlImporter = Get-WsdlImporter -wsdlUrl $wsdlUrl
trap [Exception]
{
$script:wsdlImporter = Get-WsdlImporter -wsdlUrl $wsdlUrl -httpGet $true
continue
}
break
}
"WsdlImporter" { break }
}
$generator = new-object System.ServiceModel.Description.ServiceContractGenerator
foreach($contractDescription in $wsdlImporter.ImportAllContracts())
{
[void]$generator.GenerateServiceContractType($contractDescription)
}
$parameters = New-Object System.CodeDom.Compiler.CompilerParameters
if($proxyPath -eq $null)
{
$parameters.GenerateInMemory = $true
}
else
{
$parameters.OutputAssembly = $proxyPath
}
$providerOptions = New-Object "Collections.Generic.Dictionary[String,String]"
[void]$providerOptions.Add("CompilerVersion","v3.5")
$compiler = New-Object Microsoft.CSharp.CSharpCodeProvider($providerOptions)
$result = $compiler.CompileAssemblyFromDom($parameters, $generator.TargetCompileUnit);
if($result.Errors.Count -gt 0)
{
throw "Proxy generation failed"
}
foreach($type in $result.CompiledAssembly.GetTypes())
{
if($type.BaseType.IsGenericType)
{
if($type.BaseType.GetGenericTypeDefinition().FullName -eq "System.ServiceModel.ClientBase``1" )
{
return $type
}
}
}
}
<#
.SYNOPSIS
Generate wcf proxy
.DESCRIPTION
Generate wcf proxy in a manner similar to a Get-WebServiceProxy
.EXAMPLE
$proxy = Get-WcfProxy 'http://localhost.fiddler:14232/EchoService.svc/mex'
$proxy.Echo("Justin Dearing");
#>
function global:Get-WcfProxy(
[Parameter(ParameterSetName='WsdlImporter', Position=0, Mandatory=$true, ValueFromPipeline=$true)][ServiceModel.Description.WsdlImporter] $wsdlImporter,
[Parameter(ParameterSetName='WsdlUrl', Position=0, Mandatory=$true, ValueFromPipeline=$true)][string] $wsdlUrl,
[string] $proxyPath
) {
switch ($PsCmdlet.ParameterSetName)
{
"WsdlUrl" {
$wsdlImporter = Get-WsdlImporter -wsdlUrl $wsdlUrl
trap [Exception]
{
$script:wsdlImporter = Get-WsdlImporter -wsdlUrl $wsdlUrl -httpGet $true
continue
}
break
}
}
$proxyType = Get-WcfProxyType $wsdlImporter
$endpoints = $wsdlImporter.ImportAllEndpoints();
return New-Object $proxyType($endpoints[0].Binding, $endpoints[0].Address);
}
|
PowerShellCorpus/PoshCode/SharpSsh Functions_3.ps1
|
SharpSsh Functions_3.ps1
|
## USING the binaries from:
## http://downloads.sourceforge.net/sharpssh/SharpSSH-1.1.1.13.bin.zip
[void][reflection.assembly]::LoadFrom( (Resolve-Path "~\\Documents\\WindowsPowerShell\\Libraries\\Tamir.SharpSSH.dll") )
## NOTE: These are bare minimum functions, and only cover ssh, not scp or sftp
## also, if you "expect" something that doesn't get output, you'll be completely stuck.
##
## As a suggestion, the best way to handle the output is to "expect" your prompt, and then do
## select-string matching on the output that was captured before the prompt.
function New-SshSession {
Param(
[string]$UserName
, [string]$HostName
, [string]$RSAKeyFile
, [switch]$Passthru
)
if($RSAKeyFile -and (Test-Path $RSAKeyFile)){
$global:LastSshSession = new-object Tamir.SharpSsh.SshShell `
$cred.GetNetworkCredential().Domain,
$cred.GetNetworkCredential().UserName
$global:LastSshSession.AddIdentityFile( (Resolve-Path $RSAKeyFile) )
}
else {
$cred = $host.UI.PromptForCredential("SSH Login Credentials",
"Please specify credentials in user@host format",
"$UserName@$HostName","")
$global:LastSshSession = new-object Tamir.SharpSsh.SshShell `
$cred.GetNetworkCredential().Domain,
$cred.GetNetworkCredential().UserName,
$cred.GetNetworkCredential().Password
}
$global:LastSshSession.Connect()
$global:LastSshSession.RemoveTerminalEmulationCharacters = $true
if($Passthru) {
return $global:LastSshSession
}
}
function Remove-SshSession {
Param([Tamir.SharpSsh.SshShell]$SshShell=$global:LastSshSession)
$SshShell.WriteLine( "exit" )
sleep -milli 500
if($SshShell.ShellOpened) { Write-Warning "Shell didn't exit cleanly, closing anyway." }
$SshShell.Close()
$SshShell = $null
}
function Invoke-Ssh {
Param(
[string]$command
, [regex]$expect ## there ought to be a non-regex parameter set...
, [Tamir.SharpSsh.SshShell]$SshShell=$global:LastSshSession
)
if($SshShell.ShellOpened) {
$SshShell.WriteLine( $command )
if($expect) {
$SshShell.Expect( $expect ).Split("`n")
}
else {
sleep -milli 500
$SshShell.Expect().Split("`n")
}
}
else { throw "The ssh shell isn't open!" }
}
function Send-Ssh {
Param(
[string]$command
, [Tamir.SharpSsh.SshShell]$SshShell=$global:LastSshSession
)
if($SshShell.ShellOpened) {
$SshShell.WriteLine( $command )
}
else { throw "The ssh shell isn't open!" }
}
function Receive-Ssh {
Param(
[RegEx]$expect ## there ought to be a non-regex parameter set...
, [Tamir.SharpSsh.SshShell]$SshShell=$global:LastSshSession
)
if($SshShell.ShellOpened) {
if($expect) {
$SshShell.Expect( $expect ).Split("`n")
}
else {
sleep -milli 500
$SshShell.Expect().Split("`n")
}
}
else { throw "The ssh shell isn't open!" }
}
|
PowerShellCorpus/PoshCode/Get-Netstat 0.9.ps1
|
Get-Netstat 0.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/2ee1612d-7a4e-467a-8ae1-8c310bb1cba0.ps1
|
2ee1612d-7a4e-467a-8ae1-8c310bb1cba0.ps1
|
#Purpose: To remotely query select machines for system information
#Author: Alex Smith
#Created: 6/11/2010
#Arguments: IP Addresses or Hostnames of target PCs then path and file name
#Examples: To query based on hostname or ip: C:\\>powershell .\\WMIQuery.ps1 host1
# To print to a file: C:\\>powershell .\\WMIQuery.ps1 host1 > file.txt
#########################################################################################################
##########Program Start##########
#Runs script for each argument given in commandline
foreach ($comp in $args)
{
echo ""
echo ""
echo ""
echo "System data for $comp "
echo ""
get-wmiObject win32_computerSystem -Computer $comp | format-table Manufacturer, Model -autosize #Manufacturer (Computer Manufacturer), Model (Computer Model)
get-wmiObject win32_operatingSystem -Computer $comp | format-table Name, OSArchitecture -autosize #Name (OS Name and Drive Intalled On), OSArchitecture (OS Architecture)
get-wmiObject win32_bios -Computer $comp | format-table SerialNumber -autosize #SerialNumber (Computer Serial Number)
get-wmiObject win32_processor -Computer $comp | format-table Name -autosize #Name (CPU Name, Model, Clockspeed)
get-wmiObject win32_operatingSystem -Computer $comp | format-table TotalVisibleMemorySize, FreePhysicalMemory -autosize #TotalVisibleMemorySize (Total memory), FreePhysicalMemory (Memory Available)
get-wmiObject win32_diskDrive -Computer $comp | format-table Model, InterfaceType, DeviceID, Partitions -autosize #Model (Device Model), InterfaceType (IDE, SCSI, Etc.), DeviceID (Divice ID #), Partitions (Number of Partitions on Disk)
get-wmiObject win32_volume -Computer $comp | format-table FileSystem, Label, DriveLetter, Capacity, FreeSpace -autosize #FileSystem (File System Type), Label (Drive Label), DriveLetter (C:, d:, Etc.), Capacity (Total Space), FreeSpace (Space Available)
get-wmiObject win32_operatingSystem -Computer $comp | format-table NumberOfUsers -autosize #NumberOfUsers (Total of Local User Accounts)
get-wmiObject win32_computerSystem -Computer $comp | format-table UserName -autosize #UserName (Hostname\\Current User)
get-wmiObject win32_networkAdapterConfiguration -Computer $comp | format-table MACAddress, IPAddress, DefaultIPGateway -autosize #MacAddress (MAC Address), IPAddress (IP Address), DefaultIPGateway (Default Gateway)
}
|
PowerShellCorpus/PoshCode/Upgrade Templates to v7.ps1
|
Upgrade Templates to v7.ps1
|
Function Convert-TemplateToVM($template){
Write-Host "Converting" $vm -ForegroundColor Yellow
Set-Template $template -ToVM -RunAsync | out-null
}
Function PowerOn-VM($vm){
Start-VM -VM $vm -Confirm:$false -RunAsync
do {
$vmview = get-VM $vm | Get-View
$status = $vmview.Guest.ToolsStatus
Write-Host $vm is starting! -ForegroundColor Yellow
sleep 5
}until(($status -match "toolsOld") -or ($status -match "toolsOk"))
if ($status -match "Ok"){
$Startup = "Ok"}
elseif($status -match "toolsOld"){
$Startup = "ToolsOld"}
else{
$Startup = "Not Ready"}
return $Startup
}
Function Check-ToolsStatus($vm){
$vmview = get-VM $vm | Get-View
$status = $vmview.Guest.ToolsStatus
if ($status -match "toolsOld"){
$vmTools = "Old"}
elseif($status -match "toolsNotRunning"){
$vmTools = "Not Running"}
else{
$vmTools = "Ok"}
return $vmTools
}
Function Check-VMHardwareVersion($vm){
$vmView = get-VM $vm | Get-View
$vmVersion = $vmView.Config.Version
$v4 = "vmx-04"
$v7 = "vmx-07"
if ($vmVersion -eq $v4){
$vmHardware = "Old"}
elseif($vmVersion -eq $v7){
$vmHardware = "Ok"}
else{Write-Host "Error!!" -ForegroundColor Red
$vmHardware = "Error"}
return $vmHardware
}
Function PowerOff-VM($vm){
sleep 20
Shutdown-VMGuest -VM $vm -Confirm:$false
do {
$vmview = Get-VM $vm | Get-View
$status = $vmview.Guest.ToolsStatus
Write-Host $vm is stopping! -ForegroundColor Yellow
sleep 5
}until($status -match "toolsNotRunning")
if ($status -match "toolsNotRunning"){
$Shutdown = "Ok"}
else{
$Shutdown = "Not Ready"}
return $Shutdown
}
Function ConvertTo-Template($vm){
Write-Host "Converting" $vm -ForegroundColor Yellow
$vmview = Get-VM $vm | Get-View
$vmview.MarkAsTemplate() | Out-Null
}
Function Upgrade-VMHardware($vm){
$vmview = Get-VM $vm | Get-View
$vmVersion = $vmView.Config.Version
$v4 = "vmx-04"
$v7 = "vmx-07"
if ($vmVersion -eq $v4){
Write-Host "Version 4 detected" -ForegroundColor Red
# Update Hardware
Write-Host "Upgrading Hardware on" $vm -ForegroundColor Yellow
Get-View ($vmView.UpgradeVM_Task($v7)) | Out-Null
}
}
$vCenter = Read-Host "Enter your vCenter servername"
Connect-VIServer $vCenter
$tmpfile = "$env:temp\\tmpfile.csv"
$templates = Get-Template -Name * | Export-Csv -NoTypeInformation $tmpfile
$csv = Import-CSV $tmpfile
foreach($item in $csv){
$template = $item.Name
#Convert Template back to VM
Convert-TemplateToVM $template
}
foreach($item in $csv){
$vm = $item.Name
$vmHardware = Check-VMHardwareVersion $vm
if ($vmHardware -eq "Ok"){
Write-Host $vm "is up to date" -ForegroundColor Green
ConvertTo-Template $vm
}
else{Write-Host "Hardware is old" -ForegroundColor Red
if(PowerOn-VM $vm -eq "Ok"){
Write-Host "PowerOn Complete" -ForegroundColor Green
sleep 10
$vmToolsStatus = Check-ToolsStatus $vm
if($vmToolsStatus -eq "Old"){
Write-Host "The VMware Tools are old" -ForegroundColor Red
Sleep 20
Get-VMGuest $vm | Update-Tools
Sleep 120
Write-Host "VMware Tools are installed on:" $vm -ForegroundColor Cyan
$vmToolsStatus = Check-ToolsStatus $vm
if($vmToolsStatus -eq "Ok"){
$PowerOffVM = PowerOff-VM $vm
if($PowerOffVM -eq "Ok"){
Write-Host $vm "is down" -ForegroundColor Yellow
Upgrade-VMHardware $vm
ConvertTo-Template $vm
Write-Host $vm "is up to date" -ForegroundColor Green
}
}
}
else{
$PowerOffVM = PowerOff-VM $vm
if($PowerOffVM -eq "Ok"){
Upgrade-VMHardware $vm
ConvertTo-Template $vm
Write-Host $vm "is up to date" -ForegroundColor Green
}
}
}
}
}
Remove-Item $tmpfile -Confirm:$false
Disconnect-VIServer -Confirm:$false
|
PowerShellCorpus/PoshCode/Close by window title.ps1
|
Close by window title.ps1
|
using System;
using System.Text;
using System.Drawing;
using System.Reflection;
using System.Diagnostics;
using System.Windows.Forms;
using System.ComponentModel;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CloseByTitle")]
[assembly: AssemblyVersion("3.5.0.0")]
namespace CloseByTitle {
internal static class WinAPI {
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
internal static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
internal static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll")]
internal static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
internal delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
}
internal class frmMain : Form {
public frmMain() {
InitializeComponent();
}
private TextBox txtTitle;
private Button btnClose;
private void InitializeComponent() {
this.txtTitle = new TextBox();
this.btnClose = new Button();
//
//txtTitle
//
this.txtTitle.Location = new Point(16, 16);
this.txtTitle.Width = 190;
//
//btnClose
//
this.btnClose.Location = new Point(220, 15);
this.btnClose.Text = "Close it!";
this.btnClose.Click += new EventHandler(btnClose_Click);
//
//frmMain
//
this.Controls.AddRange(new Control[] {this.txtTitle, this.btnClose});
this.ClientSize = new Size(310, 65);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.StartPosition = FormStartPosition.CenterScreen;
this.Load += new EventHandler(frmMain_Load);
}
private static string GetText(IntPtr hWnd) {
int len = WinAPI.GetWindowTextLength(hWnd);
StringBuilder sb = new StringBuilder(len + 1);
len = WinAPI.GetWindowText(hWnd, sb, sb.Capacity);
return sb.ToString(0, len);
}
private void btnClose_Click(object sender, EventArgs e) {
int pid, res;
string search = txtTitle.Text, window = null;
if (!WinAPI.EnumWindows(new WinAPI.EnumWindowsProc((hWnd, lParam) => {
window = GetText(hWnd);
if (!string.IsNullOrEmpty(window) && window.Contains(search)) {
res = WinAPI.GetWindowThreadProcessId(hWnd, out pid);
//there is an exception if rights are not enough
if (res != 0) Process.GetProcessById(pid).Kill();
}
return true;
}), IntPtr.Zero)) {
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
private void frmMain_Load(object sender, EventArgs e) {
Assembly assem = typeof(frmMain).Assembly;
string title = ((AssemblyTitleAttribute)Attribute.GetCustomAttribute(assem,
typeof(AssemblyTitleAttribute))).Title;
this.Text = title;
}
}
internal sealed class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.Run(new frmMain());
}
}
}
|
PowerShellCorpus/PoshCode/Get-Exchange-Mail.ps1
|
Get-Exchange-Mail.ps1
|
[Reflection.Assembly]::LoadFile("C:\\Program Files\\Microsoft\\Exchange\\Web Services\\1.1\\Microsoft.Exchange.WebServices.dll") | Out-Null
$s = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2007_SP1)
$s.Credentials = New-Object Net.NetworkCredential('email@domain', 'password')
$s.Url = new-object Uri("https://red001.mail.microsoftonline.com/ews/exchange.asmx")
$inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($s,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox)
$mails = $inbox.FindItems(5)
$mails | % {$_.Load()}
$mails
|
PowerShellCorpus/PoshCode/Find Local Group Members_10.ps1
|
Find Local Group Members_10.ps1
|
# Author: Hal Rottenberg
# Purpose: Find matching members in a local group
# Used tip from RichS here: http://powershellcommunity.org/Forums/tabid/54/view/topic/postid/1528/Default.aspx
# Change these two to suit your needs
$ChildGroups = "Domain Admins", "Group Two"
$LocalGroup = "Administrators"
$MemberNames = @()
# uncomment this line to grab list of computers from a file
# $Servers = Get-Content serverlist.txt
$Servers = $env:computername # for testing on local computer
foreach ( $Server in $Servers ) {
# Put $MemberNames = @() here to clear out the MemberNames variable between servers, otherwise we start to get incorrect results
$MemberNames = @()
$Group= [ADSI]"WinNT://$Server/$LocalGroup,group"
$Members = @($Group.psbase.Invoke("Members"))
$Members | ForEach-Object {
$MemberNames += $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)
}
$ChildGroups | ForEach-Object {
$output = "" | Select-Object Server, Group, InLocalAdmin
$output.Server = $Server
$output.Group = $_
$output.InLocalAdmin = $MemberNames -contains $_
Write-Output $output
}
}
|
PowerShellCorpus/PoshCode/FTP upload_3.ps1
|
FTP upload_3.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/Save-Credentials_2.ps1
|
Save-Credentials_2.ps1
|
<#
.SYNOPSIS
The script saves a username and password, encrypted with a custom key to to a file.
.DESCRIPTION
The script saves a username and password, encrypted with a custom key to to a file. The key is coded into the script but should be changed before use. The key allows the password to be decrypted by any user who has the key, on any machine. if the key parameter is omitted from ConvertFrom-SecureString, only the user who generated the file on the computer that generated the file can decrypt the password.
see http://bsonposh.com/archives/254 for more info.
To retrieve the password:
$key = [byte]57,86,59,11,72,75,18,52,73,46,0,21,56,76,47,12
$VCCred = Import-Csv 'C:\\PATH\\FILE.TXT'
$VCCred.Password = ($VCCred.Password| ConvertTo-SecureString -Key $key)
$VCCred = (New-Object -typename System.Management.Automation.PSCredential -ArgumentList $VCCred.Username,$VCCred.Password)
.NOTES
File Name : SaveCredentials.ps1
Author : Samuel Mulhearn
Version History:
Version 1.0
28 Jun 2012.
Release
.LINK
http://poshcode.org/3485
.EXAMPLE
Call the script with .\\Save-Credentials.ps1 no arguments or parameters are required
#>
$key = [byte]57,86,59,11,72,75,18,52,73,46,0,21,56,76,47,12
Write-Host "Key length is:" $key.length "The key length is acceptable if 16 or 32"
Write-Host "This script saves a username and password into a file"
Write-Host "Select an output file:"
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |Out-Null
$SaveFileDialog = New-Object System.Windows.Forms.SaveFileDialog
$SaveFileDialog.initialDirectory = $initialDirectory
$SaveFileDialog.filter = "All files (*.*)| *.*"
$SaveFileDialog.ShowDialog() | Out-Null
$OutFile = $SaveFileDialog.filename
$null | Out-File -FilePath $Outfile
$credential = Get-Credential
#| ConvertFrom-SecureString -Key $key)
$obj = New-Object -typename System.Object
$obj | Add-Member -MemberType noteProperty -name Username -value $credential.UserName
$obj | Add-Member -MemberType noteProperty -name Password -value ($credential.Password | ConvertFrom-SecureString -key $key)
$obj | Export-Csv -Path $OutFile
write-host "Username and password have been saved to $outfile"
|
PowerShellCorpus/PoshCode/GPRS Online log_8.ps1
|
GPRS Online log_8.ps1
|
<#
.SYNOPSIS
Get-GprsTime (V4.0 Update for Windows 7 and allow time correction)
(V4.2 'Interval' now incorporate previous 'FormatSpan' function)
Check the total connect time of any GPRS SIM devices from a specified date.
Use 'Get-Help .\\Get-GprsTime -full' to view Help for this script.
.DESCRIPTION
Display all the GPRS modem Event Log entries. While applications issued by the
mobile phone manufacturers will invariably monitor only their own usage, this
will show any logged GPRS activity, be it via PCMCIA, USB, mobile phone, etc.
Use the -Verbose switch for some extra information if desired. A default value
can be set with the -Monthly switch but can be temporarily overridden with any
-Start value and deleted by entering an invalid date. Now uses .NET Parse to
use any culture date input. Switches -M and -S cannot be used together.
A Balloon prompt will be issued in the Notification area for the 5 days
before the nominal month end.
NOTE: this can effectively be suppressed by using a value higher than the SIM
card term, ie something like -Account 90 for a 30 day card which will override
the default setting.
Define a function in $profile to set any permanent switches, for example to
remove 1hour 15 minutes from the total each time.
function GPRS {
Invoke-Expression ".\\Get-GprsTime -Adjust 1:15:00- $args"
}
.EXAMPLE
.\\Get-GprsTime.ps1 -Monthly 4/8/2011
This will set the default search date to start from 4/8/2011 and is used to
reset the start date each month for the average 30/31 day SIM card.
.EXAMPLE
.\\Get-GprsTime.ps1 -Start 12/07/2009 -Account 100 -Verbose
Search from 12/07/2011 and also show (Verbose) details for each session. The
Account switch will override any balloon prompt near the SIM expiry date.
.EXAMPLE
.\\Get-GprsTime.ps1 5/9/2011 -v
Search one day only and show session details.
.EXAMPLE
.\\Get-GprsTime.ps1 -Today
Show all sessions for today. This always defaults to verbose output.
.EXAMPLE
.\\Get-GprsTime.ps1 -Debug
This shows the first available Event Log record & confirms switch settings.
(Note that it will probably not be the first 'RemoteAccess' or 'RasClient'
record).
.EXAMPLE
.\\Get-GprsTime -Adjust 1:20:00
If the same SIM card is used on another computer then such times will have
to be added here manually (this should be put in a function in $profile so
that it will automatically be included - see example above).
To remove an amount of time, just put a '-' sign after the desired figure.
.NOTES
A shorter total time than that actually used will result if the Event Log
does not contain earlier dates; just increase the log size in such a case.
The author can be contacted at www.SeaStarDevelopment.Bravehost.com and a
(binary compiled) Module version of this procedure is included in the file
Gprs3xxx.zip download there; the execution time of the module being about
10 times faster than this script.
Use '(measure-Command {.\\Get-GprsTime}).TotalSeconds' to confirm the times.
For the Event Log to record connect & disconnect events, the modem software
should be set to RAS rather than NDIS if possible.
#>
Param ([String] $start,
[alias("PERIOD")][string] $adjust,
[String] $monthly,
[Int] $account = 0,
[Switch] $today,
[Switch] $verbose,
[Switch] $debug)
Trap [System.Management.Automation.MethodInvocationException] {
[Int]$line = $error[0].InvocationInfo.ScriptLineNumber
[System.Media.SystemSounds]::Hand.Play()
if ($line -eq 206) {
Write-Warning "[$name] Current GPRS variable has been deleted."
$monthly = ""
[Environment]::SetEnvironmentVariable("GPRS",$monthly,"User")
}
else {
Write-Warning "[$name] Date is missing or invalid $SCRIPT:form"
}
exit 1
}
#Establish the Operating System...We only need to confirm XP here.
#The result will be written to the 'out' variable '$osv'.
function Get-OSVersion($computer,[ref]$osv) {
$os = Get-WmiObject -class Win32_OperatingSystem -computerName $computer
Switch -regex ($os.Version) {
'^5\\.1\\.(\\d{1,4})$' { $osv.value = "xp" } #Find XP & variants.
default { $osv.value = "unknown" }
}
}
$osv = $null
Get-OSVersion -computer 'localhost' -osv ([ref]$osv)
if ($osv -eq 'xp') {
$logname = 'System'
$connEvent = 20158
$discEvent = 20159
$source = 'RemoteAccess'
}
else { #Treat As Vista or Windows 7.
$logname = 'Application'
$connEvent = 20225
$discEvent = 20226
$source = 'RasClient'
}
$entryType = 'Information'
$logEntry = $null
$oldest = Get-eventlog -LogName $logname | #Get the earliest Log record.
Sort-Object TimeGenerated |
Select-Object -first 1
if ($oldest.TimeGenerated) {
$logEntry = "System Event records available from - $($oldest.TimeGenerated.ToLongDateString())"
}
$name = $myInvocation.MyCommand
$newLine = "[$name] The switches -Start and -Monthly can only be used separately."
if ($debug) {
$DebugPreference = 'Continue'
}
if ($start -and $monthly) {
[System.Media.SystemSounds]::Hand.Play()
Write-Warning "$newLine"
exit 1
}
$SCRIPT:form = ""
#In certain cases Culture & UICulture can be different and have been known to
# return conflicting results regarding '-is [DateTime]' queries, etc.
if ($Host.CurrentCulture -eq $Host.CurrentUICulture) {
$SCRIPT:form = '-Use format mm/dd/year'
[Int]$culture = "{0:%d}" -f [DateTime] "6/5/2009" #Returns local day.
if ($culture -eq 6) {
$SCRIPT:form = '-Use format dd/mm/year'
}
}
$ErrorActionPreference = 'SilentlyContinue'
$VerbosePreference = 'SilentlyContinue'
$WarningPreference = 'Continue'
$conn = $disc = $default = $print = $null
$timeNow = [DateTime]::Now
$total = $timeNow - $timeNow #Set initial value to 00:00:00.
$insert = "since"
if ($verbose) {
$VerbosePreference = 'Continue'
}
function CreditMsg ($value, $value2) {
$value = [Math]::Abs($value)
$prefix = "CURRENT"
[DateTime] $creditDT = $value2
$creditDT = $creditDT.AddDays($value) #Add the -Account days.
$thisDay = "{0:M/d/yyyy}" -f [DateTime]::Now #Force US format.
#If we use '$number = $creditDT - (Get-Date)' instead of the line below we
#can sometimes get a value of 1 returned instead 2, hence the above lines.
$number = $creditDT - [DateTime] $thisDay
[String] $credit = $creditDT
$credit = $credit.Replace('00:00:00','') #Remove any trailing time.
$credit = "{0:d}" -f [DateTime]$credit
Switch($number.Days) {
1 {$prefix = "($value days) will expire tomorrow"; break}
0 {$prefix = "($value days) will expire today"; break}
-1 {$prefix = "($value days) expired yesterday"; break}
{($_ -lt 0)} {$prefix = "($value days) expired on $credit"; break}
{($_ -le 5)} {$prefix = "($value days) will expire on $credit"}
Default {$prefix = "CURRENT"} #Only come here if over 5 days.
}
return $prefix
}
function Interval ([String] $value) { #Convert returns of '1.11:00:00'.
Switch -regex ($value) {
'^00?:00?:\\d+(.*)$' {$suffix = "seconds"; break}
'^00?:\\d+:\\d+(.*)$' {$suffix = "minutes"; break}
'^\\d+:\\d+:\\d+(.*)$' {$suffix = " hours"; break}
'^(\\d+)\\.(\\d+)(\\D.*)$' {$suffix = " hours"
$pDays = $matches[1]
$pHours = $matches[2]
[string]$pRest = $matches[3]
[string]$tHours = (([int]$pDays) * 24)+[int]$pHours
$value = $tHours + $pRest; break}
default {$suffix = " hours"} #Should never come here!
}
return "$value $suffix"
}
function CheckSetting ($value) {
if ($value) { #Correct for local culture.
$print = $default.ToShortDateString()
}
else {
$print = "(Value not set)"
}
return $print
}
#The Script effectively starts here.............................................
$getGprs = [Environment]::GetEnvironmentVariable("GPRS","User")
#First check for GPRS variable and change from US date format to current locale.
if ([DateTime]::TryParse($getGprs, [Ref]$timeNow)) { #No error as date is valid.
$default = "{0:d}" -f [datetime]$getGprs
$default = [DateTime]::Parse($default)
$checkParts = "{0:yyyy},{0:%M}" -f $default
$times = $checkParts.Split(',')
$dayCount = [DateTime]::DaysInMonth($times[0],$times[1]) #Range 28-31.
if($account -eq 0) {
$account = $dayCount
$summary = "$($dayCount.ToString()) days"
}
else {
$summary = "$($account.Tostring()) days"
}
$text = CreditMsg $account $getGprs #Check if within 5 days of expiry date.
if ($text -ne "CURRENT") {
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon
$objNotifyIcon.Icon = [System.Drawing.SystemIcons]::Exclamation
$objNotifyIcon.BalloonTipIcon = "Info"
$objNotifyIcon.BalloonTipTitle = "GPRS online account"
$objNotifyIcon.BalloonTipText = "Credit $text"
$objNotifyIcon.Visible = $True
$objNotifyIcon.ShowBalloonTip(10000)
}
}
else {
$summary = "(Days not set)"
if ((!$today) -and (!$monthly) -and (!$start)) {
[System.Media.SystemSounds]::Hand.Play()
Write-Warning("Monthly date is either invalid or not set.")
exit 1
}
}
if ($start) {
$start = [DateTime]::Parse($start) #Trigger TRAP if invalid!
[DateTime]$limit = $start
$convert = "{0:D}" -f $limit
$print = CheckSetting $default
}
if ($monthly) {
$start = [DateTime]::Parse($monthly) #Trigger TRAP if invalid!
Write-Output "Setting GPRS (monthly) environment variable to: $monthly"
$gprs = [String]$start.Replace('00:00:00','')
[Environment]::SetEnvironmentVariable("GPRS",$gprs,"User")
[DateTime] $limit = $start #Change to required US date format.
$convert = "{0:D}" -f $limit
$print = $limit.ToShortDateString()
$summary = "(Days undetermined)" #Will show next time around.
}
if ($today) {
$verBosePreference = 'Continue' #Show VERBOSE by default.
[DateTime] $limit = (Get-Date)
$convert = "{0:D}" -f $limit
$limit = $limit.Date #Override any start date if using -Today input.
$insert = "for today"
$print = CheckSetting $default
}
if ((!$today) -and (!$monthly) -and (!$start)) {
if ($default) {
$monthly = $default
[DateTime] $limit = $monthly
$convert = "{0:D}" -f $limit
$print = CheckSetting $default
}
}
$adjustment = $null #Otherwise 'Set-Strictmode -Version latest' will catch.
if ($adjust) {
$pattern = '^(\\d{1,3}):(\\d{1,2}):(\\d{1,2})-?$'
if ($adjust -notmatch $pattern ) {
Write-Warning "Invalid format - use <hours>:<minutes>:<seconds>"
return
} #Now create the 'adjustment' to add later.
$adjustment = New-TimeSpan -hours $matches[1] -minutes $matches[2] -seconds $matches[3]
$outString = $adjust.Replace('-','')
$outString = interval $outString
}
Write-Verbose "All records $($insert.Replace('for ','')) - $convert"
Write-Verbose "Script activation - User [$($env:UserName)] Computer [$($env:ComputerName)]"
Write-Output ""
Write-Output "Calculating total connect time of all GPRS modem devices..."
#We cannot proceed beyond here without a valid $limit value.
Write-Debug "Using - [Search date] $($limit.ToShortDateString()) [Account] $summary [GPRS Monthly] $print"
if ($logEntry) {
Write-Debug "$logEntry"
}
$lines = Get-EventLog $logname | Where-Object {($_.TimeGenerated -ge $limit) -and `
($_.EventID -eq $discEvent -or $_.EventID -eq $connEvent)}
if ($lines) {
Write-Verbose "A total of $([Math]::Truncate($lines.Count/2)) online sessions extracted from the System Event Log."
}
else {
Write-Output "(There are no events indicated in the System Event Log)"
}
$lines | ForEach-Object {
try {
$source = $_.Source
}
catch {
return
}
if ($_.EventID -eq $discEvent) { #Event 20159 is Disconnect.
$disc = $_.TimeGenerated
}
else { #Event 20158 is Connect.
$conn = $_.TimeGenerated
} #We are only interested in matching pairs of DISC/CONN...
if ($disc -ne $null -and $conn -ne $null -and $disc -gt $conn) {
$diff = $disc - $conn
$total += $diff
$convDisc = "{0:G}" -f $disc
$convConn = "{0:G}" -f $conn
$period = Interval $diff
Write-Verbose "Disconnect at $convDisc. Online - $period"
Write-Verbose " Connect at $convConn."
}
} #End ForEach
if (!$source) {
$source = '(Undetermined)'
}
Write-Verbose "Using local event source - System Event Log [$source]"
$period = Interval $total
if ($adjustment -and ($total -match $pattern)) {
$outDate = New-TimeSpan -hours $matches[1] -minutes $matches[2] -seconds $matches[3]
if (!$adjust.EndsWith('-')) {
$period = $outDate + $adjustment #The '-adjust' value added at start.
$temp = [String]$period #Extract any 1.0:00:00 values if + 24 hours.
Write-Debug "Processing (Timespan) string: $temp"
$show = (interval $temp).Replace(' ',' ')
Write-Output "Total online usage $insert $convert is $show"
Write-Output "(Including $($outString.Replace(' ',' ')) adjustment time)"
}
else {
if ($outDate.TotalSeconds -gt $adjustment.TotalSeconds) {
$period = $outDate - $adjustment
$temp = [String]$period
Write-Debug "Processing (Timespan) string: $temp"
$show = (interval $temp).Replace(' ',' ')
Write-Output "Total online usage $insert $convert is $show"
Write-Output "(Excluding $($outString.Replace(' ',' ')) adjustment time)"
}
else {
Write-Output "Total online usage $insert $convert is $($period.ToString().Replace(' ',' '))."
$adjust = $adjust.Replace('-','')
Write-Warning "Invalid amount entered ($adjust) - no adjustment performed"
}
}
}
else {
Write-OutPut "Total online usage $insert $convert is $($period.ToString().Replace(' ',' '))."
}
Write-Output ""
|
PowerShellCorpus/PoshCode/Run-Query (SharePoint)_3.ps1
|
Run-Query (SharePoint)_3.ps1
|
function Run-Query($siteUrl, $queryText)
{
[reflection.assembly]::loadwithpartialname("microsoft.sharePOint") | out-null
[reflection.assembly]::loadwithpartialname("microsoft.office.server") | out-null
[reflection.assembly]::loadwithpartialname("microsoft.office.server.search") | out-null
$s = [microsoft.sharepoint.spsite]$siteUrl
$q = new-object microsoft.office.server.search.query.fulltextsqlquery -arg $s
$q.querytext = $queryText
$q.RowLimit = 100
$q.ResultTypes = "RelevantResults"
$dt = $q.Execute()
$r = $dt["RelevantResults"]
$output = @()
while ($r.Read()) {
$o = new-object PSObject
0..($r.FieldCount-1) | foreach {
add-member -inputObject $o -memberType "NoteProperty" -name $r.GetName($_) -value $r[$_].ToString()
}
$output += $o
}
return $output
}
@@
@@
@@#Sample usage:
@@#Run-Query -siteUrl "http://dev/" -queryText "SELECT PreferredName, WorkPhone FROM SCOPE() WHERE PreferredName LIKE '%JIM%'"
@@#
@@#
|
PowerShellCorpus/PoshCode/PowerShell CMatrix_1.ps1
|
PowerShell CMatrix_1.ps1
|
Set-StrictMode -off
#
# Module: PowerShell Console ScreenSaver Version 0.1
# Author: Oisin Grehan ( http://www.nivot.org )
#
# A PowerShell CMatrix-style screen saver for true-console hosts.
#
# This will not work in Micrisoft's ISE, Quest's PowerGUI or other graphical hosts.
# It should work fine in PowerShell+ from Idera which is a true console.
#
if ($host.ui.rawui.windowsize -eq $null) {
write-warning "Sorry, I only work in a true console host like powershell.exe."
throw
}
#
# Console Utility Functions
#
function New-Size {
param([int]$width, [int]$height)
new-object System.Management.Automation.Host.Size $width,$height
}
function New-Rectangle {
param(
[int]$left,
[int]$top,
[int]$right,
[int]$bottom
)
$rect = new-object System.Management.Automation.Host.Rectangle
$rect.left= $left
$rect.top = $top
$rect.right =$right
$rect.bottom = $bottom
$rect
}
function New-Coordinate {
param([int]$x, [int]$y)
new-object System.Management.Automation.Host.Coordinates $x, $y
}
function Get-BufferCell {
param([int]$x, [int]$y)
$rect = new-rectangle $x $y $x $y
[System.Management.Automation.Host.buffercell[,]]$cells = $host.ui.RawUI.GetBufferContents($rect)
$cells[0,0]
}
function Set-BufferCell {
[outputtype([System.Management.Automation.Host.buffercell])]
param(
[int]$x,
[int]$y,
[System.Management.Automation.Host.buffercell]$cell
)
$rect = new-rectangle $x $y $x $y
# return previous
get-buffercell $x $y
# use "fill" overload with single cell rect
$host.ui.rawui.SetBufferContents($rect, $cell)
}
function New-BufferCell {
param(
[string]$Character,
[consolecolor]$ForeGroundColor = $(get-buffercell 0 0).foregroundcolor,
[consolecolor]$BackGroundColor = $(get-buffercell 0 0).backgroundcolor,
[System.Management.Automation.Host.BufferCellType]$BufferCellType = "Complete"
)
$cell = new-object System.Management.Automation.Host.BufferCell
$cell.Character = $Character
$cell.ForegroundColor = $foregroundcolor
$cell.BackgroundColor = $backgroundcolor
$cell.BufferCellType = $buffercelltype
$cell
}
function log {
param($message)
[diagnostics.debug]::WriteLine($message, "PS ScreenSaver")
}
#
# Main entry point for starting the animation
#
function Start-CMatrix {
param(
[int]$maxcolumns = 8,
[int]$frameWait = 100
)
$script:winsize = $host.ui.rawui.WindowSize
$script:columns = @{} # key: xpos; value; column
$script:framenum = 0
$prevbg = $host.ui.rawui.BackgroundColor
$host.ui.rawui.BackgroundColor = "black"
cls
$done = $false
while (-not $done) {
Write-FrameBuffer -maxcolumns $maxcolumns
Show-FrameBuffer
sleep -milli $frameWait
$done = $host.ui.rawui.KeyAvailable
}
$host.ui.rawui.BackgroundColor = $prevbg
cls
}
# TODO: actually write into buffercell[,] framebuffer
function Write-FrameBuffer {
param($maxColumns)
# do we need a new column?
if ($columns.count -lt $maxcolumns) {
# incur staggering of columns with get-random
# by only adding a new one 50% of the time
if ((get-random -min 0 -max 10) -lt 5) {
# search for a column not current animating
do {
$x = get-random -min 0 -max ($winsize.width - 1)
} while ($columns.containskey($x))
$columns.add($x, (new-column $x))
}
}
$script:framenum++
}
# TODO: setbuffercontent with buffercell[,] framebuffer
function Show-FrameBuffer {
param($frame)
$completed=@()
# loop through each active column and animate a single step/frame
foreach ($entry in $columns.getenumerator()) {
$column = $entry.value
# if column has finished animating, add to the "remove" pile
if (-not $column.step()) {
$completed += $entry.key
}
}
# cannot remove from collection while enumerating, so do it here
foreach ($key in $completed) {
$columns.remove($key)
}
}
function New-Column {
param($x)
# return a new module that represents the column of letters and its state
# we also pass in a reference to the main screensaver module to be able to
# access our console framebuffer functions.
new-module -ascustomobject -name "col_$x" -script {
param(
[int]$startx,
[PSModuleInfo]$parentModule
)
$script:xpos = $startx
$script:ylimit = $host.ui.rawui.WindowSize.Height
[int]$script:head = 1
[int]$script:fade = 0
[int]$script:fadelen = [math]::Abs($ylimit / 3)
$script:fadelen += (get-random -min 0 -max $fadelen)
function Step {
# reached the bottom yet?
if ($head -lt $ylimit) {
& $parentModule Set-BufferCell $xpos $head (
& $parentModule New-BufferCell -Character `
([char](get-random -min 65 -max 122)) -Fore white) > $null
& $parentModule Set-BufferCell $xpos ($head - 1) (
& $parentModule New-BufferCell -Character `
([char](get-random -min 65 -max 122)) -Fore green) > $null
$script:head++
}
# time to start rendering the darker green "tail?"
if ($head -gt $fadelen) {
& $parentModule Set-BufferCell $xpos $fade (
& $parentModule New-BufferCell -Character `
([char](get-random -min 65 -max 122)) -Fore darkgreen) > $null
$script:fade++
}
# are we done animating?
if ($fade -lt $ylimit) {
return $true
}
$false
}
Export-ModuleMember -function Step
} -args $x, $executioncontext.sessionstate.module
}
function Start-ScreenSaver {
# feel free to tweak maxcolumns and frame delay
# currently 8 columns with 50ms wait
Start-CMatrix -max 8 -frame 50
}
function Register-Timer {
# prevent prompt from reregistering if explicit disable
if ($_ssdisabled) {
return
}
if (-not (Test-Path variable:global:_ssjob)) {
# register our counter job
$global:_ssjob = Register-ObjectEvent $_sstimer elapsed -action {
$global:_sscount++;
$global:_sssrcid = $event.sourceidentifier
# hit timeout yet?
if ($_sscount -eq $_sstimeout) {
# disable this event (prevent choppiness)
Unregister-Event -sourceidentifier $_sssrcid
Remove-Variable _ssjob -scope Global
sleep -seconds 1
# start ss
Start-ScreenSaver
}
}
}
}
function Enable-ScreenSaver {
if (-not $_ssdisabled) {
write-warning "Screensaver is not disabled."
return
}
$global:_ssdisabled = $false
}
function Disable-ScreenSaver {
if ((Test-Path variable:global:_ssjob)) {
$global:_ssdisabled = $true
Unregister-Event -SourceIdentifier $_sssrcid
Remove-Variable _ssjob -Scope global
} else {
write-warning "Screen saver is not enabled."
}
}
function Get-ScreenSaverTimeout {
new-timespan -seconds $global:_sstimeout
}
function Set-ScreenSaverTimeout {
[cmdletbinding(defaultparametersetname="int")]
param(
[parameter(position=0, mandatory=$true, parametersetname="int")]
[int]$Seconds,
[parameter(position=0, mandatory=$true, parametersetname="timespan")]
[Timespan]$Timespan
)
if ($pscmdlet.parametersetname -eq "int") {
$timespan = new-timespan -seconds $Seconds
}
if ($timespan.totalseconds -lt 1) {
throw "Timeout must be greater than 0 seconds."
}
$global:_sstimeout = $timespan.totalseconds
}
#
# Eventing / Timer Hooks, clean up and Prompt injection
#
# timeout
[int]$global:_sstimeout = 180 # default 3 minutes
# tick count
[int]$global:_sscount = 0
# modify current prompt function to reset ticks counter to 0 and
# to reregister timer, while saving for later on module onload
$self = $ExecutionContext.SessionState.Module
$function:global:prompt = $self.NewBoundScriptBlock(
[scriptblock]::create(
("{0}`n`$global:_sscount = 0`nRegister-Timer" `
-f ($global:_ssprompt = gc function:prompt))))
# configure our timer
$global:_sstimer = new-object system.timers.timer
$_sstimer.Interval = 1000 # tick once a second
$_sstimer.AutoReset = $true
$_sstimer.start()
# we start out disabled - use enable-screensaver
$global:_ssdisabled = $true
# arrange clean up on module remove
$ExecutionContext.SessionState.Module.OnRemove = {
# restore prompt
$function:global:prompt = [scriptblock]::Create($_ssprompt)
# kill off eventing subscriber, if one exists
if ($_sssrcid) {
Unregister-Event -SourceIdentifier $_sssrcid
}
# clean up timer
$_sstimer.Dispose()
# clear out globals
remove-variable _ss* -scope global
}
Export-ModuleMember -function Start-ScreenSaver, Get-ScreenSaverTimeout, `
Set-ScreenSaverTimeout, Enable-ScreenSaver, Disable-ScreenSaver
|
PowerShellCorpus/PoshCode/app memory deltas.ps1
|
app memory deltas.ps1
|
## Use ps to measure Application Memory Deltas
## Run '.\\ws_diff [Interval in Seconds] [Process Name] or
## to log all processes continually every 10 seconds -- 'while (1) {.\\WS_diff.ps1 10 cmd >> ps_out.txt }'
# Create args as Variables or Objects
$sleep_time = $args[0]
#$sleep_time = 10
# Create or define PS_Array. Default is ps is called without args.
# Then take measurements $now, $then, $count
if ($args[1] -eq $NULL )
{
$then = ps | %{$_ | Select Name,ID,WorkingSet,PrivateMemorySize,VirtualMemorySize}
sleep -seconds $sleep_time
$now = ps | %{$_ | Select Name,ID,WorkingSet,PrivateMemorySize,VirtualMemorySize}
$count = ($now | Select Name).count
}
else
{
$ps_array = ( ps $args[1] )
$then = ps -inputobject $ps_array | %{$_ | Select Name,ID,WorkingSet,PrivateMemorySize,VirtualMemorySize}
sleep -seconds $sleep_time
$now = ps -inputobject $ps_array | %{$_ | Select Name,ID,WorkingSet,PrivateMemorySize,VirtualMemorySize}
$count = ($now | Select Name).count
}
# Declare Sample Time Measurement
# Declare Hours.Minutes.Seconds.Milliseconds in body of loop for more accuracy
$date = (get-date -format g)
# Write output and find diffs. Check if process has multiple instances first
if ( $count -gt 1 )
{
$array_out = 0..$count |
%{
$date + "," +
[DateTime]::UtcNow.TimeOfDay.Hours + ":" +
[DateTime]::UtcNow.TimeOfDay.Minutes + ":" +
[DateTime]::UtcNow.TimeOfDay.Seconds + ":" +
[DateTime]::UtcNow.TimeOfDay.Milliseconds + "," +
$sleep_time + "," + $now[$_].Name + "," + $now[$_].ID + "," +
$now[$_].WorkingSet + "," +
$now[$_].PrivateMemorySize + "," +
$now[$_].VirtualMemorySize + "," +
( ($now[$_].WorkingSet) - ($then[$_].WorkingSet) ) + "," +
( ($now[$_].PrivateMemorySize) - ($then[$_].PrivateMemorySize) ) + "," +
( ($now[$_].VirtualMemorySize) - ($then[$_].VirtualMemorySize) )
}
}
else
{
$array_out =
$date + "," +
[DateTime]::UtcNow.TimeOfDay.Hours + ":" +
[DateTime]::UtcNow.TimeOfDay.Minutes + ":" +
[DateTime]::UtcNow.TimeOfDay.Seconds + ":" +
[DateTime]::UtcNow.TimeOfDay.Milliseconds + "," +
$sleep_time + "," + $now.Name + "," + $now.ID + "," +
$now.WorkingSet + "," +
$now.PrivateMemorySize + "," +
$now.VirtualMemorySize + "," +
( ($now.WorkingSet) - ($then.WorkingSet) ) + "," +
( ($now.PrivateMemorySize) - ($then.PrivateMemorySize) ) + "," +
( ($now.VirtualMemorySize) - ($then.VirtualMemorySize) )
}
write $array_out
|
PowerShellCorpus/PoshCode/Upgrade-VMToolsNoReboot.ps1
|
Upgrade-VMToolsNoReboot.ps1
|
#========================================================================
# Created on: 7/11/2012 3:59 PM
# Created by: Clint Jones
# Organization: Virtually Genius!
# Filename: Upgrade-VMToolsNoReboot
#========================================================================
Add-PSSnapin VMware.VimAutomation.Core
Connect-VIServer -Server <vi server> -Credential (Get-Credential)
$cluster = Read-Host "Cluster to upgrade:"
$oldTools = Get-Cluster $cluster | Get-VM | % {Get-View $_.ID} | Where {$_.guest.toolsstatus -match "toolsOld"}
foreach ($vm in $oldTools)
{
Get-VMGuest $vm.Name | Update-Tools -NoReboot -RunAsync
}
|
PowerShellCorpus/PoshCode/Xml Module 6.1.ps1
|
Xml Module 6.1.ps1
|
#requires -version 2.0
# Improves over the built-in Select-XML by leveraging Remove-XmlNamespace http`://poshcode.org/1492
# to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations
# and prefixes are removed from all XML nodes (by an XSL transform) before searching.
# IMPORTANT: returned results *will not* have namespaces in them, even if the input XML did.
# Also, only raw XmlNodes are returned from this function, so the output isn't completely compatible
# with the built in Select-Xml. It's equivalent to using Select-Xml ... | Select-Object -Expand Node
# Version History:
# Select-Xml 2.0 This was the first script version I wrote.
# it didn't function identically to the built-in Select-Xml with regards to parameter parsing
# Select-Xml 2.1 Matched the built-in Select-Xml parameter sets, it's now a drop-in replacement
# BUT only if you were using the original with: Select-Xml ... | Select-Object -Expand Node
# Select-Xml 2.2 Fixes a bug in the -Content parameterset where -RemoveNamespace was *presumed*
# Version 3.0 Added New-XDocument and associated generation functions for my XML DSL
# Version 3.1 Fixed a really ugly bug in New-XDocument in 3.0 which I should not have released
# Version 4.0 Never content to leave well enough alone, I've completely reworked New-XDocument
# Version 4.1 Tweaked namespaces again so they don't cascade down when they shouldn't. Got rid of the unnecessary stack.
# Version 4.2 Tightened xml: only cmdlet, function, and external scripts, with "-" in their names are exempted from being converted into xml tags.
# Fixed some alias error messages caused when PSCX is already loaded (we overwrite their aliases for cvxml and fxml)
# Version 4.3 Added a Path parameter set to Format-Xml so you can specify xml files for prety printing
# Version 4.5 Fixed possible [Array]::Reverse call on a non-array in New-XElement (used by New-XDocument)
# Work around possible variable slipping on null values by:
# 1) allowing -param:$value syntax (which doesn't fail when $value is null)
# 2) testing for -name syntax on the value and using it as an attribute instead
# Version 4.6 Added -Arguments to Convert-Xml so that you can pass arguments to XSLT transforms!
# Note: when using strings for xslt, make sure you single quote them or escape the $ signs.
# Version 4.7 Fixed a typo in the namespace parameter of Select-Xml
# Version 4.8 Fixed up some uses of Select-Xml -RemoveNamespace
# Version 5.0 Added Update-Xml to allow setting xml attributes or node content
# Version 6.0 Major cleanup, breaking changes.
# - Added Get-XmlContent and Set-XmlContent for loading/saving XML from files or strings
# - Removed Path and Content parameters from the other functions (it greatly simplifies thost functions, and makes the whole thing more maintainable)
# - Updated Update-Xml to support adding nodes "before" and "after" other nodes, and to support "remove"ing nodes
# Version 6.1 Update for PowerShell 3.0
function Add-Accelerator {
<#
.Synopsis
Add a type accelerator to the current session
.Description
The Add-Accelerator function allows you to add a simple type accelerator (like [regex]) for a longer type (like [System.Text.RegularExpressions.Regex]).
.Example
Add-Accelerator list System.Collections.Generic.List``1
$list = New-Object list[string]
Creates an accelerator for the generic List[T] collection type, and then creates a list of strings.
.Example
Add-Accelerator "List T", "GList" System.Collections.Generic.List``1
$list = New-Object "list t[string]"
Creates two accelerators for the Generic List[T] collection type.
.Parameter Accelerator
The short form accelerator should be just the name you want to use (without square brackets).
.Parameter Type
The type you want the accelerator to accelerate (without square brackets)
.Notes
When specifying multiple values for a parameter, use commas to separate the values.
For example, "-Accelerator string, regex".
PowerShell requires arguments that are "types" to NOT have the square bracket type notation, because of the way the parsing engine works. You can either just type in the type as System.Int64, or you can put parentheses around it to help the parser out: ([System.Int64])
Also see the help for Get-Accelerator and Remove-Accelerator
.Link
http://huddledmasses.org/powershell-2-ctp3-custom-accelerators-finally/
#>
[CmdletBinding()]
param(
[Parameter(Position=0,ValueFromPipelineByPropertyName=$true)]
[Alias("Key","Name")]
[string[]]$Accelerator
,
[Parameter(Position=1,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[Alias("Value","FullName")]
[type]$Type
)
process {
# add a user-defined accelerator
foreach($a in $Accelerator) {
if($xlr8r::AddReplace) {
$xlr8r::AddReplace( $a, $Type)
} else {
$null = $xlr8r::Remove( $a )
$xlr8r::Add( $a, $Type)
}
trap [System.Management.Automation.MethodInvocationException] {
if($xlr8r::get.keys -contains $a) {
if($xlr8r::get[$a] -ne $Type) {
Write-Error "Cannot add accelerator [$a] for [$($Type.FullName)]`n [$a] is already defined as [$($xlr8r::get[$a].FullName)]"
}
Continue;
}
throw
}
}
}
}
&{
$local:xlr8r = [psobject].assembly.gettype("System.Management.Automation.TypeAccelerators")
$local:xlinq = [Reflection.Assembly]::Load("System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
$xlinq.GetTypes() | ? { $_.IsPublic -and !$_.IsSerializable -and $_.Name -ne "Extensions" -and !$xlr8r::Get[$_.Name] } | Add-Accelerator
Add-Accelerator "Dictionary" "System.Collections.Generic.Dictionary``2, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
Add-Accelerator "Dictionary", "System.Collections.Generic.Dictionary``2, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
Add-Accelerator "PSParser", "System.Management.Automation.PSParser, System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
}
function Get-XmlContent {
#.Synopsis
# Load an XML file as an XmlDocument
param(
# Specifies a string that contains the XML to load, or a path to a file which has the XML to load (wildcards are permitted).
[Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath","Path")]
[String[]]$Content
,
# If set, loads XML with all namespace qualifiers removed, and all entities expanded.
[Alias("Rn","Rm")]
[Switch]$RemoveNamespace
)
begin {
[Text.StringBuilder]$XmlContent = [String]::Empty
[bool]$Path = $true
}
process {
if($Path -and ($Path = Test-Path @($Content)[0] -EA 0)) {
foreach($file in Resolve-Path $Content) {
$xml = New-Object System.Xml.XmlDocument;
if($file.Provider.Name -eq "FileSystem") {
Write-Verbose $file.ProviderPath
$xml.Load( $file.ProviderPath )
} else {
$ofs = "`n"
$xml.LoadXml( ([String](Get-Content $file)) )
}
if($RemoveNamespace) {
[System.Xml.XmlNode[]]$Xml = @(Remove-XmlNamespace -Xml $node)
}
Write-Output $xml
}
} else {
# If the "path" parameter isn't actually a path, assume that it's actually content
foreach($line in $content) {
$null = $XmlContent.AppendLine( $line )
}
}
}
end {
if(!$Path) {
$xml = New-Object System.Xml.XmlDocument;
$xml.LoadXml( $XmlContent.ToString() )
if($RemoveNamespace) {
$Xml = @(Remove-XmlNamespace -Xml $xml)
}
Write-Output $xml
}
}}
Set-Alias Import-Xml Get-XmlContent
Set-Alias ipxml Get-XmlContent
Set-Alias ipx Get-XmlContent
Set-Alias Get-Xml Get-XmlContent
Set-Alias gxml Get-XmlContent
Set-Alias gx Get-XmlContent
function Set-XmlContent {
param(
[Parameter(Mandatory=$true, Position=1)]
[Alias("PSPath")]
[String]$Path
,
# Specifies one or more XML nodes to search.
[Parameter(Position=5,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[Xml]$Xml
)
process {
$xml.Save( $Path )
}
}
Set-Alias Export-Xml Set-XmlContent
Set-Alias epxml Set-XmlContent
Set-Alias epx Set-XmlContent
Set-Alias Set-Xml Set-XmlContent
Set-Alias sxml Set-XmlContent
Set-Alias sx Set-XmlContent
function Format-Xml {
#.Synopsis
# Pretty-print formatted XML source
#.Description
# Runs an XmlDocument through an auto-indenting XmlWriter
#.Parameter Xml
# The Xml Document
#.Parameter Path
# The path to an xml document (on disc or any other content provider).
#.Parameter Indent
# The indent level (defaults to 2 spaces)
#.Example
# [xml]$xml = get-content Data.xml
# C:\\PS>Format-Xml $xml
#.Example
# get-content Data.xml | Format-Xml
#.Example
# Format-Xml C:\\PS\\Data.xml
#.Example
# ls *.xml | Format-Xml
#
[CmdletBinding()]
param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Document")]
[xml]$Xml
,
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName="File")]
[Alias("PsPath")]
[string]$Path
,
[Parameter(Mandatory=$false)]
$Indent=2
)
process {
## Load from file, if necessary
if($Path) { [xml]$xml = Get-Content $Path }
$StringWriter = New-Object System.IO.StringWriter
$XmlWriter = New-Object System.Xml.XmlTextWriter $StringWriter
$xmlWriter.Formatting = "indented"
$xmlWriter.Indentation = $Indent
$xml.WriteContentTo($XmlWriter)
$XmlWriter.Flush()
$StringWriter.Flush()
Write-Output $StringWriter.ToString()
}}
Set-Alias fxml Format-Xml -EA 0
Set-Alias fx Format-Xml -EA 0
function Select-XmlNodeInternal {
[CmdletBinding()]
param([Xml.XmlNode[]]$Xml, [String[]]$XPath, [Hashtable]$NamespaceManager)
begin {
Write-Verbose "XPath = $($XPath -join ',')"
foreach($node in $xml) {
if($NamespaceManager) {
$nsManager = new-object System.Xml.XmlNamespaceManager $node.NameTable
foreach($ns in $NamespaceManager.GetEnumerator()) {
$nsManager.AddNamespace( $ns.Key, $ns.Value )
}
Write-Verbose "Names = $($nsManager | % { @{ $_ = $nsManager.LookupNamespace($_) } } | Out-String)"
}
foreach($path in $xpath) {
$node.SelectNodes($path, $nsManager)
}
}
}}
function Select-Xml {
#.Synopsis
# The Select-XML cmdlet lets you use XPath queries to search for text in XML strings and documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched.
#.Description
# Improves over the built-in Select-XML by leveraging Remove-XmlNamespace to provide a -RemoveNamespace parameter -- if it's supplied, all of the namespace declarations and prefixes are removed from all XML nodes (by an XSL transform) before searching.
#
# However, only raw XmlNodes are returned from this function, so the output isn't currently compatible with the built in Select-Xml, but is equivalent to using Select-Xml ... | Select-Object -Expand Node
#
# Also note that if the -RemoveNamespace switch is supplied the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically.
[CmdletBinding(DefaultParameterSetName="Xml")]
param(
# Specifies an XPath search query. The query language is case-sensitive. This parameter is required.
[Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[Alias("Query")]
[String[]]$XPath
,
# Specifies a string that contains the XML to search. You can also pipe strings to Select-XML.
[Parameter(ParameterSetName="Content",Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$Content
,
# Specifies the path and file names of the XML files to search. Wildcards are permitted.
[Parameter(Position=5,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("PSPath")]
[String[]]$Path
,
# Specifies one or more XML nodes to search.
[Parameter(Position=5,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
# Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}.
[Parameter(Position=10,Mandatory=$false)]
[ValidateNotNullOrEmpty()]
[Alias("Ns")]
[Hashtable]$Namespace
,
# Allows the execution of XPath queries without namespace qualifiers.
#
# If you specify the -RemoveNamespace switch, all namespace declarations and prefixes are actually removed from the Xml before the XPath search query is evaluated, and your XPath query should therefore NOT contain any namespace prefixes.
#
# Note that this means that the returned results *will not* have namespaces in them, even if the input XML did, and entities get expanded automatically.
[Alias("Rn","Rm")]
[Switch]$RemoveNamespace
)
begin {
$NSM = $Null; if($PSBoundParameters.ContainsKey("Namespace")) { $NSM = $Namespace }
$XmlNodes = New-Object System.Xml.XmlNode[] 1
if($PSCmdlet.ParameterSetName -eq "Content") {
$XmlNodes = ConvertTo-Xml $Content -RemoveNamespace:$RemoveNamespace
Select-XmlNodeInternal $XmlNodes $XPath $NSM
}
}
process {
switch($PSCmdlet.ParameterSetName) {
"Path" {
$node = ConvertTo-Xml $Path -RemoveNamespace:$RemoveNamespace
Select-XmlNodeInternal $node $XPath $NSM
}
"Xml" {
foreach($node in $Xml) {
if($RemoveNamespace) {
[Xml]$node = Remove-XmlNamespace -Xml $node
}
Select-XmlNodeInternal $node $XPath $NSM
}
}
}
}}
Set-Alias slxml Select-Xml -EA 0
Set-Alias slx Select-Xml -EA 0
function Update-Xml {
#.Synopsis
# The Update-XML cmdlet lets you use XPath queries to replace text in nodes in XML documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched.
#.Description
# Allows you to update an attribute value, xml node contents, etc.
#
#.Notes
# We still need to implement RemoveNode and RemoveAttribute and even ReplaceNode
[CmdletBinding(DefaultParameterSetName="Set")]
param(
# Specifies an XPath for an element where you want to insert the new node.
[Parameter(ParameterSetName="Before",Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[Switch]$Before
,
# Specifies an XPath for an element where you want to insert the new node.
[Parameter(ParameterSetName="After",Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[Switch]$After
,
# If set, the new value will be added as a new child of the node identified by the XPath
[Parameter(ParameterSetName="Append",Mandatory=$true)]
[Switch]$Append
,
# If set, the node identified by the XPath will be removed instead of set
[Parameter(ParameterSetName="Remove",Mandatory=$true)]
[Switch]$Remove
,
# If set, the node identified by the XPath will be Replace instead of set
[Parameter(ParameterSetName="Replace",Mandatory=$true)]
[Switch]$Replace
,
# Specifies an XPath for the node to update. This could be an element node *or* an attribute node (remember: //element/@attribute )
[Parameter(Position=1,Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$XPath
,
# The new value to place in the xml
[Parameter(Position=2,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[String]$Value
,
# Specifies one or more XML nodes to search.
[Parameter(Position=5,Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
# Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}.
[Parameter(Position=10,Mandatory=$false)]
[ValidateNotNullOrEmpty()]
[Alias("Ns")]
[Hashtable]$Namespace
,
# Output the XML documents after adding updating them
[Switch]$Passthru
)
process
{
foreach($XmlNode in $Xml) {
$select = @{}
$select.Xml = $XmlNode
$select.XPath = $XPath
if($Namespace) {
$select.Namespace = $Namespace
}
$document =
if($XmlNode -is [System.Xml.XmlDocument]) {
$XmlNode
} else {
$XmlNode.get_OwnerDocument()
}
if($xValue = $Value -as [Xml]) {
$xValue = $document.ImportNode($xValue.SelectSingleNode("/*"), $true)
}
$nodes = Select-Xml @Select | Where-Object { $_ }
if(@($nodes).Count -eq 0) { Write-Warning "No nodes matched your XPath, nothing will be updated" }
foreach($node in $nodes) {
$select.XPath = "$XPath/parent::*"
$parent = Select-Xml @Select
if(!$xValue) {
if($node -is [System.Xml.XmlAttribute] -and $Value.Contains("=")) {
$aName, $aValue = $Value.Split("=",2)
if($aName.Contains(":")){
$ns,$name = $aName.Split(":",2)
$xValue = $document.CreateAttribute( $name, $Namespace[$ns] )
} else {
$xValue = $document.CreateAttribute( $aName )
}
$xValue.Value = $aValue
}
}
switch($PSCmdlet.ParameterSetName) {
"Before" {
$null = $parent.InsertBefore( $xValue, $node )
}
"After" {
$null = $parent.InsertAfter( $xValue, $node )
}
"Append" {
$null = $parent.AppendChild( $xValue )
}
"Remove" {
$null = $parent.RemoveChild( $node )
}
"Replace" {
if(!$xValue) {
$xValue = $document.CreateTextNode( $Value )
}
$null = $parent.ReplaceChild( $xValue, $node )
}
"Set" {
if(!$xValue -and $node."#text") {
$node."#text" = $Value
} else {
if($node -is [System.Xml.XmlElement]) {
if(!$xValue) {
$xValue = $document.CreateTextNode( $Value )
}
$null = $node.set_innerXml("")
$null = $node.AppendChild($xValue)
}
elseif($node -is [System.Xml.XmlAttribute]) {
$node.Value = $Value
} else {
Write-Warning "$XPath selects a node of type $($node.GetType()), which we haven't handled. Please add that handler!"
}
}
}
}
}
if($Passthru) {
Write-Output $XmlNode
}
}
}}
Set-Alias uxml Update-Xml -EA 0
Set-Alias ux Update-Xml -EA 0
function Convert-Node {
#.Synopsis
# Convert a single XML Node via XSL stylesheets
[CmdletBinding(DefaultParameterSetName="Reader")]
param(
[Parameter(ParameterSetName="ByNode",Mandatory=$true,ValueFromPipeline=$true)]
[System.Xml.XmlNode]$Node
,
[Parameter(ParameterSetName="Reader",Mandatory=$true,ValueFromPipeline=$true)]
[System.Xml.XmlReader]$XmlReader
,
[Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)]
[System.Xml.Xsl.XslCompiledTransform]$StyleSheet
,
[Parameter(Position=2,Mandatory=$false)]
[Alias("Parameters")]
[hashtable]$Arguments
)
PROCESS {
if($PSCmdlet.ParameterSetName -eq "ByNode") {
$XmlReader = New-Object Xml.XmlNodeReader $node
}
$output = New-Object IO.StringWriter
$argList = $null
if($Arguments) {
$argList = New-Object System.Xml.Xsl.XsltArgumentList
foreach($arg in $Arguments.GetEnumerator()) {
$namespace, $name = $arg.Key -split ":"
## Fix namespace
if(!$name) {
$name = $Namespace
$namespace = ""
}
Write-Verbose "ns:$namespace name:$name value:$($arg.Value)"
$argList.AddParam($name,"$namespace",$arg.Value)
}
}
$StyleSheet.Transform( $XmlReader, $argList, $output )
Write-Output $output.ToString()
}
}
function Convert-Xml {
#.Synopsis
# The Convert-XML function lets you use Xslt to transform XML strings and documents.
#.Description
# Documentation TODO
[CmdletBinding(DefaultParameterSetName="Xml")]
param(
# Specifies one or more XML nodes to process.
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
,
# Specifies an Xml StyleSheet to transform with...
[Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]
[ValidateNotNullOrEmpty()]
[Alias("StyleSheet")]
[String]$Xslt
,
# Specify arguments to the XSL Transformation
[Alias("Parameters")]
[hashtable]$Arguments
)
begin {
$StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform
if(Test-Path $Xslt -EA 0) {
Write-Verbose "Loading Stylesheet from $(Resolve-Path $Xslt)"
$StyleSheet.Load( (Resolve-Path $Xslt) )
} else {
$OFS = "`n"
Write-Verbose "$Xslt"
$StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader $Xslt))))
}
}
process {
foreach($node in $Xml) {
Convert-Node -Xml (New-Object Xml.XmlNodeReader $node) $StyleSheet $Arguments
}
}
}
Set-Alias cvxml Convert-Xml -EA 0
function Remove-XmlNamespace {
#.Synopsis
# Removes namespace definitions and prefixes from xml documents
#.Description
# Runs an xml document through an XSL Transformation to remove namespaces from it if they exist.
# Entities are also naturally expanded
#.Parameter Content
# Specifies a string that contains the XML to transform.
#.Parameter Path
# Specifies the path and file names of the XML files to transform. Wildcards are permitted.
#
# There will bne one output document for each matching input file.
#.Parameter Xml
# Specifies one or more XML documents to transform
[CmdletBinding(DefaultParameterSetName="Xml")]
PARAM(
[Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias("Node")]
[System.Xml.XmlNode[]]$Xml
)
BEGIN {
$StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform
$StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader @"
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:template match="/|comment()|processing-instruction()">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
"@))))
[Text.StringBuilder]$XmlContent = [String]::Empty
}
PROCESS {
$Xml | Convert-Node $StyleSheet
}
}
Set-Alias rmns Remove-XmlNamespace -EA 0
Set-Alias rmxns Remove-XmlNamespace -EA 0
######## Helper functions for working with CliXml
function ConvertFrom-CliXml {
param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[String[]]$InputObject
)
begin
{
$OFS = "`n"
[String]$xmlString = ""
}
process
{
$xmlString += $InputObject
}
end
{
$type = [psobject].assembly.gettype("System.Management.Automation.Deserializer")
$ctor = $type.getconstructor("instance,nonpublic", $null, @([xml.xmlreader]), $null)
$sr = new-object System.IO.StringReader $xmlString
$xr = new-object System.Xml.XmlTextReader $sr
$deserializer = $ctor.invoke($xr)
$method = @($type.getmethods("nonpublic,instance") | where-object {$_.name -like "Deserialize"})[1]
$done = $type.getmethod("Done", [System.Reflection.BindingFlags]"nonpublic,instance")
while (!$done.invoke($deserializer, @()))
{
try {
$method.invoke($deserializer, "")
} catch {
write-warning "Could not deserialize ${string}: $_"
}
}
$xr.Close()
$sr.Dispose()
}
}
function ConvertTo-CliXml {
param(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
[PSObject[]]$InputObject
)
begin {
$type = [psobject].assembly.gettype("System.Management.Automation.Serializer")
$ctor = $type.getconstructor("instance,nonpublic", $null, @([System.Xml.XmlWriter]), $null)
$sw = new-object System.IO.StringWriter
$xw = new-object System.Xml.XmlTextWriter $sw
$serializer = $ctor.invoke($xw)
$method = $type.getmethod("Serialize", "nonpublic,instance", $null, [type[]]@([object]), $null)
$done = $type.getmethod("Done", [System.Reflection.BindingFlags]"nonpublic,instance")
}
process {
try {
[void]$method.invoke($serializer, $InputObject)
} catch {
write-warning "Could not serialize $($InputObject.gettype()): $_"
}
}
end {
[void]$done.invoke($serializer, @())
$sw.ToString()
$xw.Close()
$sw.Dispose()
}
}
######## From here down is all the code related to my XML DSL:
function New-XDocument {
#.Synopsis
# Creates a new XDocument (the new xml document type)
#.Description
# This is the root for a new XML mini-dsl, akin to New-BootsWindow for XAML
# It creates a new XDocument, and takes scritpblock(s) to define it's contents
#.Parameter root
# The root node name
#.Parameter version
# Optional: the XML version. Defaults to 1.0
#.Parameter encoding
# Optional: the Encoding. Defaults to UTF-8
#.Parameter standalone
# Optional: whether to specify standalone in the xml declaration. Defaults to "yes"
#.Parameter args
# this is where all the dsl magic happens. Please see the Examples. :)
#
#.Example
# [string]$xml = New-XDocument rss -version "2.0" {
# channel {
# title {"Test RSS Feed"}
# link {"http`://HuddledMasses.org"}
# description {"An RSS Feed generated simply to demonstrate my XML DSL"}
# item {
# title {"The First Item"}
# link {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"}
# guid -isPermaLink true {"http`://huddledmasses.org/new-site-new-layout-lost-posts/"}
# description {"Ema Lazarus' Poem"}
# pubDate {(Get-Date 10/31/2003 -f u) -replace " ","T"}
# }
# }
# }
#
# C:\\PS>$xml.Declaration.ToString() ## I can't find a way to have this included in the $xml.ToString()
# C:\\PS>$xml.ToString()
#
# <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
# <rss version="2.0">
# <channel>
# <title>Test RSS Feed</title>
# <link>http ://HuddledMasses.org</link>
# <description>An RSS Feed generated simply to demonstrate my XML DSL</description>
# <item>
# <title>The First Item</title>
# <link>http ://huddledmasses.org/new-site-new-layout-lost-posts/</link>
# <guid isPermaLink="true">http ://huddledmasses.org/new-site-new-layout-lost-posts/</guid>
# <description>Ema Lazarus' Poem</description>
# <pubDate>2003-10-31T00:00:00Z</pubDate>
# </item>
# </channel>
# </rss>
#
#
# Description
# -----------
# This example shows the creation of a complete RSS feed with a single item in it.
#
# NOTE that the backtick in the http`: in the URLs in the input is unecessary, and I added the space after the http: in the URLs in the output -- these are accomodations to PoshCode's spam filter. Backticks are not need in the input, and spaces do not appear in the actual output.
#
#
#.Example
# [XNamespace]$atom="http`://www.w3.org/2005/Atom"
# C:\\PS>[XNamespace]$dc = "http`://purl.org/dc/elements/1.1"
#
# C:\\PS>New-XDocument ($atom + "feed") -Encoding "UTF-16" -$([XNamespace]::Xml +'lang') "en-US" -dc $dc {
# title {"Test First Entry"}
# link {"http`://HuddledMasses.org"}
# updated {(Get-Date -f u) -replace " ","T"}
# author {
# name {"Joel Bennett"}
# uri {"http`://HuddledMasses.org"}
# }
# id {"http`://huddledmasses.org/" }
#
# entry {
# title {"Test First Entry"}
# link {"http`://HuddledMasses.org/new-site-new-layout-lost-posts/" }
# id {"http`://huddledmasses.org/new-site-new-layout-lost-posts/" }
# updated {(Get-Date 10/31/2003 -f u) -replace " ","T"}
# summary {"Ema Lazarus' Poem"}
# link -rel license -href "http`://creativecommons.org/licenses/by/3.0/" -title "CC By-Attribution"
# dc:rights { "Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)" }
# category -scheme "http`://huddledmasses.org/tag/" -term "huddled-masses"
# }
# } | % { $_.Declaration.ToString(); $_.ToString() }
#
# <?xml version="1.0" encoding="UTF-16" standalone="yes"?>
# <feed xml:lang="en-US" xmlns="http ://www.w3.org/2005/Atom">
# <title>Test First Entry</title>
# <link>http ://HuddledMasses.org</link>
# <updated>2009-07-29T17:25:49Z</updated>
# <author>
# <name>Joel Bennett</name>
# <uri>http ://HuddledMasses.org</uri>
# </author>
# <id>http ://huddledmasses.org/</id>
# <entry>
# <title>Test First Entry</title>
# <link>http ://HuddledMasses.org/new-site-new-layout-lost-posts/</link>
# <id>http ://huddledmasses.org/new-site-new-layout-lost-posts/</id>
# <updated>2003-10-31T00:00:00Z</updated>
# <summary>Ema Lazarus' Poem</summary>
# <link rel="license" href="http ://creativecommons.org/licenses/by/3.0/" title="CC By-Attribution" />
# <dc:rights>Copyright 2009, Some rights reserved (licensed under the Creative Commons Attribution 3.0 Unported license)</dc:rights>
# <category scheme="http ://huddledmasses.org/tag/" term="huddled-masses" />
# </entry>
# </feed>
#
#
# Description
# -----------
# This example shows the use of a default namespace, as well as additional specific namespaces for the "dc" namespace. It also demonstrates how you can get the <?xml?> declaration which does not appear in a simple .ToString().
#
# NOTE that the backtick in the http`: in the URLs in the input is unecessary, and I added the space after the http: in the URLs in the output -- these are accomodations to PoshCode's spam filter. Backticks are not need in the input, and spaces do not appear in the actual output.#
#
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true, Position = 0)]
[System.Xml.Linq.XName]$root
,
[Parameter(Mandatory = $false)]
[string]$Version = "1.0"
,
[Parameter(Mandatory = $false)]
[string]$Encoding = "UTF-8"
,
[Parameter(Mandatory = $false)]
[string]$Standalone = "yes"
,
[AllowNull()][AllowEmptyString()][AllowEmptyCollection()]
[Parameter(Position=99, Mandatory = $false, ValueFromRemainingArguments=$true)]
[PSObject[]]$args
)
BEGIN {
$script:NameSpaceHash = New-Object 'Dictionary[String,XNamespace]'
if($root.NamespaceName) {
$script:NameSpaceHash.Add("", $root.Namespace)
}
}
PROCESS {
New-Object XDocument (New-Object XDeclaration $Version, $Encoding, $standalone),(
New-Object XElement $(
$root
while($args) {
$attrib, $value, $args = $args
if($attrib -is [ScriptBlock]) {
# Write-Verbose "Preparsed DSL: $attrib"
$attrib = ConvertFrom-XmlDsl $attrib
Write-Verbose "Reparsed DSL: $attrib"
&$attrib
} elseif ( $value -is [ScriptBlock] -and "-CONTENT".StartsWith($attrib.TrimEnd(':').ToUpper())) {
$value = ConvertFrom-XmlDsl $value
&$value
} elseif ( $value -is [XNamespace]) {
New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-").TrimEnd(':')), $value
$script:NameSpaceHash.Add($attrib.TrimStart("-").TrimEnd(':'), $value)
} else {
Write-Verbose "XAttribute $attrib = $value"
New-Object XAttribute $attrib.TrimStart("-").TrimEnd(':'), $value
}
}
))
}
}
Set-Alias xml New-XDocument -EA 0
Set-Alias New-Xml New-XDocument -EA 0
function New-XAttribute {
#.Synopsys
# Creates a new XAttribute (an xml attribute on an XElement for XDocument)
#.Description
# This is the work-horse for the XML mini-dsl
#.Parameter name
# The attribute name
#.Parameter value
# The attribute value
[CmdletBinding()]
Param([Parameter(Mandatory=$true)]$name,[Parameter(Mandatory=$true)]$value)
New-Object XAttribute $name, $value
}
Set-Alias xa New-XAttribute -EA 0
Set-Alias New-XmlAttribute New-XAttribute -EA 0
function New-XElement {
#.Synopsys
# Creates a new XElement (an xml tag for XDocument)
#.Description
# This is the work-horse for the XML mini-dsl
#.Parameter tag
# The name of the xml tag
#.Parameter args
# this is where all the dsl magic happens. Please see the Examples. :)
[CmdletBinding()]
Param(
[Parameter(Mandatory = $true, Position = 0)]
[System.Xml.Linq.XName]$tag
,
[AllowNull()][AllowEmptyString()][AllowEmptyCollection()]
[Parameter(Position=99, Mandatory = $false, ValueFromRemainingArguments=$true)]
[PSObject[]]$args
)
PROCESS {
New-Object XElement $(
$tag
while($args) {
$attrib, $value, $args = $args
if($attrib -is [ScriptBlock]) { # then it's content
&$attrib
} elseif ( $value -is [ScriptBlock] -and "-CONTENT".StartsWith($attrib.TrimEnd(':').ToUpper())) { # then it's content
&$value
} elseif ( $value -is [XNamespace]) {
New-Object XAttribute ([XNamespace]::Xmlns + $attrib.TrimStart("-").TrimEnd(':')), $value
$script:NameSpaceHash.Add($attrib.TrimStart("-").TrimEnd(':'), $value)
} elseif($value -match "-(?!\\d)\\w") {
$args = @($value)+@($args)
} elseif($value -ne $null) {
New-Object XAttribute $attrib.TrimStart("-").TrimEnd(':'), $value
}
}
)
}
}
Set-Alias xe New-XElement
Set-Alias New-XmlElement New-XElement
function ConvertFrom-XmlDsl {
Param([ScriptBlock]$script)
$parserrors = $null
$global:tokens = [PSParser]::Tokenize( $script, [ref]$parserrors )
[Array]$duds = $global:tokens | Where-Object { $_.Type -eq "Command" -and !$_.Content.Contains('-') -and ($(Get-Command $_.Content -Type Cmdlet,Function,ExternalScript -EA 0) -eq $Null) }
[Array]::Reverse( $duds )
[string[]]$ScriptText = "$script" -split "`n"
ForEach($token in $duds ) {
# replace : notation with namespace notation
if( $token.Content.Contains(":") ) {
$key, $localname = $token.Content -split ":"
$ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Remove( $token.StartColumn -1, $token.Length ).Insert( $token.StartColumn -1, "'" + $($script:NameSpaceHash[$key] + $localname) + "'" )
} else {
$ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Remove( $token.StartColumn -1, $token.Length ).Insert( $token.StartColumn -1, "'" + $($script:NameSpaceHash[''] + $token.Content) + "'" )
}
# insert 'xe' before everything (unless it's a valid command)
$ScriptText[($token.StartLine - 1)] = $ScriptText[($token.StartLine - 1)].Insert( $token.StartColumn -1, "xe " )
}
Write-Output ([ScriptBlock]::Create( ($ScriptText -join "`n") ))
}
######## Xaml
# if($PSVersionTable.CLRVersion -ge "4.0"){
# trap { continue }
# [Reflection.Assembly]::LoadWithPartialName("System.Xaml") | Out-Null
# if("System.Xaml.XamlServices" -as [type]) {
# }
# }
Export-ModuleMember -alias * -function New-XDocument, New-XAttribute, New-XElement, Remove-XmlNamespace, Get-XmlContent, Set-XmlContent, ConvertTo-Xml, Select-Xml, Update-Xml, Format-Xml, ConvertTo-CliXml, ConvertFrom-CliXml
# SIG # Begin signature block
# MIIdZgYJKoZIhvcNAQcCoIIdVzCCHVMCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU7i/4rcSOaFh6MGBAPJLn0Vpy
# SVegghkkMIIDnzCCAoegAwIBAgIQeaKlhfnRFUIT2bg+9raN7TANBgkqhkiG9w0B
# AQUFADBTMQswCQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xKzAp
# BgNVBAMTIlZlcmlTaWduIFRpbWUgU3RhbXBpbmcgU2VydmljZXMgQ0EwHhcNMTIw
# NTAxMDAwMDAwWhcNMTIxMjMxMjM1OTU5WjBiMQswCQYDVQQGEwJVUzEdMBsGA1UE
# ChMUU3ltYW50ZWMgQ29yc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MxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0xMjA2MjEwNTAw
# NTlaMCMGCSqGSIb3DQEJBDEWBBSODCUreYZBSE+ys+civTtfLRjcLjANBgkqhkiG
# 9w0BAQEFAASBgFrvbqX/d1ys5yFuOrI2PeQOPEAkE5DdaU7KmGtYUR7B8aLQGXfw
# EP3AoFVdswv8zHnZuMMiV3xhtzAT0w0xQKj+CQQ7iQLgyWpSU0zonMT/bRkDglKF
# JfC6tpo0dJnqqLXfc3p9JJiSJyI5HneFwtbVSyhmWfYLBJ6kB6Ofypn+
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Get-Parameter 2.6.ps1
|
Get-Parameter 2.6.ps1
|
#Requires -version 2.0
#.Synopsis
# Enumerates the parameters of one or more commands
#.Notes
# With many thanks to Hal Rottenberg, Oisin Grehan and Shay Levy
# Version 0.80 - April 2008 - By Hal Rottenberg http://poshcode.org/186
# Version 0.81 - May 2008 - By Hal Rottenberg http://poshcode.org/255
# Version 0.90 - June 2008 - By Hal Rottenberg http://poshcode.org/445
# Version 0.91 - June 2008 - By Oisin Grehan http://poshcode.org/446
# Version 0.92 - April 2008 - By Hal Rottenberg http://poshcode.org/549
# - ADDED resolving aliases and avoided empty output
# Version 0.93 - Sept 24, 2009 - By Hal Rottenberg http://poshcode.org/1344
# Version 1.0 - Jan 19, 2010 - By Joel Bennett http://poshcode.org/1592
# - Merged Oisin and Hal's code with my own implementation
# - ADDED calculation of dynamic paramters
# Version 2.0 - July 22, 2010 - By Joel Bennett http://poshcode.org/get/2005
# - CHANGED uses FormatData so the output is objects
# - ADDED calculation of shortest names to the aliases (idea from Shay Levy http://poshcode.org/1982,
# but with a correct implementation)
# Version 2.1 - July 22, 2010 - By Joel Bennett http://poshcode.org/2007
# - FIXED Help for SCRIPT file (script help must be separated from #Requires by an emtpy line)
# - Fleshed out and added dates to this version history after Bergle's criticism ;)
# Version 2.2 - July 29, 2010 - By Joel Bennett http://poshcode.org/2030
# - FIXED a major bug which caused Get-Parameters to delete all the parameters from the CommandInfo
# Version 2.3 - July 29, 2010 - By Joel Bennett
# - ADDED a ToString ScriptMethod which allows queries like:
# $parameters = Get-Parameter Get-Process; $parameters -match "Name"
# Version 2.4 - July 29, 2010 - By Joel Bennett http://poshcode.org/2032
# - CHANGED "Name" to CommandName
# - ADDED ParameterName parameter to allow filtering parameters
# - FIXED bug in 2.3 and 2.2 with dynamic parameters
# Version 2.5 - December 13, 2010 - By Jason Archer http://poshcode.org/2404
# - CHANGED format temp file to have static name, prevents bloat of random temporary files
# Version 2.6 - July 23, 2011 - By Jason Archer (This Version)
# - FIXED miscalculation of shortest unique name (aliases count as unique names),
# this caused some parameter names to be thrown out (like "Object")
# - CHANGED code style cleanup
#
#.Description
# Lists all the parameters of a command, by ParameterSet, including their aliases, type, etc.
#
# By default, formats the output to tables grouped by command and parameter set
#.Example
# Get-Command Select-Xml | Get-Parameter
#.Example
# Get-Parameter Select-Xml
#.Parameter CommandName
# The name of the command to get parameters for
#.Parameter ParameterName
# Wilcard-enabled filter for parameter names
#.Parameter ModuleName
# The name of the module which contains the command (this is for scoping)
#.Parameter Force
# Forces including the CommonParameters in the output
[CmdletBinding()]
param (
[Parameter(Position=1,ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
[Alias("Name")]
[string[]]$CommandName
,
[Parameter(Position=2,ValueFromPipelineByPropertyName=$true,Mandatory=$false)]
[string[]]$ParameterName="*"
,
[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$false)]
$ModuleName
,
[switch]$Force
)
Function global:Get-Parameter {
#.Synopsis
# Enumerates the parameters of one or more commands
#.Description
# Lists all the parameters of a command, by ParameterSet, including their aliases, type, etc.
#
# By default, formats the output to tables grouped by command and parameter set
#.Example
# Get-Command Select-Xml | Get-Parameter
#.Example
# Get-Parameter Select-Xml
#.Parameter CommandName
# The name of the command to get parameters for
#.Parameter ParameterName
# Wilcard-enabled filter for parameter names
#.Parameter ModuleName
# The name of the module which contains the command (this is for scoping)
#.Parameter Force
# Forces including the CommonParameters in the output
[CmdletBinding()]
param(
[Parameter(Position = 1, Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
[string[]]$CommandName
,
[Parameter(Position = 2, ValueFromPipelineByPropertyName=$true)]
[string[]]$ParameterName = "*"
,
[Parameter(ValueFromPipelineByPropertyName = $true)]
$ModuleName
,
[switch]$Force
)
begin {
$PropertySet = @( "Name",
@{n="Position";e={if($_.Position -lt 0){"Named"}else{$_.Position}}},
"Aliases",
@{n="Short";e={$_.Name}},
@{n="Type";e={$_.ParameterType.Name}},
@{n="ParameterSet";e={$paramset}},
@{n="Command";e={$command}},
@{n="Mandatory";e={$_.IsMandatory}},
@{n="Provider";e={$_.DynamicProvider}},
@{n="ValueFromPipeline";e={$_.ValueFromPipeline}},
@{n="ValueFromPipelineByPropertyName";e={$_.ValueFromPipelineByPropertyName}}
)
function Join-Object {
Param(
[Parameter(Position=0)]
$First
,
[Parameter(ValueFromPipeline=$true,Position=1)]
$Second
)
begin {
[string[]] $p1 = $First | Get-Member -MemberType Properties | Select-Object -ExpandProperty Name
}
process {
$Output = $First | Select-Object $p1
foreach ($p in $Second | Get-Member -MemberType Properties | Where-Object {$p1 -notcontains $_.Name} | Select-Object -ExpandProperty Name) {
Add-Member -InputObject $Output -MemberType NoteProperty -Name $p -Value $Second."$p"
}
$Output
}
}
}
process {
foreach ($cmd in $CommandName) {
if ($ModuleName) {$cmd = "$ModuleName\\$cmd"}
$commands = @(Get-Command $cmd)
foreach ($command in $commands) {
# resolve aliases (an alias can point to another alias)
while ($command.CommandType -eq "Alias") {
$command = @(Get-Command ($command.definition))[0]
}
if (-not $command) {continue}
$Parameters = @{}
foreach ($provider in Get-PSProvider) {
$drive = "{0}\\{1}::\\" -f $provider.ModuleName, $provider.Name
Write-Verbose ("Get-Command $command -Args $drive | Select -Expand Parameters")
[Array]$MoreParameters = (Get-Command $command -Args $drive).Parameters.Values
[Array]$Dynamic = $MoreParameters | Where-Object {$_.IsDynamic}
foreach ($p in $MoreParameters | Where-Object{!$Parameters.ContainsKey($_.Name)}) {$Parameters.($p.Name) = $p}
# Write-Verbose "Drive: $Drive | Parameters: $($Parameters.Count)"
if ($dynamic) {
foreach ($d in $dynamic) {
if (Get-Member -InputObject $Parameters.($d.Name) -Name DynamicProvider) {
Write-Debug ("ADD:" + $d.Name + " " + $provider.Name)
$Parameters.($d.Name).DynamicProvider += $provider.Name
} else {
Write-Debug ("CREATE:" + $d.Name + " " + $provider.Name)
$Parameters.($d.Name) = $Parameters.($d.Name) | Add-Member NoteProperty DynamicProvider @($provider.Name) -Passthru
}
}
}
}
## Calculate the shortest distinct parameter name -- do this BEFORE removing the common parameters or else.
$Aliases = $Parameters.Values | Select-Object -ExpandProperty Aliases ## Get defined aliases
foreach ($p in $($Parameters.Keys)) {
$shortest = "^"
foreach ($char in [char[]]$p) {
$shortest += $char
$Matches = (($Parameters.Keys + $Aliases) -match $Shortest).Count
Write-Debug "$($shortest.SubString(1)) $Matches"
if ($Matches -eq 1) {
$Parameters.$p = $Parameters.$p | Add-Member NoteProperty Aliases ($Parameters.$p.Aliases + @($shortest.SubString(1).ToLower($PSUICulture))) -Force -Passthru
break
}
}
}
Write-Verbose "Parameters: $($Parameters.Count)`n $($Parameters | ft | out-string)"
foreach ($paramset in @($command.ParameterSets | Select-Object -ExpandProperty "Name")) {
foreach ($parameter in $Parameters.Keys | Sort-Object) {
Write-Verbose "Parameter: $Parameter"
if (!$Force -and ($Parameters.$Parameter.Aliases -match '^(vb|db|ea|wa|ev|wv|ov|ob|wi|cf)$')) {continue}
if ($Parameters.$Parameter.ParameterSets.ContainsKey($paramset) -or $Parameters.$Parameter.ParameterSets.ContainsKey("__AllParameterSets")) {
if ($Parameters.$Parameter.ParameterSets.ContainsKey($paramset)) {
$output = Join-Object $Parameters.$Parameter $Parameters.$Parameter.ParameterSets.$paramSet
} else {
$output = Join-Object $Parameters.$Parameter $Parameters.$Parameter.ParameterSets.__AllParameterSets
}
Write-Output $Output | Select-Object $PropertySet | ForEach-Object {
$null = $_.PSTypeNames.Insert(0,"System.Management.Automation.ParameterMetadata")
$null = $_.PSTypeNames.Insert(0,"System.Management.Automation.ParameterMetadataEx")
Write-Verbose "$(($_.PSTypeNames.GetEnumerator()) -join ", ")"
$_
} |
Add-Member ScriptMethod ToString { $this.Name } -Force -Passthru |
Where-Object {$(foreach($pn in $ParameterName) {$_ -like $Pn}) -contains $true}
}
}
}
}
}
}
}
# Since you can't update format data without a file that has a ps1xml ending, let's make one up...
$tempFile = "$([System.IO.Path]::GetTempPath())Get-Parameter.ps1xml"
Set-Content $tempFile @'
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<Controls>
<Control>
<Name>ParameterGroupingFormat</Name>
<CustomControl>
<CustomEntries>
<CustomEntry>
<CustomItem>
<Frame>
<LeftIndent>4</LeftIndent>
<CustomItem>
<Text>Command: </Text>
<ExpressionBinding>
<ScriptBlock>"{0}/{1}" -f $(if($_.command.ModuleName){$_.command.ModuleName}else{$_.Command.CommandType.ToString()+":"}),$_.command.Name</ScriptBlock>
</ExpressionBinding>
<NewLine/>
<Text>Set: </Text>
<ExpressionBinding>
<ScriptBlock>if($_.ParameterSet -eq "__AllParameterSets"){"Default"}else{$_.ParameterSet}</ScriptBlock>
</ExpressionBinding>
<NewLine/>
</CustomItem>
</Frame>
</CustomItem>
</CustomEntry>
</CustomEntries>
</CustomControl>
</Control>
</Controls>
<ViewDefinitions>
<View>
<Name>ParameterMetadataEx</Name>
<ViewSelectedBy>
<TypeName>System.Management.Automation.ParameterMetadataEx</TypeName>
</ViewSelectedBy>
<GroupBy>
<PropertyName>ParameterSet</PropertyName>
<CustomControlName>ParameterGroupingFormat</CustomControlName>
</GroupBy>
<TableControl>
<TableHeaders>
<TableColumnHeader>
<Label>Name</Label>
<Width>22</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Aliases</Label>
<Width>12</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Position</Label>
<Width>8</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Mandatory</Label>
<Width>9</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Pipeline</Label>
<Width>8</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>ByName</Label>
<Width>6</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Provider</Label>
<Width>15</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Type</Label>
</TableColumnHeader>
</TableHeaders>
<TableRowEntries>
<TableRowEntry>
<TableColumnItems>
<TableColumnItem>
<PropertyName>Name</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Aliases</PropertyName>
</TableColumnItem>
<TableColumnItem>
<!--PropertyName>Position</PropertyName-->
<ScriptBlock>if($_.Position -lt 0){"Named"}else{$_.Position}</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Mandatory</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>ValueFromPipeline</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>ValueFromPipelineByPropertyName</PropertyName>
</TableColumnItem>
<TableColumnItem>
<!--PropertyName>Provider</PropertyName-->
<ScriptBlock>if($_.Provider){$_.Provider}else{"All"}</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Type</PropertyName>
</TableColumnItem>
</TableColumnItems>
</TableRowEntry>
</TableRowEntries>
</TableControl>
</View>
</ViewDefinitions>
</Configuration>
'@
Update-FormatData -Append $tempFile
# This is nested stuff, so that you can call the SCRIPT, and after it defines the global function, we will call that.
Get-Parameter @PSBoundParameters
|
PowerShellCorpus/PoshCode/Get-InstalledSoftware.ps.ps1
|
Get-InstalledSoftware.ps.ps1
|
##############################################################################\n##\n## Get-InstalledSoftware\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nLists installed software on the current computer.\n\n.EXAMPLE\n\nGet-InstalledSoftware *Frame* | Select DisplayName\n\nDisplayName\n-----------\nMicrosoft .NET Framework 3.5 SP1\nMicrosoft .NET Framework 3.5 SP1\nHotfix for Microsoft .NET Framework 3.5 SP1 (KB953595)\nHotfix for Microsoft .NET Framework 3.5 SP1 (KB958484)\nUpdate for Microsoft .NET Framework 3.5 SP1 (KB963707)\n\n#>\n\nparam(\n ## The name of the software to search for\n $DisplayName = "*"\n)\n\nSet-StrictMode -Off\n\n## Get all the listed software in the Uninstall key\n$keys =\n Get-ChildItem HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\n\n## Get all of the properties from those items\n$items = $keys | Foreach-Object { Get-ItemProperty $_.PsPath }\n\n## For each of those items, display the DisplayName and Publisher\nforeach($item in $items)\n{\n if(($item.DisplayName) -and ($item.DisplayName -like $displayName))\n {\n $item\n }\n}
|
PowerShellCorpus/PoshCode/Run-Defrag.ps1
|
Run-Defrag.ps1
|
# Run-Defrag
# Defragments the targeted hard drives.
#
# Args:
# $server: A target Server 2003 or 2008 system
# $drive: An optional drive letter. If this is blank then all
# drives are defragmented
# $force: If this switch is set then a defrag will be forced
# even if the drive is low on space
#
# Returns:
# The result description for each drive.
function Run-Defrag {
param([string]$server, [string]$drive, [switch]$force)
[string]$query = 'Select * from Win32_Volume where DriveType = 3'
if ($drive) {
$query += " And DriveLetter LIKE '$drive%'"
}
$volumes = Get-WmiObject -Query $query -ComputerName $server
foreach ($volume in $volumes) {
Write-Host "Defragmenting $($volume.DriveLetter)..." -noNewLine
$result = $volume.Defrag($force)
switch ($result) {
0 {'Success'}
1 {'Access Denied'}
2 {'Not Supported'}
3 {'Volume Dirty Bit Set'}
4 {'Not Enough Free Space'}
5 {'Corrupt MFT Detected'}
6 {'Call Cancelled'}
7 {'Cancellation Request Requested Too Late'}
8 {'Defrag In Progress'}
9 {'Defrag Engine Unavailable'}
10 {'Defrag Engine Error'}
11 {'Unknown Error'}
}
}
}
|
PowerShellCorpus/PoshCode/New-ElevatedTask.ps1
|
New-ElevatedTask.ps1
|
#requires -version 2.0
####################################################################################################
## 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
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($args -contains "-?" -or $TargetPath.Trim(" ").Length -eq 0 -or (-not (Test-Path $TargetPath) )) {
if( -not($args -contains "-?")) { Write-Error "TargetPath must be an existing file for the scheduled task to point at!" }
Write-Host $UseMessage
return
}
$xml = @"
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<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>
<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>
<DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession>
<UseUnifiedSchedulingEngine>false</UseUnifiedSchedulingEngine>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>P3D</ExecutionTimeLimit>
<Priority>7</Priority>
</Settings>
<Actions Context="Author">
<Exec>
<Command>{1}</Command>
<Arguments>{2}</Arguments>
<WorkingDirectory>{3}</WorkingDirectory>
</Exec>
</Actions>
</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 -eq $null -or $IconLocation.Length -eq 0) {
$IconLocation = $TargetPath
}
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/Find Local Group Members_9.ps1
|
Find Local Group Members_9.ps1
|
# Author: Hal Rottenberg
# Purpose: Find matching members in a local group
# Used tip from RichS here: http://powershellcommunity.org/Forums/tabid/54/view/topic/postid/1528/Default.aspx
# Change these two to suit your needs
$ChildGroups = "Domain Admins", "Group Two"
$LocalGroup = "Administrators"
$MemberNames = @()
# uncomment this line to grab list of computers from a file
# $Servers = Get-Content serverlist.txt
$Servers = $env:computername # for testing on local computer
foreach ( $Server in $Servers ) {
$Group= [ADSI]"WinNT://$Server/$LocalGroup,group"
$Members = @($Group.psbase.Invoke("Members"))
$Members | ForEach-Object {
$MemberNames += $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)
}
$ChildGroups | ForEach-Object {
$output = "" | Select-Object Server, Group, InLocalAdmin
$output.Server = $Server
$output.Group = $_
$output.InLocalAdmin = $MemberNames -contains $_
Write-Output $output
}
}
|
PowerShellCorpus/PoshCode/Test-UserCredential_1.ps1
|
Test-UserCredential_1.ps1
|
function Test-UserCredential {
[CmdletBinding()] [OutputType([System.Boolean])]
param(
[Parameter(Mandatory=$true, ParameterSetName="string", position=0)]
[ValidateNotNullOrEmpty()]
[String] $Username,
[Parameter(Mandatory=$true, ParameterSetName="string", position=1)]
[ValidateNotNullOrEmpty()]
[String] $Password,
[Parameter(Mandatory=$true, ParameterSetName="PSCredential", ValueFromPipeline=$true, position=0)]
[ValidateNotNullOrEmpty()]
[Management.Automation.PSCredential] $Credential,
[Parameter(position=2)]
[Switch] $Domain
)
Begin {
try { $assem = [system.reflection.assembly]::LoadWithPartialName('System.DirectoryServices.AccountManagement') }
catch { throw 'Failed to load assembly "System.DirectoryServices.AccountManagement". The error was: "{0}".' -f $_ }
}
Process {
try {
$system = Get-WmiObject -Class Win32_ComputerSystem
if ($PSCmdlet.ParameterSetName -eq 'PSCredential') {
$Username = $Credential.GetNetworkCredential().UserName
$Password = $Credential.GetNetworkCredential().Password
}
if ($Domain) {
if (0, 2 -contains $system.DomainRole) {
throw 'This computer is not a member of a domain.'
} else {
$principalContext = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext 'Domain', $system.Domain
}
} else {
$principalContext = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext 'Machine', $env:COMPUTERNAME
}
return $principalContext.ValidateCredentials($Username, $Password)
} 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.
.EXAMPLE
PS C:\\> Test-UserCredential -Username andy -password secret
.EXAMPLE
PS C:\\> Test-UserCredential -Username 'mydomain\\andy' -password secret -domain
.EXAMPLE
PS C:\\> Test-UserCredential -Username 'andy' -password secret -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.
#>
}
|
PowerShellCorpus/PoshCode/Start-BootsTimer_3.ps1
|
Start-BootsTimer_3.ps1
|
Add-BootsFunction -Type "System.Windows.Threading.DispatcherTimer"
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
}
## 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 ...
PowerBoots\\New-BootsWindow -WindowStyle None -AllowsTransparency -Tag $TimerStuff {
Param($window)
TextBlock "00:00:00" -FontSize $window.Tag.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)
## We'll create a timer
$window.Tag["Timer"] = DispatcherTimer -Tag $window -Interval "0:0:0.05" -On_Tick {
trap {
write-host "Error: $_" -fore Red
write-host $($_.InvocationInfo.PositionMessage) -fore Red
write-host $($_.Exception.StackTrace | Out-String) -fore Red
}
$remain = 100
if($this.Tag.Tag.TimerEnd -and $this.Tag.Content.Foreground.GradientStops.Count -ge 3) {
Write-Verbose $($this.Tag.Tag|Out-String) #-fore magenta
$diff = $this.Tag.Tag.TimerEnd - [DateTime]::Now;
if($diff.Ticks -ge 0) {
$this.Tag.Content.Text = ([DateTime]$diff.Ticks).ToString(" HH:mm.ss")
} else {
$this.Tag.Content.Text = ([DateTime][Math]::Abs($diff.Ticks)).ToString("-HH:mm.ss")
}
#Write-Host "Remain: $remain or $($diff.TotalSeconds) of $($this.tag.tag.seconds)"
$remain = $diff.TotalSeconds / $this.tag.tag.seconds
Write-Verbose "Remain: $remain or $($diff.TotalSeconds) of $($this.tag.tag.seconds)"
## Move the gradient a little bit each time.
$this.tag.Content.Foreground.GradientStops[2].Offset = 0.0 # [Math]::Max(0.0, $remain)
$this.tag.Content.Foreground.GradientStops[1].Offset = 0.0 # [Math]::Max(0.0, $remain - 0.05)
#Write-Host "Gradient: $($this.tag.Content.Foreground.GradientStops[2].Offset) of $($this.tag.Content.Foreground.GradientStops[1].Offset)"
} else { Write-Host "Wahat!" }
## 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
$this.tag.Add_MouseDown( { $this.tag.Close() } )
## But if they chose -SingleAlarm, they don't neeto bother
if($this.tag.tag["SingleAlarm"]) { $this.tag.Close() }
}
& {
if($this.tag.Tag["Sound"]) {
$this.tag.Tag["Sound"].Play()
} else {
[System.Media.SystemSounds]::Exclamation.Play()
}
if($this.tag.Tag["EndMessage"]) {
$null = $this.tag.Tag["Voice"].Speak( $this.tag.Tag["EndMessage"], 1 )
}
}
}
}
## Now handle starting and stopping the timer
# $window.Add_SourceInitialized( { $window.Tag.Timer.Start() } )
$window.Add_Closed( { Write-Host "Shutting Down $this"; $this.Tag.Timer.Stop() } )
} -On_MouseDown {
if($_.ChangedButton -eq "Left") { $this.DragMove() }
} -Async -Topmost -Background Transparent -ShowInTaskbar:$False -Passthru |
## In lieu of the SourceInitialized event which fires BEFORE we can hook it:
ForEach { Invoke-BootsWindow $_ { $BootsWindow.Tag.Timer.Start() } }
}
|
PowerShellCorpus/PoshCode/chkhash_14.ps1
|
chkhash_14.ps1
|
# calculate SHA512 of file.
function Get-SHA512([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]'))
{
$stream = $null;
$cryptoServiceProvider = [System.Security.Cryptography.SHA512CryptoServiceProvider];
$hashAlgorithm = new-object $cryptoServiceProvider
$stream = $file.OpenRead();
$hashByteArray = $hashAlgorithm.ComputeHash($stream);
$stream.Close();
## We have to be sure that we close the file stream if any exceptions are thrown.
trap
{
if ($stream -ne $null)
{
$stream.Close();
}
break;
}
foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }}
return [string]$result;
}
function noequal ( $first, $second)
{
if (!($second) -or $second -eq "") {return $true}
$first=join-path $first "\\"
foreach($s in $second)
{
if ($first.tolower().startswith($s.tolower())) {return $false}
}
return $true
}
# chkhash.ps1 [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #3] [-u] [-h [path of .xml database]]
# -u updates the XML file database and exits
# otherwise, all files are checked against the XML file database.
# -h specifies location of xml hash database
$hashespath=".\\hashes.xml"
del variable:\\args3 -ea 0
del variable:\\args2 -ea 0
del variable:\\xfiles -ea 0
del variable:\\files -ea 0
del variable:\\exclude -ea 0
$args3=@()
$args2=@($args)
$nu = 0
$errs = 0
$fc = 0
$fm = 0
$upd = $false
$create = $false
for($i=0;$i -lt $args2.count; $i++)
{
if ($args2[$i] -like "-h*") # -help specified?
{
"Usage: .\\chkhash.ps1 [-h] [-u] [-c] [-x <file path of hashes .xml database>] [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #n] [-e <Dirs>]"
"Options: -h - Help display."
" -c - Create hash database. If .xml hash database does not exist, -c will be assumed."
" -u - Update changed files and add new files to existing database."
" -x - specifies .xml database file path to use. Default is .\\hashes.xml"
" -e - exclude dirs. Put this after the files/dirs you want to check with SHA512 and needs to be fullpath (e.g. c:\\users\\bob not ..\\bob)."
""
"Examples: PS>.\\chkhash.ps1 c:\\ d:\\ -c -x c:\\users\\bob\\hashes\\hashes.xml"
" PS>.\\chkhash.ps1 c:\\users\\alice\\pictures\\sunset.jpg -u -x c:\\users\\alice\\hashes\\pictureshashes.xml"
" PS>.\\chkhash.ps1 c:\\users\\eve\\documents d:\\media\\movies -x c:\\users\\eve\\hashes\\private.xml"
" PS>.\\chkhash.ps1 c:\\users\\eve -x c:\\users\\eve\\hashes\\private.xml -e c:\\users\\eve\\hashes"
""
"Note: files in subdirectories of any specified directory are automatically processed."
" if you specify only an -x option, or no option and .\\hash.xml exists, only files in the database will be checked."
exit
}
if ($args2[$i] -like "-u*") {$upd=$true;continue} # Update and Add new files to database?
if ($args2[$i] -like "-c*") {$create=$true;continue} # Create database specified?
if ($args2[$i] -like "-x*")
{
$i++ # Get hashes xml database path
if ($i -ge $args2.count)
{
write-host "-X specified but no file path of .xml database specified. Exiting."
exit
}
$hashespath=$args2[$i]
continue
}
if ($args2[$i] -like "-e*") # Exclude files, dirs
{
while (($i+1) -lt $args2.count)
{
$i++
if ($args2[$i] -like "-*") {break}
$exclude+=@(join-path $args2[$i] "\\") # collect array of excluded directories.
}
continue
}
$args3+=@($args2[$i]) # Add files/dirs
}
"ChkHash.ps1 - .\\chkhash.ps1 -h for usage."
""
if ($args3.count -ne 0)
{
# Get list of files and SHA512 hash them.
"Enumerating files from specified locations..."
$files=@(dir $args3 -recurse -ea 0 | ?{$_.mode -notmatch "d"} | ?{noequal $_.directoryname $exclude}) # Get list of files
if ($files.count -eq 0) {"No files found. Exiting."; exit}
if ($create -eq $true -or !(test-path $hashespath)) # Create database?
{
# Create SHA512 hashes of files and write to new database
$files = $files | %{write-host "SHA-512 Hashing `"$($_.fullname)`" ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru}
$files |export-clixml $hashespath
"Created $hashespath"
"$($files.count) file hash(es) saved. Exiting."
exit
}
$xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database
}
else
{
if (!(test-path $hashespath)) {"No database found or specified, exiting."; exit}
$xfiles=@(import-clixml $hashespath|?{noequal $_.directoryname $exclude}) # Load database and check it
if ($xfiles.count -eq 0) {"No files specified and no files in Database. Exiting.";Exit}
$files=$xfiles
}
"Loaded $($xfiles.count) file hash(es) from $hashespath"
$hash=@{}
for($x=0;$x -lt $xfiles.count; $x++) # Build dictionary (hash) of filenames and indexes into file array
{
if ($hash.contains($xfiles[$x].fullname)) {continue}
$hash.Add($xfiles[$x].fullname,$x)
}
foreach($f in $files)
{
if ((get-item -ea 0 $f.fullname) -eq $null) {continue} # skip if file no longer exists.
$n=($hash.($f.fullname))
if ($n -eq $null)
{
$nu++ # increment needs/needed updating count
if ($upd -eq $false) {"Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue
"SHA-512 Hashing `"$($f.fullname)`" ..."
# Create SHA512 hash of file
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force}
$xfiles+=@($f) # then add file + hash to list
continue
}
$f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru -force}
$fc++ # File checked increment.
if ($xfiles[$n].SHA512 -eq $f.SHA512) # Check SHA512 for mixmatch.
{$fm++;continue} # if matched, increment file matches and continue loop
$errs++ # increment mixmatches
if ($upd -eq $true) { $xfiles[$n]=$f; "Updated `"$($f.fullname)`"";continue}
"Bad SHA-512 found: `"$($f.fullname)`""
}
if ($upd -eq $true) # if database updated
{
$xfiles|export-clixml $hashespath # write xml database
"Updated $hashespath"
"$nu file hash(es) added to database."
"$errs file hash(es) updated in database."
exit
}
"$errs SHA-512 mixmatch(es) found."
"$fm file(s) SHA512 matched."
"$fc file(s) checked total."
if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
|
PowerShellCorpus/PoshCode/Snapshot VM in a folder.ps1
|
Snapshot VM in a folder.ps1
|
#Revision 1
#7-29-2008
#author Jon Owings
#contact - jowings at securas dot com
#
#Create a snapshot of all the vm's in a folder,
#be sure to change to match your enviroment. use at your own risk, snapshots have been known to
#cause certain configurations to lock (freeze) so test in a dev enviroment first.
#
$vCenter = VirtualCenterServer
$vFolder = VirtualCenterFolder
$sName = SnapshotName
Get-vc -server $vCenter
#remove old snapshots with the same name
Get-Folder $vFolder | get-vm | Get-Snapshot -Name $sName | Remove-Snapshot -Confirm:$false
#create a snapshot of each vm in that folder
Get-Folder $vFolder | get-vm | new-snapshot -Name $sName | ConvertTo-Html | Out-File create.htm
$smtpclient = New-Object System.Net.Mail.SmtpClient
$smtpclient.host = "mailserver.foo.bar"
$msg = New-Object system.Net.Mail.MailMessage
$att = New-Object System.Net.Mail.Attachment("create.htm")
$msg.Attachments.add($att)
$msg.From = "your@email.com"
$msg.to.add("your@email.com")
$msg.Subject = "Snapshot Backups"
$msg.Body = "This is the result of the snapshot scripts."
$smtpclient.send($msg)
Echo Done
|
PowerShellCorpus/PoshCode/Set-LocalPassword.ps1
|
Set-LocalPassword.ps1
|
# Sets local account passwords on one or more computers
# usage [computerName1,computerName2,... | ] ./Set-LocalPassword.ps1 [-user] <userName> [-password] <password> [[-computers] computerName1,computerName2,...]
param(
[string] $User
, [string] $Password
, [string[]] $ComputerNames = @()
)
$ComputerNames += @($input)
if (! $ComputerNames)
{
$ComputerNames = $env:computername
}
function ChangePassword ([string] $ChangeComputer, [string] $ChangeUser, [string] $ChangePassword) {
"*** Setting password for $ChangeComputer/$ChangeUser"
& {
$ErrorActionPreference="silentlycontinue"
([ADSI] "WinNT://$computer/$user").SetPassword($password)
if ($?) { " Success" }
else { " Failed: $($error[0])" }
}
}
function ShowUsage {
@'
usage [computerName1,computerName2,... | ] ./Set-LocalPassword.ps1 [-user] <userName> [-password] <password> [[-computers] computerName1,computerName2,...]
'@
}
if ($user -match '^$|-\\?|/\\?|-help' -or ! $password) { ShowUsage; break; }
ForEach ($computer in $ComputerNames) {
ChangePassword $computer $user $password
}
|
PowerShellCorpus/PoshCode/SVMotion-VM_2.ps1
|
SVMotion-VM_2.ps1
|
# author: Hal Rottenberg
# Website/OpenID: http://halr9000.com
# purpose: does "real" SVMotion of a VM
# usage: get-vm | SVMotion-VM -destination (get-datastore foo)
function SVMotion-VM {
param(
[VMware.VimAutomation.Client20.DatastoreImpl]$destination
)
Begin {
$datastoreView = Get-View -VIObject $destination
$relocationSpec = New-Object VMware.Vim.VirtualMachineRelocateSpec
$relocationSpec.Datastore = $datastoreView.MoRef
}
Process {
if ( $_ -isnot [VMware.VimAutomation.Client20.VirtualMachineImpl] ) {
Write-Warning "Expected virtual machine object on pipeline. skipping $_"
continue
}
$vmView = Get-View -VIObject $_
$vmView.RelocateVM_Task($relocationSpec)
}
}
|
PowerShellCorpus/PoshCode/Monitor-FileSize_1.ps1
|
Monitor-FileSize_1.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
else{"File does not exist!"}
Write-Output "The files at location, $FilePath , have exceeded $Size kb and are now $('{0:N4}' -f $FileSize.Sum) kb in size."
}
|
PowerShellCorpus/PoshCode/ConvertFrom-FahrenheitWi.ps1
|
ConvertFrom-FahrenheitWi.ps1
|
## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n\nparam([double] $Fahrenheit)\n\nSet-StrictMode -Version Latest\n\n## Convert Fahrenheit to Celsius\nfunction ConvertFahrenheitToCelsius([double] $fahrenheit)\n{\n $celsius = $fahrenheit - 32\n $celsius = $celsius / 1.8\n $celsius\n}\n\n$celsius = ConvertFahrenheitToCelsius $fahrenheit\n\n## Output the answer\n"$fahrenheit degrees Fahrenheit is $celsius degrees Celsius."
|
PowerShellCorpus/PoshCode/Get-PDC09Videos_2.ps1
|
Get-PDC09Videos_2.ps1
|
#requires -version 2.0
PARAM (
[Parameter(Position=1, Mandatory=$true)]
[ValidateSet("wmv","wmvhigh","ppt")] # the "mp4" files aren't there yet
[String]$MediaType,
[string]$Destination = $PWD
)
if( ([System.Environment]::OSVersion.Version.Major -gt 5) -and -not ( # Vista and ...
new-object Security.Principal.WindowsPrincipal (
[Security.Principal.WindowsIdentity]::GetCurrent()) # current user is admin
).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) ) {
Write-Warning @"
On VISTA and above, BITS limits the number of jobs in the queue to 300 jobs and the number of jobs that a non-administrator user can create to 60 jobs.
You MUST run this script from an elevated host if you're on Vista, Windows 7, or Server 2008
"@
}
Import-Module BitsTransfer
Push-Location $Destination
$Extension = $(switch -wildcard($MediaType){"wmv*"{"wmv"} "mp4"{"mp4"} "ppt"{"pptx"}})
$BaseUrl = "http://ecn.channel9.msdn.com/o9/pdc09/{0}/{2}.{1}"
"CL09","CL18","FT02","FT06","FT11","PR05","SVC01","SVC10","SVC20","SVR03","CL30","CL33","FT30",
"FT31","PR31","SVC30","SVC37","SVR33","VTL30","VTL32","CL04","CL14","CL25","FT18","FT19","FT25",
"PR02","SVC13","SVR01","SVR14","CL13","CL29","FT10","FT28","FT57","PR11","SVC52","SVR15","SVR17",
"CL11","CL17","CL23","FT03","FT08","PR10","SVR16","VTL01","CL01","FT50","FT52","FT55","FT59","PR13",
"SVC02","SVC03","SVC15","CL31","CL34","FT32","FT34","FT36","SVC31","SVC32","SVR31","VTL31","CL15",
"FT12","FT17","FT58","SVC16","SVC28","SVC53","SVR11","VTL05","CL06","FT04","FT07","FT29","PR06",
"SVC09","SVC17","SVR13","VTL04","CL12","CL22","FT22","FT23","FT26","SVC04","SVC14","SVC19","SVC54",
"SVR12","CL02","CL05","CL16","FT21","FT56","PR03","SVC08","SVC18","SVR10","VTL03","CL10","FT13",
"FT53","FT60","PR07","SVC06","SVC25","SVR07","SVR18","VTL02","CL03","CL21","CL27","FT14","FT20",
"FT24","PR09","SVC12","SVR09","SVR19","CL32","CL35","CL36","FT33","FT35","PR30","PR33","SVC33",
"SVC36","SVR32","CL07","CL24","CL28","FT09","FT16","FT27","PR12","SVC27","SVR02","SVR06","CL26",
"FT05","FT54","PR01","PR14","SVC23","SVC26","SVR08","KYN01-PGM","KYN02-PGM" |
ForEach { Start-BitsTransfer -Source $($BaseUrl -f $MediaType, $Extension, $_) -Async }
Pop-Location
Write-Host "You may now use Get-BitsTransfer to check on the status of the downloads. By default, failed transfers will be retried every 10 minutes for two weeks."
# SIG # Begin signature block
# MIIRDAYJKoZIhvcNAQcCoIIQ/TCCEPkCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU5g0RdBrlScbfFYcyJUxEORi9
# Kg6ggg5CMIIHBjCCBO6gAwIBAgIBFTANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQG
# EwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERp
# Z2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2Vy
# dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDcxMDI0MjIwMTQ1WhcNMTIxMDI0MjIw
# MTQ1WjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzAp
# BgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRlIFNpZ25pbmcxODA2BgNV
# BAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJbnRlcm1lZGlhdGUgT2JqZWN0
# IENBMIIBIjANBgkqhkiG9w0BAQEF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# SIG # End signature block
|
PowerShellCorpus/PoshCode/Read-Choice_3.ps1
|
Read-Choice_3.ps1
|
# 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
}
}
# }
|
PowerShellCorpus/PoshCode/Hardware Inventory.ps1
|
Hardware Inventory.ps1
|
# Synopsis:
# Windows Script to collect Hardware information on a local system
# And Convert it to a JSON String and Upload that to a CouchDB
# Database
# Requirements:
# -Local Admin Access in Powershell v2
# -SSL(443/TCP) allowed to CouchDB Host
# -Proxy verified and communication to it
Write-Host "
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
_ _ _____ _ _
| \\ | |_ _| / \\ ___ ___ ___| |_
| \\| | | | / _ \\ / __/ __|/ _ \\ __|
| |\\ | | | / ___ \\\\__ \\__ \\ __/ |_
|_| \\_| |_| /_/ \\_\\___/___/\\___|\\__|
___ _
|_ _|_ ____ _____ _ __ | |_ ___ _ __ _ _
| || '_ \\ \\ / / _ \\ '_ \\| __/ _ \\| '__| | | |
| || | | \\ V / __/ | | | || (_) | | | |_| |
|___|_| |_|\\_/ \\___|_| |_|\\__\\___/|_| \\__, |
|___/
by VulcanX
2011-09-29
v1.0
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"
#Adding ConvertTo-JSON function for use later on in script
Filter ConvertTo-JSON {
Function New-JSONProperty ($name, $value) {
@"
"$name": $value
"@
}
$targetObject = $_
$jsonProperties = @()
$properties = $_ | Get-Member -MemberType *property
ForEach ($property in $properties) {
#"$($property.Name)=$($targetObject.$($property.Name)) [$($($targetObject.$($property.Name)).GetType())]"
#(($targetObject.($property.Name)).GetType()).Name
$value = $targetObject.($property.Name)
$dataType = (($targetObject.($property.Name)).GetType()).Name
switch -regex ($dataType) {
'String' {$jsonProperties += New-JSONProperty $property.Name "`"$value`""}
'Int32|Double' {$jsonProperties += New-JSONProperty $property.Name $value}
'Object\\[\\]' {
#$jsonProperties += "`t`"$($property.Name)`": [$($($targetObject.($property.Name)) -join ',')]"
$str = "`t`"$($property.Name)`": ["
$count = $targetObject.($property.Name).Count
For($idx=0; $idx -lt $count; $idx++) {
$v = $targetObject.($property.Name)[$idx]
switch -regex ($v.GetType()) {
'String' {$v="`"$v`""}
}
if($idx+1 -lt $count) {
$comma = ","
} else {
$comma = ""
}
$str += "$v$($comma)"
}
$jsonProperties += "$str]"
}
default {$_}
}
}
"{`r`n $($jsonProperties -join ",`r`n") `r`n}"
}
#Get WMI Info
#Declaring all variables for use later in JSON
$HOSTNAME1 = Get-WmiObject win32_computersystem | Select-Object -ExpandProperty Name
$HOSTNAME2 = Get-WmiObject win32_computersystem | Select-Object -ExpandProperty Domain
$HOSTNAME = "$HOSTNAME1.$HOSTNAME2"
$OS = Get-WmiObject win32_operatingsystem | Select-Object -ExpandProperty Caption
$OS_RELEASE = Get-WmiObject win32_operatingsystem | Select-Object -ExpandProperty Version
$IP_ADDRESS_1 = Get-WmiObject win32_NetworkAdapterConfiguration | Where { $_.IPAddress -and $_.IPAddress -notlike ':' } | Select -ExpandProperty IPAddress
$IP_ADDRESS = $IP_ADDRESS_1 -join ' ' # Adding multiple address onto one line
$MAC_ADDRESS_1 = Get-WmiObject win32_networkadapter | Where { $_.PhysicalAdapter -eq $TRUE -and $_.MacAddress -ne $null } | Select-Object -ExpandProperty MACAddress
$MAC_ADDRESS = $MAC_ADDRESS_1 -join ' ' #Adding multiple addresses onto one line
$MEMORY = Get-WmiObject win32_computersystem | Select-Object -ExpandProperty TotalPhysicalMemory
$BIOS_VENDOR = Get-WmiObject win32_bios | Select-Object -ExpandProperty Manufacturer
$BIOS_VERSION = Get-WmiObject win32_bios | Select-Object -ExpandProperty SMBIOSBIOSVersion
$BIOS_RELEASE_DATE = Get-WmiObject win32_bios | Select-Object @{label='Release Date';expression={$_.ConvertToDateTime($_.releasedate).ToShortDateString()}} | Select-Object -ExpandProperty 'Release Date'
$SYSTEM_MANUFACTURER = Get-WmiObject win32_computersystemproduct | Select-Object -ExpandProperty Vendor
$SYSTEM_PRODUCT_NAME = Get-WmiObject win32_computersystemproduct | Select-Object -ExpandProperty Name
$SYSTEM_VERSION = Get-WmiObject win32_computersystemproduct | Select-Object -ExpandProperty Version
$SYSTEM_SERIAL_NUMBER = Get-WmiObject win32_computersystemproduct | Select-Object -ExpandProperty IdentifyingNumber
$SYSTEM_UUID = Get-WmiObject win32_computersystemproduct | Select-Object -ExpandProperty UUID
$BASEBOARD_MANUFACTURER = Get-WmiObject win32_baseboard | Select-Object -ExpandProperty Manufacturer
$BASEBOARD_PRODUCT_NAME = Get-WmiObject win32_baseboard | Select-Object -ExpandProperty Product
$BASEBOARD_VERSION = Get-WmiObject win32_baseboard | Select-Object -ExpandProperty Version
$BASEBOARD_SERIAL_NUMBER = Get-WmiObject win32_baseboard | Select-Object -ExpandProperty SerialNumber
$BASEBOARD_ASSET_TAG = Get-WmiObject win32_baseboard | Select-Object -ExpandProperty Tag
$CHASSIS_MANUFACTURER = Get-WmiObject win32_systemenclosure | Select-Object -ExpandProperty Manufacturer
$CHASSIS_TYPE = Get-WmiObject win32_systemenclosure | Select-Object -ExpandProperty ChassisTypes
$CHASSIS_VERSION = Get-WmiObject win32_systemenclosure | Select-Object -ExpandProperty Version
$CHASSIS_SERIAL_NUMBER = Get-WmiObject win32_systemenclosure | Select-Object -ExpandProperty SerialNumber
$CHASSIS_ASSET_TAG = Get-WmiObject win32_systemenclosure | Select-Object -ExpandProperty SMBIOSAssetTag
$PROCESSOR_FAMILY = Get-WmiObject win32_processor | Select-Object -ExpandProperty Family
$PROCESSOR_MANUFACTURER = Get-WmiObject win32_processor | Select-Object -ExpandProperty Manufacturer
$PROCESSOR_VERSION = Get-WmiObject win32_processor | Select-Object -ExpandProperty Name
$PROCESSOR_ARCH = Get-WmiObject win32_processor | Select-Object -ExpandProperty Architecture
$PROCESSOR_FREQUENCY = Get-WmiObject win32_processor | Select-Object -ExpandProperty MaxClockSpeed
# Storing all the information in a variable to convert to JSON Later
$RESULTS = (New-Object PSObject |
add-member -pass noteproperty HOSTNAME "$HOSTNAME" |
add-member -pass noteproperty OS "$OS" |
add-member -pass noteproperty OS-RELEASE "$OS_RELEASE" |
add-member -pass noteproperty IP-ADDRESS "$IP_ADDRESS" |
add-member -pass noteproperty MAC-ADDRESS "$MAC_ADDRESS" |
add-member -pass noteproperty MEMORY "$MEMORY" |
add-member -pass noteproperty BIOS-VENDOR "$BIOS_VENDOR" |
add-member -pass noteproperty BIOS-VERSION "$BIOS_VERSION" |
add-member -pass noteproperty BIOS-RELEASE-DATE "$BIOS_RELEASE_DATE" |
add-member -pass noteproperty SYSTEM-MANUFACTURER "$SYSTEM_MANUFACTURER" |
add-member -pass noteproperty SYSTEM-PRODUCT-NAME "$SYSTEM_PRODUCT_NAME" |
add-member -pass noteproperty SYSTEM-VERSION "$SYSTEM_VERSION" |
add-member -pass noteproperty SYSTEM-SERIAL-NUMBER "$SYSTEM_SERIAL_NUMBER" |
add-member -pass noteproperty SYSTEM-UUID "$SYSTEM_UUID" |
add-member -pass noteproperty BASEBOARD-MANUFACTURER "$BASEBOARD_MANUFACTURER" |
add-member -pass noteproperty BASEBOARD-PRODUCT-NAME "$BASEBOARD_PRODUCT_NAME" |
add-member -pass noteproperty BASEBOARD-VERSION "$BASEBOARD_VERSION" |
add-member -pass noteproperty BASEBOARD-SERIAL-NUMBER "$BASEBOARD_SERIAL_NUMBER" |
add-member -pass noteproperty BASEBOARD-ASSET-TAG "$BASEBOARD_ASSET_TAG" |
add-member -pass noteproperty CHASSIS-MANUFACTURER "$CHASSIS_MANUFACTURER" |
add-member -pass noteproperty CHASSIS-TYPE "$CHASSIS_TYPE" |
add-member -pass noteproperty CHASSIS-VERSION "$CHASSIS_VERSION" |
add-member -pass noteproperty CHASSIS-SERIAL-NUMBER "$CHASSIS_SERIAL_NUMBER" |
add-member -pass noteproperty CHASSIS-ASSET-TAG "$CHASSIS_ASSET_TAG" |
add-member -pass noteproperty PROCESSOR-FAMILY "$PROCESSOR_FAMILY" |
add-member -pass noteproperty PROCESSOR-MANUFACTURER "$PROCESSOR_MANUFACTURER" |
add-member -pass noteproperty PROCESSOR-VERSION "$PROCESSOR_VERSION" |
add-member -pass noteproperty PROCESSOR-ARCH "$PROCESSOR_ARCH" |
add-member -pass noteproperty PROCESSOR-FREQUENCY "$PROCESSOR_FREQUENCY" ) | ConvertTo-Json # Converting $RESULTS to JSON Format
# Double check the structure and layout is all correct
echo $RESULTS
# CouchDB Credentials
$username = Read-Host "CouchDB Username"
$password = Read-Host "CouchDB Password"
# Creating the document on the CouchDB Database
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} ; # Accepts all certificates from the host
$request = [System.Net.WebRequest]::Create("https://couchdb-host/database/$HOSTNAME1")
# Converting the Header and adding the username and password to it in base64 encoding
$auth = [System.Text.Encoding]::UTF8.GetBytes("$username" + ":" + "$password")
$base64 = [System.Convert]::ToBase64String($auth)
$authorization = "Authorization: Basic " + $base64
$request.Headers.Add($authorization)
# Adding credentials for the webrequest and address of the proxy
$request.Credentials = New-Object System.Net.NetworkCredential($username, $password)
$request.Proxy = New-Object -TypeName System.Net.WebProxy -ArgumentList "http://randomproxy:8080" # http://*hostname*:*port* format
$data = [Text.Encoding]::UTF8.GetBytes($RESULTS)
# Specifying what method to use
$request.ContentLength = $data.Length
$request.Method = "PUT"
# Be careful to set your content type appropriately...
# This is what you're going to SEND THEM
$request.ContentType = "application/json"; # 'text/xml;charset="utf-8"'; "application/x-www-form-urlencoded"
# This is what you expect back
$request.Accept = "application/json"; # "text/xml"
# Executing the PUT request
$put = new-object IO.StreamWriter $request.GetRequestStream()
$put.Write($data,0,$data.Length)
$put.Flush()
$put.Close()
|
PowerShellCorpus/PoshCode/ConvertTo-CliXml_1.ps1
|
ConvertTo-CliXml_1.ps1
|
function ConvertTo-CliXml {
param(
[parameter(position=0,mandatory=$true,valuefrompipeline=$true)]
[validatenotnull()]
[psobject]$object
)
begin {
$type = [type]::gettype("System.Management.Automation.Serializer")
$ctor = $type.getconstructor("instance,nonpublic", $null, @([xml.xmlwriter]), $null)
$sw = new-object io.stringwriter
$xw = new-object xml.xmltextwriter $sw
$serializer = $ctor.invoke($xw)
$method = $type.getmethod("Serialize", "nonpublic,instance", $null, [type[]]@([object]), $null)
$done = $type.getmethod("Done", [reflection.bindingflags]"nonpublic,instance")
}
process {
try {
[void]$method.invoke($serializer, $object)
} catch {
write-warning "Could not serialize $($object.gettype()): $_"
}
}
end {
[void]$done.invoke($serializer, @())
$sw.ToString()
}
}
|
PowerShellCorpus/PoshCode/Add new smtp_set prmary.ps1
|
Add new smtp_set prmary.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/Hack ESXi_2.ps1
|
Hack ESXi_2.ps1
|
$screen = " You see here a virtual switch. ------------ ------
#...........| |....|
--------------- ###------------ |...(|
|..%...........|########## ###-@...|
|...%...........### # ## |....|
+.......<......| ### ### |..!.|
--------------- ### ### ------
---.----- ###
|.......|####
---------
.
Clyde the Sysadmin St:7 Dx:9 Co:10 In:18 Wi:18 Ch:6 Chaotic Evil
Dlvl:3 $:120 HP:39(41) Pw:36(36) AC:6 Exp:5 T:1073
"
Set-VMHostAdvancedConfiguration -name Annotations.WelcomeMessage -value $screen
|
PowerShellCorpus/PoshCode/Get-RemoteRegistry.ps1
|
Get-RemoteRegistry.ps1
|
# Get-RemoteRegistry
# NOTE: you have to have access, and the remote registry service has to be running
param(
[string]$computer = $(Read-Host "Remote Computer Name")
,[string]$Path = $(Read-Host "Remote Registry Path (must start with HKLM,HKCU,etc)")
,[switch]$Verbose
)
if ($Verbose) { $VerbosePreference = 2 } # Only affects this script.
$root, $last = $Path.Split("\\")
$last = $last[-1]
$Path = $Path.Substring($root.Length + 1,$Path.Length - ( $last.Length + $root.Length + 2))
#split the path to get a list of subkeys that we will need to access
# ClassesRoot, CurrentUser, LocalMachine, Users, PerformanceData, CurrentConfig, DynData
switch($root) {
"HKCR" { $root = "ClassesRoot"}
"HKCU" { $root = "CurrentUser" }
"HKLM" { $root = "LocalMachine" }
"HKU" { $root = "Users" }
"HKPD" { $root = "PerformanceData"}
"HKCC" { $root = "CurrentConfig"}
"HKDD" { $root = "DynData"}
default { return "Path argument is not valid" }
}
#Access Remote Registry Key using the static OpenRemoteBaseKey method.
Write-Verbose "Accessing $root from $computer"
$rootkey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($root,$computer)
if(-not $rootkey) { Write-Error "Can't open the remote $root registry hive" }
Write-Verbose "Opening $Path"
$key = $rootkey.OpenSubKey( $Path )
if(-not $key) { Write-Error "Can't open $($root + '\\' + $Path) on $computer" }
$subkey = $key.OpenSubKey( $last )
if($subkey) {
$subkey.GetSubKeyNames() | foreach { "{0}\\" -f $_ }
$subkey.GetValueNames() | foreach { "({3}) {0} = {1}" -f $_, $subkey.GetValue($_), $subkey.GetValueKind($_) }
}
else
{
$key.GetValue($last)
}
|
PowerShellCorpus/PoshCode/Highlight syntax_1.ps1
|
Highlight syntax_1.ps1
|
#code which need highlight
$code = @'
#just example
Get-Process | % {
try {
"{0, 7} {1}" -f $_.Id, $_.MainModule.ModuleName
}
catch [System.ComponentModel.Win32Exception] {}
}
'@
function frmMain_Show {
Add-Type -AssemblyName System.Windows.Forms
#keywords
$type = New-Object "Collections.Generic.Dictionary[String, [Drawing.Color]]"
$type["Command"] = [Drawing.Color]::Cyan
$type["Comment"] = [Drawing.Color]::Gray
$type["GroupStart"] = [Drawing.Color]::Orange
$type["GroupEnd"] = [Drawing.Color]::Orange
$type["Keyword"] = [Drawing.Color]::FromArgb(0, 255, 0)
$type["Member"] = [Drawing.Color]::Tomato
$type["Operator"] = [Drawing.Color]::Linen
$type["String"] = [Drawing.Color]::Yellow
$type["Type"] = [Drawing.Color]::Silver
$type["Variable"] = [Drawing.Color]::Crimson
#main form
$frmMain = New-Object Windows.Forms.Form
$txtEdit = New-Object Windows.Forms.RichTextBox
#
#txtEdit
#
$txtEdit.BackColor = [Drawing.Color]::FromArgb(1, 36, 86)
$txtEdit.Dock = "Fill"
$txtEdit.Font = New-Object Drawing.Font("Courier New", 10, [Drawing.FontStyle]::Bold)
$txtEdit.Text = $code
#
#frmMain
#
$frmMain.ClientSize = New-Object Drawing.Size(490, 190)
$frmMain.Controls.Add($txtEdit)
$frmMain.FormBorderStyle = "FixedSingle"
$frmMain.MaximizeBox = $false
$frmMain.StartPosition = "CenterScreen"
$frmMain.Text = "gregzakh@gmail.com"
#counter
$i = 0
#highlight code
[Management.Automation.PSParser]::Tokenize(
$txtEdit.Text,
[ref](New-Object "Collections.ObjectModel.Collection[Management.Automation.PSParseError]")
) | % {
$txtEdit.SelectionStart = $_.Start - $i
$txtEdit.SelectionLength = $_.Length
#skip unnecessary types
if ($_.Type -eq "LineContinuation" -or $_.Type -eq "NewLine") {
$i++
}
else {
$txtEdit.SelectionColor = $type[$_.Type.ToString()]
}
}
#when done
$txtEdit.DeselectAll()
#show form
[void]$frmMain.ShowDialog()
}
frmMain_Show
|
PowerShellCorpus/PoshCode/vibackup-lx_1.ps1
|
vibackup-lx_1.ps1
|
Param (
$viServer,
$bakVM,
$lxDest
)
#region check
if (!$viServer) { $viServer = Read-Host -Prompt "VI Server " }
if (!$bakVM) { $bakVM = Read-Host -Prompt "VM to Backup " }
if (!$lxDest) { $lxDest = Read-Host -Prompt "Backup Path (ex. /srv/backup) " }
#endregion
#region globalvars
$encoding = "OEM"
$version = "0.7"
$scriptout = @()
[regex]$curlpat = "(\\s{1})+(.*vmdk$)"
#endregion
#region stkmvars
$viUser = "vmware"
$viPass = "vmware"
#endregion
Write-Host "viBackup Script Generator - " $version
Write-Host "--------------------------------------------"
if (($vmCon = Connect-VIServer -Protocol https $viServer) -eq "") { exit }
$vm = Get-VM $bakVM -Server $vmCon -ErrorAction SilentlyContinue
if (!$vm) {
Write-Host "No VM found."
Write-Host "Enter the Display Name from the VI Center:" -NoNewline
$tvm = Read-Host
if (!($vm=Get-VM $tvm -ErrorAction SilentlyContinue)) {
return $false
exit
}
Write-Host "You have entered 2 different Names. Please check that the VMX and the VM Name are the same!"
Write-Host -ForegroundColor yellow "Entered VMX Name: {$bakVM}"
Write-Host -ForegroundColor yellow "Entered VM Name: {$tvm}"
Write-Host -ForegroundColor yellow "Returned VM Name: {$vm}"
Write-Host -ForegroundColor yellow "IS THIS CORRECT (Yes/No)?:" -NoNewline
$sure = Read-Host
if ($sure -ne "yes") { exit }
}
#check Snapshots
if ((Get-Snapshot -VM $vm -Server $vmCon)) {
Write-Host "VM has Snapshots. No Backup possible."
return $false
exit
}
#check HardDisk Mode
foreach ($hd in $vm.harddisks) {
if ($hd.Persistence -ne "Persistent") {
write-host "Hard Disk is not Persistent - no Snapshot allowed."
return $false
exit
}
}
#write script
$scriptname = $vm.name + ".sh"
$vmname = $vm.name
$vmhost = $vm.Host
$vmview= Get-View $vm.id
$vmvname = $vmview.config.files.vmpathname
#generate Text
$header = "#!/bin/bash"
$user = "USER=`"${viUser}`""
$pass = "PASS=`"${viPass}`""
$dest = "DEST=`"${lxDest}`""
$lxVM = "VM=`"${vmname}`""
$dcPath = $vm | Get-Datacenter
#region writefile
$scriptout += $header
$scriptout += $user
$scriptout += $pass
$scriptout += $dest
$scriptout += $lxvm
$scriptout += ""
$scriptout += "BKUP=`"${vmvname}`""
$scriptout += "SNAPCHECK=``vmware-cmd -H ${viserver} -T ${vmhost} -U `${USER} -P `${PASS} `"`${BKUP}`" hassnapshot`` "
$scriptout += "if [ `"`$SNAPCHECK`" != `"hassnapshot () =`" ]; then `n echo 'VM has a Snapshot. Aborting...' `n exit `n fi"
$scriptout += "vmrun -T esx -h https://${viserver}/sdk -u `${USER} -p `${PASS} snapshot `"`${BKUP}`" vmBackup"
# Hard Disk
foreach ($hd in $vm.Harddisks) {
$hdname = $hd.Filename
$patstr = $curlpat.split($hdname)
#dirty hack
$patstr[0] = $patstr[0].replace("[","")
$patstr[0] = $patstr[0].replace("]","")
$dsPath = $patstr[0].replace(" ","%20")
$vmdkpath = $patstr[2].replace(" ","%20")
$vmdkflatpath = $patstr[2].replace(".vmdk","-flat.vmdk")
#curl options
$vmdk = "curl --user `${USER}:`${PASS} -o `${DEST}/`${VM}.vmdk `"https://${viserver}/folder/${vmdkpath}?dcPath=${dcPath}&dsName=${dsPath}`" --insecure "
$vmdkflat = "curl --user `${USER}:`${PASS} -o `${DEST}/`${VM}.vmdk `"https://${viserver}/folder/${vmdkflatpath}?dcPath=${dcPath}&dsName=${dsPath}`" --insecure"
#$vmdk = "vifs --server ${viserver} --dc 'KM' --username `${USER} --password `${PASS} --get `"``echo $hdname```" `${DEST}/`${VM}.vmdk "
#$vmdkflat = "vifs --server ${viserver} --dc 'KM' --username `${USER} --password `${PASS} --get `"``echo $hdname | sed 's/.vmdk/-flat.vmdk/g'```" `${DEST}/`${VM}-flat.vmdk "
$scriptout += $vmdk
$scriptout += $vmdkflat
}
$scriptout += "vmrun -T esx -h https://${viserver}/sdk -u `${USER} -p `${PASS} deleteSnapshot `"`${BKUP}`" vmBackup"
$scriptout | Out-File $scriptname -Encoding $encoding
#endregion
Write-Host "Finished"
Write-Host "Don't forget to convert the script under *nix/Linux with dos2unix!"
|
PowerShellCorpus/PoshCode/Compare-AD.ps1
|
Compare-AD.ps1
|
###############################################################################
# Compare-AD - a set of functions (and sample code using them) to create
# snapshots of user accounts in the current Active Directory domain
# save them in an xml file, and then compare live AD environment
# against that XML
#
# (C) Dmitry Sotnikov
# http://dmitrysotnikov.wordpress.com/2008/10/14/compare-ad-against-snapshotscompare-ad-against-snapshots
#
###############################################################################
# Requires QAD cmdlets
if ((Get-PSSnapin "Quest.ActiveRoles.ADManagement" `
-ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin "Quest.ActiveRoles.ADManagement"
}
###############################################################################
# Functions
###############################################################################
# Retrives all AD users from the current domain and stores the selected
# set of properties (passed as an array of strings in the $properties parameter)
# as an xml file by the path passed as $path
# See sample use below
function New-Snapshot {
param($path, $properties)
Get-QADUser -SizeLimit 0 -DontUseDefaultIncludedProperties `
-IncludedProperties $properties |
Select $properties | Export-Clixml $path
}
# Load the snapshot and compare it against current AD domain
function Compare-ActiveDirectory {
param($path, $properties)
# $old is the snapshot, $new is the current environment data
$old = Import-Clixml $path
$new = Get-QADUser -SizeLimit 0 -DontUseDefaultIncludedProperties `
-IncludedProperties $properties |
Select $properties
# First lets report the ones which got created or deleted
$diff = Compare-Object $old $new -Property Name
$created = , ($diff | where { $_.SideIndicator -eq "=>" })
$deleted = , ($diff | where { $_.SideIndicator -eq "<=" })
if ( $created.Count -gt 0 ) {
"New accounts:"
$created | Format-Table Name
}
if ( $deleted.Count -gt 0 ) {
"Deleted accounts:"
$deleted | Format-Table Name
}
# Now let's load the accounts in a hash-table so it is easier to locate them
$hash = @{}
$new | ForEach-Object { $hash[$_.DistinguishedName] = $_ }
# Let's enumerate the accounts and their properties and report any changes
"Modified objects:"
foreach ( $snapshot in $old ) {
$current = $hash[$snapshot.DistinguishedName]
if ( $current -and
($current.ModificationDate -ne $snapshot.ModificationDate )) {
@"
Object $($snapshot.distinguishedname)
Modified at $($current.ModificationDate)
Property`tOld Value`tNew Value
========`t=========`t=========
"@
foreach ($property in $properties) {
if ( ($property -ne "ModificationDate") -and
($snapshot.$property -ne $current.$property )) {
"$property`t$($snapshot.$property)`t$($current.$property)"
}
}
}
}
}
###############################################################################
# Common parameters
###############################################################################
# These are the properties to be compared
# Make sure they include Name, DistinguishedName, and ModificationDate
# Remove the TS attributes if your system requirements for retrieving those
# are not met:
# http://dmitrysotnikov.wordpress.com/2008/07/23/system-requirements-for-powershell-terminal-services-management/
$Members_to_Compare = @( "Name", "DistinguishedName", "ModificationDate",
"AccountIsDisabled", "AccountIsLockedOut", "AccountName",
"CanonicalName", "City", "Company", "Department", "Description",
"DisplayName", "Email", "Fax",
"FirstName", "HomeDirectory", "HomeDrive", "HomePhone", "Initials",
"LastName", "LdapDisplayName", "LogonName", "LogonScript", "Manager",
"MobilePhone", "Notes", "Office", "Pager",
"ParentContainerDN", "PasswordNeverExpires",
"PhoneNumber", "PostalCode", "PostOfficeBox", "ProfilePath",
"SamAccountName", "StateOrProvince", "StreetAddress", "Title",
"TsAllowLogon", "TsBrokenConnectionAction", "TsConnectClientDrives",
"TsConnectPrinterDrives", "TsDefaultToMainPrinter", "TsHomeDirectory",
"TsHomeDrive", "TsInitialProgram", "TsMaxConnectionTime",
"TsMaxDisconnectionTime", "TsMaxIdleTime", "TsProfilePath",
"TsReconnectionAction", "TsRemoteControl", "TsWorkDirectory",
"UserPrincipalName", "WebPage" )
# Path to the snapshot file
$SnapshotPath = "c:\\snapshot.xml"
###############################################################################
# Sample usage
###############################################################################
# Create a snapshot
New-Snapshot -Path $SnapshotPath -Properties $Members_to_Compare
# Make some changes
New-QADUser -Name "Lawrence Alford" -ParentContainer mydomain.local/test
Set-QADUser "Jennifer Clarke" -PhoneNumber "(249) 111-22-33"
Set-QADUser "Ernest Cantrell" -City "San Francisco"
Remove-QADObject "Andreas Bold" -Force
# Let's see if we find them
Compare-ActiveDirectory -Path $SnapshotPath -Properties $Members_to_Compare
|
PowerShellCorpus/PoshCode/SuperMario PowerShell.ps1
|
SuperMario PowerShell.ps1
|
[System.Console]::Beep(659, 125)
[System.Console]::Beep(659, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(659, 125)
Start-Sleep -Milliseconds 167
[System.Console]::Beep(523, 125)
[System.Console]::Beep(659, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(784, 125)
Start-Sleep -Milliseconds 375
[System.Console]::Beep(392, 125)
Start-Sleep -Milliseconds 375
[System.Console]::Beep(523, 125)
Start-Sleep -Milliseconds 250
[System.Console]::Beep(392, 125)
Start-Sleep -Milliseconds 250
[System.Console]::Beep(330, 125)
Start-Sleep -Milliseconds 250
[System.Console]::Beep(440, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(494, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(466, 125)
Start-Sleep -Milliseconds 42
[System.Console]::Beep(440, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(392, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(659, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(784, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(880, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(698, 125)
[System.Console]::Beep(784, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(659, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(523, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(587, 125)
[System.Console]::Beep(494, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(523, 125)
Start-Sleep -Milliseconds 250
[System.Console]::Beep(392, 125)
Start-Sleep -Milliseconds 250
[System.Console]::Beep(330, 125)
Start-Sleep -Milliseconds 250
[System.Console]::Beep(440, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(494, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(466, 125)
Start-Sleep -Milliseconds 42
[System.Console]::Beep(440, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(392, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(659, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(784, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(880, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(698, 125)
[System.Console]::Beep(784, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(659, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(523, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(587, 125)
[System.Console]::Beep(494, 125)
Start-Sleep -Milliseconds 375
[System.Console]::Beep(784, 125)
[System.Console]::Beep(740, 125)
[System.Console]::Beep(698, 125)
Start-Sleep -Milliseconds 42
[System.Console]::Beep(622, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(659, 125)
Start-Sleep -Milliseconds 167
[System.Console]::Beep(415, 125)
[System.Console]::Beep(440, 125)
[System.Console]::Beep(523, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(440, 125)
[System.Console]::Beep(523, 125)
[System.Console]::Beep(587, 125)
Start-Sleep -Milliseconds 250
[System.Console]::Beep(784, 125)
[System.Console]::Beep(740, 125)
[System.Console]::Beep(698, 125)
Start-Sleep -Milliseconds 42
[System.Console]::Beep(622, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(659, 125)
Start-Sleep -Milliseconds 167
[System.Console]::Beep(698, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(698, 125)
[System.Console]::Beep(698, 125)
Start-Sleep -Milliseconds 625
[System.Console]::Beep(784, 125)
[System.Console]::Beep(740, 125)
[System.Console]::Beep(698, 125)
Start-Sleep -Milliseconds 42
[System.Console]::Beep(622, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(659, 125)
Start-Sleep -Milliseconds 167
[System.Console]::Beep(415, 125)
[System.Console]::Beep(440, 125)
[System.Console]::Beep(523, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(440, 125)
[System.Console]::Beep(523, 125)
[System.Console]::Beep(587, 125)
Start-Sleep -Milliseconds 250
[System.Console]::Beep(622, 125)
Start-Sleep -Milliseconds 250
[System.Console]::Beep(587, 125)
Start-Sleep -Milliseconds 250
[System.Console]::Beep(523, 125)
Start-Sleep -Milliseconds 1125
[System.Console]::Beep(784, 125)
[System.Console]::Beep(740, 125)
[System.Console]::Beep(698, 125)
Start-Sleep -Milliseconds 42
[System.Console]::Beep(622, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(659, 125)
Start-Sleep -Milliseconds 167
[System.Console]::Beep(415, 125)
[System.Console]::Beep(440, 125)
[System.Console]::Beep(523, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(440, 125)
[System.Console]::Beep(523, 125)
[System.Console]::Beep(587, 125)
Start-Sleep -Milliseconds 250
[System.Console]::Beep(784, 125)
[System.Console]::Beep(740, 125)
[System.Console]::Beep(698, 125)
Start-Sleep -Milliseconds 42
[System.Console]::Beep(622, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(659, 125)
Start-Sleep -Milliseconds 167
[System.Console]::Beep(698, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(698, 125)
[System.Console]::Beep(698, 125)
Start-Sleep -Milliseconds 625
[System.Console]::Beep(784, 125)
[System.Console]::Beep(740, 125)
[System.Console]::Beep(698, 125)
Start-Sleep -Milliseconds 42
[System.Console]::Beep(622, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(659, 125)
Start-Sleep -Milliseconds 167
[System.Console]::Beep(415, 125)
[System.Console]::Beep(440, 125)
[System.Console]::Beep(523, 125)
Start-Sleep -Milliseconds 125
[System.Console]::Beep(440, 125)
[System.Console]::Beep(523, 125)
[System.Console]::Beep(587, 125)
Start-Sleep -Milliseconds 250
[System.Console]::Beep(622, 125)
Start-Sleep -Milliseconds 250
[System.Console]::Beep(587, 125)
Start-Sleep -Milliseconds 250
[System.Console]::Beep(523, 125)
Start-Sleep -Milliseconds 625
|
PowerShellCorpus/PoshCode/Send-MailMessage_1.ps1
|
Send-MailMessage_1.ps1
|
##############################################################################
##
## Send-MailMessage
##
## From Windows PowerShell Cookbook (O'Reilly)
## by Lee Holmes (http://www.leeholmes.com/guide)
##
## Illustrate the techniques used to send an email in PowerShell.
## In version two, use the Send-MailMessage cmdlet.
##
## Example:
##
## PS >$body = @"
## >> Hi from another satisfied customer of The PowerShell Cookbook!
## >> "@
## >>
## PS >$to = "guide_feedback@leeholmes.com"
## PS >$subject = "Thanks for all of the scripts."
## PS >$mailHost = "mail.leeholmes.com"
## PS >Send-MailMessage $to $subject $body $mailHost
##
##############################################################################
param(
## The recipient of the mail message
[string[]] $To = $(throw "Please specify the destination mail address"),
## The subjecty of the message
[string] $Subject = "<No Subject>",
## The body of the message
[string] $Body = $(throw "Please specify the message content"),
## The SMTP host that will transmit the message
[string] $SmtpHost = $(throw "Please specify a mail server."),
## The sender of the message
[string] $From = "$($env:UserName)@example.com"
)
## Create the mail message
$email = New-Object System.Net.Mail.MailMessage
## Populate its fields
foreach($mailTo in $to)
{
$email.To.Add($mailTo)
}
$email.From = $from
$email.Subject = $subject
$email.Body = $body
## Send the mail
$client = New-Object System.Net.Mail.SmtpClient $smtpHost
$client.UseDefaultCredentials = $true
$client.Send($email)
|
PowerShellCorpus/PoshCode/ISE-Lines_3.ps1
|
ISE-Lines_3.ps1
|
#requires -version 2.0
## ISE-Lines module v 1.1
## DEVELOPED FOR CTP3
## See comments for each function for changes ...
##############################################################################################################
## Provides Line cmdlets for working with ISE
## Duplicate-Line - Duplicates current line
## Conflate-Line - Conflates current and next line
## MoveUp-Line - Moves current line up
## MoveDown-Line - Moves current line down
## Delete-TrailingBlanks - Deletes trailing blanks in the whole script
##############################################################################################################
## Duplicate-Line
##############################################################################################################
## Duplicates current line
##############################################################################################################
function Duplicate-Line
{
$editor = $psISE.CurrentFile.Editor
$caret_row = $editor.CaretLine
$caret_col = $editor.CaretColumn
$this_line_text = $editor.Text.Split("`n")[$caret_row - 1].TrimEnd([environment]::NewLine)
$editor.SetCaretPosition($caret_row, $this_line_text.length + 1)
$editor.InsertText("`r`n" + $this_line_text)
$editor.SetCaretPosition($caret_row, $caret_col)
}
## Conflate-Line
##############################################################################################################
## Conflates current and next line
## v 1.1 fixed bug on last but one line and remove line continuation character while joining
##############################################################################################################
function Conflate-Line
{
$editor = $psISE.CurrentOpenedFile.Editor
$caretLine = $editor.CaretLine
$caretColumn = $editor.CaretColumn
$text = $editor.Text.Split("`n")
if ( $caretLine -ne $text.Count )
{
$line = $text[$caretLine -1] + $text[$caretLine] -replace ("(``)?`r", "")
$newText = @()
if ( $caretLine -gt 1 )
{
$newText = $text[0..($caretLine -2)]
}
$newText += $line
if ( $caretLine -ne $text.Count - 1)
{
$newText += $text[($caretLine +1)..($text.Count -1)]
}
$editor.Text = [String]::Join("`n", $newText)
$editor.SetCaretPosition($caretLine, $caretColumn)
}
}
## MoveUp-Line
##############################################################################################################
## Moves current line up
##############################################################################################################
function MoveUp-Line
{
$editor = $psISE.CurrentOpenedFile.Editor
$caretLine = $editor.CaretLine
if ( $caretLine -ne 1 )
{
$caretColumn = $editor.CaretColumn
$text = $editor.Text.Split("`n")
$line = $text[$caretLine -1]
$lineBefore = $text[$caretLine -2]
$newText = @()
if ( $caretLine -gt 2 )
{
$newText = $text[0..($caretLine -3)]
}
$newText += $line
$newText += $lineBefore
if ( $caretLine -ne $text.Count )
{
$newText += $text[$caretLine..($text.Count -1)]
}
$editor.Text = [String]::Join("`n", $newText)
$editor.SetCaretPosition($caretLine - 1, $caretColumn)
}
}
## MoveDown-Line
##############################################################################################################
## Moves current line down
##############################################################################################################
function MoveDown-Line
{
$editor = $psISE.CurrentOpenedFile.Editor
$caretLine = $editor.CaretLine
$caretColumn = $editor.CaretColumn
$text = $editor.Text.Split("`n")
if ( $caretLine -ne $text.Count )
{
$line = $text[$caretLine -1]
$lineAfter = $text[$caretLine]
$newText = @()
if ( $caretLine -ne 1 )
{
$newText = $text[0..($caretLine -2)]
}
$newText += $lineAfter
$newText += $line
if ( $caretLine -lt $text.Count -1 )
{
$newText += $text[($caretLine +1)..($text.Count -1)]
}
$editor.Text = [String]::Join("`n", $newText)
$editor.SetCaretPosition($caretLine +1, $caretColumn)
}
}
## Delete-TrailingBlanks
##############################################################################################################
## Deletes trailing blanks in the whole script
##############################################################################################################
function Delete-TrailingBlanks
{
$editor = $psISE.CurrentOpenedFile.Editor
$caretLine = $editor.CaretLine
$newText = @()
foreach ( $line in $editor.Text.Split("`n") )
{
$newText += $line -replace ("\\s+$", "")
}
$editor.Text = [String]::Join("`n", $newText)
$editor.SetCaretPosition($caretLine, 1)
}
##############################################################################################################
## Inserts a submenu Lines to ISE's Custum Menu
## Inserts command Duplicate Line to submenu Lines
## Inserts command Conflate Line Selected to submenu Lines
## Inserts command Move Up Line to submenu Lines
## Inserts command Move Down Line to submenu Lines
## Inserts command Delete Trailing Blanks to submenu Lines
##############################################################################################################
if (-not( $psISE.CustomMenu.Submenus | where { $_.DisplayName -eq "Line" } ) )
{
$lineMenu = $psISE.CustomMenu.Submenus.Add("_Lines", $null, $null)
$null = $lineMenu.Submenus.Add("Duplicate Line", {Duplicate-Line}, "Ctrl+Alt+D")
$null = $lineMenu.Submenus.Add("Conflate Line", {Conflate-Line}, "Ctrl+Alt+J")
$null = $lineMenu.Submenus.Add("Move Up Line", {MoveUp-Line}, "Ctrl+Shift+Up")
$null = $lineMenu.Submenus.Add("Move Down Line", {MoveDown-Line}, "Ctrl+Shift+Down")
$null = $lineMenu.Submenus.Add("Delete Trailing Blanks", {Delete-TrailingBlanks}, "Ctrl+Shift+Del")
}
|
PowerShellCorpus/PoshCode/ShowUI Clock 6.ps1
|
ShowUI Clock 6.ps1
|
New-UIWidget -AsJob -Content {
$shadow = DropShadowEffect -Color Black -Shadow 0 -Blur 8
$now = Get-Date;
StackPanel {
TextBlock -Name "Time" ('{0:h:mm tt}' -f $now) -FontSize 108 -LineHeight 100 -LineStackingStrategy BlockLineHeight -Margin 0 -Padding 0 -Foreground White -Effect $shadow -FontFamily "Century Gothic"
StackPanel -Orientation Horizontal {
TextBlock -Name "Day" ('{0:dd}' -f $now) -FontSize 80 -LineHeight 80 -LineStackingStrategy BlockLineHeight -Margin 0 -Padding 0 -Foreground White -Opacity 0.6 -Effect $shadow -FontFamily "Century Gothic"
StackPanel {
TextBlock -Name "Month" ('{0:MMMM}' -f $now).ToUpper() -fontsize 40 -LineHeight 40 -LineStackingStrategy BlockLineHeight -Margin 0 -Padding 0 -FontFamily "Century Gothic"
TextBlock -Name "Weekday" ('{0:dddd}' -f $now).ToUpper() -fontsize 28 -LineHeight 28 -LineStackingStrategy BlockLineHeight -Margin 0 -Padding 0 -Foreground White -Effect $shadow -FontFamily "Century Gothic"
} -Margin 0
} -Margin 0
} -Margin 0
} -Interval "0:0:0.2" -UpdateBlock {
$now = Get-Date
$Time.Text = '{0:h:mm tt}' -f $now
$Day.Text = '{0:dd}' -f $now
$Month.Text = ('{0:MMMM}' -f $now).ToUpper()
$Weekday.Text = ('{0:dddd}' -f $now).ToUpper()
}
|
PowerShellCorpus/PoshCode/GPRS Online log_5.ps1
|
GPRS Online log_5.ps1
|
<#
.SYNOPSIS
Get-GprsTime (V3.3 Update for Windows 7) Check the total connect time of any
GPRS devices from a specified date.
Use Get-Help .\\Get-GprsTime -full to view Help for this file.
.DESCRIPTION
Display all the GPRS modem Event Log entries. While applications issued by the
mobile phone manufacturers will invariably monitor only their own usage, this
will show any logged GPRS activity, be it via PCMCIA, USB, mobile phone, etc.
Use the -Verbose switch for some extra information if desired. A default value
can be set with the -Monthly switch but can be temporarily overridden with any
-Start value and deleted by entering an invalid date. Now uses .NET Parse to
use any culture date input. Switches -M and -S cannot be used together.
A Balloon prompt will be issued in the Notification area for the 5 days
before the nominal month end.
NOTE: this can effectively be suppressed by using a value higher than the SIM
card term, ie something like -Account 90 for a 30 day card which will override
the default setting. Use -Today to check only today's usage.
Define a function in $profile to set any permanent switches, for example to
set the account value permanently to 30 days.
function GPRS {
Invoke-Expression "Get-GprsTime -Account 30 $args"
}
.EXAMPLE
.\\Get-GprsTime.ps1 -Monthly 4/8/2011
This will set the default search date to start from 4/8/2011 and is used to
reset the start date each month for the average 30/31 day SIM card.
.EXAMPLE
.\\Get-GprsTime.ps1 -Start 12/07/2009 -Account 100 -Verbose
Search from 12/07/2011 and also show (Verbose) details for each session. The
Account switch will override any balloon prompt near the SIM expiry date.
.EXAMPLE
.\\Get-GprsTime.ps1 5/9/2011 -v
Search one day only and show session details.
.EXAMPLE
.\\Get-GprsTime.ps1 -Today
Show all sessions for today. This always defaults to verbose output.
.EXAMPLE
.\\Get-GprsTime.ps1 -Debug
This shows the first available Event Log record & confirms switch settings.
(Note that it will probably not be the first 'RemoteAccess' or 'RasClient'
record).
.NOTES
A shorter total time than that actually used will result if the Event Log
does not contain earlier dates; just increase the log size in such a case.
The author can be contacted at www.SeaStarDevelopment.Bravehost.com and a
(binary compiled) Module version of this procedure is included in the file
Gprs3xxx.zip download there; the execution time of the module being about
10 times faster than this script.
Use '(measure-Command {.\\Get-GprsTime}).TotalSeconds' to confirm the times.
For the Event Log to record connect & disconnect events, the modem software
should be set to RAS rather than NDIS if possible.
#>
Param ([String] $start,
[String] $monthly,
[Int] $account = 0, #Start warning prompt 5 days before month end.
[Switch] $today,
[Switch] $verbose,
[Switch] $debug)
Trap [System.Management.Automation.MethodInvocationException] {
[Int]$line = $error[0].InvocationInfo.ScriptLineNumber
[System.Media.SystemSounds]::Hand.Play()
if ($line -eq 197) {
Write-Warning "[$name] Current GPRS variable has been deleted."
$monthly = ""
[Environment]::SetEnvironmentVariable("GPRS",$monthly,"User")
}
else {
Write-Warning "[$name] Date is missing or invalid $SCRIPT:form"
}
exit 1
}
#Establish the Operating System...We only need to confirm XP here.
#The result will be written to the 'out' variable '$osv'.
function Get-OSVersion($computer,[ref]$osv) {
$os = Get-WmiObject -class Win32_OperatingSystem -computerName $computer
Switch -regex ($os.Version) {
'^5\\.1\\.(\\d{1,4})$' { $osv.value = "xp" } #Find XP & variants.
default { $osv.value = "unknown" }
}
}
$osv = $null
Get-OSVersion -computer 'localhost' -osv ([ref]$osv)
if ($osv -eq 'xp') {
$logname = 'System'
$connEvent = 20158
$discEvent = 20159
$source = 'RemoteAccess'
}
else { #Treat As Vista or Windows 7.
$logname = 'Application'
$connEvent = 20225
$discEvent = 20226
$source = 'RasClient'
}
$entryType = 'Information'
$logEntry = $null
$oldest = Get-eventlog -LogName $logname | #Get the earliest Log record.
Sort-Object TimeGenerated |
Select-Object -first 1
if ($oldest.TimeGenerated) {
$logEntry = "System Event records available from - $($oldest.TimeGenerated.ToLongDateString())"
}
$name = $myInvocation.MyCommand
$newLine = "[$name] The switches -Start and -Monthly can only be used separately."
if ($debug) {
$DebugPreference = 'Continue'
}
if ($start -and $monthly) {
[System.Media.SystemSounds]::Hand.Play()
Write-Warning "$newLine"
exit 1
}
$SCRIPT:form = ""
#In certain cases Culture & UICulture can be different and have been known to
# return conflicting results regarding '-is [DateTime]' queries, etc.
if ($Host.CurrentCulture -eq $Host.CurrentUICulture) {
$SCRIPT:form = '-Use format mm/dd/year'
[Int]$culture = "{0:%d}" -f [DateTime] "6/5/2009" #Returns local day.
If ($culture -eq 6) {
$SCRIPT:form = '-Use format dd/mm/year'
}
}
$ErrorActionPreference = 'SilentlyContinue'
$VerbosePreference = 'SilentlyContinue'
$WarningPreference = 'Continue'
$conn = $disc = $default = $print = $null
$timeNow = [DateTime]::Now
$total = $timeNow - $timeNow #Set initial value to 00:00:00.
$insert = "since"
if ($verbose) {
$VerbosePreference = 'Continue'
}
function CreditMsg ($value, $value2) {
$value = [Math]::Abs($value)
$prefix = "CURRENT"
[DateTime] $creditDT = $value2
$creditDT = $creditDT.AddDays($value) #Add the -Account days.
$thisDay = "{0:M/d/yyyy}" -f [DateTime]::Now #Force US format.
#If we use '$number = $creditDT - (Get-Date)' instead of the line below we
#can sometimes get a value of 1 returned instead 2, hence the above lines.
$number = $creditDT - [DateTime] $thisDay
[String] $credit = $creditDT
$credit = $credit.Replace('00:00:00','') #Remove any trailing time.
$credit = "{0:d}" -f [DateTime]$credit
Switch($number.Days) {
1 {$prefix = "($value days) will expire tomorrow"; break}
0 {$prefix = "($value days) will expire today"; break}
-1 {$prefix = "($value days) expired yesterday"; break}
{($_ -lt 0)} {$prefix = "($value days) expired on $credit"; break}
{($_ -le 5)} {$prefix = "($value days) will expire on $credit"}
Default {$prefix = "CURRENT"} #Only come here if over 5 days.
}
return $prefix
}
function Interval ([String] $value) {
Switch -regex ($value) {
'^00:00:\\d+(.*)$' {$suffix = "seconds"; break}
'^00:\\d+:\\d+(.*)$' {$suffix = "minutes"; break}
'^\\d+:\\d+:\\d+(.*)$' {$suffix = " hours"; break}
'^(\\d+)\\D(\\d+)(.*)$' {$suffix = " hours"
$pDays = $matches[1]
$pHours = $matches[2]
[string]$pMinSec = $matches[3]
[string]$tHours = (([int]$pDays) * 24)+[int]$pHours
$value = $tHours + $pminSec; break}
default {$suffix = " hours"} #Should never come here!
}
return "$value $suffix"
}
function CheckSetting ($value) {
if ($value) { #Correct for local culture.
$print = $default.ToShortDateString()
}
else {
$print = "(Value not set)"
}
return $print
}
#The Script effectively starts here.............................................
$getGprs = [Environment]::GetEnvironmentVariable("GPRS","User")
#First check for GPRS variable and change from US date format to current locale.
if ([DateTime]::TryParse($getGprs, [Ref]$timeNow)) { #No error as date is valid.
$default = "{0:d}" -f [datetime]$getGprs
$default = [DateTime]::Parse($default)
$checkParts = "{0:yyyy},{0:%M}" -f $default
$times = $checkParts.Split(',')
$dayCount = [DateTime]::DaysInMonth($times[0],$times[1]) #Range 28-31.
if($account -eq 0) {
$account = $dayCount
$summary = "$($dayCount.ToString()) days"
}
else {
$summary = "$($account.Tostring()) days"
}
$text = CreditMsg $account $getGprs #Check if within 5 days of expiry date.
if ($text -ne "CURRENT") {
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon
$objNotifyIcon.Icon = [System.Drawing.SystemIcons]::Exclamation
$objNotifyIcon.BalloonTipIcon = "Info"
$objNotifyIcon.BalloonTipTitle = "GPRS online account"
$objNotifyIcon.BalloonTipText = "Credit $text"
$objNotifyIcon.Visible = $True
$objNotifyIcon.ShowBalloonTip(10000)
}
}
else {
$summary = "(Days not set)"
if ((!$today) -and (!$monthly) -and (!$start)) {
[System.Media.SystemSounds]::Hand.Play()
Write-Warning("Monthly date is either invalid or not set.")
exit 1
}
}
if ($start) {
$start = [DateTime]::Parse($start) #Trigger TRAP if invalid!
[DateTime]$limit = $start
$convert = "{0:D}" -f $limit
$print = CheckSetting $default
}
if ($monthly) {
$start = [DateTime]::Parse($monthly) #Trigger TRAP if invalid!
Write-Output "Setting GPRS (monthly) environment variable to: $monthly"
$gprs = [String]$start.Replace('00:00:00','')
[Environment]::SetEnvironmentVariable("GPRS",$gprs,"User")
[DateTime] $limit = $start #Change to required US date format.
$convert = "{0:D}" -f $limit
$print = $limit.ToShortDateString()
$summary = "(Days undetermined)" #Will show next time around.
}
if ($today) {
$verBosePreference = 'Continue' #Show VERBOSE by default.
[DateTime] $limit = (Get-Date)
$convert = "{0:D}" -f $limit
$limit = $limit.Date #Override any start date if using -Today input.
$insert = "for today"
$print = CheckSetting $default
}
if ((!$today) -and (!$monthly) -and (!$start)) {
if ($default) {
$monthly = $default
[DateTime] $limit = $monthly
$convert = "{0:D}" -f $limit
$print = CheckSetting $default
}
}
Write-Verbose "All records $($insert.Replace('for ','')) - $convert"
Write-Verbose "Script activation - User [$($env:UserName)] Computer [$($env:ComputerName)]"
Write-Output ""
Write-Output "Calculating total connect time of all GPRS modem devices..."
#We cannot proceed beyond here without a valid $limit value.
Write-Debug "Using - [Search date] $($limit.ToShortDateString()) [Account] $summary [GPRS Monthly] $print"
if ($logEntry) {
Write-Debug "$logEntry"
}
$lines = Get-EventLog $logname | Where-Object {($_.TimeGenerated -ge $limit) -and `
($_.EventID -eq $discEvent -or $_.EventID -eq $connEvent)}
if ($lines) {
Write-Verbose "A total of $([Math]::Truncate($lines.Count/2)) online sessions extracted from the System Event Log."
}
else {
Write-Output "(There are no events indicated in the System Event Log)"
}
$lines | ForEach-Object {
$source = $_.Source
if ($_.EventID -eq $discEvent) { #Event 20159 is Disconnect.
$disc = $_.TimeGenerated
}
else { #Event 20158 is Connect.
$conn = $_.TimeGenerated
} #We are only interested in matching pairs of DISC/CONN...
if ($disc -ne $null -and $conn -ne $null -and $disc -gt $conn) {
$diff = $disc - $conn
$total += $diff
$convDisc = "{0:G}" -f $disc
$convConn = "{0:G}" -f $conn
$period = Interval $diff
Write-Verbose "Disconnect at $convDisc. Online - $period"
Write-Verbose " Connect at $convConn."
}
} #End ForEach
if (!$source) {
$source = '(Undetermined)'
}
Write-Verbose "Using local event source - System Event Log [$source]"
$period = Interval $total
Write-Output "Total online usage $insert $convert is $($period.Replace(' ',' '))."
Write-Output ""
|
PowerShellCorpus/PoshCode/LetterDiamondOneliner v_3.ps1
|
LetterDiamondOneliner v_3.ps1
|
&{param([char]$c)[int]$s=65;$p=$c-$s;$r=,(' '*$p+[char]$s);$r+=@(do{"{0,$p} {1}{0}"-f([char]++$s),(' '*$f++)}until(!--$p));$r;$r[-2..-99]}Z
# trimmed 130 chars w/o arg
&{param([char]$c)$p=$c-($s=65);$r=,(' '*$p+[char]$s);do{$r+="{0,$p} {1}{0}"-f([char]++$s),(' '*$f++)}until(!--$p);$r;$r[-2..-99]}J
# trimmed to 127 chars w/o arg
&{$p=[char]$args[0]-($s=65);$r=,(' '*$p+[char]$s);do{$r+="{0,$p} {1}{0}"-f([char]++$s),(' '*$f++)}until(!--$p);$r;$r[-2..-99]}J
|
PowerShellCorpus/PoshCode/ConvertFrom-Property_2.ps1
|
ConvertFrom-Property_2.ps1
|
<#
.SYNOPSIS
Converts data from flat or single-level property files into PSObjects
.DESCRIPTION
Converts delimited string data into objects
.PARAMETER InputObject
The text to be parsed
.PARAMETER FilePath
A file containing text to be parsed (so you can pipeline files to be processed)
.PARAMETER ValueSeparator
The value separator string used between name=value pairs. Allows regular expressions.
Typical values are "=" or ":" or ";"
Defaults to "="
.PARAMETER PropertySeparator
The property separator string used between sets of name=value pairs. Allows regular expressions.
Typical values are "`n" or "`n`n" or "\\n\\s*\\n"
Defaults to "\\n\\s*\\n?"
.PARAMETER CountOfPropertiesPerRecord
Separate the input into groups of a certain number of properties.
If your input file has no specific record separator, you can usually match the first property by using a look-ahead expression *(See Example 2)*
However, if the properties aren't in the same order each time or regular expressions make you queasy, and each of your records have the same number of properties on each record, you can use this to separate them by count.
.PARAMETER RecordSeparator
The record separator string is used between records or sections in a text file.
Typical values are "\\n\\s*\\n" or "\\n\\[(.*)\\]\\s*\\n"
Defaults to "\\n\\[(.+)\\]\\s*\\n" (the correct value for ini files).
To support named sections or records, make sure to use a regular expression here that has a capture group defined.
.PARAMETER AutomaticRecords
Supports guessing when a new record starts based on the repetition of a property name. You can use this whenever your input has multiple records and the properties are always in the same order.
.PARAMETER SimpleOutput
Prevent outputting the PSName parameter which indicates the source of the object when pipelineing file names
.EXAMPLE
ConvertFrom-PropertyString config.ini
Reads in an ini file (which has key=value pairs), using the default settings
.EXAMPLE
@"
ID:3468
Type:Developer
StartDate:1998-02-01
Code:SWENG3
Name:Baraka
ID:11234
Type:Management
StartDate:2005-05-21
Code:MGR1
Name:Jax
"@ |ConvertFrom-PropertyString -sep ":" -RecordSeparator "\\r\\n\\s*\\r\\n" | Format-Table
Code StartDate Name ID Type
---- --------- ---- -- ----
SWENG3 1998-02-01 Baraka 3468 Developer
MGR1 2005-05-21 Jax 11234 Management
Reads records from a key:value string with records separated by blank lines.
NOTE that in this example you could also have used -AutomaticRecords or -Count 5 instead of specifying a RecordSeparator
.EXAMPLE
@"
Name=Fred
Address=Street1
Number=123
Name=Janet
Address=Street2
Number=345
"@ | ConvertFrom-PropertyString -RecordSeparator "`n(?=Name=)"
Reads records from a key=value string and uses a look-ahead record separator to start a new record whenever "Name=" is encountered
NOTE that in this example you could have used -AutomaticRecords or -Count 3 instead of specifying a RecordSeparator
.EXAMPLE
ConvertFrom-PropertyString data.txt -ValueSeparator ":"
Reads in a property file which has key:value pairs
.EXAMPLE
Get-Content data.txt -RecordSeparator "`r`n`r`n" | ConvertFrom-PropertyString -ValueSeparator ";"
Reads in a property file with key;value pairs, and records separated by blank lines, and converts it to objects
.EXAMPLE
ls *.data | ConvertFrom-PropertyString
Reads in a set of *.data files which have an object per file defined with key:value pairs of properties, one-per line.
.EXAMPLE
ConvertFrom-PropertyString data.txt -RecordSeparator "^;(.*?)\\r*\\n" -ValueSeparator ";"
Reads in a property file with key:value pairs, and sections with a header that starts with the comment character ';'
.NOTES
3.0 2010 Aug 4 (This Version)
- Renamed most of the parameters because I couldn't tell which did what from the Syntax help
- Added a -AutomaticRecords switch which creates new output objects whenevr it encounters a duplicated property
- Added a -SimpleOutput swicth which prevents the output of the PSChildName property
- Added a -CountOfPropertiesPerRecord parameter which allows splitting input by count instead of regex or automatic
2.0 2010 July 9 http://poshcode.org/get/1956
- changes the output so that if there are multiple instances of the same key, we collect the values in an array
1.0 2010 June 15 http://poshcode.org/get/1915
- Initial release
#>
#function ConvertFrom-PropertyString {
[CmdletBinding(DefaultParameterSetName="Data")]
param(
[Parameter(Position=99, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Data")]
[Alias("Data","Content","IO")]
[string]$InputObject
,
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName="File")]
[Alias("PSPath")]
[string]$FilePath
,
[Parameter(ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false)]
[Alias("VS","Separator")]
[String]$ValueSeparator="\\s*=\\s*"
,
[Parameter(ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false)]
[Alias("PS","Delimiter")]
[String]$PropertySeparator='(?:\\s*\\n+\\s*)+'
,
[Parameter(ValueFromPipeline=$false, ValueFromPipelineByPropertyName=$false)]
[Alias("RS")]
[String]$RecordSeparator='(?:\\n|^)\\[([^\\]]+)\\]\\s*\\n'
,
[Parameter(ParameterSetName="Data")]
[Alias("MultiRecords","MR","MultipleRecords","AR","AutoRecords")]
[Switch]$AutomaticRecords
,
[Parameter()]
[int]$CountOfPropertiesPerRecord
,
[Parameter()]
[Switch]$SimpleOutput
)
begin {
function new-output {
[CmdletBinding()]
param(
[Switch]$SimpleOutput
,
[AllowNull()][AllowEmptyString()]
[String]$Key
,
[AllowNull()][AllowEmptyString()]
$FilePath
)
end {
if(!$SimpleOutput -and ("" -ne $Key)) { @{"PSName"=$key} }
elseif(!$SimpleOutput -and $FilePath) { @{"PSName"=((get-item $FilePath).PSChildName)} }
else { @{} }
}
}
function out-output {
[CmdletBinding()]
param([Hashtable]$output)
end {
## If we made arrays out of single values, unwrap those
foreach($k in $Output.Keys | Where { $Output.$_.Count -eq 1 } ) {
$Output.$k = $Output.$k[0]
}
if($output.Count) {
New-Object PSObject -Property $output
}
}
}
Write-Verbose "Setting up the regular expressions: `n`tRecord: '$RecordSeparator' `n`tProperty: '$PropertySeparator' `n`tValue: '$ValueSeparator'"
[Regex]$ReRecordSeparator = New-Object Regex ([System.String]$RecordSeparator), ([System.Text.RegularExpressions.RegexOptions]"Multiline,IgnoreCase,Compiled")
[Regex]$RePropertySeparator = New-Object Regex ([System.String]$PropertySeparator), ([System.Text.RegularExpressions.RegexOptions]"Multiline,IgnoreCase,Compiled")
[Regex]$ReValueSeparator = New-Object Regex ([System.String]$ValueSeparator), ([System.Text.RegularExpressions.RegexOptions]"Multiline,IgnoreCase,Compiled")
}
process {
## some kind of PowerShell bug when expecting pipeline input:
if(!"$ReRecordSeparator"){
Write-Verbose "Setting up the record regex in the PROCESS block: '$RecordSeparator'"
[Regex]$ReRecordSeparator = New-Object Regex ([System.String]$RecordSeparator), ([System.Text.RegularExpressions.RegexOptions]"Multiline,IgnoreCase,Compiled")
}
if(!"$RePropertySeparator"){
Write-Verbose "Setting up the property regex in the PROCESS block: '$PropertySeparator'"
[Regex]$RePropertySeparator = New-Object Regex ([System.String]$PropertySeparator), ([System.Text.RegularExpressions.RegexOptions]"Multiline,IgnoreCase,Compiled")
}
if(!"$ReValueSeparator") {
Write-Verbose "Setting up the value regex in the PROCESS block: '$ValueSeparator'"
[Regex]$ReValueSeparator = New-Object Regex ([System.String]$ValueSeparator), ([System.Text.RegularExpressions.RegexOptions]"Multiline,IgnoreCase,Compiled")
}
Write-Verbose "ParameterSet: $($PSCmdlet.ParameterSetName)"
Write-Verbose "ValueSeparator: $($ReValueSeparator)"
$InputData = @{}
if($PSCmdlet.ParameterSetName -eq "File") {
$AutomaticRecords = $true
$InputObject = Get-Content $FilePath -Delimiter ([char]0)
}
## Separate RecordText with the RecordSeparator if the user asked us to:
if($PsBoundParameters.ContainsKey('RecordSeparator') -or $AutomaticRecords ) {
$Records = $ReRecordSeparator.Split( $InputObject ) | Where-Object { $_ }
Write-Verbose "There are $($ReRecordSeparator.GetGroupNumbers().Count) groups and $(@($Records).Count) records!"
if($ReRecordSeparator.GetGroupNumbers().Count -gt 1 -and @($Records).Count -gt 1) {
while($Records) {
$Key,$Value,$Records = $Records
Write-Verbose "RecordSeparator with grouping: $Key = $Value"
$InputData.$Key += @($Value)
}
} elseif(@($Records).Count -gt 1) {
$InputData."" = @($Records)
$InputObject = $Records
} else {
$InputObject = $Records
}
}
## Separate RecordText into properties and group them together by count if we were told a count
if($PsBoundParameters.ContainsKey('CountOfPropertiesPerRecord')) {
$Properties = $RePropertySeparator.Split($InputObject)
Write-Verbose "Separating Records by Property count = $CountOfPropertiesPerRecord of $($Properties.Count)"
for($Index = 0; $Index -lt $Properties.Count; $Index += $CountOfPropertiesPerRecord) {
$InputData."" += @($Properties[($Index..($Index+$CountOfPropertiesPerRecord-1))] -Join ([char]0))
Write-Verbose "Record ($Index..) $($Index/$CountOfPropertiesPerRecord) = $(@($Properties[($Index..($Index+$CountOfPropertiesPerRecord-1))] -Join ([char]0)))"
}
## We have to manually set the PropertySeparator because we can't generate text from your regex pattern to match your regex pattern
$SetPropertySeparator = $RePropertySeparator
[Regex]$RePropertySeparator = New-Object Regex ([System.String][char]0), ([System.Text.RegularExpressions.RegexOptions]"Multiline,IgnoreCase,Compiled")
}
if($InputData.Keys.Count -eq 0){
Write-Verbose "Keyless entry enabled!"
$InputData."" = @($InputObject)
}
Write-Verbose "InputData: $($InputData.GetEnumerator() | ft -auto -wrap| out-string)"
## Process each Record
foreach($key in $InputData.Keys) { foreach($record in $InputData.$Key) {
Write-Verbose "Record($Key): $record"
$output = new-output -SimpleOutput:$SimpleOutput -Key:$Key -FilePath:$FilePath
foreach($Property in $RePropertySeparator.Split("$record")) {
[string[]]$data = $ReValueSeparator.split($Property,2) | foreach { $_.Trim() } | where { $_ }
Write-Verbose "Property: $Property --> $($data -join ': ')"
if($AutomaticRecords -and $Output.ContainsKey($Data[0])) {
out-output $output
$output = new-output -SimpleOutput:$SimpleOutput -Key:$Key -FilePath:$FilePath
}
switch($data.Count) {
1 { $output.($Data[0]) += @($null) }
2 { $output.($Data[0]) += @($Data[1]) }
}
}
out-output $output
} }
## Put this back in case there's more input
$RePropertySeparator = $SetPropertySeparator
}
#}
|
PowerShellCorpus/PoshCode/adv2.ps1
|
adv2.ps1
|
#--------------------------------------------------------
# Script : Advanced2_2011.ps1
# Author : marc carter (marcadamcarter)
# Date : 4/5/2011
# Keywords: PowerShell, Scripting Games
# Comments:
# Expected Arguments: ADquery, Excel, textfile, <device_name_or_ip>
# Examples: .\\Advanced2_2011.ps1 ADquery
# .\\Advanced2_2011.ps1 Excel <file_fullname>
# .\\Advanced2_2011.ps1 textfile <file_fullname> - File format: List of device names, one per line.
# .\\Advanced2_2011.ps1 <device_name_or_ip>
#--------------------------------------------------------
#Begin Functions
Function get-runningServices{
#--------------------------------------------------------
<#
.SYNOPSIS
Retrieves currently running Services and their Dependent services and reports on the dependent services status
.DESCRIPTION
Retrieves currently running Services and their Dependent services and reports on the dependent services status
.PARAMETER server
Name of the server(s) you wish to query.
.NOTES
Name: get-runningServices
Author: Marc Carter
DateCreated: 5APR2011
.EXAMPLE
get-ModuleInfo LOCALHOST
Description
------------
Returns a formatted list of running Services and their dependancies.
#>
[cmdletbinding(
DefaultParameterSetName = 'server',
ConfirmImpact = 'low'
)]
Param(
[Parameter(
Mandatory = $True,
Position = 0,
ParameterSetName = '',
ValueFromPipeline = $True)]
[string][ValidatePattern(".{2,}")]$server
)
Begin{
$ErrorActionPreference = "SilentlyContinue"
$array = @()
}
Process{
$isServer = get-OSVersion $server
#Test to see if running server OS
if($isServer){
get-service -ComputerName $server | where-object {$_.Status -eq "Running"} | Select-Object name | % {
$BaseServiceName = $_.Name
Get-Service -name $_.Name -DependentServices | Sort-Object Name | Select-Object Name, Status | % {
#Group values into a custom object in order to output in table view.
$tmpObj = New-Object Object
$tmpObj | add-member -membertype noteproperty -name "BaseServiceName" -value $BaseServiceName
$tmpObj | add-member -membertype noteproperty -name "DependentName" -value $_.Name
$tmpObj | add-member -membertype noteproperty -name "DependentStatus" -value $_.Status
#Append the object to the existing array.
$array += $tmpObj
}
}
}
else { "Skipping $server (Not running Server OS)" }
}
End{
#Output results of the array and set both to $Null when done.
$array | ft @{Name='BaseServiceName';Expression={$_.BaseServiceName}; Align='Right';}, @{Name='DependentName';Expression={$_.DependentName};}, @{Name='DependentStatus';Expression={$_.DependentStatus};align='Left';} -auto
$array = $Null
$tmpObj = $Null
}
}
#--------------------------------------------------------
#End function get-runningServices
function get-listFromAD{
#--------------------------------------------------------
<#
.SYNOPSIS
Retrieves list of devices from active directory.
.DESCRIPTION
Retrieves list of devices from active directory.
Description
------------
Returns list of devices from AD query.
#>
$strFilter = "(&(objectcategory=computer)(operatingsystem=Windows Server*))" #All Server OS
$props = "cn"
$dse = [ADSI]"LDAP://rootdse"
#$root = "LDAP://"+$dse.defaultNamingContext
$ds = New-Object DirectoryServices.DirectorySearcher([ADSI]$root,$strFilter,$props)
$ds.PageSize = 1000
$results = $ds.FindAll()
foreach($obj in $results){
$obj.properties.cn
}
}
#--------------------------------------------------------
#End function get-listFromAD
function get-OSVersion($computer){
#--------------------------------------------------------
$os = Get-WmiObject -class Win32_OperatingSystem -computerName $computer
Switch ($os.Version){
"5.1.2600" { $False }
"5.1.3790" { $True }
"6.0.6001" {
if($os.ProductType -eq 1){ $False }
else{ $True }
}
"6.1.7600"{
if($os.ProductType -eq 1){ $False }
else{ $True }
}
DEFAULT { "N/A" }
}
}
#--------------------------------------------------------
#End get-OSVersion
#End Functions
#Main Script
#--------------------------------------------------------
#If arguments are present, determine how to proceed.
if($args){
<#
If arguments exist, assume input from external sorce
.Expected: ADquery, Excel, Text, <device_name_or_ip>
.Examples: .\\Advanced2_2011.ps1 ADquery
.\\Advanced2_2011.ps1 Excel <file_fullname>
.\\Advanced2_2011.ps1 textfile <file_fullname> - File format: List of device names, one per line.
.\\Advanced2_2011.ps1 <device_name_or_ip>
#>
switch($args[0].toLower()){
"adquery" {
foreach($device in get-listFromAD){
$device.toUpper()
get-runningServices $device
}
}
"excel" {
if(Test-Path $args[1]){
$xlCSV=6
$xls=$args[1]
$csv=$args[1] -replace(".xls",".csv")
$xl=New-Object -com "Excel.Application"
$wb=$xl.workbooks.open($xls)
$wb.SaveAs($csv,$xlCSV)
$xl.displayalerts=$False
$xl.quit()
Import-Csv $csv | Select-Object name | % {
$_.name
get-runningServices $_.name
}
}
else{
Write-Error "`nInvalid path for $args[1]`nCheck the path and try again."
}
}
"textfile" {
if(Test-Path $args[1]){
Get-Content -Path $args[1] | % {
$_
get-runningServices $_
}
}
else{
Write-Error "`nInvalid path for $args[1]`nCheck the path and try again."
}
}
Default {
#Initiate the function taking the first argument (assume single server instance name).
get-runningServices $args[0]
}
}
}
else{
#Otherwise, initiate the function and prompt for device.
get-runningServices
}
|
PowerShellCorpus/PoshCode/Find Permissions.ps1
|
Find Permissions.ps1
|
function findPermission ([string]$a, [string]$b)
{
$string = $a
$user = $b
$initialArray = @{}
$lowerArray = @{}
do{
$initialArray = get-acl $string | %{$_.access} | %{$_.IdentityReference}
$lowerArray = $initialArray | %{$_.value.toLower()} | %{$_.SubString(12)}
foreach($item in $lowerArray)
{
if($item.Contains($user))
{
$a1 = new-object -comobject wscript.shell
$b = $a1.popup($string,0,"Permission Found",1)
}
}
$string = $string.SubString(0, $string.LastIndexOf("\\"))
}while($string.Contains("\\"))
}
|
PowerShellCorpus/PoshCode/Set-PowerGUIWelcomePage_2.ps1
|
Set-PowerGUIWelcomePage_2.ps1
|
########################################################
# Modifies the default PowerGUI admin console
# welcome screen to the mht file you supply
# Details available at:
# http://dmitrysotnikov.wordpress.com/2009/02/11/rebranding-powergui-consolerebranding-powergui-console/
########################################################
# Usage:
# To change the homepage:
# & .\\Set-PowerGUIWelcomePage.ps1 \\\\server\\share\\my.mht
# To rollback the change:
# & .\\Set-PowerGUIWelcomePage.ps1 -ResetToDefault $true
########################################################
# (c) Dmitry Sotnikov, Oleg Shevnin
# 1.2 - Mar 30:
# added parameter to reset home page to default
# fixed the issue which aroused when path was supplied interactively
# 1.1 - Mar 17: added exception if PowerGUI Admin Console is running
# v1, Feb 11, 2009
#
########################################################
param ([string] $mhtpath, [bool] $ResetToDefault = $false)
# this should be path (local or UNC) to the new welcome page
# make sure that the admin console is closed
if (( get-process Quest.PowerGUI -ErrorAction SilentlyContinue ) -ne $null) {
throw "Please close the PowerGUI administrative console before running this script"
}
# Locate PowerGUI configuration for current user on this computer
$cfgpath = "$($env:APPDATA)\\Quest Software\\PowerGUI\\quest.powergui.xml"
# Create backup
Copy-Item $cfgpath "$cfgpath.backupconfig"
# Read the file
$xml = [xml]$(Get-Content $cfgpath)
# check if this is run to roll back the changes or to introduced them
if ( $ResetToDefault ) {
# Locate the custom homepage section
$node = $xml.SelectSingleNode("//container[@id='4b510268-a4eb-42e0-9276-06223660291d']")
if ($node -eq $null) {
"Configuration is already using default homepage. No rollback required."
} else {
$xml.SelectSingleNode("/configuration/items").RemoveChild($node) | Out-Null
$xml.Save($cfgpath)
"SUCCESS: Successfully rolled PowerGUI back to default welcome page."
}
} else {
# change the welcome screen to the mht supplied as parameter
# verify that the new file exists and is mht
if ( $mhtpath -eq $null ) {
$mhtpath = Read-Host "Please provide path to the MHT file"
}
$mhtfile = Get-ChildItem $mhtpath
if ( $mhtfile -eq $null) {
throw "MHT file $mhtpath not found. Please verify the script parameter."
}
if ( $mhtfile.Extension -ne ".mht" ) {
throw "File $mhtpath is not an MHT file. Only MHT files are supported."
}
# If the section for custom welcome page does not exist - create it
$node = $xml.SelectSingleNode("//container[@id='4b510268-a4eb-42e0-9276-06223660291d']")
if ($node -eq $null) {
$node = $xml.CreateElement("container")
$node.SetAttribute("id", "4b510268-a4eb-42e0-9276-06223660291d")
$node.SetAttribute("name", "Home Page")
$node.AppendChild($xml.CreateElement("value")) | Out-Null
$xml.SelectSingleNode("/configuration/items").AppendChild($node) | Out-Null
}
# Set the new value and save the file
$node.Value = [String] $mhtpath
$xml.Save($cfgpath)
"SUCCESS: $mhtpath is now set as your custom welcome screen."
}
|
PowerShellCorpus/PoshCode/Get-MountPointInfo.ps1
|
Get-MountPointInfo.ps1
|
function Get-MountPointInfo {
<#
.Synopsis
Get mount point volume free space information
.Parameter Name
Name of the system to query
.Parameter Credential
The Credentals to use when adding the system
.Example
Get-MountPointInfo -Name "Server1","Server2" -Credential (Get-Credential)
#>
[CmdletBinding()]
param(
[parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$TRUE)]
[string[]]
$Name,
[parameter(Mandatory=$false)]
[System.Management.Automation.PSCredential]
$Credential
)
Process
{
If ($Credential)
{
Get-WmiObject -Class Win32_MountPoint -ComputerName $name -Credential Credential|
Where-Object {$_.Directory -like ĹWin32_Directory.Name="D:\\\\MDBDATA*"ĺ} |
ForEach-Object {
$vol = $_.Volume
Get-WmiObject -Class Win32_Volume -ComputerName $_.__SERVER -Credential Credential |
Where-Object {$_.__RELPATH -eq $vol} |
Select-object @{
Name="Folder"
Expression={$_.Caption}
},@{
Name="Server"
Expression={$_.SystemName}
},@{
Name="Size"
Expression={"{0:F3}" -f $($_.Capacity / 1GB)}
},@{
Name="Free"
Expression={"{0:F3}" -f $($_.FreeSpace / 1GB)}
},@{
Name="% Free"
Expression={"{0:F2}" -f $(($_.FreeSpace/$_.Capacity)*100)}
}
}
}
Else
{
Get-WmiObject -Class Win32_MountPoint -ComputerName $name |
Where-Object {$_.Directory -like ĹWin32_Directory.Name="D:\\\\MDBDATA*"ĺ} |
ForEach-Object {
$vol = $_.Volume
Get-WmiObject -Class Win32_Volume -ComputerName $_.__SERVER|
Where-Object {$_.__RELPATH -eq $vol} |
Select-object @{
Name="Folder"
Expression={$_.Caption}
},@{
Name="Server"
Expression={$_.SystemName}
},@{
Name="Size"
Expression={"{0:F3}" -f $($_.Capacity / 1GB)}
},@{
Name="Free"
Expression={"{0:F3}" -f $($_.FreeSpace / 1GB)}
},@{
Name="% Free"
Expression={"{0:F2}" -f $(($_.FreeSpace/$_.Capacity)*100)}
}
}
}
}
}
|
PowerShellCorpus/PoshCode/Export-PSCredential.ps1
|
Export-PSCredential.ps1
|
# Author: Hal Rottenberg <hal@halr9000.com>
# Url: http://halr9000.com/article/tag/lib-authentication.ps1
# Purpose: These functions allow one to easily save network credentials to disk in a relatively
# secure manner. The resulting on-disk credential file can only [1] be decrypted
# by the same user account which performed the encryption. For more details, see
# the help files for ConvertFrom-SecureString and ConvertTo-SecureString as well as
# MSDN pages about Windows Data Protection API.
# [1]: So far as I know today. Next week I'm sure a script kiddie will break it.
#
# Usage: Export-PSCredential [-Credential <PSCredential object>] [-Path <file to export>]
#
# If Credential is not specififed, user is prompted by Get-Credential cmdlet.
# If not specififed, Path is "./credentials.enc.xml".
# Output: FileInfo object referring to saved credentials
#
# Import-PSCredential [-Path <file to import>]
#
# If not specififed, Path is "./credentials.enc.xml".
# Output: PSCredential object
function Export-PSCredential {
param ( $Credential = (Get-Credential), $Path = "credentials.enc.xml" )
# Test for valid credential object
if ( !$Credential -or ( $Credential -isnot [system.Management.Automation.PSCredential] ) ) {
Throw "You must specify a credential object to export to disk."
}
# Create temporary object to be serialized to disk
$export = "" | Select-Object Username, EncryptedPassword
# Give object a type name which can be identified later
$export.PSObject.TypeNames.Insert(0,ĺExportedPSCredentialĺ)
$export.Username = $Credential.Username
# Encrypt SecureString password using Data Protection API
# Only the current user account can decrypt this cipher
$export.EncryptedPassword = $Credential.Password | ConvertFrom-SecureString
# Export using the Export-Clixml cmdlet
$export | Export-Clixml $Path
Write-Host -foregroundcolor Green "Credentials saved to: " -noNewLine
# Return FileInfo object referring to saved credentials
Get-Item $Path
}
function Import-PSCredential {
param ( $Path = "credentials.enc.xml" )
# Import credential file
$import = Import-Clixml $Path
# Test for valid import
if ( $import.PSObject.TypeNames -notcontains 'Deserialized.ExportedPSCredential' ) {
Throw "Input is not a valid ExportedPSCredential object, exiting."
}
$Username = $import.Username
$SecurePass = $import.EncryptedPassword | ConvertTo-SecureString
$Credential = New-Object System.Management.Automation.PSCredential $Username, $SecurePass
Write-Output $Credential
}
|
PowerShellCorpus/PoshCode/Get-VariableType.ps1
|
Get-VariableType.ps1
|
function Get-VariableType {
param([string]$Name)
get-variable $name | select -expand attributes | ? {
$_.gettype().name -eq "ArgumentTypeConverterAttribute" } | % {
$_.gettype().invokemember("_convertTypes", "NonPublic,Instance,GetField", $null, $_, @())
}
}
|
PowerShellCorpus/PoshCode/Manage ASP.NET Providers.ps1
|
Manage ASP.NET Providers.ps1
|
# Manage_ASP_NET_Providers.ps1
# by Chistian Glessner
# http://iLoveSharePoint.com
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Web") # posh 2.0: Add-Type -Assembly "System.Web"
function global:Set-AppConfigPath($path=$(throw "-path is mandatory"))
{
[System.AppDomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $path )
}
function global:Get-MembershipProvider($appConfigPath=$null, $providerName=$null)
{
if($appConfigPath -ne $null)
{
Set-WebConfigPath $webConfigPath
}
if($providerName -eq $null)
{
return [System.Web.Security.Membership]::Provider
}
else
{
return [System.Web.Security.Membership]::Providers[$providerName]
}
}
function global:Get-RoleProvider($appConfigPath=$null, $providerName=$null)
{
if($appConfigPath -ne $null)
{
Set-WebConfigPath $webConfigPath
}
if($providerName -eq $null)
{
return [System.Web.Security.Roles]::Provider
}
else
{
return [System.Web.Security.Roles]::Providers[$providerName]
}
}
function global:Get-ProfileProvider($appConfigPath=$null, $providerName=$null)
{
if($appConfigPath -ne $null)
{
Set-WebConfigPath $webConfigPath
}
if($providerName -eq $null)
{
return [System.Web.Profile.ProfileManager]::Provider
}
else
{
return [System.Web.Profile.ProfileManager]::Providers[$providerName]
}
}
|
PowerShellCorpus/PoshCode/Get User for Svc_Tasks.ps1
|
Get User for Svc_Tasks.ps1
|
#==========================================================================
# NAME: GetServiceAndTaskAccounts.ps1
#
# AUTHOR: Stephen Wheet
# Version: 2.0
# Date: 7/21/10
#
# COMMENT:
# This script was created to find out which any which services on any of
# the servers are running as domain accounts. It will ignore local
# accounts
#
# Version 2: Added grabbing Scheduled Tasks info.
#
#==========================================================================
get-pssnapin -registered | add-pssnapin -passthru
$ReqVersion = [version]"1.2.2.1254"
$QadVersion = (Get-PSSnapin Quest.ActiveRoles.ADManagement).Version #Need Quest plugins installed
if($QadVersion -lt $ReqVersion) {
throw "Quest AD cmdlets version '$ReqVersion' is required. Please download the latest version"
} #end If
$ErrorActionPreference = "SilentlyContinue"
# Accounts to ignore
$IgnoreAcct = "NT AUTHORITY\\LocalService",
"LocalSystem",
".\\*",
"NT AUTHORITY\\NETWORK SERVICE",
"NT AUTHORITY\\NetworkService"
#Place Headers on out-put file
$list = "Server,Service,Account,"
$list | format-table | Out-File "c:\\reports\\GetSVCAccts\\SVCAccounts.csv"
$list2 = "Server,Task,Next Run Time,Account,"
$list2 | format-table | Out-File "c:\\reports\\GetSVCAccts\\TASKAccounts.csv"
#Get all the servers from the specified OU
$Servers = get-QADComputer -SearchRoot domain.local/' -OSName "*Server*" # change the container based on site.
Foreach ($server in $Servers ) {
$serverFQDN = $server.dnsname
#Test ping server to make sure it's up before querying it
$ping = new-object System.Net.NetworkInformation.Ping
$Reply = $ping.Send($serverFQDN)
if ($Reply.status -eq "Success"){
Write-Host "$serverFQDN ************* Online"
# Get service info
$error.clear()
gwmi win32_service -computer $serverFQDN -property name, startname, caption |
% {
$name = $_.Name
$Acctname = $_.StartName
If ( $IgnoreAcct -notcontains $AcctName )
{
Write-host "$serverFQDN $Name $Acctname"
$list = "$serverFQDN,$Name,$Acctname"
$list | format-table | Out-File -append "d:\\reports\\GetSVCAccts\\SVCAccounts.csv"
} #end If
} #end ForEachObj
#Write log if no access
if (!$?) {
$errmsg = "$serverFQDN,No RPC server,ACCESS DENIED"
$errmsg | format-table | Out-File -append "d:\\reports\\GetSVCAccts\\SVCAccounts.csv"
} # end Error
#Get scheduled tasks
$SchQuery = Schtasks.exe /query /s $serverFQDN /NH /V /FO CSV
If ($SchQuery -ne "INFO: There are no scheduled tasks present in the system.")
{
ForEach ($Sch in $SchQuery)
{
Write-host "*********************"
$Schfixed = $Sch.Replace("`"","")
$Props = $Schfixed.Split(',')
ForEach ($Prop in $Props)
{
If ($Prop -like "firm\\*")
{
$list2 = $Props[0],$Props[1],$Props[2],$Prop
$list2 | format-table | Out-File -append "d:\\reports\\GetSVCAccts\\TASKAccounts.csv"
Write-host $list
} # end If
} #end ForEach
} #end ForEach
} #end If
Else
{
$list2 = $serverFQDN,$SchQuery
$list2 | format-table | Out-File -append "d:\\reports\\GetSVCAccts\\TASKAccounts.csv"
Write-host $list
} #end else
} #end If
Else
{
Write-Host "$serverFQDN ************* OffLine"
$list = "$serverFQDN,OFFLINE"
$list | format-table | Out-File -append "d:\\reports\\GetSVCAccts\\SVCAccounts.csv"
} #end Else
} #end ForEach
|
PowerShellCorpus/PoshCode/Exchange Mailbox report.ps1
|
Exchange Mailbox report.ps1
|
function Send-SMTPmail($to, $from, $subject, $smtpserver, $body) {
$mailer = new-object Net.Mail.SMTPclient($smtpserver)
$msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body)
$msg.IsBodyHTML = $true
$mailer.send($msg)
}
Function Get-CustomHTML ($Header){
$Report = @"
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
<html><head><title>$($Header)</title>
<META http-equiv=Content-Type content='text/html; charset=windows-1252'>
<style type="text/css">
TABLE {
TABLE-LAYOUT: fixed;
FONT-SIZE: 100%;
align: center;
}
*
{
margin:0
}
.dspcont {
BORDER-RIGHT: #bbbbbb 1px solid;
BORDER-TOP: #bbbbbb 1px solid;
PADDING-LEFT: 0px;
FONT-SIZE: 8pt;
MARGIN-BOTTOM: -1px;
PADDING-BOTTOM: 5px;
MARGIN-LEFT: 0px;
BORDER-LEFT: #bbbbbb 1px solid;
WIDTH: 95%;
COLOR: #000000;
MARGIN-RIGHT: 0px;
PADDING-TOP: 4px;
BORDER-BOTTOM: #bbbbbb 1px solid;
FONT-FAMILY: Tahoma;
POSITION: relative;
BACKGROUND-COLOR: #f9f9f9
}
.filler {
BORDER-RIGHT: medium none;
BORDER-TOP: medium none;
DISPLAY: block;
BACKGROUND: none transparent scroll repeat 0% 0%;
MARGIN-BOTTOM: -1px;
FONT: 100%/8px Tahoma;
MARGIN-LEFT: 43px;
BORDER-LEFT: medium none;
COLOR: #ffffff;
MARGIN-RIGHT: 0px;
PADDING-TOP: 4px;
BORDER-BOTTOM: medium none;
POSITION: relative
}
.pageholder {
margin: 0px auto;
}
.dsp
{
BORDER-RIGHT: #bbbbbb 1px solid;
PADDING-RIGHT: 0px;
BORDER-TOP: #bbbbbb 1px solid;
DISPLAY: block;
PADDING-LEFT: 0px;
FONT-WEIGHT: bold;
FONT-SIZE: 8pt;
MARGIN-BOTTOM: -1px;
MARGIN-LEFT: 0px;
BORDER-LEFT: #bbbbbb 1px solid;
COLOR: #FFFFFF;
MARGIN-RIGHT: 0px;
PADDING-TOP: 4px;
BORDER-BOTTOM: #bbbbbb 1px solid;
FONT-FAMILY: Tahoma;
POSITION: relative;
HEIGHT: 2.25em;
WIDTH: 95%;
TEXT-INDENT: 10px;
}
.dsphead0 {
BACKGROUND-COLOR: #$($Colour1);
}
.dsphead1 {
BACKGROUND-COLOR: #$($Colour2);
}
.dspcomments {
BACKGROUND-COLOR:#FFFFE1;
COLOR: #000000;
FONT-STYLE: ITALIC;
FONT-WEIGHT: normal;
FONT-SIZE: 8pt;
}
td {
VERTICAL-ALIGN: TOP;
FONT-FAMILY: Tahoma;
}
th {
VERTICAL-ALIGN: TOP;
COLOR: #$($Colour1);
TEXT-ALIGN: left;
}
BODY {
margin-left: 4pt;
margin-right: 4pt;
margin-top: 6pt;
}
.MainTitle {
font-family:Arial, Helvetica, sans-serif;
font-size:20px;
font-weight:bolder;
}
.SubTitle {
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
font-weight:bold;
}
.Created {
font-family:Arial, Helvetica, sans-serif;
font-size:10px;
font-weight:normal;
margin-top: 20px;
margin-bottom:5px;
}
.links { font:Arial, Helvetica, sans-serif;
font-size:10px;
FONT-STYLE: ITALIC;
}
</style>
</head>
<body>
<div class="MainTitle">$($Header)</div>
<hr size="8" color="#$($Colour1)">
<div class="SubTitle">Generated on $($ENV:Computername)</div>
<br/>
<div class="Created">Report created on $(Get-Date)</div>
"@
Return $Report
}
Function Get-CustomHeader0 ($Title){
$Report = @"
<div class="pageholder">
<h1 class="dsp dsphead0">$($Title)</h1>
<div class="filler"></div>
"@
Return $Report
}
Function Get-CustomHeader ($Title, $cmnt){
$Report = @"
<h2 class="dsp dsphead1">$($Title)</h2>
"@
If ($Comments) {
$Report += @"
<div class="dsp dspcomments">$($cmnt)</div>
"@
}
$Report += @"
<div class="dspcont">
"@
Return $Report
}
Function Get-CustomHeaderClose{
$Report = @"
</DIV>
<div class="filler"></div>
"@
Return $Report
}
Function Get-CustomHeader0Close{
$Report = @"
</DIV>
"@
Return $Report
}
Function Get-CustomHTMLClose{
$Report = @"
</div>
</body>
</html>
"@
Return $Report
}
Function Get-HTMLTable {
param([array]$Content)
$HTMLTable = $Content | ConvertTo-Html
$HTMLTable = $HTMLTable -replace '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">', ""
$HTMLTable = $HTMLTable -replace '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">', ""
$HTMLTable = $HTMLTable -replace '<html xmlns="http://www.w3.org/1999/xhtml">', ""
$HTMLTable = $HTMLTable -replace '<html>', ""
$HTMLTable = $HTMLTable -replace '<head>', ""
$HTMLTable = $HTMLTable -replace '<title>HTML TABLE</title>', ""
$HTMLTable = $HTMLTable -replace '</head><body>', ""
$HTMLTable = $HTMLTable -replace '</body></html>', ""
$HTMLTable = $HTMLTable -replace '<', "<"
$HTMLTable = $HTMLTable -replace '>', ">"
Return $HTMLTable
}
Function Get-HTMLDetail ($Heading, $Detail){
$Report = @"
<TABLE>
<tr>
<th width='50%'><b>$Heading</b></font></th>
<td width='50%'>$($Detail)</td>
</tr>
</TABLE>
"@
Return $Report
}
$Colour1 = "CC0000" # Main Title - currently red
$Colour2 = "7BA7C7" # Secondary Title - currently blue
$Date = Get-Date -Format g
$Comments = $CommentsSet
$Comments = $false
$exchserver = "nau-xs2.naucom.com"
#All Mailboxes Count
$allmailboxes = ((Get-MailboxStatistics -Server "$exchserver"))
#Active Mailboxes
$activemail = Get-MailboxStatistics -Server "$exchserver" | where-object {$_.LastLogonTime -gt ((Get-Date).adddays(-30))} | Select-Object DisplayName,DatabaseName,ItemCount,LastLogonTime,TotalDeletedItemSize,TotalItemSize | Sort-Object TotalItemSize -Descending:$true
#Mailboxes That haven't logged in for 30 days
$inactivemail = Get-MailboxStatistics -Server "$exchserver" | where-object {$_.LastLogonTime -lt ((Get-Date).adddays(-30))} | Select-Object DisplayName,DatabaseName,ItemCount,LastLogonTime,TotalDeletedItemSize,TotalItemSize | Sort-Object LastLogonTime -Descending:$true
$activesize = $activemail | Measure-Object -Property TotalItemSize -Sum
$activedel = $activemail | Measure-Object -Property TotalDeletedItemSize -Sum
$inactivesize = $inactivemail | Measure-Object -Property TotalItemSize -Sum
$inactivedel = $inactivemail | Measure-Object -Property TotalDeletedItemSize -Sum
$MyReport = Get-CustomHTML "Exchange Mailbox Report"
$MyReport += Get-CustomHeader0 "Exchange Mailbox Statistics"
$MyReport += Get-CustomHeader "General Details" ""
$MyReport += Get-HTMLDetail "Total Number of Mailboxes: " ($allmailboxes.Count)
$MyReport += Get-HTMLDetail "Number of Active Mailboxes: " ($activemail.Count)
$MyReport += Get-HTMLDetail "Number of Inactive Mailboxes: " ($inactivemail.Count)
$MyReport += Get-HTMLDetail "Total Size of Active Mailboxes(GB): " ([math]::truncate($activesize.Sum / 1GB))
$MyReport += Get-HTMLDetail "Deleted Item Size of Active Mailboxes(GB): " ([math]::truncate($activedel.Sum / 1GB))
$MyReport += Get-HTMLDetail "Total Size of Inactive Mailboxes(GB): " ([math]::truncate($inactivesize.Sum / 1GB))
$MyReport += Get-HTMLDetail "Deleted Item size of Inactive Mailboxes(GB): " ([math]::truncate($inactivedel.Sum / 1GB))
$MyReport += Get-HTMLDetail "Average Mailbox Size(MB): " ([math]::truncate((($allmailboxes | Measure-Object -Property TotalItemSize -Average).Average) / 1MB))
$MyReport += Get-CustomHeaderClose
$Comments = $true
$MyReport += Get-CustomHeader "Active Mailboxes" "These are mailboxes who have had activity within the last 30 days."
$HTMLTable = $activemail | ConvertTo-Html @{label=”User”;expression={$_.DisplayName}},@{label=”Total Size (MB)”;expression={$_.TotalItemSize.Value.ToMB()}},@{label=”Deleted Size (MB)”;expression={$_.TotalDeletedItemSize.Value.ToMB()}},@{label=”Items”;expression={$_.ItemCount}},@{label=”Database”;expression={$_.DataBaseName}},@{label="LastLogon”;expression={$_.LastLogonTime}}
$HTMLTable = $HTMLTable -replace '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">', ""
$HTMLTable = $HTMLTable -replace '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">', ""
$HTMLTable = $HTMLTable -replace '<html xmlns="http://www.w3.org/1999/xhtml">', ""
$HTMLTable = $HTMLTable -replace '<html>', ""
$HTMLTable = $HTMLTable -replace '<head>', ""
$HTMLTable = $HTMLTable -replace '<title>HTML TABLE</title>', ""
$HTMLTable = $HTMLTable -replace '</head><body>', ""
$HTMLTable = $HTMLTable -replace '</body></html>', ""
$HTMLTable = $HTMLTable -replace '<', "<"
$HTMLTable = $HTMLTable -replace '>', ">"
$MyReport += $HTMLTable
$MyReport += Get-CustomHeaderClose
$Comments = $true
$MyReport += Get-CustomHeader "Inactive Mailboxes" "These are mailboxes who have not logged in within the last 30 days."
$HTMLTable = $inactivemail | ConvertTo-Html @{label=”User”;expression={$_.DisplayName}},@{label=”Total Size (MB)”;expression={$_.TotalItemSize.Value.ToMB()}},@{label=”Deleted Size (MB)”;expression={$_.TotalDeletedItemSize.Value.ToMB()}},@{label=”Items”;expression={$_.ItemCount}},@{label=”Database”;expression={$_.DataBaseName}},@{label="LastLogon”;expression={$_.LastLogonTime}}
$HTMLTable = $HTMLTable -replace '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">', ""
$HTMLTable = $HTMLTable -replace '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">', ""
$HTMLTable = $HTMLTable -replace '<html xmlns="http://www.w3.org/1999/xhtml">', ""
$HTMLTable = $HTMLTable -replace '<html>', ""
$HTMLTable = $HTMLTable -replace '<head>', ""
$HTMLTable = $HTMLTable -replace '<title>HTML TABLE</title>', ""
$HTMLTable = $HTMLTable -replace '</head><body>', ""
$HTMLTable = $HTMLTable -replace '</body></html>', ""
$HTMLTable = $HTMLTable -replace '<', "<"
$HTMLTable = $HTMLTable -replace '>', ">"
$MyReport += $HTMLTable
$MyReport += Get-CustomHeaderClose
$MyReport += Get-CustomHeader0Close
$MyReport += Get-CustomHTMLClose
$MyReport | Out-File H:\\exreport.html
#send-SMTPmail "to@some-email.com" "from@some-email.com" "Weekly Exchange Report" "smtp-ip.address" $MyReport
|
PowerShellCorpus/PoshCode/Get-Parameter _1.5.ps1
|
Get-Parameter _1.5.ps1
|
#Requires -version 2.0
#.Synopsis
# Enumerates the parameters of one or more commands
#.Notes
# With many thanks to Hal Rottenberg, Oisin Grehan and Shay Levy
# Version 0.80 - April 2008 - By Hal Rottenberg http://poshcode.org/186
# Version 0.81 - May 2008 - By Hal Rottenberg http://poshcode.org/255
# Version 0.90 - June 2008 - By Hal Rottenberg http://poshcode.org/445
# Version 0.91 - June 2008 - By Oisin Grehan http://poshcode.org/446
# Version 0.92 - April 2008 - By Hal Rottenberg http://poshcode.org/549
# - Added resolving aliases and avoided empty output
# Version 0.93 - Sept 24, 2009 - By Hal Rottenberg http://poshcode.org/1344
# Version 1.0 - Jan 19, 2010 - By Joel Bennett http://poshcode.org/1592
# - Merged Oisin and Hal's code with my own implementation
# - Added calculation of dynamic paramters
# Version 2.0 - July 22, 2010 - By Joel Bennett http://poshcode.org/get/2005
# - Now uses FormatData so the output is objects
# - Added calculation of shortest names to the aliases (idea from Shay Levy http://poshcode.org/1982, but with a correct implementation)
# Version 2.1 - July 22, 2010 - By Joel Bennett http://poshcode.org/2007
# - Fixed Help for SCRIPT file (script help must be separated from #Requires by an emtpy line)
# - Fleshed out and added dates to this version history after Bergle's criticism ;)
# Version 2.2 - July 29, 2010 - By Joel Bennett http://poshcode.org/2030
# - Fixed a major bug which caused Get-Parameters to delete all the parameters from the CommandInfo
# Version 2.3 - July 29, 2010 - By Joel Bennett
# - Added a ToString ScriptMethod which allows queries like:
# $parameters = Get-Parameter Get-Process; $parameters -match "Name"
# Version 2.4 - July 29, 2010 - By Joel Bennett http://poshcode.org/2032
# - CHANGED "Name" to CommandName
# - ADDED ParameterName parameter to allow filtering parameters
# - Fixed bug in 2.3 and 2.2 with dynamic parameters
# Version 2.5 - December 13, 2010 - By Jason Archer (This Version)
# - CHANGED format temp file to have static name, prevents bloat of random temporary files
#
#.Description
# Lists all the parameters of a command, by ParameterSet, including their aliases, type, etc.
#
# By default, formats the output to tables grouped by command and parameter set
#.Example
# Get-Command Select-Xml | Get-Parameter
#.Example
# Get-Parameter Select-Xml
#.Parameter CommandName
# The name of the command to get parameters for
#.Parameter ParameterName
# Wilcard-enabled filter for parameter names
#.Parameter ModuleName
# The name of the module which contains the command (this is for scoping)
#.Parameter Force
# Forces including the CommonParameters in the output
[CmdletBinding()]
param (
[Parameter(Position=1,ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
[Alias("Name")]
[string[]]$CommandName
,
[Parameter(Position=2,ValueFromPipelineByPropertyName=$true,Mandatory=$false)]
[string[]]$ParameterName="*"
,
[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$false)]
$ModuleName
,
[switch]$Force
)
Function global:Get-Parameter {
#.Synopsis
# Enumerates the parameters of one or more commands
#.Description
# Lists all the parameters of a command, by ParameterSet, including their aliases, type, etc.
#
# By default, formats the output to tables grouped by command and parameter set
#.Example
# Get-Command Select-Xml | Get-Parameter
#.Example
# Get-Parameter Select-Xml
#.Parameter CommandName
# The name of the command to get parameters for
#.Parameter ParameterName
# Wilcard-enabled filter for parameter names
#.Parameter ModuleName
# The name of the module which contains the command (this is for scoping)
#.Parameter Force
# Forces including the CommonParameters in the output
[CmdletBinding()]
param (
[Parameter(Position=1,ValueFromPipelineByPropertyName=$true,Mandatory=$true)]
[string[]]$CommandName
,
[Parameter(Position=2,ValueFromPipelineByPropertyName=$true,Mandatory=$false)]
[string[]]$ParameterName="*"
,
[Parameter(ValueFromPipelineByPropertyName=$true,Mandatory=$false)]
$ModuleName
,
[switch]$Force
)
begin {
$PropertySet = @( "Name",
@{n="Position";e={if($_.Position -lt 0){"Named"}else{$_.Position}}},
"Aliases",
@{n="Short";e={$_.Name}},
@{n="Type";e={$_.ParameterType.Name}},
@{n="ParameterSet";e={$paramset}},
@{n="Command";e={$command}},
@{n="Mandatory";e={$_.IsMandatory}},
@{n="Provider";e={$_.DynamicProvider}},
@{n="ValueFromPipeline";e={$_.ValueFromPipeline}},
@{n="ValueFromPipelineByPropertyName";e={$_.ValueFromPipelineByPropertyName}}
)
function Join-Object {
Param(
[Parameter(Position=0)]
$First
,
[Parameter(ValueFromPipeline=$true,Position=1)]
$Second
)
begin {
[string[]] $p1 = $First | gm -type Properties | select -expand Name
}
process {
$Output = $First | Select $p1
foreach($p in $Second | gm -type Properties | Where { $p1 -notcontains $_.Name } | select -expand Name) {
Add-Member -in $Output -type NoteProperty -name $p -value $Second."$p"
}
$Output
}
}
}
process{
foreach($cmd in $CommandName) {
if($ModuleName) { $cmd = "$ModuleName\\$cmd" }
$commands = @(Get-Command $cmd)
foreach($command in $commands) {
# resolve aliases (an alias can point to another alias)
while ($command.CommandType -eq "Alias") {
$command = @(Get-Command ($command.definition))[0]
}
if (-not $command) { continue }
$Parameters = @{}
foreach($provider in Get-PSProvider) {
$drive = "{0}\\{1}::\\" -f $provider.ModuleName, $provider.Name
Write-Verbose ("Get-Command $command -Args $drive | Select -Expand Parameters")
[Array]$MoreParameters = (Get-Command $command -Args $drive).Parameters.Values
[Array]$Dynamic = $MoreParameters | Where { $_.IsDynamic }
foreach($p in $MoreParameters | Where { !$Parameters.ContainsKey( $_.Name ) } ){ $Parameters.($p.Name) = $p }
# Write-Verbose "Drive: $Drive | Parameters: $($Parameters.Count)"
if($dynamic) {
foreach($d in $dynamic) {
if(Get-Member -input $Parameters.($d.Name) -Name DynamicProvider) {
Write-Debug ("ADD:" + $d.Name + " " + $provider.Name)
$Parameters.($d.Name).DynamicProvider += $provider.Name
} else {
Write-Debug ("CREATE:" + $d.Name + " " + $provider.Name)
$Parameters.($d.Name) = $Parameters.($d.Name) | Add-Member NoteProperty DynamicProvider @($provider.Name) -Passthru
}
}
}
}
## Calculate the shortest distinct parameter name -- do this BEFORE removing the common parameters or else.
foreach($p in $($Parameters.Keys))
{
$shortest="^"
foreach($char in [char[]]$p)
{
$shortest += $char
$Matches = ($Parameters.Keys -match $Shortest).Count
Write-Debug "$($shortest.SubString(1)) $Matches"
if($Matches -eq 1)
{
$Parameters.$p = $Parameters.$p | Add-Member NoteProperty Aliases ($Parameters.$p.Aliases + @($shortest.SubString(1).ToLower($PSUICulture))) -Force -Passthru
break
}
}
}
Write-Verbose "Parameters: $($Parameters.Count)`n $($Parameters | ft | out-string)"
foreach ($paramset in @($command.ParameterSets | Select -Expand "Name")){
foreach($parameter in $Parameters.Keys | Sort) {
Write-Verbose "Parameter: $Parameter"
if(!$Force -and ($Parameters.$Parameter.aliases -match "vb|db|ea|wa|ev|wv|ov|ob|wi|cf")) { continue }
if($Parameters.$Parameter.ParameterSets.ContainsKey($paramset) -or $Parameters.$Parameter.ParameterSets.ContainsKey("__AllParameterSets")) {
if($Parameters.$Parameter.ParameterSets.ContainsKey($paramset)) {
$output = Join-Object $Parameters.$Parameter $Parameters.$Parameter.ParameterSets.$paramSet
} else {
$output = Join-Object $Parameters.$Parameter $Parameters.$Parameter.ParameterSets.__AllParameterSets
}
Write-Output $Output | Select-Object $PropertySet | ForEach {
$null = $_.PSTypeNames.Insert(0,"System.Management.Automation.ParameterMetadata")
$null = $_.PSTypeNames.Insert(0,"System.Management.Automation.ParameterMetadataEx")
Write-Verbose "$(($_.PSTypeNames.GetEnumerator()) -join ", ")"
$_
} |
Add-Member ScriptMethod ToString { $this.Name } -Force -Passthru |
Where-Object { $(foreach($pn in $ParameterName){ $_ -like $Pn}) -contains $true }
}
}
}
}
}
}
}
# Since you can't update format data without a file that has a ps1xml ending, let's make one up...
$tempFile = "$([System.IO.Path]::GetTempPath())Get-Parameter.ps1xml"
Set-Content $tempFile @'
<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<Controls>
<Control>
<Name>ParameterGroupingFormat</Name>
<CustomControl>
<CustomEntries>
<CustomEntry>
<CustomItem>
<Frame>
<LeftIndent>4</LeftIndent>
<CustomItem>
<Text>Command: </Text>
<ExpressionBinding>
<ScriptBlock>"{0}/{1}" -f $(if($_.command.ModuleName){$_.command.ModuleName}else{$_.Command.CommandType.ToString()+":"}),$_.command.Name</ScriptBlock>
</ExpressionBinding>
<NewLine/>
<Text>Set: </Text>
<ExpressionBinding>
<ScriptBlock>if($_.ParameterSet -eq "__AllParameterSets"){"Default"}else{$_.ParameterSet}</ScriptBlock>
</ExpressionBinding>
<NewLine/>
</CustomItem>
</Frame>
</CustomItem>
</CustomEntry>
</CustomEntries>
</CustomControl>
</Control>
</Controls>
<ViewDefinitions>
<View>
<Name>ParameterMetadataEx</Name>
<ViewSelectedBy>
<TypeName>System.Management.Automation.ParameterMetadataEx</TypeName>
</ViewSelectedBy>
<GroupBy>
<PropertyName>ParameterSet</PropertyName>
<CustomControlName>ParameterGroupingFormat</CustomControlName>
</GroupBy>
<TableControl>
<TableHeaders>
<TableColumnHeader>
<Label>Name</Label>
<Width>22</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Aliases</Label>
<Width>12</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Position</Label>
<Width>8</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Mandatory</Label>
<Width>9</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Pipeline</Label>
<Width>8</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>ByName</Label>
<Width>6</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Provider</Label>
<Width>15</Width>
</TableColumnHeader>
<TableColumnHeader>
<Label>Type</Label>
</TableColumnHeader>
</TableHeaders>
<TableRowEntries>
<TableRowEntry>
<TableColumnItems>
<TableColumnItem>
<PropertyName>Name</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Aliases</PropertyName>
</TableColumnItem>
<TableColumnItem>
<!--PropertyName>Position</PropertyName-->
<ScriptBlock>if($_.Position -lt 0){"Named"}else{$_.Position}</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Mandatory</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>ValueFromPipeline</PropertyName>
</TableColumnItem>
<TableColumnItem>
<PropertyName>ValueFromPipelineByPropertyName</PropertyName>
</TableColumnItem>
<TableColumnItem>
<!--PropertyName>Provider</PropertyName-->
<ScriptBlock>if($_.Provider){$_.Provider}else{"All"}</ScriptBlock>
</TableColumnItem>
<TableColumnItem>
<PropertyName>Type</PropertyName>
</TableColumnItem>
</TableColumnItems>
</TableRowEntry>
</TableRowEntries>
</TableControl>
</View>
</ViewDefinitions>
</Configuration>
'@
Update-FormatData -Append $tempFile
# This is nested stuff, so that you can call the SCRIPT, and after it defines the global function, we will call that.
Get-Parameter @PSBoundParameters
|
PowerShellCorpus/PoshCode/HelpModules 2.0.ps1
|
HelpModules 2.0.ps1
|
# HelpModules
# A Module for generating module stubs so you can Update-Help (or Save-Help)
# Includes two options for reading the help from those modules (StubFunctions or Get-ModuleHelp)
# 1.0 - 2013/2/1 - Initial release Friday, Feb 1st, 2013
# 2.0 - 2013/2/1 - Updated release with improved pipeline/remoting support
$PSModuleHelpRoot = Convert-Path "~\\Documents\\WindowsPowerShellModuleHelp"
function New-HelpModule {
#.Synopsis
# Creates a dummy module and fetches the help files for it
#.Example
# Get-Module Hyper-V -ListAvailable | New-HelpModule
#
# Generates a new module stub from an existing module
#.Example
# Invoke-Command -ComputerName $Servers { Get-Module -ListAvailable | Where HelpInfoUri } | New-HelpModule
#
# Generates local Help-only Modules for all the updatable help modules which exist on the specified server
#.Example
# New-HelpModule Hyper-V '1.0' 'af4bddd0-8583-4ff2-84b2-a33f5c8de8a7' 'http://go.microsoft.com/fwlink/?LinkId=206726'
#
# Generates a new help module from the specified values (You can get the information about the module in an email, text message, phone call, etc!)
[CmdletBinding(DefaultParameterSetName="ModuleInfo")]
param(
# The name of the module you want to create a dummy for.
[Parameter(ValueFromPipelineByPropertyName=$true, Mandatory=$true, Position=0)]
[Alias("Name")]
[String]$ModuleName,
# The version of the module you want to create a dummy for.
[Parameter(ValueFromPipelineByPropertyName=$true, Mandatory=$true, Position=1)]
[String]$Version,
# The exact guid of the module you want to create a dummy for.
[Parameter(ValueFromPipelineByPropertyName=$true, Mandatory=$true, Position=2)]
[Guid]$Guid,
# The HelpInfoUri of the module you want to create a dummy for.
[Parameter(ValueFromPipelineByPropertyName=$true, Mandatory=$true, Position=3)]
[String]$HelpInfoUri,
# A list of commands to generate StubFunctions for.
#
# NOTE: stub functions will not be generated unless you also specify the -StubFunctions switch (see help on that parameter)
[Parameter(ValueFromPipelineByPropertyName=$true)]
$ExportedCommands,
# A path to put the help modules in. Defaults to $PSModuleHelpRoot (which defaults to "~\\Documents\\WindowsPowerShellModuleHelp").
[String]$ModuleHelpRoot = $PSModuleHelpRoot,
# The culture(s) you want to fetch help for (defaults to $PSUICulture)
[Alias("Culture","PSCulture")]
[CultureInfo[]]$HelpCulture = ${PSUICulture},
# If set, generates a Blank.psm1 with stub functions in it so that you can import the dummy module and use the built-in Get-Help instead of our Get-ModuleHelp
#
# Setting this may pollute your PowerShell session with dozens or hudreds of commands which don't do anything. You probably shouldn't, for instance, add your ModuleHelpRoot path to your PSModulePath if you do this.
[Switch]$StubFunctions
)
begin {
$ModulesToUpdate = @()
}
process {
# Make the ModuleHelpRoot\\ModuleName folder if it's not there
$ModuleDir = mkdir ${ModuleHelpRoot}\\${ModuleName}\\ -Force
if($ExportedCommands -is [System.Collections.Generic.Dictionary[System.String,System.Management.Automation.CommandInfo]]) {
[string[]]$ExportedCommands = $ExportedCommands.Keys
}
# Generate the stub ModuleManifest
New-ModuleManifest -Path ${ModuleHelpRoot}\\${ModuleName}\\${ModuleName}.psd1 `
-Guid $Guid -HelpInfoUri $HelpInfoUri -ModuleVersion $Version `
-FunctionsToExport $ExportedCommands `
-RootModule "Blank.psm1"
$ModulesToUpdate += $ModuleName
# Generate stub FunctionsToExport
if($StubFunctions) {
Remove-Item "${ModuleHelpRoot}\\${ModuleName}\\Blank.psm1" -ErrorAction SilentlyContinue
foreach($name in $ExportedCommands) {
Add-Content "${ModuleHelpRoot}\\${ModuleName}\\Blank.psm1" "#.ExternalHelp *.xml `nfunction $name {}`n"
}
}
}
end {
# Update the help files -- this is why we're here.
# TODO: if we're generating a lot of modules, it would be really to only do this once!
PowerShell -NoProfile -Command "&{ `$Env:PSModulePath = '$ModuleHelpRoot'; Update-Help -Module '$($ModulesToUpdate -join "','")' -UICulture '$($HelpCulture -join "','")'}"
}
}
function Get-ModuleHelp {
#.Synopsis
# Gets help from the XML help files directly without worrying about whether the commands actually exist.
[CmdletBinding(DefaultParameterSetName="MamlCommandHelpInfo")]
param(
# The command you want help for
[Alias("Name")]
[Parameter(Mandatory=$true, Position = 0, ValueFromPipelineByPropertyName = $true)]
$CommandName,
# The name of the module the command is in
# TODO: Search Get-Module -ListAvailable for modules which *say* they have the command
[Parameter(Mandatory=$true, Position = 1, ValueFromPipelineByPropertyName = $true)]
$ModuleName,
# A path to search for help modules in. Defaults to $PSModuleHelpRoot (which defaults to "~\\Documents\\WindowsPowerShellModuleHelp").
$ModuleHelpRoot = $PSModuleHelpRoot,
# Displays only the detailed descriptions of the specified parameters. Wildcards are permitted.
[Parameter(ParameterSetName="MamlCommandHelpInfo#parameter")]
[String]$Parameter,
# Displays only the name, synopsis, and examples".
[Parameter(ParameterSetName="MamlCommandHelpInfo#ExamplesView")]
[Switch]$Examples,
# Displays the entire help topic for a cmdlet, including parameter descriptions and attributes, examples, input and output object types, and additional notes.
[Parameter(ParameterSetName="MamlCommandHelpInfo#FullView")]
[Switch]$Full,
# Adds parameter descriptions and examples to the basic help display.
[Parameter(ParameterSetName="MamlCommandHelpInfo#DetailedView")]
[Switch]$Detailed,
# The culture you want to fetch help for (defaults to $PSUICulture)
[Alias("Culture","PSCulture")]
[CultureInfo]$HelpCulture = ${PSUICulture}
)
process {
Write-Verbose "Culture: $HelpCulture HelpSet: $($PSCmdlet.ParameterSetName)"
$matched = $false
foreach($node in Select-Xml "//*[local-name() = 'details']/*[local-name() = 'name' and text() = '$CommandName']/../.." -Path ${ModuleHelpRoot}\\${ModuleName}\\${PSUICulture}\\*.xml | Select-Object -Expand Node) {
if($Parameter) {
foreach($param in $node.parameters.parameter) {
if($param.name -like $Parameter) {
$matched = $true
$param | FixMaml -Type $($PSCmdlet.ParameterSetName)
}
}
if(!$matched) {
throw "No parameter matches criteria $Parameter"
}
} else {
$matched = $true
$node | FixMaml -Type $($PSCmdlet.ParameterSetName)
}
}
}
}
function FixMaml {
#.Synopsis
# Internal command for tweaking the XML just enough that PowerShell will format it properly
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
$Node,
[Parameter(Mandatory=$true)]
$Type = "MamlCommandHelpInfo"
)
process {
$node.PSTypeNames.Clear()
$node.PSTypeNames.Add($type)
if($node.description) {
Add-Member -Input $node NoteProperty description @(
$Node.RemoveChild($node.description).para | % {
$p = New-Object PSObject -Property @{ Text = $_ };
$p.PSTypeNames.Clear();
$p.PSTypeNames.Add("MamlParaTextItem");
$p
} )
}
if($node.details) {
# Fix them, but don't output recursively
$null = $node.details | FixMaml -Type $Type
}
Write-Output $node
}
}
Export-ModuleMember -Function New-HelpModule, Get-ModuleHelp -Variable PSModuleHelpRoot
# SIG # Begin signature block
# MIIfIAYJKoZIhvcNAQcCoIIfETCCHw0CAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUQd5uFIgV7FnAngosuRU8JFdS
# InagghpSMIID7jCCA1egAwIBAgIQfpPr+3zGTlnqS5p31Ab8OzANBgkqhkiG9w0B
# AQUFADCBizELMAkGA1UEBhMCWkExFTATBgNVBAgTDFdlc3Rlcm4gQ2F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hidQbM4eDG6iMR06Weoqhh7Gn6
# 3W/JAA==
# SIG # End signature block
|
PowerShellCorpus/PoshCode/Seach-LocalGroupMemberDo.ps1
|
Seach-LocalGroupMemberDo.ps1
|
function Seach-LocalGroupMemberDomenNetwork() {
param(
$Domen,
$User
)
function Ping ($Name){
$ping = new-object System.Net.NetworkInformation.Ping
if ($ping.send($Name).Status -eq "Success") {$True}
else {$False}
trap {Write-Verbose "Ошибка пинга"; $False; continue}
}
[string[]]$Info
[string[]]$Computers
if ($User){$Connection = Get-Credential -Credential $User}
$Computers = Get-QADComputer -Service $Domen -OSName '*XP*','*Vista*','*7*' -SizeLimit 0 -ErrorAction SilentlyContinue |
Select-Object name -ExpandProperty name
Foreach ($Computer in $Computers){
$Alive = Ping $Computer
if ($Alive -eq "True"){
if ($Connection) {
Trap {Write-Host "Error WMI $Computer";Continue}
$GroupName = Get-WmiObject win32_group -ComputerName $Computer -Credential $Connection |
Where-Object {$_.SID -eq 'S-1-5-32-544'} |
Select-Object name -ExpandProperty name
}
else {
Trap {Write-Host "Error WMI $Computer";Continue}
$GroupName = Get-WmiObject win32_group -ComputerName $Computer |
Where-Object {$_.SID -eq 'S-1-5-32-544'} |
Select-Object name -ExpandProperty name
}
if ($GroupName){
$Users = ([ADSI]"WinNT://$Computer/$GroupName").psbase.invoke("Members") |
% {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}
$Info += $Users | % {$_ | Select-Object @{e={$Computer};n='Компьютер'},@{e={$_};n='Логин'}}
}
}
}
$Info
}
|
PowerShellCorpus/PoshCode/JSON 1.3.ps1
|
JSON 1.3.ps1
|
#requires -version 2.0\n# Version History:\n# v 0.5 - First Public version\n# v 1.0 - Made ConvertFrom-Json work with arbitrary JSON \n# - switched to xsl style sheets for ConvertTo-JSON\n# v 1.1 - Changed ConvertFrom-Json to handle single item results\n# v 1.2 - CodeSigned to make a fellow geek happy\n# v 1.3 - Changed ConvertFrom-Json to handle zero item results (I hope)\n#\n# There is no help (yet) because I'm still changing and renaming everything every time I mess with this code\n# Full RoundTrip capability:\n#\n# > ls | ConvertTo-Json | ConvertFrom-Json\n# > ps | ConvertTo-Json | Convert-JsonToXml | Convert-XmlToJson | convertFrom-Json\n#\n# You may frequently want to use the DEPTH or NoTypeInformation parameters:\n#\n# > ConvertTo-Json -Depth 2 -NoTypeInformation\n#\n# But then you have to specify the type when you reimport (and you can't do that for deep objects). \n# This problem also occurs if you convert the result of a SELECT statement (ie: PSCustomObject).\n# For Example:\n#\n# > PS | Select PM, WS, CPU, ID, ProcessName |\n# >> ConvertTo-json -NoType |\n# >> convertfrom-json -Type System.Diagnostics.Process\n\n\nAdd-Type -AssemblyName System.ServiceModel.Web, System.Runtime.Serialization\n$utf8 = [System.Text.Encoding]::UTF8\n\nfunction Write-String {\nPARAM(\n [Parameter()]$stream,\n [Parameter(ValueFromPipeline=$true)]$string\n)\nPROCESS {\n $bytes = $utf8.GetBytes($string)\n $stream.Write( $bytes, 0, $bytes.Length )\n} \n}\n\nfunction Convert-JsonToXml {\nPARAM([Parameter(ValueFromPipeline=$true)][string[]]$json)\nBEGIN { \n $mStream = New-Object System.IO.MemoryStream \n}\nPROCESS {\n $json | Write-String -stream $mStream\n}\nEND {\n $mStream.Position = 0\n $jsonReader = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonReader($mStream,[System.Xml.XmlDictionaryReaderQuotas]::Max)\n try\n {\n $xml = New-Object Xml.XmlDocument\n $xml.Load($jsonReader)\n $xml\n }\n finally\n {\n $jsonReader.Close()\n $mStream.Dispose()\n }\n}\n}\n \nfunction Convert-XmlToJson {\nPARAM([Parameter(ValueFromPipeline=$true)][Xml]$xml)\nPROCESS {\n $mStream = New-Object System.IO.MemoryStream\n $jsonWriter = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonWriter($mStream)\n try\n {\n $xml.Save($jsonWriter)\n $bytes = $mStream.ToArray()\n [System.Text.Encoding]::UTF8.GetString($bytes,0,$bytes.Length)\n }\n finally\n {\n $jsonWriter.Close()\n $mStream.Dispose()\n }\n}\n}\n\n## Rather than rewriting ConvertTo-Xml ...\nFunction ConvertTo-Json {\n[CmdletBinding()]\nParam(\n [Parameter(Mandatory=$true,Position=1,ValueFromPipeline=$true)]$InputObject\n,\n [Parameter(Mandatory=$false)][Int]$Depth=1\n,\n [Switch]$NoTypeInformation\n)\nEND { \n ## You must output ALL the input at once \n ## ConvertTo-Xml outputs differently if you just have one, so your results would be different\n $input | ConvertTo-Xml -Depth:$Depth -NoTypeInformation:$NoTypeInformation -As Document | Convert-CliXmlToJson\n}\n}\n\nFunction Convert-CliXmlToJson {\nPARAM(\n [Parameter(ValueFromPipeline=$true)][Xml.XmlNode]$xml\n)\nBEGIN {\n $xmlToJsonXsl = @'\n<?xml version="1.0" encoding="UTF-8"?>\n<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">\n<!--\n CliXmlToJson.xsl\n\n Copyright (c) 2006,2008 Doeke Zanstra\n Copyright (c) 2009 Joel Bennett\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without modification, \n are permitted provided that the following conditions are met:\n\n Redistributions of source code must retain the above copyright notice, this \n list of conditions and the following disclaimer. Redistributions in binary \n form must reproduce the above copyright notice, this list of conditions and the \n following disclaimer in the documentation and/or other materials provided with \n the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND \n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED \n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. \n IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, \n INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, \n BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, \n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF \n LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR \n OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF \n THE POSSIBILITY OF SUCH DAMAGE.\n-->\n\n <xsl:output indent="no" omit-xml-declaration="yes" method="text" encoding="UTF-8" media-type="text/x-json"/>\n <xsl:strip-space elements="*"/>\n <!--contant-->\n <xsl:variable name="d">0123456789</xsl:variable>\n\n <!-- ignore document text -->\n <xsl:template match="text()[preceding-sibling::node() or following-sibling::node()]"/>\n\n <!-- string -->\n <xsl:template match="text()">\n <xsl:call-template name="escape-string">\n <xsl:with-param name="s" select="."/>\n </xsl:call-template>\n </xsl:template>\n \n <!-- Main template for escaping strings; used by above template and for object-properties \n Responsibilities: placed quotes around string, and chain up to next filter, escape-bs-string -->\n <xsl:template name="escape-string">\n <xsl:param name="s"/>\n <xsl:text>"</xsl:text>\n <xsl:call-template name="escape-bs-string">\n <xsl:with-param name="s" select="$s"/>\n </xsl:call-template>\n <xsl:text>"</xsl:text>\n </xsl:template>\n \n <!-- Escape the backslash (\\) before everything else. -->\n <xsl:template name="escape-bs-string">\n <xsl:param name="s"/>\n <xsl:choose>\n <xsl:when test="contains($s,'\\')">\n <xsl:call-template name="escape-quot-string">\n <xsl:with-param name="s" select="concat(substring-before($s,'\\'),'\\\\')"/>\n </xsl:call-template>\n <xsl:call-template name="escape-bs-string">\n <xsl:with-param name="s" select="substring-after($s,'\\')"/>\n </xsl:call-template>\n </xsl:when>\n <xsl:otherwise>\n <xsl:call-template name="escape-quot-string">\n <xsl:with-param name="s" select="$s"/>\n </xsl:call-template>\n </xsl:otherwise>\n </xsl:choose>\n </xsl:template>\n \n <!-- Escape the double quote ("). -->\n <xsl:template name="escape-quot-string">\n <xsl:param name="s"/>\n <xsl:choose>\n <xsl:when test="contains($s,'"')">\n <xsl:call-template name="encode-string">\n <xsl:with-param name="s" select="concat(substring-before($s,'"'),'\\"')"/>\n </xsl:call-template>\n <xsl:call-template name="escape-quot-string">\n <xsl:with-param name="s" select="substring-after($s,'"')"/>\n </xsl:call-template>\n </xsl:when>\n <xsl:otherwise>\n <xsl:call-template name="encode-string">\n <xsl:with-param name="s" select="$s"/>\n </xsl:call-template>\n </xsl:otherwise>\n </xsl:choose>\n </xsl:template>\n \n <!-- Replace tab, line feed and/or carriage return by its matching escape code. Can't escape backslash\n or double quote here, because they don't replace characters (� becomes \\t), but they prefix \n characters (\\ becomes \\\\). Besides, backslash should be seperate anyway, because it should be \n processed first. This function can't do that. -->\n <xsl:template name="encode-string">\n <xsl:param name="s"/>\n <xsl:choose>\n <!-- tab -->\n <xsl:when test="contains($s,'	')">\n <xsl:call-template name="encode-string">\n <xsl:with-param name="s" select="concat(substring-before($s,'	'),'\\t',substring-after($s,'	'))"/>\n </xsl:call-template>\n </xsl:when>\n <!-- line feed -->\n <xsl:when test="contains($s,'
')">\n <xsl:call-template name="encode-string">\n <xsl:with-param name="s" select="concat(substring-before($s,'
'),'\\n',substring-after($s,'
'))"/>\n </xsl:call-template>\n </xsl:when>\n <!-- carriage return -->\n <xsl:when test="contains($s,'
')">\n <xsl:call-template name="encode-string">\n <xsl:with-param name="s" select="concat(substring-before($s,'
'),'\\r',substring-after($s,'
'))"/>\n </xsl:call-template>\n </xsl:when>\n <xsl:otherwise><xsl:value-of select="$s"/></xsl:otherwise>\n </xsl:choose>\n </xsl:template>\n\n <!-- number (no support for javascript mantise) -->\n <xsl:template match="text()[not(string(number())='NaN' or\n (starts-with(.,'0' ) and . != '0'))]">\n <xsl:value-of select="."/>\n </xsl:template>\n\n <!-- boolean, case-insensitive -->\n <xsl:template match="text()[translate(.,'TRUE','true')='true']">true</xsl:template>\n <xsl:template match="text()[translate(.,'FALSE','false')='false']">false</xsl:template>\n\n <!-- root object(s) -->\n <xsl:template match="*" name="base">\n <xsl:if test="not(preceding-sibling::*)">\n <xsl:choose>\n <xsl:when test="count(../*)>1"><xsl:text>[</xsl:text></xsl:when>\n <xsl:otherwise><xsl:text>{</xsl:text></xsl:otherwise>\n </xsl:choose>\n </xsl:if>\n <xsl:call-template name="escape-string">\n <xsl:with-param name="s" select="name()"/>\n </xsl:call-template>\n <xsl:text>:</xsl:text>\n <!-- check type of node -->\n <xsl:choose>\n <!-- null nodes -->\n <xsl:when test="count(child::node())=0">null</xsl:when>\n <!-- other nodes -->\n <xsl:otherwise>\n <xsl:apply-templates select="child::node()"/>\n </xsl:otherwise>\n </xsl:choose>\n <!-- end of type check -->\n <xsl:if test="following-sibling::*">,</xsl:if>\n <xsl:if test="not(following-sibling::*)">\n <xsl:choose>\n <xsl:when test="count(../*)>1"><xsl:text>]</xsl:text></xsl:when>\n <xsl:otherwise><xsl:text>}</xsl:text></xsl:otherwise>\n </xsl:choose>\n </xsl:if>\n </xsl:template>\n\n <!-- properties of objects -->\n <xsl:template match="*[count(../*[name(../*)=name(.)])=count(../*) and count(../*)>1]">\n <xsl:variable name="inArray" select="translate(local-name(),'OBJECT','object')='object' or ../@Type[starts-with(.,'System.Collections') or contains(.,'[]') or (contains(.,'[') and contains(.,']'))]"/>\n <xsl:if test="not(preceding-sibling::*)">\n <xsl:choose>\n <xsl:when test="$inArray"><xsl:text>[</xsl:text></xsl:when>\n <xsl:otherwise>\n <xsl:text>{</xsl:text>\n <xsl:if test="../@Type">\n <xsl:text>"__type":</xsl:text> \n <xsl:call-template name="escape-string">\n <xsl:with-param name="s" select="../@Type"/>\n </xsl:call-template>\n <xsl:text>,</xsl:text> \n </xsl:if>\n </xsl:otherwise>\n </xsl:choose>\n </xsl:if>\n <xsl:choose>\n <xsl:when test="not(child::node())">\n <xsl:call-template name="escape-string">\n <xsl:with-param name="s" select="@Name"/>\n </xsl:call-template>\n <xsl:text>:null</xsl:text>\n </xsl:when>\n <xsl:when test="$inArray">\n <xsl:apply-templates select="child::node()"/>\n </xsl:when>\n <!--\n <xsl:when test="not(@Name) and not(@Type)">\n <xsl:call-template name="escape-string">\n <xsl:with-param name="s" select="local-name()"/>\n </xsl:call-template>\n <xsl:text>:</xsl:text> \n <xsl:apply-templates select="child::node()"/>\n </xsl:when>\n -->\n <xsl:when test="not(@Name)">\n <xsl:call-template name="escape-string">\n <xsl:with-param name="s" select="local-name()"/>\n </xsl:call-template>\n <xsl:text>:</xsl:text> \n <xsl:apply-templates select="child::node()"/>\n </xsl:when> \n <xsl:otherwise>\n <xsl:call-template name="escape-string">\n <xsl:with-param name="s" select="@Name"/>\n </xsl:call-template>\n <xsl:text>:</xsl:text>\n <xsl:apply-templates select="child::node()"/>\n </xsl:otherwise>\n </xsl:choose>\n <xsl:if test="following-sibling::*">,</xsl:if>\n <xsl:if test="not(following-sibling::*)"> \n <xsl:choose>\n <xsl:when test="$inArray"><xsl:text>]</xsl:text></xsl:when>\n <xsl:otherwise><xsl:text>}</xsl:text></xsl:otherwise>\n </xsl:choose>\n </xsl:if>\n </xsl:template>\n \n \n <!-- convert root element to an anonymous container -->\n <xsl:template match="/">\n <xsl:apply-templates select="node()"/>\n </xsl:template> \n</xsl:stylesheet>\n'@\n}\nPROCESS {\n if(Get-Member -InputObject $xml -Name root) {\n Write-Verbose "Ripping to Objects"\n $xml = $xml.root.Objects\n } else {\n Write-Verbose "Was already Objects"\n }\n Convert-Xml -Xml $xml -Xsl $xmlToJsonXsl\n}\n}\n\nFunction ConvertFrom-Xml {\n [CmdletBinding(DefaultParameterSetName="AutoType")]\n PARAM(\n [Parameter(ValueFromPipeline=$true,Mandatory=$true,Position=1)]\n [Xml.XmlNode]\n $xml\n ,\n [Parameter(Mandatory=$true,ParameterSetName="ManualType")]\n [Type]$Type\n ,\n [Switch]$ForceType\n )\n PROCESS{ \n if(Get-Member -InputObject $xml -Name root) {\n return $xml.root.Objects | \n } elseif(Get-Member -InputObject $xml -Name Objects) {\n return $xml.Objects | \n }\n $propbag = @{}\n foreach($name in Get-Member -InputObject $xml -MemberType Property | Where-Object{$_.Name -notmatch "^__|type"} | Select-Object -ExpandProperty name) {\n Write-Verbose "$Name Type: $($xml.$Name.type)"\n switch( $xml."$Name".type ) {\n "object" {\n $propbag."$Name" = ConvertFrom-Xml -Xml $xml."$Name"\n break\n } \n "string" {\n $propbag."$Name" = $xml."$Name".get_InnerText()\n $MightBeADate = $xml."$Name".get_InnerText() -as [DateTime]\n ## Strings that are actually dates (*grumble* JSON is crap) \n if($MightBeADate -and $propbag."$Name" -eq $MightBeADate.ToString("G")) {\n $propbag."$Name" = $MightBeADate\n }\n break\n }\n "number" {\n $number = $xml."$Name".get_InnerText()\n if($number -eq ($number -as [int])) {\n $propbag."$Name" = $number -as [int]\n } elseif($number -eq ($number -as [double])) {\n $propbag."$Name" = $number -as [double]\n } else {\n $propbag."$Name" = $number -as [decimal]\n }\n break\n }\n "boolean" {\n $propbag."$Name" = [bool]::parse($xml."$Name".get_InnerText())\n }\n "null" {\n $propbag."$Name" = $null\n }\n default {\n $propbag."$Name" = $xml."$Name"\n break\n }\n }\n }\n if(!$Type -and $xml.HasAttribute("__type")) { $Type = $xml.__Type }\n if($ForceType -and $Type) {\n try {\n $output = New-Object $Type -Property $propbag\n } catch {\n $output = New-Object PSObject -Property $propbag\n $output.PsTypeNames.Insert(0, $xml.__type)\n }\n } else {\n $output = New-Object PSObject -Property $propbag\n if($Type) {\n $output.PsTypeNames.Insert(0, $Type)\n }\n }\n Write-Output $output\n }\n}\n\nFunction ConvertFrom-Json {\n [CmdletBinding(DefaultParameterSetName="AutoType")]\nPARAM(\n [Parameter(ValueFromPipeline=$true,Mandatory=$true,Position=1)]\n [string]$InputObject\n ,\n [Parameter(Mandatory=$true,ParameterSetName="ManualType")]\n [Type]$Type\n ,\n [Switch]$ForceType\n)\nPROCESS {\n $null = $PSBoundParameters.Remove("InputObject")\n [Xml.XmlElement]$xml = (Convert-JsonToXml $InputObject).Root\n if($xml.Objects) {\n $xml.Objects.Item.GetEnumerator() | ConvertFrom-Xml @PSBoundParameters\n }elseif($xml.Item -isnot [System.Management.Automation.PSParameterizedProperty]) {\n $xml.Item | ConvertFrom-Xml @PSBoundParameters\n }else {\n $xml | ConvertFrom-Xml @PSBoundParameters\n }\n}\n}\n\n#########\n### The JSON library is dependent on Convert-Xml from my Xml script module\n\nfunction Convert-Node {\nparam(\n[Parameter(Mandatory=$true,ValueFromPipeline=$true)]\n[System.Xml.XmlReader]$XmlReader,\n[Parameter(Position=1,Mandatory=$true,ValueFromPipeline=$false)]\n[System.Xml.Xsl.XslCompiledTransform]$StyleSheet\n) \nPROCESS {\n $output = New-Object IO.StringWriter\n $StyleSheet.Transform( $XmlReader, $null, $output )\n Write-Output $output.ToString()\n}\n}\n \nfunction Convert-Xml {\n#.Synopsis\n# The Convert-XML function lets you use Xslt to transform XML strings and documents.\n#.Description\n#.Parameter Content\n# Specifies a string that contains the XML to search. You can also pipe strings to Select-XML.\n#.Parameter Namespace\n# Specifies a hash table of the namespaces used in the XML. Use the format @{<namespaceName> = <namespaceUri>}.\n#.Parameter Path\n# Specifies the path and file names of the XML files to search. Wildcards are permitted.\n#.Parameter Xml\n# Specifies one or more XML nodes to search.\n#.Parameter Xsl\n# Specifies an Xml StyleSheet to transform with...\n[CmdletBinding(DefaultParameterSetName="Xml")]\nPARAM(\n [Parameter(Position=1,ParameterSetName="Path",Mandatory=$true,ValueFromPipelineByPropertyName=$true)]\n [ValidateNotNullOrEmpty()]\n [Alias("PSPath")]\n [String[]]$Path\n,\n [Parameter(Position=1,ParameterSetName="Xml",Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]\n [ValidateNotNullOrEmpty()]\n [Alias("Node")]\n [System.Xml.XmlNode[]]$Xml\n,\n [Parameter(ParameterSetName="Content",Mandatory=$true,ValueFromPipeline=$true)]\n [ValidateNotNullOrEmpty()]\n [String[]]$Content\n,\n [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false)]\n [ValidateNotNullOrEmpty()]\n [Alias("StyleSheet")]\n [String[]]$Xslt\n)\nBEGIN { \n $StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform\n if(Test-Path @($Xslt)[0] -ErrorAction 0) { \n Write-Verbose "Loading Stylesheet from $(Resolve-Path @($Xslt)[0])"\n $StyleSheet.Load( (Resolve-Path @($Xslt)[0]) )\n } else {\n Write-Verbose "$Xslt"\n $StyleSheet.Load(([System.Xml.XmlReader]::Create((New-Object System.IO.StringReader ($Xslt -join "`n")))))\n }\n [Text.StringBuilder]$XmlContent = [String]::Empty \n}\nPROCESS {\n switch($PSCmdlet.ParameterSetName) {\n "Content" {\n $null = $XmlContent.AppendLine( $Content -Join "`n" )\n }\n "Path" {\n foreach($file in Get-ChildItem $Path) {\n Convert-Node -Xml ([System.Xml.XmlReader]::Create((Resolve-Path $file))) $StyleSheet\n }\n }\n "Xml" {\n foreach($node in $Xml) {\n Convert-Node -Xml (New-Object Xml.XmlNodeReader $node) $StyleSheet\n }\n }\n }\n}\nEND {\n if($PSCmdlet.ParameterSetName -eq "Content") {\n [Xml]$Xml = $XmlContent.ToString()\n Convert-Node -Xml $Xml $StyleSheet\n }\n}\n}\n\n\nNew-Alias fromjson ConvertFrom-Json\nNew-Alias tojson ConvertTo-Json\n\n#New-Alias ipjs Import-Json\n#New-Alias epjs Export-Json\n#Import-Json, Export-Json, \n\nExport-ModuleMember -Function ConvertFrom-Json, ConvertTo-Json, Convert-JsonToXml, Convert-XmlToJson, Convert-CliXmlToJson -Alias *\n\n# SIG # Begin signature block\n# MIIIDQYJKoZIhvcNAQcCoIIH/jCCB/oCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB\n# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR\n# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQU+J8LYGWMiaqeDmLkaF7AdmYh\n# I/CgggUrMIIFJzCCBA+gAwIBAgIQKQm90jYWUDdv7EgFkuELajAN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9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgor\n# BgEEAYI3AgELMQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQUBVF+ztMd\n# tXJCMAG6x1/KcHeXsU4wDQYJKoZIhvcNAQEBBQAEggEAsCe4s24+t34jepfGUelp\n# 493eFxSTlsM4lvbWMTpsfmn7m8byO3spiE9MIHwXUuXn+ymDfYcA90unQggksLQO\n# Cb1cZoEmDuH2gMKIKxqDQMRMTnkeYrTS45WHl77DLYgDlmdA1RmULTZcO2MYKitH\n# do4PZtoyzrA/D3dlWQnHzZIRQxwhAOOW7lYUv8vgRm6rbhmk1DZNTgdK7M0EDu6e\n# nTSKcHf2w0EKDkglDxz1gpN6S6/NCUi8760p5U303+oEZp7ZyU6NAU2l2eN/GdzE\n# GjdCkOPF494rnwWVnFxd5ji04vtBxaVicxw04/otbBsf5SI+16bLmKHNiL3vSEDc\n# 2g==\n# SIG # End signature block
|
PowerShellCorpus/PoshCode/Get-DLRestriction.ps1
|
Get-DLRestriction.ps1
|
###########################################
# Get-DLRestriction
#
# Uses QAD cmdlets to retrieve distribution list restriction attributes
# and then provides a list of users which can send email messages to the group.
#
# Usage: Get-DLRestriction "Worldwide Everyone"
#
# Dmitry Sotnikov, http://dmitrysotnikov.wordpress.com
############################################
function Get-DLRestriction {
param([System.String] $DLName )
"Checking restrictions for $DLName"
$DL = Get-QADGroup $DLName `
-IncludedProperties AuthOrig, UnauthOrig, dLMemRejectPerms,`
dLMemSubmitPerms, msExchRequireAuthToSendTo
# we'll set this to true if we see a restriction
$restricted = $false
# if the group with such a name is found
if ( $DL -ne $null ) {
if ( $DL.AuthOrig -ne $null ) {
$restricted = $true
"`n The following users can send messages to this list:"
$DL.AuthOrig | Get-QADUser
}
if ( $DL.UnauthOrig -ne $null ) {
$restricted = $true
"`n Anyone BUT the following users can send messages to this list:"
$DL.UnauthOrig | Get-QADUser
}
if ( $DL.dLMemSubmitPerms -ne $null ) {
$restricted = $true
"n` Members of this group can send messages to this list: $($DL.dLMemSubmitPerms | Get-QADGroup).Name) :"
Get-QADGroupMember $DL.dLMemSubmitPerms
}
if ( $DL.dLMemRejectPerms -ne $null ) {
$restricted = $true
"`n Anyone BUT members of this group can send messages to this list: $($DL.dLMemRejectPerms | Get-QADGroup).Name) :"
Get-QADGroupMember $DL.dLMemRejectPerms
}
if ( $DL.msExchRequireAuthToSendTo ) {
$restricted = $true
"`n Only authenticated users can send messages to this list.`nExternal senders get blocked."
}
if ( -not $restricted ) {
"`n This list is not restricted. Anyone can email it."
}
} else {
"`n DL $DLName not found."
}
}
|
PowerShellCorpus/PoshCode/Set-IPAddress_3.ps1
|
Set-IPAddress_3.ps1
|
function Set-IPAddress {
param( [string]$networkinterface =$(read-host "Enter the name of the NIC (ie Local Area Connection)"),
[string]$ip = $(read-host "Enter an IP Address (ie 10.10.10.10)"),
[string]$mask = $(read-host "Enter the subnet mask (ie 255.255.255.0)"),
[string]$gateway = $(read-host "Enter the current name of the NIC you want to rename"),
[string]$dns1 = $(read-host "Enter the first DNS Server (ie 10.2.0.28)"),
[string]$dns2,
[string]$registerDns = "TRUE"
)
$dns = $dns1
@@ if($dns2){$dns ="$dns1","$dns2"}
$index = (gwmi Win32_NetworkAdapter | where {$_.netconnectionid -eq $networkinterface}).InterfaceIndex
$NetInterface = Get-WmiObject Win32_NetworkAdapterConfiguration | where {$_.InterfaceIndex -eq $index}
$NetInterface.EnableStatic($ip, $subnetmask)
$NetInterface.SetGateways($gateway)
$NetInterface.SetDNSServerSearchOrder($dns)
$NetInterface.SetDynamicDNSRegistration($registerDns)
}
|
PowerShellCorpus/PoshCode/finddupe_19.ps1
|
finddupe_19.ps1
|
# new version has more error handling, "-delete" and "-noprompt" and "-recurse" 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] [-recurse]"
$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
if ($args -eq "-recurse")
{
$files=@(dir -ea 0 -recurse ($args | ?{$_ -ne "-delete" -and $_ -ne "-noprompt" -and $_ -ne "-recurse"} |?{if ((get-item -ea 0 $_) -eq $null){write-host "`aError: " -f red -nonewline; write-host "$_ not found.";exit} else {$_}})|?{$_.psiscontainer -ne $true} )
}
else
{
$files=@(dir -ea 0 ($args | ?{$_ -ne "-delete" -and $_ -ne "-noprompt" -and $_ -ne "-recurse"} |?{if ((get-item -ea 0 $_) -eq $null){write-host "`aError: " -f red -nonewline; write-host "$_ not found.";exit} else {$_}})|?{$_.psiscontainer -ne $true} )
}
if ($files.count -lt 2) {"Need at least two files to compare.`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 ($args -eq "-delete")
{
if ($args -eq "-noprompt")
{
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/WhileTimeout.ps1
|
WhileTimeout.ps1
|
function WhileTimeout ( [int]$interval, [int]$maxTries, [scriptblock]$condition )
{
$i = 0
$startTime = Get-Date
while ( &$condition ) {
$i++
if ( $i -lt $maxTries ) {
Start-Sleep -seconds $interval
} else {
Throw "Operation exceeded timeout"
}
}
$endTime = Get-Date
$duration = ( $endTime - $startTime ).TotalSeconds
Write-Verbose "Operation elapsed time: $duration seconds"
}
|
PowerShellCorpus/PoshCode/Set-WinSchedule_2.ps1
|
Set-WinSchedule_2.ps1
|
# Set-WinSchedule
# Written by Tome Tanasovski
# http://powertoe.wordpress.com
# version 1.0
# Created March 2010
#
# Please read through the synopsis->Description to see the list of features that I hope to get
# in a final release. If you choose to work on any of the issues by all means, but please contact
# me to let me know so that no effort is duplicated
# Winform Assemblies
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
function Set-WinSchedule {
<#
.Synopsis
Creates a winform to select a schedule and creates a scheduled task
.Description
Set-WinSchedule gives a GUI to select a schedule and schedules a task using schtasks
This is a beta. There are still a lot of features to implement:
Need to have more scheduling options. I expect to have all options available in a recurring outlook calendar item
Need to have methods for scheduling with all 3 providers: schtasks, wmi, and at. Currently it only uses schtasks
Need to design the return object properties:
Should contain the text paths for each provider type
Should contain a date/time for start time
Need to provide a method to overwrite an existing task if it has the same name and the user confirms that it is ok to overwrite. Should also provide
a -force parameter for this option.
Need to ensure that files piped from get-item will be scheduled
Need a parameter to override ok box at the end
.Example
Set-WinSchedule c:\\windows\\notepad.exe notepadtask
.Parameter TaskRun
The name of the command to be scheduled
.Parameter ScheduleName
The name that the scheduled task will be given.
.Notes
NAME: Set-Schedule
AUTHOR: Tome Tanasovski
LASTEDIT: 3/11/2010
KEYWORDS:
.Link
http://powertoe.wordpress.com
#>
param(
[Parameter(Position=1,Mandatory=$true)]
[string] $taskrun,
[Parameter(Position=2,Mandatory=$true)]
[string] $taskname
)
$command = "& schtasks.exe /query /tn $taskname"
$job = start-job $ExecutionContext.InvokeCommand.NewScriptBlock($command)
Wait-Job $job
if ($job.ChildJobs[0].output -ne "") {
[System.windows.forms.messagebox]::show("A task named $taskname already exists. You must delete this task before you can use the name.")
return
}
$SchedulePickerForm = New-Object System.Windows.Forms.Form
$comboTime = New-Object System.Windows.Forms.ComboBox
$label4 = New-Object System.Windows.Forms.Label
$buttonCancel = New-Object System.Windows.Forms.Button
$buttonOK = New-Object System.Windows.Forms.Button
$group = New-Object System.Windows.Forms.GroupBox
$checkSaturday = New-Object System.Windows.Forms.CheckBox
$checkFriday = New-Object System.Windows.Forms.CheckBox
$checkThursday = New-Object System.Windows.Forms.CheckBox
$checkWednesday = New-Object System.Windows.Forms.CheckBox
$checkTuesday = New-Object System.Windows.Forms.CheckBox
$checkMonday = New-Object System.Windows.Forms.CheckBox
$checkSunday = New-Object System.Windows.Forms.CheckBox
$labelDays = New-Object System.Windows.Forms.Label
$labelHours = New-Object System.Windows.Forms.Label
$boxHourlyDaily = New-Object System.Windows.Forms.TextBox
$labelEvery = New-Object System.Windows.Forms.Label
$radioHourly = New-Object System.Windows.Forms.RadioButton
$radioWeekly = New-Object System.Windows.Forms.RadioButton
$radioDaily = New-Object System.Windows.Forms.RadioButton
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
$checkboxes = ($checkMonday,$checkTuesday,$checkWednesday,$checkThursday,$checkFriday,$checkSaturday,$checkSunday)
function VisibleInvisibleCheckBoxes {
Write-Host $checkboxes
$checkboxes |foreach {$_.visible = -not $_.visible}
}
# Events
$handler_radioButtonChanged = {
switch ($true) {
($radioHourly.Checked) {
$labelHours.Visible = $true
$labelDays.Visible = $false
$boxHourlyDaily.Visible = $true
$checkboxes |foreach {$_.visible = $false}
}
($radioDaily.Checked) {
$labelHours.Visible = $false
$labelDays.Visible = $true
$boxHourlyDaily.Visible = $true
$checkboxes |foreach {$_.visible = $false}
}
($radioWeekly.Checked) {
$labelHours.Visible = $false
$labelDays.Visible = $false
$boxHourlyDaily.Visible = $false
$checkboxes |foreach {$_.visible = $true}
}
}
}
$buttonCancel_OnClick = {
$SchedulePickerForm.Close()
return $null
}
$buttonOK_OnClick = {
$doit = $false
switch ($true) {
($radioHourly.Checked -or $radioDaily.Checked) {
try {
$recurrence = [Convert]::ToInt32($boxHourlyDaily.Text)
if ($recurrence -gt 0) {
try {
switch ($true) {
($radiohourly.checked) {
if ($recurence -gt 23) {
[System.windows.forms.messagebox]::show("Hourly recurrence must be 1-23 hours")
$boxHourlyDaily.Focus()
}
else {
& schtasks /create /tn $taskname /tr "$taskrun" /sc hourly /mo $boxHourlyDaily.Text /st $comboTime.Text /f
[System.Windows.Forms.Messagebox]::show("Task has been scheduled")
$SchedulePickerForm.Close()
}
}
($radioDaily.checked) {
if ($recurence -gt 365) {
[System.windows.forms.messagebox]::show("Hourly recurrence must be 1-365 hours")
$boxhourlydaily.focus()
}
else {
& schtasks /create /tn $taskname /tr $taskrun /sc daily /mo $boxHourlyDaily.Text /st $comboTime.Text /f
$SchedulePickerForm.Close()
}
}
}
}
catch {
[System.windows.forms.messagebox]::show($error[0])
}
}
else {
[System.windows.forms.messagebox]::show("Recurrence must be greater than 0")
$boxHourlyDaily.Focus()
}
}
catch {
[System.windows.forms.messagebox]::show("You must enter a valid integer recurrence")
$boxHourlyDaily.Focus()
}
}
($radioWeekly.Checked) {
$dflag = ""
$checkboxes|foreach {
if ($_.checked) {
$dflag += $_.text.substring(0,3) + ","
}
}
if ($dflag -ne "") {
$dflag = $dflag.substring(0,$dflag.length-1)
& schtasks /create /tn $taskname /tr $taskrun /sc weekly /st $comboTime.Text /d "$dflag" /f
$SchedulePickerForm.Close()
}
else {
[System.windows.forms.messagebox]::show("You must select at least one day for weekly recurrence")
}
}
}
}
$OnLoadForm_StateCorrection={
#Correct the initial state of the form to prevent the .Net maximized form issue
$SchedulePickerForm.WindowState = $InitialFormWindowState
}
$SchedulePickerForm.Text = "Schedule Picker"
$SchedulePickerForm.MaximizeBox = $False
$SchedulePickerForm.Name = "SchedulePickerForm"
$SchedulePickerForm.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 476
$System_Drawing_Size.Height = 157
$SchedulePickerForm.ClientSize = $System_Drawing_Size
$SchedulePickerForm.FormBorderStyle = 5
$comboTime.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 121
$System_Drawing_Size.Height = 21
$comboTime.Size = $System_Drawing_Size
$comboTime.DataBindings.DefaultDataSourceUpdateMode = 0
$comboTime.Name = "comboTime"
$comboTime.Items.Add("00:00")|Out-Null
$comboTime.Items.Add("00:30")|Out-Null
$comboTime.Items.Add("01:00")|Out-Null
$comboTime.Items.Add("01:30")|Out-Null
$comboTime.Items.Add("02:00")|Out-Null
$comboTime.Items.Add("02:30")|Out-Null
$comboTime.Items.Add("03:00")|Out-Null
$comboTime.Items.Add("03:30")|Out-Null
$comboTime.Items.Add("04:00")|Out-Null
$comboTime.Items.Add("04:30")|Out-Null
$comboTime.Items.Add("05:00")|Out-Null
$comboTime.Items.Add("05:30")|Out-Null
$comboTime.Items.Add("06:00")|Out-Null
$comboTime.Items.Add("06:30")|Out-Null
$comboTime.Items.Add("07:00")|Out-Null
$comboTime.Items.Add("07:30")|Out-Null
$comboTime.Items.Add("08:00")|Out-Null
$comboTime.Items.Add("08:30")|Out-Null
$comboTime.Items.Add("09:00")|Out-Null
$comboTime.Items.Add("09:30")|Out-Null
$comboTime.Items.Add("10:00")|Out-Null
$comboTime.Items.Add("10:30")|Out-Null
$comboTime.Items.Add("11:00")|Out-Null
$comboTime.Items.Add("11:30")|Out-Null
$comboTime.Items.Add("12:00")|Out-Null
$comboTime.Items.Add("12:30")|Out-Null
$comboTime.Items.Add("13:00")|Out-Null
$comboTime.Items.Add("13:30")|Out-Null
$comboTime.Items.Add("14:00")|Out-Null
$comboTime.Items.Add("14:30")|Out-Null
$comboTime.Items.Add("15:00")|Out-Null
$comboTime.Items.Add("15:30")|Out-Null
$comboTime.Items.Add("16:00")|Out-Null
$comboTime.Items.Add("16:30")|Out-Null
$comboTime.Items.Add("17:00")|Out-Null
$comboTime.Items.Add("17:30")|Out-Null
$comboTime.Items.Add("18:00")|Out-Null
$comboTime.Items.Add("18:30")|Out-Null
$comboTime.Items.Add("19:00")|Out-Null
$comboTime.Items.Add("19:30")|Out-Null
$comboTime.Items.Add("20:00")|Out-Null
$comboTime.Items.Add("20:30")|Out-Null
$comboTime.Items.Add("21:00")|Out-Null
$comboTime.Items.Add("21:30")|Out-Null
$comboTime.Items.Add("22:00")|Out-Null
$comboTime.Items.Add("22:30")|Out-Null
$comboTime.Items.Add("23:00")|Out-Null
$comboTime.Items.Add("23:30")|Out-Null
$comboTime.Text = "08:00"
$comboTime.DropDownStyle = "DropDownList"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 53
$System_Drawing_Point.Y = 119
$comboTime.Location = $System_Drawing_Point
$comboTime.TabIndex = 1
$SchedulePickerForm.Controls.Add($comboTime)
$label4.TabIndex = 3
$label4.TextAlign = 16
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 35
$System_Drawing_Size.Height = 23
$label4.Size = $System_Drawing_Size
$label4.Text = "Start:"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 12
$System_Drawing_Point.Y = 116
$label4.Location = $System_Drawing_Point
$label4.DataBindings.DefaultDataSourceUpdateMode = 0
$label4.Name = "label4"
$SchedulePickerForm.Controls.Add($label4)
$buttonCancel.TabIndex = 3
$buttonCancel.Name = "buttonCancel"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 75
$System_Drawing_Size.Height = 23
$buttonCancel.Size = $System_Drawing_Size
$buttonCancel.UseVisualStyleBackColor = $True
$buttonCancel.Text = "Cancel"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 368
$System_Drawing_Point.Y = 119
$buttonCancel.Location = $System_Drawing_Point
$buttonCancel.DataBindings.DefaultDataSourceUpdateMode = 0
$buttonCancel.add_Click($buttonCancel_OnClick)
$SchedulePickerForm.Controls.Add($buttonCancel)
$buttonOK.TabIndex = 2
$buttonOK.Name = "buttonOK"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 75
$System_Drawing_Size.Height = 23
$buttonOK.Size = $System_Drawing_Size
$buttonOK.UseVisualStyleBackColor = $True
$buttonOK.Text = "OK"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 287
$System_Drawing_Point.Y = 119
$buttonOK.Location = $System_Drawing_Point
$buttonOK.DataBindings.DefaultDataSourceUpdateMode = 0
$buttonOK.add_Click($buttonOK_OnClick)
$SchedulePickerForm.Controls.Add($buttonOK)
$group.Name = "group"
$group.Text = "Recurrence pattern"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 431
$System_Drawing_Size.Height = 101
$group.Size = $System_Drawing_Size
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 12
$System_Drawing_Point.Y = 12
$group.Location = $System_Drawing_Point
$group.TabStop = $False
$group.TabIndex = 0
$group.DataBindings.DefaultDataSourceUpdateMode = 0
$SchedulePickerForm.Controls.Add($group)
$checkSaturday.UseVisualStyleBackColor = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 73
$System_Drawing_Size.Height = 24
$checkSaturday.Size = $System_Drawing_Size
$checkSaturday.TabIndex = 13
$checkSaturday.Text = "Saturday"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 274
$System_Drawing_Point.Y = 64
$checkSaturday.Location = $System_Drawing_Point
$checkSaturday.DataBindings.DefaultDataSourceUpdateMode = 0
$checkSaturday.Name = "checkSaturday"
$checkSaturday.Visible = $False
$group.Controls.Add($checkSaturday)
$checkFriday.UseVisualStyleBackColor = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 64
$System_Drawing_Size.Height = 24
$checkFriday.Size = $System_Drawing_Size
$checkFriday.TabIndex = 12
$checkFriday.Text = "Friday"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 204
$System_Drawing_Point.Y = 64
$checkFriday.Location = $System_Drawing_Point
$checkFriday.DataBindings.DefaultDataSourceUpdateMode = 0
$checkFriday.Name = "checkFriday"
$checkFriday.Visible = $False
$group.Controls.Add($checkFriday)
$checkThursday.UseVisualStyleBackColor = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 70
$System_Drawing_Size.Height = 24
$checkThursday.Size = $System_Drawing_Size
$checkThursday.TabIndex = 11
$checkThursday.Text = "Thursday"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 129
$System_Drawing_Point.Y = 64
$checkThursday.Location = $System_Drawing_Point
$checkThursday.DataBindings.DefaultDataSourceUpdateMode = 0
$checkThursday.Name = "checkThursday"
$checkThursday.Visible = $False
$group.Controls.Add($checkThursday)
$checkWednesday.UseVisualStyleBackColor = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 83
$System_Drawing_Size.Height = 24
$checkWednesday.Size = $System_Drawing_Size
$checkWednesday.TabIndex = 10
$checkWednesday.Text = "Wednesday"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 342
$System_Drawing_Point.Y = 44
$checkWednesday.Location = $System_Drawing_Point
$checkWednesday.DataBindings.DefaultDataSourceUpdateMode = 0
$checkWednesday.Name = "checkWednesday"
$checkWednesday.Visible = $False
$group.Controls.Add($checkWednesday)
$checkTuesday.UseVisualStyleBackColor = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 68
$System_Drawing_Size.Height = 24
$checkTuesday.Size = $System_Drawing_Size
$checkTuesday.TabIndex = 9
$checkTuesday.Text = "Tuesday"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 274
$System_Drawing_Point.Y = 44
$checkTuesday.Location = $System_Drawing_Point
$checkTuesday.DataBindings.DefaultDataSourceUpdateMode = 0
$checkTuesday.Name = "checkTuesday"
$checkTuesday.Visible = $False
$group.Controls.Add($checkTuesday)
$checkMonday.UseVisualStyleBackColor = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 64
$System_Drawing_Size.Height = 24
$checkMonday.Size = $System_Drawing_Size
$checkMonday.TabIndex = 8
$checkMonday.Text = "Monday"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 204
$System_Drawing_Point.Y = 44
$checkMonday.Location = $System_Drawing_Point
$checkMonday.DataBindings.DefaultDataSourceUpdateMode = 0
$checkMonday.Name = "checkMonday"
$checkMonday.Visible = $False
$group.Controls.Add($checkMonday)
$checkSunday.UseVisualStyleBackColor = $True
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 104
$System_Drawing_Size.Height = 24
$checkSunday.Size = $System_Drawing_Size
$checkSunday.TabIndex = 7
$checkSunday.Text = "Sunday"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 129
$System_Drawing_Point.Y = 44
$checkSunday.Location = $System_Drawing_Point
$checkSunday.DataBindings.DefaultDataSourceUpdateMode = 0
$checkSunday.Name = "checkSunday"
$checkSunday.Visible = $False
$group.Controls.Add($checkSunday)
$labelDays.TabIndex = 6
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 64
$System_Drawing_Size.Height = 18
$labelDays.Size = $System_Drawing_Size
$labelDays.Visible = $False
$labelDays.Text = "day(s)"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 189
$System_Drawing_Point.Y = 23
$labelDays.Location = $System_Drawing_Point
$labelDays.DataBindings.DefaultDataSourceUpdateMode = 0
$labelDays.Name = "labelDays"
$group.Controls.Add($labelDays)
$labelHours.TabIndex = 5
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 100
$System_Drawing_Size.Height = 23
$labelHours.Size = $System_Drawing_Size
$labelHours.Text = "hour(s)"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 189
$System_Drawing_Point.Y = 23
$labelHours.Location = $System_Drawing_Point
$labelHours.DataBindings.DefaultDataSourceUpdateMode = 0
$labelHours.Name = "labelHours"
$group.Controls.Add($labelHours)
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 28
$System_Drawing_Size.Height = 20
$boxHourlyDaily.Size = $System_Drawing_Size
$boxHourlyDaily.DataBindings.DefaultDataSourceUpdateMode = 0
$boxHourlyDaily.Text = "1"
$boxHourlyDaily.Name = "boxHourlyDaily"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 155
$System_Drawing_Point.Y = 20
$boxHourlyDaily.Location = $System_Drawing_Point
$boxHourlyDaily.TabIndex = 4
$group.Controls.Add($boxHourlyDaily)
$labelEvery.TabIndex = 3
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 67
$System_Drawing_Size.Height = 23
$labelEvery.Size = $System_Drawing_Size
$labelEvery.Text = "Every"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 116
$System_Drawing_Point.Y = 23
$labelEvery.Location = $System_Drawing_Point
$labelEvery.DataBindings.DefaultDataSourceUpdateMode = 0
$labelEvery.Name = "labelEvery"
$group.Controls.Add($labelEvery)
$radioHourly.TabIndex = 0
$radioHourly.Name = "radioHourly"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 104
$System_Drawing_Size.Height = 24
$radioHourly.Size = $System_Drawing_Size
$radioHourly.UseVisualStyleBackColor = $True
$radioHourly.Text = "Hourly"
$radioHourly.Checked = $True
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 6
$System_Drawing_Point.Y = 17
$radioHourly.Location = $System_Drawing_Point
$radioHourly.DataBindings.DefaultDataSourceUpdateMode = 0
$radioHourly.TabStop = $True
$radioHourly.add_Click($handler_radioButtonChanged)
$group.Controls.Add($radioHourly)
$radioWeekly.TabIndex = 2
$radioWeekly.Name = "radioWeekly"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 104
$System_Drawing_Size.Height = 24
$radioWeekly.Size = $System_Drawing_Size
$radioWeekly.UseVisualStyleBackColor = $True
$radioWeekly.Text = "Weekly"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 6
$System_Drawing_Point.Y = 56
$radioWeekly.Location = $System_Drawing_Point
$radioWeekly.DataBindings.DefaultDataSourceUpdateMode = 0
$radioWeekly.add_Click($handler_radioButtonChanged)
$group.Controls.Add($radioWeekly)
$radioDaily.TabIndex = 1
$radioDaily.Name = "radioDaily"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 104
$System_Drawing_Size.Height = 24
$radioDaily.Size = $System_Drawing_Size
$radioDaily.UseVisualStyleBackColor = $True
$radioDaily.Text = "Daily"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 6
$System_Drawing_Point.Y = 37
$radioDaily.Location = $System_Drawing_Point
$radioDaily.DataBindings.DefaultDataSourceUpdateMode = 0
$radioDaily.add_Click($handler_radioButtonChanged)
$group.Controls.Add($radioDaily)
$SchedulePickerForm.CancelButton = $buttonCancel
$SchedulePickerForm.AcceptButton = $buttonOK
#Save the initial state of the form
$InitialFormWindowState = $SchedulePickerForm.WindowState
#Init the OnLoad event to correct the initial state of the form
$SchedulePickerForm.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$SchedulePickerForm.ShowDialog() |out-null
}
|
PowerShellCorpus/PoshCode/Set-TopMost_2.ps1
|
Set-TopMost_2.ps1
|
#Requires -Version 2.0
$signature = @"
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
public static IntPtr FindWindow(string windowName){
return FindWindow(null,windowName);
}
[DllImport("user32.dll")]
public static extern bool SetWindowPos(IntPtr hWnd,
IntPtr hWndInsertAfter, int X,int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
const UInt32 SWP_NOSIZE = 0x0001;
const UInt32 SWP_NOMOVE = 0x0002;
const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;
public static void MakeTopMost (IntPtr fHandle)
{
SetWindowPos(fHandle, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);
}
public static void MakeNormal (IntPtr fHandle)
{
SetWindowPos(fHandle, HWND_NOTOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);
}
"@
$app = Add-Type -MemberDefinition $signature -Name Win32Window -Namespace ScriptFanatic.WinAPI -ReferencedAssemblies System.Windows.Forms -Using System.Windows.Forms -PassThru
function Set-TopMost
{
param(
[Parameter(
Position=0,ValueFromPipelineByPropertyName=$true
)][Alias('MainWindowHandle')]$hWnd=0,
[Parameter()][switch]$Disable
)
if($hWnd -ne 0)
{
if($Disable)
{
Write-Verbose "Set process handle :$hWnd to NORMAL state"
$null = $app::MakeNormal($hWnd)
return
}
Write-Verbose "Set process handle :$hWnd to TOPMOST state"
$null = $app::MakeTopMost($hWnd)
}
else
{
Write-Verbose "$hWnd is 0"
}
}
function Get-WindowByTitle($WindowTitle="*")
{
Write-Verbose "WindowTitle is: $WindowTitle"
if($WindowTitle -eq "*")
{
Write-Verbose "WindowTitle is *, print all windows title"
Get-Process | Where-Object {$_.MainWindowTitle} | Select-Object Id,Name,MainWindowHandle,MainWindowTitle
}
else
{
Write-Verbose "WindowTitle is $WindowTitle"
Get-Process | Where-Object {$_.MainWindowTitle -like "*$WindowTitle*"} | Select-Object Id,Name,MainWindowHandle,MainWindowTitle
}
}
Exaples:
# set powershell console on top of other windows
gps powershell | Set-TopMost
# unset
gps powershell | Set-TopMost -disable
# set an application on top of other windows by its windows title (wildcard is supported)
Get-WindowByTitle *pad* | Set-TopMost
# unset
Get-WindowByTitle textpad | Set-TopMost -Disable
|
PowerShellCorpus/PoshCode/Amazon AWS user data.ps1
|
Amazon AWS user data.ps1
|
<powershell>
$ComputerName = $env:COMPUTERNAME
$user = [adsi]"WinNT://$ComputerName/Administrator,user"
$user.setpassword("Password")
</powershell>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.