full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PoshCode/Get-SRVPriority.ps1
Get-SRVPriority.ps1
#Returns the priority SRV hostname and port for a particular service and domain. function Get-SRVPriority { param( [string] $query = $( Throw "Query required in the format _Service._Proto.DomainName (ie, `"_ftp._tcp.myserver.net`" or `"_xmpp-client._tcp.gmail.com`").") ) #get all the SRV records for this service/domain, sorted by descending priority (lower priority = preferred server) $srvrecords = @(get-dns $query -type SRV | sort-object -Property PRIORITY -des) #verify that there are some records if ($srvrecords.Length -eq 0) { Throw "No records found." } #now gather all the records that are of the lowest priority, and sort them by weight (higher weight = preferred server) $srvrecords = @($srvrecords | ?{$_.PRIORITY -eq $srvrecords[0].PRIORITY} | sort -Property WEIGHT) #got it: "$($srvrecords[0].TARGET):$($srvrecords[0].PORT)" }
PowerShellCorpus/PoshCode/AD Exch Users to Groups.ps1
AD Exch Users to Groups.ps1
##Purpose: Search Active Directory for all users, add them to specific groups based on homemta value, remove disabled users from same groups, and export all users to excel. ##Requires Excel 2003 or 2007 be installed on the local machine for exporting. ##Requires Quest ActiveRoles Management Shell for Active Directory ##http://www.quest.com/powershell/activeroles-server.aspx ##Helpful tool: ADSIEDIT.MSC ##Use it to find the values for most of these Active Directory variables. ##For the example values, I used the values presented in this link: ##http://technet.microsoft.com/en-us/library/bb125087(EXCHG.65).aspx Add-PSSnapin Quest.ActiveRoles.ADManagement $strRootLDAP = 'contoso.com/Users' ##$strServerx = the homeMTA value in AD for your users. $strServer1 = "CN=Microsoft MTA,CN=Exchange1,CN=Servers,CN=AG1,CN=Administrative Groups,CN=Organization,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=contoso,DC=com" $strServer2 = "CN=Microsoft MTA,CN=Exchange2,CN=Servers,CN=AG1,CN=Administrative Groups,CN=Organization,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=contoso,DC=com" ##$strGroupNamex = the name of the group you want your users to be added to based on their mail server. $strGroupName1 = "Exchange1 Users" $strGroupName2 = "Exchange2 Users" ##$objGroupx = the distinguished name of the groups above. $strGroupDN1 = "CN=Exchange1 Users,OU=Groups,DC=contoso,DC=com" $strGroupDN2 = "CN=Exchange2 Users,OU=Groups,DC=contoso,DC=com" ##$strServerx = the homeMDB value in AD for your users. $strServer1DB1SG1 = "CN=DB1,CN=SG1,CN=InformationStore,CN=Exchange1,CN=Servers,CN=AG1,CN=Administrative Groups,CN=Organization,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=contoso,DC=com" $strServer1DB1SG2 = "CN=DB1,CN=SG2,CN=InformationStore,CN=Exchange1,CN=Servers,CN=AG1,CN=Administrative Groups,CN=Organization,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=contoso,DC=com" $strServer1DB2SG1 = "CN=DB2,CN=SG1,CN=InformationStore,CN=Exchange1,CN=Servers,CN=AG1,CN=Administrative Groups,CN=Organization,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=contoso,DC=com" $strServer1DB2SG2 = "CN=DB2,CN=SG2,CN=InformationStore,CN=Exchange1,CN=Servers,CN=AG1,CN=Administrative Groups,CN=Organization,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=contoso,DC=com" $strServer2DB1SG1 = "CN=DB1,CN=SG1,CN=InformationStore,CN=Exchange2,CN=Servers,CN=AG1,CN=Administrative Groups,CN=Organization,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=contoso,DC=com" $strServer2DB1SG2 = "CN=DB1,CN=SG2,CN=InformationStore,CN=Exchange2,CN=Servers,CN=AG1,CN=Administrative Groups,CN=Organization,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=contoso,DC=com" $strServer2DB2SG1 = "CN=DB2,CN=SG1,CN=InformationStore,CN=Exchange2,CN=Servers,CN=AG1,CN=Administrative Groups,CN=Organization,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=contoso,DC=com" $strServer2DB2SG2 = "CN=DB2,CN=SG2,CN=InformationStore,CN=Exchange2,CN=Servers,CN=AG1,CN=Administrative Groups,CN=Organization,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=contoso,DC=com" function ScanEnabledUsers ($colEnabledUserResults) { $rowcounter = 1 $intTotal = $colEnabledUserResults.Count foreach ($colEnabledUserResult in $colEnabledUserResults) { $strName = $colEnabledUserResult.name $strDN = $colEnabledUserResult.distinguishedname $strMTA = $colEnabledUserResult.homemta switch ($strMTA) { $strServer1 { Write-Host "$rowcounter of $intTotal : Exchange1 : $strName" add-QADGroupMember -Identity $strGroupDN1 -Member "$strDN" foreach ($strMemberof in $colEnabledUserResult.memberof) { switch ($strMemberOf) { $strGroupDN2 { Write-Host -ForegroundColor Red "Removing from Exchange2: $strName" Remove-QADGroupMember -Identity $strGroupDN2 -Member $strDN } } } } $strServer2 { Write-Host "$rowcounter of $intTotal : Exchange2 : $strName" add-QADGroupMember -Identity $strGroupDN2 -Member "$strDN" foreach ($strMemberof in $colEnabledUserResult.memberof) { switch ($strMemberOf){ $strGroupDN1 { Write-Host -ForegroundColor Red "Removing from Exchange1: $strName" Remove-QADGroupMember -Identity $strGroupDN1 -Member $strDN } } } } } $rowcounter++ } } function ScanDisabledUsers ($colDisabledUserResults) { ## Now to remove any "disabled" users from these groups. Write-Host "Checking all disabled User accounts and removing them from distribution groups." $rowcounter = 1 $intTotal = $colDisabledUserResults.Count foreach ($colDisabledUserResult in $colDisabledUserResults) { #$objItem = $objResult.Properties; #$strDN = $objItem.distinguishedname $strDN = $colDisabledUserResult.distinguishedname $strName = $colDisabledUserResult.Name Write-Host $rowcounter of $intTotal : $strName foreach ($strMemberOf in $colDisabledUserResult.memberof) { switch ($strMemberOf) { $strGroupDN1 { Write-Host -ForegroundColor Red "Removing from Exchange1: $strName" Remove-QADGroupMember -Identity $strGroupDN1 -Member $strDN } $strGroupDN2 { Write-Host -ForegroundColor Red "Removing from Exchange2: $strName" Remove-QADGroupMember -Identity $strGroupDN2 -Member $strDN } } } $rowcounter++ } } function ExportGroupToExcel ($strRootLDAP) { Write-Host Exporting Users to Excel... $colExcelUserResults = $colEnabledUserResults + $colDisabledUserResults $intEnabledCount = [int]$colEnabledUserResults.Count Write-Host Enabled Count: $intEnabledCount $intDisabledCount = [int]$colDisabledUserResults.Count Write-Host Disabled Count: $intDisabledCount $intTotalCount = [int]$colExcelUserResults.Count Write-Host Total Count: $intTotalCount ##$rowcounter needs to be set to two in order to leave a line for the header row. $rowcounter = 2 $ws.Cells.Item(1,1) = "Name" $ws.Cells.Item(1,2) = "Logon Name" $ws.Cells.Item(1,3) = "CAC ID Number" $ws.Cells.Item(1,4) = "Exch Server" $ws.Cells.Item(1,5) = "Exch DB & SG" $ws.Cells.Item(1,6) = "Logon Count" $ws.Cells.Item(1,7) = "Dis/Enabled" $ws.Cells.Item(1,8) = "Exchange Server DistinguishedName LONG" $ws.Cells.Item(1,9) = "Exchange Database and Storage Group LONG" foreach ($colQADUserResult in $colExcelUserResults) { ##I'm using write-progress here just to learn how to use it. $intComplete = ($rowcounter/$intTotalCount)*100 write-progress "Export to Excel in Progress" "Complete % : " -PercentComplete $intComplete $ws.Cells.Item("$rowcounter",1) = $colQADUserResult.name $ws.Cells.Item("$rowcounter",2) = $colQADUserResult.samaccountname $ws.Cells.Item("$rowcounter",3) = $colQADUserResult.employeeid $strMTA = $colQADUserResult.homemta switch ($strMTA) { $strServer1 {$ws.Cells.Item("$rowcounter",4) = "Exchange1"} $strServer2 {$ws.Cells.Item("$rowcounter",4) = "Exchange2"} } $strMDB = $colQADUserResult.homemdb switch ($strMDB) { $strServer1DB1SG1 {$ws.Cells.Item("$rowcounter",5) = "DB1 SG1"} $strServer1DB1SG2 {$ws.Cells.Item("$rowcounter",5) = "DB1 SG2"} $strServer1DB2SG1 {$ws.Cells.Item("$rowcounter",5) = "DB2 SG1"} $strServer1DB2SG2 {$ws.Cells.Item("$rowcounter",5) = "DB2 SG2"} $strServer2DB1SG1 {$ws.Cells.Item("$rowcounter",5) = "DB1 SG1"} $strServer2DB1SG2 {$ws.Cells.Item("$rowcounter",5) = "DB1 SG2"} $strServer2DB2SG1 {$ws.Cells.Item("$rowcounter",5) = "DB2 SG1"} $strServer2DB2SG2 {$ws.Cells.Item("$rowcounter",5) = "DB2 SG2"} } $ws.Cells.Item("$rowcounter",6) = $colQADUserResult.logoncount if (($rowcounter - 1) -le [int]$colEnabledUserResults.Count) {$ws.Cells.Item("$rowcounter",7) = "Enabled"} else {$ws.Cells.Item("$rowcounter",7) = "Disabled"} ##I still record the raw $strMTA and $strMDB in Excel here because I found the exchange team ##creating mailboxes on the bridgehead server. This helps spot the oddballs when sorting. $ws.Cells.Item("$rowcounter",8) = $strMTA $ws.Cells.Item("$rowcounter",9) = $strMDB $rowcounter++ } } Write-Host 'Searching for all "Enabled" User accounts in $strRootLDAP' $colEnabledUserResults = Get-QADUser -Enabled -SearchRoot $strRootLDAP -SizeLimit 0 -DontUseDefaultIncludedProperties -IncludedProperties 'memberof','name','distinguishedname','employeeid','samaccountname','homemta','homemdb','logoncount' Write-Host 'Searching for all "Disabled" User accounts in $strRootLDAP' $colDisabledUserResults = Get-QADUser -Disabled -SearchRoot $strRootLDAP -SizeLimit 0 -DontUseDefaultIncludedProperties -IncludedProperties 'memberof','name','distinguishedname','employeeid','samaccountname','homemta','homemdb','logoncount' ScanEnabledUsers ($colEnabledUserResults) ScanDisabledUsers ($colDisabledUserResults) $a = New-Object -comobject Excel.Application $b = $a.Workbooks.Add() $ws = $b.Worksheets.Item(1) $ws.Name = "Users" $a.Visible = $True ExportGroupToExcel ($strRootLDAP)
PowerShellCorpus/PoshCode/Delete Empty Folders.ps1
Delete Empty Folders.ps1
$Drive = Read-Host "Path to Folders" Write-Host "This will delete all empty folders in this directory!" $a = Get-ChildItem $drive -recurse | Where-Object {$_.PSIsContainer -eq $True} $a | Where-Object {$_.GetFiles().Count -lt 1} | Select-Object FullName | ForEach-Object {remove-item $_.fullname -recurse} Write-Host "All Done!"
PowerShellCorpus/PoshCode/CertMgmt pack_5.ps1
CertMgmt pack_5.ps1
##################################################################### # CertMgmtPack.ps1 # Version 0.51 # # Digital certificate management pack # # Vadims Podans (c) 2009 # http://www.sysadmins.lv/ ##################################################################### #requires -Version 2.0 function Import-Certificate { <# .Synopsis Imports digital certificates to Certificate Store from files .Description Improrts digital certificates to Certificate Store from various types of certificates files, such .CER, .DER, .PFX (password required), .P7B. .Parameter Path Specifies the path to certificate file .Parameter Password Specifies password to PFX/PKCS#12 file only. For other certificate types is not required. Note: this parameter must be passed as SecureString. .Parameter Storage Specifies place in Sertificate Store for certificate. For user certificates (default) you MAY specify 'User' and importing certificate will be stored in CurrentUser Certificate Store. For computer certificates you MUST specify 'Computer' and importing certificates will be stored in LocalMachine Certificate Store. .Parameter Container Specifies container within particular Certificate Store location. Container may be one of AuthRoot/CA/Disallowed/My/REQUEST/Root/SmartCardRoot/Trust/TrustedPeople/ TrustedPublisher/UserDS. These containers represent MMC console containers as follows: AddressBook - AddressBook AuthRoot - Third-Party Root CAs CA - Intermediate CAs Disallowed - Untrused Certificates My - Personal REQUEST - Certificate Enrollment Requests Root - Trusted Root CAs SmartCardRoot - Smart Card Trusted Roots Trust - Enterprise Trust TrustedPeople - Trusted People TrustedPublishers - Trusted Publishers UserDS - Active Directory User Object .Parameter Exportable Marks imported certificates private key as exportable. May be used only for PFX files only. If this switch is not presented for PFX files, after importing you will not be able to export this certificate with private key again. .Parameter StrongProtection Enables private key strong protection that requires user password each time when certificate private key is used. Not available for computer certificates, because computers certificates are used under LocalSystem account and here is no UI for user to type password. .Outputs This command provide a simple message if the export is successful. #> [CmdletBinding()] param ( [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)] [string]$Path, [Parameter(Position = 1)] [System.Security.SecureString]$Password, [Parameter(Position = 2)] [string][ValidateSet("CurrentUser", "LocalMachine")]$Storage = "CurrentUser", [string][ValidateSet("AddressBook", "AuthRoot", "CA", "Disallowed", "My", "REQUEST", "Root", "SmartCardRoot", "Trust", "TrustedPeople", "TrustedPublisher", "UserDS")]$Container = "My", [switch]$Exportable, [switch]$StrongProtection ) if (!(Resolve-Path $Path)) {throw "Looks like your specified certificate file doesn't exist"} $file = gi $Path -Force -ErrorAction Stop $certs = New-Object system.security.cryptography.x509certificates.x509certificate2 switch ($Storage) { "CurrentUser" {$flags = "UserKeySet"} "LocalMachine" {$flags = "MachineKeySet"} } switch -regex ($file.Extension) { ".CER|.DER" {$certs.Import($file.FullName, $null, $flags)} ".PFX" { if (!$password) {throw "For PFX files password is required."} if ($StrongProtection -and $Storage -eq "Computer") { throw "You cannot use Private Key Strong Protection for computer certificates!" } if ($Exportable) {$flags = $flags + ", Exportable"} if ($StrongProtection) {$flags = $flags + ", UserProtected"} $certs.Import($file.FullName, $password, $flags) } ".P7B|.SST" { $certs = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection $certs.Import([System.IO.File]::ReadAllBytes($file.FullName)) } default {throw "Looks like your specified file is not a certificate file"} } $store = New-Object system.security.cryptography.X509Certificates.X509Store $Container, $Storage $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) $certs | %{$store.Add($_)} if ($?) {Write-Host -ForegroundColor Green Certificate file`: $file.fullname was successfully added to $Container container} $store.Close() } function Export-Certificate { <# .Synopsis Exports digital certificates to file Certificate Store. .Description Exports digital certificates from Certificate Store to various types of certificate file such .CER, .DER, .PFX (password required), .P7B or .SST (serializd store). .Parameter Path Specifies the path to certificate storing folder .Parameter Type Specifies type of imported certificate. May be one of CERT/PFX/PKCS#12/P7B/PKCS#7. .Parameter Password Specifies a password for PFX files and used only if type is specified as PFX/PKCS#12. Note: password must be supplied as SecureString. .Parameter Storage Specifies place in Sertificate Store for certificate. For user certificates (default) you MAY specify 'User' to export certificates from CurrentUser Certificate Store. For computer certificates you MUST specify 'Computer' to export certificates from LocalMachine Certificate Store. .Parameter Container Specifies container within particular Certificate Store location. Container may be one of AuthRoot/CA/Disallowed/My/REQUEST/Root/SmartCardRoot/Trust/TrustedPeople/ TrustedPublisher/UserDS. These containers represent MMC console containers as follows: AddressBook - AddressBook AuthRoot - Third-Party Root CAs CA - Intermediate CAs Disallowed - Untrused Certificates My - Personal REQUEST - Certificate Enrollment Requests Root - Trusted Root CAs SmartCardRoot - Smart Card Trusted Roots Trust - Enterprise Trust TrustedPeople - Trusted People TrustedPublishers - Trusted Publishers UserDS - Active Directory User Object .EXAMPLE .Outputs This command doesn't provide any output, except errors. .Link #> [CmdletBinding()] param ( [Parameter(Position = 0)] [string]$Path, [Parameter(Mandatory = $true, Position = 1)] [string][ValidatePattern("Cert|Pfx|pkcs12|pkcs7|SST")]$Type, [Parameter(Position = 2)] [System.Security.SecureString]$Password, [Parameter(Position = 3)] [string][ValidateSet("CurrentUser", "LocalMachine")]$Storage = "CurrentUser", [Parameter(ValueFromPipeline = $true, Position = 4)] [string][ValidateSet("AddressBook", "AuthRoot", "CA", "Disallowed", "My", "REQUEST", "Root", "SmartCardRoot", "Trust", "TrustedPeople", "TrustedPublisher", "UserDS")]$Container = "My", [string]$Thumbprint, [string]$Subject, [string]$Issuer, [string]$SerialNumber, [string]$NotAfter, [string]$NotBefore, [switch]$DeleteKey, [switch]$Recurse ) if (!(Test-Path $Path)) { New-Item -ItemType directory -Path $Path -Force -ErrorAction Stop } if ((Resolve-Path $Path).Provider.Name -ne "FileSystem") { throw "Spicifed path is not recognized as filesystem path. Try again" } if ($Recurse) { function dirx ($Storage) { dir cert:\\$Storage -Recurse | ?{!$_.PsIsContainer} } } else { function dirx ($Storage, $Container) { dir cert:\\$Storage\\$Container } } if ($Type -eq 'pkcs12') {$Type = "PFX"} if ($Type -eq 'SST') {$Type = "SerializedStore"} if ($Type -eq "PFX" -and !$Password) {throw "For PFX files password is required."} $Type = [System.Security.Cryptography.X509Certificates.X509ContentType]::$Type if ($NotAfter) {$NotAfter = [datetime]::ParseExact($NotAfter, "dd.MM.yyy", $null)} if ($NotBefore) {$NotBefore = [datetime]::ParseExact($NotBefore, "dd.MM.yyy", $null)} if ($Thumbprint) {$certs = @(dirx | ?{$_.Thumbprint -like "*$Thumbprint*"})} elseif ($Subject) {$certs = @(dirx | ?{$_.Subject -like "*$Subject*"})} elseif ($Issuer) {$certs = @(dirx | ?{$_.Issuer -like "*$Issuer*"})} elseif ($SerialNumber) {$certs = @(dirx | ?{$_.SerialNumber -like "*$SerialNumber*"})} elseif ($NotAfter -and !$NotBefore) {$certs = @(dirx | ?{$_.NotAfter -lt $NotAfter})} elseif (!$NotAfter -and $NotBefore) {$certs = @(dirx | ?{$_.NotBefore -gt $NotBefore})} elseif ($NotAfter -and $NotBefore) {$certs = @(dirx | ?{$_.NotAfter -lt $NotAfter ` -and $_.NotBefore -gt $NotBefore})} else {$certs = @(dirx)} if ($certs.Count -eq 0) {Write-Warning "Sorry, we unable to find certificates that correspond your filter :("; return} switch -regex ($Type) { "Cert" { foreach ($cert in $certs) { [void]($cert.Subject -match 'CN=([^,]+)') $CN = $matches[1] -replace '[\\\\/:\\*?`"<>|]', '' $bytes = $cert.Export($type) $base64Data = [System.Convert]::ToBase64String($bytes) Set-Content -LiteralPath $(Join-Path $Path ($CN + "_" + $cert.Thumbprint + ".cer")) -Value $base64Data } } "PFX" { foreach ($cert in $certs) { [void]($cert.Subject -match 'CN=([^,]+)') $CN = $matches[1] -replace '[\\\\/:\\*?`"<>|]', '' $bytes = $cert.Export($Type, $Password) [System.IO.File]::WriteAllBytes($(Join-Path $Path ($CN + "_" + $cert.Thumbprint + ".pfx")), $bytes) if ($DeleteKey) { $tempcert = $cert.Export("Cert") $store = New-Object system.security.cryptography.X509Certificates.X509Store $container, $Storage $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) $store.Remove($cert) $store.Add($tempcert) $store.Close() } } } "Pkcs7|SerializedStore" { $certcol = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection $certs | %{[void]$certcol.Add($_)} $bytes = $certcol.Export($Type) if ($Type -eq "Pkcs7") {$ext = ".p7b"} else {$ext = ".sst"} [System.IO.File]::WriteAllBytes($("ExportedCertificates" + $ext, $bytes)) } } }
PowerShellCorpus/PoshCode/Get-Delegate.ps1
Get-Delegate.ps1
## Get-Delegate.ps1\n###################################################################################################\n## Use Reflection and IL to emit arbitrary delegates ...\n## A trick they taught us on the PowerShell blog\n## http://blogs.msdn.com/powershell/archive/2006/07/25/678259.aspx\n###################################################################################################\nparam([type] $type, [ScriptBlock] $scriptBlock)\n\n# Helper function to emit an IL opcode\nfunction emit($opcode)\n{\n if ( ! ($op = [System.Reflection.Emit.OpCodes]::($opcode)))\n {\n throw "new-method: opcode '$opcode' is undefined"\n }\n\n if ($args.Length -gt 0)\n {\n $ilg.Emit($op, $args[0])\n }\n else\n {\n $ilg.Emit($op)\n }\n}\n\n# Get the method info for this delegate invoke...\n$delegateInvoke = $type.GetMethod("Invoke")\n\n# Get the argument type signature for the delegate invoke\n$parameters = @($delegateInvoke.GetParameters())\n$returnType = $delegateInvoke.ReturnParameter.ParameterType\n\n$argList = new-object Collections.ArrayList\n[void] $argList.Add([ScriptBlock])\nforeach ($p in $parameters)\n{\n [void] $argList.Add($p.ParameterType);\n}\n\n$dynMethod = new-object reflection.emit.dynamicmethod ("",\n $returnType, $argList.ToArray(), [object], $false)\n$ilg = $dynMethod.GetILGenerator()\n\n# Place the scriptblock on the stack for the method call\nemit Ldarg_0\n\nemit Ldc_I4 ($argList.Count - 1) # Create the parameter array\nemit Newarr ([object])\n\nfor ($opCount = 1; $opCount -lt $argList.Count; $opCount++)\n{\n emit Dup # Dup the array reference\n emit Ldc_I4 ($opCount - 1); # Load the index\n emit Ldarg $opCount # Load the argument\n if ($argList[$opCount].IsValueType) # Box if necessary\n {\n emit Box $argList[$opCount]\n }\n emit Stelem ([object]) # Store it in the array\n}\n\n# Now emit the call to the ScriptBlock invoke method\nemit Call ([ScriptBlock].GetMethod("InvokeReturnAsIs"))\n\nif ($returnType -eq [void])\n{\n # If the return type is void, pop the returned object\n emit Pop\n}\nelse\n{\n # Otherwise emit code to convert the result type which looks\n # like LanguagePrimitives.ConvertTo(value, type)\n\n $signature = [object], [type]\n $convertMethod =\n [Management.Automation.LanguagePrimitives].GetMethod(\n "ConvertTo", $signature);\n $GetTypeFromHandle = [Type].GetMethod("GetTypeFromHandle");\n emit Ldtoken $returnType # And the return type token...\n emit Call $GetTypeFromHandle\n emit Call $convertMethod\n}\nemit Ret\n\n#\n# Now return a delegate from this dynamic method...\n#\n\n$dynMethod.CreateDelegate($type, $scriptBlock)
PowerShellCorpus/PoshCode/62334bcd-6366-4c6e-b6ae-220d2a0dc2f5.ps1
62334bcd-6366-4c6e-b6ae-220d2a0dc2f5.ps1
## Tab-Completion ################# ## Please dot souce this script file. ## In first loading, it may take a several minutes, in order to generate ProgIDs and TypeNames list. ## What this can do is: ## ## [datetime]::n<tab> ## [datetime]::now.d<tab> ## $a = New-Object "Int32[,]" 2,3; $b = "PowerShell","PowerShell" ## $c = [ref]$a; $d = [ref]$b,$c ## $d[0].V<tab>[0][0].Get<tab> ## $d[1].V<tab>[0,0].tos<tab> ## $function:a<tab> ## $env:a<tab> ## [System.Type].a<tab> ## [datetime].Assembly.a<tab> ## ).a<tab> # shows System.Type properties and methods... ## #native command name expansion ## fsu<tab> ## #command option name expansion (for fsutil ipconfig net powershell only) ## fsutil <tab> ## ipconfig <tab> ## net <tab> ## powershell <tab> ## #TypeNames expansion ## [Dec<tab> ## [Microsoft.PowerShell.Com<tab> ## New-Object -TypeName IO.Dir<tab> ## New-Object System.Management.Auto<tab> ## #ProgIDs expansion ## New-Object -Com shel<tab> ## #Enum option expansion ## Set-ExecutionPolicy <tab> ## Set-ExecutionPolicy All<tab> ## Set-ExcusionPolisy -ex <tab> ## Get-TraceSourceÅ@Inte<tab> ## iex -Err <tab> -wa Sil<tab> ## #WmiClasses expansion ## Get-WmiObject -class Win32_<tab> ## gwmi __Instance<tab> ## #Encoding expansion ## [Out-File | Export-CSV | Select-String | Export-Clixml] -enc <tab> ## [Add-Content | Get-Content | Set-Content} -Encoding Big<tab> ## #PSProvider name expansion ## [Get-Location | Get-PSDrive | Get-PSProvider | New-PSDrive | Remove-PSDrive] [-PSProvider] <tab> ## Get-PSProvider <tab> ## pwd -psp al<tab> ## #PSDrive name expansion ## [Get-PSDrive | New-PSDrive | Remove-PSDrive] [-Name] <tab> ## Get-PSDrive <tab> ## pwd -psd <tab> ## #PSSnapin name expansion ## [Add-PSSnapin | Get-PSSnapin | Remove-PSSnapin ] [-Name] <tab> ## Get-Command -PSSnapin <tab> ## Remove-PSSnapin <tab> ## Get-PSSnapin M<tab> ## #Eventlog name and expansion ## Get-Eventlog -Log <tab> ## Get-Eventlog w<tab> ## #Eventlog's entrytype expansion ## Get-EventLog -EntryType <tab> ## Get-EventLog -EntryType Er<tab> ## Get-EventLog -Ent <tab> ## #Service name expansion ## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-Name] <tab> ## New-Service -DependsOn <tab> ## New-Service -Dep e<tab> ## Get-Service -n <tab> ## Get-Service <tab>,a<tab>,p<tab> ## gsv <tab> ## #Service display name expansion ## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-DisplayName] <tab> ## Get-Service -Dis <tab> ## gsv -Dis <tab>,w<tab>,b<tab> ## #Cmdlet and Topic name expansion ## Get-Help [-Name] about_<tab> ## Get-Help <tab> ## #Category name expansion ## Get-Help -Category c<tab>,<tab> ## #Command name expansion ## Get-Command [-Name] <tab> ## Get-Command -Name <tab> ## gcm a<tab>,<tab> ## #Scope expansion ## [Clear-Variable | Export-Alias | Get-Alias | Get-PSDrive | Get-Variable | Import-Alias ## New-Alias | New-PSDrive | New-Variable | Remove-Variable | Set-Alias | Set-Variable] -Scope <tab> ## Clear-Variable -Scope G<tab> ## Set-Alias -s <tab> ## #Process name expansion ## [Get-Process | Stop-Process] [-Name] <tab> ## Stop-Process -Name <tab> ## Stop-Process -N pow<tab> ## Get-Process <tab> ## ps power<tab> ## #Trace sources expansion ## [Trace-Command | Get-TraceSource | Set-TraceSource] [-Name] <tab>,a<tab>,p<tab> ## #Trace -ListenerOption expansion ## [Set-TraceSource | Trace-Command] -ListenerOption <tab> ## Set-TraceSource -Lis <tab>,n<tab> ## #Trace -Option expansion ## [Set-TraceSource | Trace-Command] -Option <tab> ## Set-TraceSource -op <tab>,con<tab> ## #ItemType expansion ## New-Item -Item <tab> ## ni -ItemType d<tab> ## #ErrorAction and WarningAction option expansion ## CMDLET [-ErrorAction | -WarningAction] <tab> ## CMDLET -Error s<tab> ## CMDLET -ea con<tab> ## CMDLET -wa <tab> ## #Continuous expansion with comma when parameter can treat multiple option ## # if there are spaces, occur display bug in the line ## # if strings contains '$' or '-', not work ## Get-Command -CommandType <tab>,<tab><tab>,cm<tab> ## pwd -psp <tab>,f<tab>,va<tab> ## Get-EventLog -EntryType <tab>,i<tab>,s<tab> ## #Enum expansion in method call expression ## # this needs one or more spaces after left parenthesis or comma ## $str = "day night" ## $str.Split( " ",<space>rem<tab> ## >>> $str.Split( " ", "RemoveEmptyEntries" ) <Enter> ERROR ## $str.Split( " ", "RemoveEmptyEntries" -as<space><tab> ## >>> $str.Split( " ", "RemoveEmptyEntries" -as [System.StringSplitOptions] ) <Enter> Success ## $type = [System.Type] ## $type.GetMembers(<space>Def<tab> ## [IO.Directory]::GetFiles( "C:\\", "*",<space>All<tab> ## # this can do continuous enum expansion with comma and no spaces ## $type.GetMembers( "IgnoreCase<comma>Dec<tab><comma>In<tab>" ## [IO.Directory]::GetAccessControl( "C:\\",<space>au<tab><comma>ac<tab><comma>G<tab> ## #Better '$_.' expansion when cmdlet output objects or method return objects ## ls |group { $_.Cr<tab>.Tost<tab>"y")} | tee -var foo| ? { $_.G<tab>.c<tab> -gt 5 } | % { md $_.N<tab> ; copy $_.G<tab> $_.N<tab> } ## [IO.DriveInfo]::GetDrives() | ? { $_.A<tab> -gt 1GB } ## $Host.UI.RawUI.GetBufferContents($rect) | % { $str += $_.c<tab> } ## gcm Add-Content |select -exp Par<tab>|select -exp <tab> | ## select -ExpandProperty Par<tab>| | ? { $_.Par<tab>.N<tab> -eq "string" } ## #when Get-PipeLineObject failed, '$_.' shows methods and properties name of FileInfo and String and Type ## #Property name expansion ## [ Format-List | Format-Custom | Format-Table | Format-Wide | Compare-Object | ## ConvertTo-Html | Measure-Object | Select-Object | Group-Object | Sort-Object ] [-Property] <tab> ## Select-Object -ExcludeProperty <tab> ## Select-Object -ExpandProperty <tab> ## gcm Get-Acl|select -exp Par<tab> ## ps |group na<tab> ## ls | ft A<tab>,M<tab>,L<tab> ## #Hashtable key expansion in the variable name and '.<tab>' ## Get-Process | Get-Unique | % { $hash += @{$_.ProcessName=$_} } ## $hash.pow<tab>.pro<tab> ### Generate ProgIDs list... if ($_ProgID -eq $null) { $_HKCR = [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\") [Object[]] $_ProgID = $null foreach ( $_subkey in $_HKCR.GetSubKeyNames() ) { foreach ( $_i in [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\$_subkey\\ProgID") ) { if ($_i -ne $null) { $_ProgID += $_i.GetValue("") } } } '$_ProgID was updated...' | Out-Host $_ProgID = $_ProgID|sort -Unique Set-Content -Value $_ProgID -Path $PSHOME\\ProgIDs.txt Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_ProgID = Get-Content -Path C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\ProgIDs.txt;' } ### Generate TypeNames list... if ( $_TypeNames -eq $null ) { [Object[]] $_TypeNames = $null foreach ( $_asm in [AppDomain]::CurrentDomain.GetAssemblies() ) { foreach ( $_type in $_asm.GetTypes() ) { $_TypeNames += $_type.FullName } } '$_TypeNames was updated...' | Out-Host $_TypeNames = $_TypeNames | sort -Unique Set-Content -Value $_TypeNames -Path $PSHOME\\TypeNames.txt Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_TypeNames = Get-Content -Path $PSHOME\\TypeNames.txt;' } if ( $_TypeNames_System -eq $null ) { [Object[]] $_TypeNames_System = $null foreach ( $_type in $_TypeNames -like "System.*" ) { $_TypeNames_System += $_type.Substring(7) } '$_TypeNames_System was updated...' | Out-Host Set-Content -Value $_TypeNames_System -Path $PSHOME\\TypeNames_System.txt Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_TypeNames_System = Get-Content -Path $PSHOME\\TypeNames_System.txt;' } ### Generate WMIClasses list... if ( $_WMIClasses -eq $null ) { [Object[]] $_WMIClasses = $null foreach ( $_class in gwmi -List ) { $_WMIClasses += $_class.Name } $_WMIClasses = $_WMIClasses | sort -Unique '$_WMIClasses was updated...' | Out-Host Set-Content -Value $_WMIClasses -Path $PSHOME\\WMIClasses.txt Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_WMIClasses = Get-Content -Path $PSHOME\\WMIClasses.txt;' } $global:_snapin = $null # Load Get-PipeLineObject function for $_ and property name expansion. $_scriptpath = gi $MyInvocation.MyCommand.Path iex (". " + (Join-Path $_scriptpath.DirectoryName "Get-PipeLineObject.ps1")) function TabExpansion { # This is the default function to use for tab expansion. It handles simple # member expansion on variables, variable name expansion and parameter completion # on commands. It doesn't understand strings so strings containing ; | ( or { may # cause expansion to fail. param($line, $lastWord) & { # Helper function to write out the matching set of members. It depends # on dynamic scoping to get $_base, _$expression and $_pat function Write-Members ($sep='.') { # evaluate the expression to get the object to examine... Invoke-Expression ('$_val=' + $_expression) if ( $_expression -match '^\\$global:_dummy' ) { $temp = $_expression -replace '^\\$global:_dummy(.*)','$1' $_expression = '$_' + $temp } $_method = [Management.Automation.PSMemberTypes] ` 'Method,CodeMethod,ScriptMethod,ParameterizedProperty' if ($sep -eq '.') { $members = ( [Object[]](Get-Member -InputObject $_val.PSextended $_pat) + [Object[]](Get-Member -InputObject $_val.PSadapted $_pat) + [Object[]](Get-Member -InputObject $_val.PSbase $_pat) ) if ( $_val -is [Hashtable] ) { [Microsoft.PowerShell.Commands.MemberDefinition[]]$_keys = $null foreach ( $_name in $_val.Keys ) { $_keys += ` New-Object Microsoft.PowerShell.Commands.MemberDefinition ` [int],$_name,"Property",0 } $members += [Object[]]$_keys | ? { $_.Name -like $_pat } } foreach ($_m in $members | sort membertype,name -Unique) { if ($_m.MemberType -band $_method) { # Return a method... $_base + $_expression + $sep + $_m.name + '(' } else { # Return a property... $_base + $_expression + $sep + $_m.name } } } else { foreach ($_m in Get-Member -Static -InputObject $_val $_pat | Sort-Object membertype,name) { if ($_m.MemberType -band $_method) { # Return a method... $_base + $_expression + $sep + $_m.name + '(' } else { # Return a property... $_base + $_expression + $sep + $_m.name } } } } switch -regex ($lastWord) { # Handle property and method expansion at '$_' '(^.*)(\\$_\\.)(\\w*)$' { $_base = $matches[1] $_expression = '$global:_dummy' $_pat = $matches[3] + '*' $global:_dummy = $null Get-PipeLineObject if ( $global:_dummy -eq $null ) { if ( $global:_exp -match '^\\$.*\\(.*$' ) { $type = ( iex $_exp.Split("(")[0] ).OverloadDefinitions[0].Split(" ")[0] -replace '\\[[^\\[\\]]*\\]$' -as [type] if ( $_expression -match '^\\$global:_dummy' ) { $temp = $_expression -replace '^\\$global:_dummy(.*)','$1' $_expression = '$_' + $temp } foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } ) { if ($_m.MemberType -eq "Method") { $_base + $_expression + '.' + $_m.name + '(' } else { $_base + $_expression + '.' + $_m.name } } break; } elseif ( $global:_exp -match '^\\[.*\\:\\:.*\\(.*$' ) { $tname, $mname = $_exp.Split(":(", "RemoveEmptyEntries"-as [System.StringSplitOptions])[0,1] $type = @(iex ($tname + '.GetMember("' + $mname + '")'))[0].ReturnType.FullName -replace '\\[[^\\[\\]]*\\]$' -as [type] if ( $_expression -match '^\\$global:_dummy' ) { $temp = $_expression -replace '^\\$global:_dummy(.*)','$1' $_expression = '$_' + $temp } foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } ) { if ($_m.MemberType -eq "Method") { $_base + $_expression + '.' + $_m.name + '(' } else { $_base + $_expression + '.' + $_m.name } } break; } else { $global:_dummy = $global:_mix } } Write-Members break; } # Handle property and method expansion rooted at variables... # e.g. $a.b.<tab> '(^.*)(\\$(\\w|\\.)+)\\.(\\w*)$' { $_base = $matches[1] $_expression = $matches[2] [void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock] $_pat = $matches[4] + '*' if ( $_expression -match '^\\$_\\.' ) { $_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1') } Write-Members break; } # Handle simple property and method expansion on static members... # e.g. [datetime]::n<tab> '(^.*)(\\[(\\w|\\.)+\\])\\:\\:(\\w*)$' { $_base = $matches[1] $_expression = $matches[2] $_pat = $matches[4] + '*' Write-Members '::' break; } # Handle complex property and method expansion on static members # where there are intermediate properties... # e.g. [datetime]::now.d<tab> '(^.*)(\\[(\\w|\\.)+\\]\\:\\:(\\w+\\.)+)(\\w*)$' { $_base = $matches[1] # everything before the expression $_expression = $matches[2].TrimEnd('.') # expression less trailing '.' $_pat = $matches[5] + '*' # the member to look for... Write-Members break; } # Handle variable name expansion... '(^.*\\$)(\\w+)$' { $_prefix = $matches[1] $_varName = $matches[2] foreach ($_v in Get-ChildItem ('variable:' + $_varName + '*')) { $_prefix + $_v.name } break; } # Handle env&function drives variable name expansion... '(^.*\\$)(.*\\:)(\\w+)$' { $_prefix = $matches[1] $_drive = $matches[2] $_varName = $matches[3] if ($_drive -eq "env:" -or $_drive -eq "function:") { foreach ($_v in Get-ChildItem ($_drive + $_varName + '*')) { $_prefix + $_drive + $_v.name } } break; } # Handle array's element property and method expansion # where there are intermediate properties... # e.g. foo[0].n.b<tab> '(^.*)(\\$((\\w+\\.)|(\\w+(\\[(\\w|,)+\\])+\\.))+)(\\w*)$' { $_base = $matches[1] $_expression = $matches[2].TrimEnd('.') $_pat = $Matches[8] + '*' [void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock] if ( $_expression -match '^\\$_\\.' ) { $_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1') } Write-Members break; } # Handle property and method expansion rooted at type object... # e.g. [System.Type].a<tab> '(^\\[(\\w|\\.)+\\])\\.(\\w*)$' { if ( $(iex $Matches[1]) -isnot [System.Type] ) { break; } $_expression = $Matches[1] $_pat = $Matches[$matches.Count-1] + '*' Write-Members break; } # Handle complex property and method expansion on type object members # where there are intermediate properties... # e.g. [datetime].Assembly.a<tab> '^(\\[(\\w|\\.)+\\]\\.(\\w+\\.)+)(\\w*)$' { $_expression = $matches[1].TrimEnd('.') # expression less trailing '.' $_pat = $matches[4] + '*' # the member to look for... if ( $(iex $_expression) -eq $null ) { break; } Write-Members break; } # Handle property and method expansion rooted at close parenthes... # e.g. (123).a<tab> '^(.*)\\)((\\w|\\.)*)\\.(\\w*)$' { $_base = $Matches[1] + ")" if ( $matches[3] -eq $null) { $_expression = '[System.Type]' } else { $_expression = '[System.Type]' + $Matches[2] } $_pat = $matches[4] + '*' iex "$_expression | Get-Member $_pat | sort MemberType,Name" | % { if ( $_.MemberType -like "*Method*" -or $_.MemberType -like "*Parameterized*" ) { $parenthes = "(" } if ( $Matches[2] -eq "" ) { $_base + "." + $_.Name + $parenthes } else { $_base + $Matches[2] + "." + $_.Name + $parenthes } } break; } # Handle .NET type name expansion ... # e.g. [Microsoft.PowerShell.Com<tab> '^\\[((\\w+\\.?)+)$' { $_opt = $matches[1] + '*' foreach ( $_exp in $_TypeNames_System -like $_opt ) { '[' + $_exp } foreach ( $_exp in $_TypeNames -like $_opt ) { '[' + $_exp } break; } # Do completion on parameters... '^-([\\w0-9]*)' { $_pat = $matches[1] + '*' # extract the command name from the string # first split the string into statements and pipeline elements # This doesn't handle strings however. $_cmdlet = [regex]::Split($line, '[|;=]')[-1] # Extract the trailing unclosed block e.g. ls | foreach { cp if ($_cmdlet -match '\\{([^\\{\\}]*)$') { $_cmdlet = $matches[1] } # Extract the longest unclosed parenthetical expression... if ($_cmdlet -match '\\(([^()]*)$') { $_cmdlet = $matches[1] } # take the first space separated token of the remaining string # as the command to look up. Trim any leading or trailing spaces # so you don't get leading empty elements. $_cmdlet = $_cmdlet.Trim().Split()[0] # now get the info object for it... $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0] } # expand the parameter sets and emit the matching elements foreach ($_n in $_cmdlet.ParameterSets | Select-Object -expand parameters | Sort-Object -Unique name) { $_n = $_n.name if ($_n -like $_pat) { '-' + $_n } } break; } # try to find a matching command... default { $lastex = [regex]::Split($line, '[|;=]')[-1] if ($lastex -match '[[$].*\\w+\\(.*-as\\s*$') { '['+ $global:_enum + ']' } elseif ( $lastex -match '([[$].*(\\w+))\\((.*)$' ) #elseif ( $lastex -match '([[$].*(\\w+))\\(([^)]*)$' ) { $_method = $Matches[1] if ( $Matches[3] -match "(.*)((`"|')(\\w+,)+(\\w*))$" ) { $continuous = $true $_opt = $Matches[5] + '*' $_base = $Matches[2].TrimStart('"') -replace '(.*,)\\w+$','$1' $position = $Matches[1].Split(",").Length } else { $continuous = $false $_opt = ($Matches[3].Split(',')[-1] -replace '^\\s*','') + "*" $position = $Matches[3].Split(",").Length } if ( ($_mdefs = iex ($_method + ".OverloadDefinitions")) -eq $null ) { $tname, $mname = $_method.Split(":", "RemoveEmptyEntries" -as [System.StringSplitOptions]) $_mdefs = iex ($tname + '.GetMember("' + $mname + '") | % { $_.ToString() }') } foreach ( $def in $_mdefs ) { [void] ($def -match '\\((.*)\\)') foreach ( $param in [regex]::Split($Matches[1], ', ')[$position-1] ) { if ($param -eq $null -or $param -eq "") { continue; } $type = $param.split()[0] if ( $type -like '*`[*' -or $type -eq "Params" -or $type -eq "" ) { continue; } $fullname = @($_typenames -like "*$type*") foreach ( $name in $fullname ) { if ( $continuous -eq $true -and ( $name -as [System.Type] ).IsEnum ) { $output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$',($_base + '$1') $output | sort } elseif ( ( $name -as [System.Type] ).IsEnum ) { $global:_enum = $name $output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$','"$1"' $output | sort } } } } if ( $output -ne $null ) { break; } } if ( $line[-1] -eq " " ) { $_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-1] # now get the info object for it... $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0] } if ( "Set-ExecutionPolicy" -eq $_cmdlet.Name ) { "Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" | sort break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ) { Get-TraceSource | % { $_.Name } | sort -Unique break; } if ( "New-Object" -eq $_cmdlet.Name ) { $_TypeNames_System $_TypeNames break; } if ( $_cmdlet.Noun -like "*WMI*" ) { $_WMIClasses break; } if ( "Get-Process" -eq $_cmdlet.Name ) { Get-Process | % { $_.Name } | sort break; } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name ) { if ( $global:_snapin -ne $null ) { $global:_snapin break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin break; } } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" ) { Get-PSDrive | sort break; } if ( "Get-Eventlog" -eq $_cmdlet.Name ) { Get-EventLog -List | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name ) { Get-Help -Category all | % { $_.Name } | sort -Unique break; } if ( "Get-Service", "Restart-Service", "Resume-Service", "Start-Service", "Stop-Service", "Suspend-Service" ` -contains $_cmdlet.Name ) { Get-Service | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name ) { Get-Command -CommandType All | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object", "ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" ` -contains $_cmdlet.Name ) { Get-PipeLineObject $_dummy | Get-Member -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } } if ( $line[-1] -eq " " ) { # extract the command name from the string # first split the string into statements and pipeline elements # This doesn't handle strings however. $_cmdlet = [regex]::Split($line, '[|;=]')[-1] # Extract the trailing unclosed block e.g. ls | foreach { cp if ($_cmdlet -match '\\{([^\\{\\}]*)$') { $_cmdlet = $matches[1] } # Extract the longest unclosed parenthetical expression... if ($_cmdlet -match '\\(([^()]*)$') { $_cmdlet = $matches[1] } # take the first space separated token of the remaining string # as the command to look up. Trim any leading or trailing spaces # so you don't get leading empty elements. $_cmdlet = $_cmdlet.Trim().Split()[0] # now get the info object for it... $_cmdlet = @(Get-Command -type 'Application' $_cmdlet)[0] if ( $_cmdlet.Name -eq "powershell.exe" ) { "-PSConsoleFile", "-Version", "-NoLogo", "-NoExit", "-Sta", "-NoProfile", "-NonInteractive", "-InputFormat", "-OutputFormat", "-EncodedCommand", "-File", "-Command" | sort break; } if ( $_cmdlet.Name -eq "fsutil.exe" ) { "behavior query", "behavior set", "dirty query", "dirty set", "file findbysid", "file queryallocranges", "file setshortname", "file setvaliddata", "file setzerodata", "file createnew", "fsinfo drives", "fsinfo drivetype", "fsinfo volumeinfo", "fsinfo ntfsinfo", "fsinfo statistics", "hardlink create", "objectid query", "objectid set", "objectid delete", "objectid create", "quota disable", "quota track", "quota enforce", "quota violations", "quota modify", "quota query", "reparsepoint query", "reparsepoint delete", "sparse setflag", "sparse queryflag", "sparse queryrange", "sparse setrange", "usn createjournal", "usn deletejournal", "usn enumdata", "usn queryjournal", "usn readdata", "volume dismount", "volume diskfree" | sort break; } if ( $_cmdlet.Name -eq "net.exe" ) { "ACCOUNTS ", " COMPUTER ", " CONFIG ", " CONTINUE ", " FILE ", " GROUP ", " HELP ", "HELPMSG ", " LOCALGROUP ", " NAME ", " PAUSE ", " PRINT ", " SEND ", " SESSION ", "SHARE ", " START ", " STATISTICS ", " STOP ", " TIME ", " USE ", " USER ", " VIEW" | sort break; } if ( $_cmdlet.Name -eq "ipconfig.exe" ) { "/?", "/all", "/renew", "/release", "/flushdns", "/displaydns", "/registerdns", "/showclassid", "/setclassid" break; } } if ( $line -match '\\w+\\s+(\\w+(\\.|[^\\s\\.])*)$' ) { #$_opt = $Matches[1] + '*' $_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-2] $_opt = $Matches[1].Split(" ,")[-1] + '*' $_base = $Matches[1].Substring(0,$Matches[1].Length-$Matches[1].Split(" ,")[-1].length) # now get the info object for it... $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0] } if ( "Set-ExecutionPolicy" -eq $_cmdlet.Name ) { "Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" -like $_opt | sort break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ) { Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "New-Object" -eq $_cmdlet.Name ) { $_TypeNames_System -like $_opt $_TypeNames -like $_opt break; } if ( $_cmdlet.Name -like "*WMI*" ) { $_WMIClasses -like $_opt break; } if ( "Get-Process" -eq $_cmdlet.Name ) { Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name ) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-PSProvider" -eq $_cmdlet.Name ) { Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Eventlog" -eq $_cmdlet.Name ) { Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name ) { Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique break; } if ( "Get-Service", "Restart-Service", "Resume-Service", "Start-Service", "Stop-Service", "Suspend-Service" ` -contains $_cmdlet.Name ) { Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name ) { Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object", "ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" ` -contains $_cmdlet.Name ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } } if ( $line -match '(-(\\w+))\\s+([^-]*$)' ) { $_param = $matches[2] + '*' $_opt = $Matches[3].Split(" ,")[-1] + '*' $_base = $Matches[3].Substring(0,$Matches[3].Length-$Matches[3].Split(" ,")[-1].length) #$_opt = ($Matches[3] -replace '(^.*\\s*,?\\s*)\\w*$','$1') + '*' # extract the command name from the string # first split the string into statements and pipeline elements # This doesn't handle strings however. $_cmdlet = [regex]::Split($line, '[|;=]')[-1] # Extract the trailing unclosed block e.g. ls | foreach { cp if ($_cmdlet -match '\\{([^\\{\\}]*)$') { $_cmdlet = $matches[1] } # Extract the longest unclosed parenthetical expression... if ($_cmdlet -match '\\(([^()]*)$') { $_cmdlet = $matches[1] } # take the first space separated token of the remaining string # as the command to look up. Trim any leading or trailing spaces # so you don't get leading empty elements. $_cmdlet = $_cmdlet.Trim().Split()[0] # now get the info object for it... $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0] } if ( $_param.TrimEnd("*") -eq "ea" -or $_param.TrimEnd("*") -eq "wa" ) { "SilentlyContinue", "Stop", "Continue", "Inquire" | ? { $_ -like $_opt } | sort -Unique break; } if ( "Out-File","Export-CSV","Select-String","Export-Clixml" -contains $_cmdlet.Name ` -and "Encoding" -like $_param) { "Unicode", "UTF7", "UTF8", "ASCII", "UTF32", "BigEndianUnicode", "Default", "OEM" | ? { $_ -like $_opt } | sort -Unique break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ` -and "Name" -like $_param) { Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "New-Object" -like $_cmdlet.Name ) { if ( "ComObject" -like $_param ) { $_ProgID -like $_opt | % { $_ -replace '\\s','` ' } break; } if ( "TypeName" -like $_param ) { $_TypeNames_System -like $_opt $_TypeNames -like $_opt break; } } if ( "New-Item" -eq $_cmdlet.Name ) { if ( "ItemType" -like $_param ) { "directory", "file" -like $_opt break; } } if ( "Get-Location", "Get-PSDrive", "Get-PSProvider", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name ` -and "PSProvider" -like $_param ) { Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Location" -eq $_cmdlet.Name -and "PSDrive" -like $_param ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" -like $_param ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name -and "PSSnapin" -like $_param) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + $_ } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" ` -contains $_cmdlet.Name -and "Name" -like $_param ) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + $_ } break; } } if ( "Clear-Variable", "Export-Alias", "Get-Alias", "Get-PSDrive", "Get-Variable", "Import-Alias", " New-Alias", "New-PSDrive", "New-Variable", "Remove-Variable", "Set-Alias", "Set-Variable" ` -contains $_cmdlet.Name -and "Scope" -like $_param ) { "Global", "Local", "Script" -like $_opt break; } if ( "Get-Process", "Stop-Process", "Wait-Process" -contains $_cmdlet.Name -and "Name" -like $_param ) { Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Eventlog" -eq $_cmdlet.Name -and "LogName" -like $_param ) { Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name ) { if ( "Name" -like $_param ) { Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique break; } if ( "Category" -like $_param ) { "Alias", "Cmdlet", "Provider", "General", "FAQ", "Glossary", "HelpFile", "All" -like $_opt | sort | % { $_base + $_ } break; } } if ( "Get-Service", "Restart-Service", "Resume-Service", "Start-Service", "Stop-Service", "Suspend-Service" ` -contains $_cmdlet.Name ) { if ( "Name" -like $_param ) { Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "DisplayName" -like $_param ) { Get-Service -Name $_opt | sort DisplayName | % { $_base + ($_.DisplayName -replace '\\s','` ') } break; } } if ( "New-Service" -eq $_cmdlet.Name -and "dependsOn" -like $_param ) { Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Get-EventLog" -eq $_cmdlet.Name -and "EntryType" -like $_param ) { "Error", "Information", "FailureAudit", "SuccessAudit", "Warning" -like $_opt | sort | % { $_base + $_ } break; } if ( "Get-Command" -eq $_cmdlet.Name -and "Name" -like $_param ) { Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( $_cmdlet.Noun -like "*WMI*" ) { if ( "Class" -like $_param ) { $_WMIClasses -like $_opt break; } } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object", "ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" ` -contains $_cmdlet.Name -and "Property" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Select-Object" -eq $_cmdlet.Name ) { if ( "ExcludeProperty" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "ExpandProperty" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_.Name } break; } } select -InputObject $_cmdlet -ExpandProperty ParameterSets | select -ExpandProperty Parameters | ? { $_.Name -like $_param } | ? { $_.ParameterType.IsEnum } | % { [Enum]::GetNames($_.ParameterType) } | ? { $_ -like $_opt } | sort -Unique | % { $_base + $_ } } if ( $line[-1] -match "\\s" ) { break; } if ( $lastWord -ne $null -and $lastWord.IndexOfAny('/\\') -eq -1 ) { $command = $lastWord.Substring( ($lastWord -replace '([^\\|\\(;={]*)$').Length ) $_base = $lastWord.Substring( 0, ($lastWord -replace '([^\\|\\(;={]*)$').Length ) $pattern = $command + "*" gcm -Name $pattern -CommandType All | % { $_base + $_.Name } | sort -Unique } } } } }
PowerShellCorpus/PoshCode/rajabatak@my.opera.com.ps1
rajabatak@my.opera.com.ps1
$ewsPath = "C:\\Program Files\\Microsoft\\Exchange\\Web Services\\1.1\\Microsoft.Exchange.WebServices.dll" Add-Type -Path $ewsPath $ews = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList "Exchange2007_SP1" $cred = (Get-Credential).GetNetworkCredential() $ews.Credentials = New-Object System.Net.NetworkCredential -ArgumentList $cred.UserName, $cred.Password, $cred.Domain $ews.AutodiscoverUrl( ( Read-Host "Enter mailbox (email address)" ) ) $results = $ews.FindItems( "Inbox", ( New-Object Microsoft.Exchange.WebServices.Data.ItemView -ArgumentList 10 ) ) $results.Items | ForEach-Object { $_.Subject }
PowerShellCorpus/PoshCode/dvSwitchNetworkAdapter.ps1
dvSwitchNetworkAdapter.ps1
<# .SYNOPSIS Retrieves the virtual network adapters available on a vSphere server. .DESCRIPTION A replacement for the default cmdlet will work with either a standard vSwitch or a dvSwitch. Retrieves the virtual network adapters available on a vSphere server. .PARAMETER VM Specify the virtual machines from which you want to retrieve virtual network adapters. .EXAMPLE Get-VM | Get-dvSwitchNetworkAdapter .OUTPUTS PSObject .LINK Set-dvSwitchNetworkAdapter #> Function Get-dvSwitchNetworkAdapter { [cmdletbinding()] param( [parameter(Mandatory = $true, ValueFromPipeline = $true)] [VMware.VimAutomation.Client20.VirtualMachineImpl[]] $VM ) process { Foreach ($VirtualMachine in (get-view -VIObject $VM -Property "Config.Hardware.Device","Network")) { $VirtualVmxnets = $VirtualMachine.Config.Hardware.Device | Where-Object {"VirtualEthernetCard","VirtualVmxnet" -contains $_.GetType().BaseType.Name} Foreach ($VirtualVmxnet in $VirtualVmxnets) { New-Object PSObject -Property @{ MacAddress = $VirtualVmxnet.MacAddress WakeOnLanEnabled = $VirtualVmxnet.WakeOnLanEnabled NetworkName = switch ($VirtualVmxnet.Backing.GetType().Name) { "VirtualEthernetCardNetworkBackingInfo" { Get-View $VirtualVmxnet.Backing.network -Property 'Name'| Select-Object -ExpandProperty 'Name' } Default { Get-view -ID $VirtualMachine.Network -Property 'Name','Key' | Where-Object {$_.Key -eq $VirtualVmxnet.Backing.Port.PortgroupKey} | Select-Object -ExpandProperty 'Name' } } Type = $VirtualVmxnet.GetType().Name ParentId = $VirtualMachine.MoRef.Type + "-" + $VirtualMachine.MoRef.Value ConnectionState = New-Object PSObject -Property @{ Connected = $VirtualVmxnet.Connectable.Connected StartConnected = $VirtualVmxnet.Connectable.StartConnected } Id = "{0}-{1}/{2}" -f $VirtualMachine.MoRef.Type,$VirtualMachine.MoRef.Value, $VirtualVmxnet.Key Name = $VirtualVmxnet.DeviceInfo.Label } } } } } <# .SYNOPSIS Changes the configuration of the virtual network adapter. .DESCRIPTION A replacement for the default cmdlet will work with either a standard vSwitch or a dvSwitch. Changes the configuration of the virtual network adapter. .PARAMETER NetworkAdapter Specify the name of the network to which you want to connect the virtual network adapter. NetworkName must be globally unique within vSphere. .PARAMETER NetworkName Specify the virtual network adapter you want to configure. .PARAMETER StartConnected If the value is $true, the virtual network adapter starts connected when its associated virtual machine powers on. If the value is $false, it starts disconnected. If Nothing is Supplied than nothing will be changed. .PARAMETER Connected If the value is $true, the virtual network adapter is connected after its creation. If the value is $false, it is disconnected. If Nothing is Supplied than nothing will be changed. .RunAsync If supplied then the cmdlet will not wait for the completion of the network reconfiguration. Instead a Task object will be returned and the cmdlet will process the next object in the pipeline. .EXAMPLE Get-VM | Get-dvSwitchNetworkAdapter | Where-object{$_.NetworkName -eq "192.168.1.0"}| Set-dvSwitchNetworkAdapter -NetworkName "dvSwitch0_192.168.1.0" .EXAMPLE Get-VM | Get-dvSwitchNetworkAdapter | Set-dvSwitchNetworkAdapter -StartConnected $True .OUTPUTS PSObject .LINK Get-dvSwitchNetworkAdapter #> Function Set-dvSwitchNetworkAdapter { [cmdletbinding(SupportsShouldProcess=$true)] param( [parameter(Mandatory = $true, ValueFromPipeline = $true)] [PSCustomObject[]] $NetworkAdapter , [parameter(Mandatory = $false)] [string] $NetworkName , [parameter()] [bool] $StartConnected , [parameter()] [bool] $Connected , [parameter()] [switch] $RunAsync ) process { Foreach ($netAdapter in $NetworkAdapter) { $VirtualMachine = Get-View $netAdapter.ParentId -Property 'Runtime.Host','Config.Hardware.Device','Name' $HostSystem = Get-View -ID $VirtualMachine.Runtime.Host -Property 'Network','Name' $VirtualDeviceConfigSpec = New-Object VMware.Vim.VirtualDeviceConfigSpec $VirtualDeviceConfigSpec.operation = "edit" Try { $VirtualDeviceConfigSpec.device = $VirtualMachine.Config.Hardware.Device | Where-Object {$_.GetType().Name -eq $netAdapter.Type -and $_.MacAddress -eq $netAdapter.MacAddress} } Catch { write-warning "$($netAdapter.Name) not found on $($VirtualMachine.name)" break; } $Msg = "" if ($NetworkName) { $Network = Get-View -Id $HostSystem.Network -Property 'Name','Config' | Where-Object { $_.Name -eq $NetworkName } if ($Network) { $Msg += "Connecting $($netAdapter.Name) to $($NetworkName) " # Determine backing type switch($Network.GetType().Name) { "Network" { $VirtualDeviceConfigSpec.device.backing = New-Object VMware.Vim.VirtualEthernetCardNetworkBackingInfo $VirtualDeviceConfigSpec.device.backing.deviceName = $NetworkName } "DistributedVirtualPortgroup" { $VirtualDeviceConfigSpec.device.Backing = New-Object VMware.Vim.VirtualEthernetCardDistributedVirtualPortBackingInfo $VirtualDeviceConfigSpec.device.backing.port = New-Object VMware.Vim.DistributedVirtualSwitchPortConnection $VirtualDeviceConfigSpec.device.backing.port.switchUuid = (Get-View $Network.Config.DistributedVirtualSwitch).Uuid $VirtualDeviceConfigSpec.device.backing.port.portgroupKey = $Network.Config.Key } } } Else { Write-Warning "$($NetworkName) was not found on $($HostSystem.Name)" } } if ($PSCmdlet.MyInvocation.BoundParameters.Connected -ne $null) { $Msg += "Connected:$($Connected) " $VirtualDeviceConfigSpec.Device.Connectable.Connected = $Connected } Else { $VirtualDeviceConfigSpec.Device.Connectable.Connected = $netAdapter.ConnectionState.Connected } if ($PSCmdlet.MyInvocation.BoundParameters.StartConnected -ne $null) { $Msg += "StartConnected:$($StartConnected) " $VirtualDeviceConfigSpec.Device.Connectable.StartConnected = $StartConnected } Else { $VirtualDeviceConfigSpec.Device.Connectable.StartConnected = $netAdapter.ConnectionState.StartConnected } $VirtualMachineConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec $VirtualMachineConfigSpec.deviceChange += $VirtualDeviceConfigSpec IF ($PSCmdlet.ShouldProcess($VirtualMachine.Name,$Msg)) { $Task = Get-VIObjectByVIView -MORef $VirtualMachine.ReconfigVM_Task($VirtualMachineConfigSpec) if (-Not $RunAsync) { Wait-Task -Task $Task | Out-Null $returnNetworkAdapter = $netAdapter $returnNetworkAdapter.NetworkName = $NetworkName $returnNetworkAdapter.ConnectionState.StartConnected = $VirtualDeviceConfigSpec.Device.Connectable.StartConnected $returnNetworkAdapter.ConnectionState.Connected = $VirtualDeviceConfigSpec.Device.Connectable.Connected $returnNetworkAdapter } else { $task } } } } } New-Alias -Name Get-NetworkAdapter -Value Get-dvSwitchNetworkAdapter New-Alias -Name Set-NetworkAdapter -Value Set-dvSwitchNetworkAdapter Export-ModuleMember -Function Get-dvSwitchNetworkAdapter, Set-dvSwitchNetworkAdapter -Alias Get-NetworkAdapter,Set-NetworkAdapter
PowerShellCorpus/PoshCode/Disable-CopyPasta-1.ps1
Disable-CopyPasta-1.ps1
Begin { $disableCopy = "isolation.tools.copy.enable" $disableCopy_value = "false" $disablePaste = "isolation.tools.paste.enable" $disablePaste_value = "false" $disableGUI = "isolation.tools.setGUIOptions.enable" $disableGUI_value = "false" } Process { #Make Sure it's a VM if ( $_ -isnot [VMware.VimAutomation.Client20.VirtualMachineImpl] ) { co ntinue } #Setup our Object $vm = Get-View $_.Id $vmConfigSpec = New-Object VMware.Vim.VirtualMachineConfigSpec $vmConfigSpec.extraconfig += New-Object VMware.Vim.optionvalue $vmConfigSpec.extraconfig += New-Object VMware.Vim.optionvalue $vmConfigSpec.extraconfig += New-Object VMware.Vim.optionvalue $vmConfigSpec.extraconfig[0].Key=$disableCopy $vmConfigSpec.extraconfig[0].Value=$disableCopy_value $vmConfigSpec.extraconfig[1].Key=$disablePaste $vmConfigSpec.extraconfig[1].Value=$disablePaste_value $vmConfigSpec.extraconfig[2].Key=$disableGUI $vmConfigSpec.extraconfig[2].Value=$disableGUI_value #Run the change $vm.ReconfigVM($vmConfigSpec) }
PowerShellCorpus/PoshCode/Get Old Outlook Events.ps1
Get Old Outlook Events.ps1
# Copyright (c) 2011, Chris Cmolik <chris@chriscmolik.com> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the <organization> nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # software, even if advised of the possibility of such damage # get-old-outlook-events.ps1 # powershell script to retrieve all appointments that haven't been modified in the past three months using the outlook object model param ( [datetime] $rangestart = [datetime]::now.addmonths(-3) , [datetime] $rangeend = [datetime]::now) $outlook = new-object -comobject outlook.application #dictionary to hold users and their events $dict =@{} # labeling report "running report for {0}..." -f [environment]::username # needed because `n makes too much sense... # ensure we are logged into a session $session = $outlook.session $session.logon() # folder for events in outlook = 9 $apptitems = $session.getdefaultfolder(9).items $apptItems.Sort("[Start]") #$apptItems.IncludeRecurrences = $true $restriction = "[End] >= '{0}' AND [Start] <= '{1}' AND [IsRecurring] = TRUE" -f $rangeStart.ToString("g"), $rangeEnd.ToString("g") foreach($appt in $apptItems.Restrict($restriction)) { if ($appt.GetRecurrencePattern().PatternEndDate -gt $rangeEnd -and $appt.GetRecurrencePattern().PatternStartDate -lt $rangeStart ) { $payload = "" $payload += "Event title: {0}`n" -f $appt.Subject $payload += "Event's recurring began on: {0:MM/dd/yy}`n" -f [DateTime]$appt.GetRecurrencePattern().PatternStartDate # Get recurrence pattern $recPattern = $appt.GetRecurrencePattern() switch($recPattern.RecurrenceType) { 0 { "Recurs Daily." } 1 { if($recPattern.interval -eq 1) { switch($recPattern.DayOfWeekMask) { 1 { $payload += "Occurs every Sunday.`n" } 2 { $payload += "Occurs every Monday.`n" } 4 { $payload += "Occurs every Tuesday.`n" } 8 { $payload += "Occurs every Wednesday.`n" } 16 { $payload += "Occurs every Thursday.`n" } 32 { $payload += "Occurs every Friday.`n" } 64 { $payload += "Occurs every Saturday.`n" } } } else { switch($recPattern.DayOfWeekMask){ 1 { $payload += "Occurs every {0} weeks on Sunday.`n" -f $recPattern.interval } 2 { $payload += "Occurs every {0} weeks on Monday.`n" -f $recPattern.interval } 4 { $payload += "Occurs every {0} weeks on Tuesday.`n" -f $recPattern.interval } 8 { $payload +="Occurs every {0} weeks on Wednesday.`n" -f $recPattern.interval } 16 { $payload +="Occurs every {0} weeks on Thursday.`n" -f $recPattern.interval } 32 { $payload +="Occurs every {0} weeks on Friday.`n" -f $recPattern.interval } 64 { $payload +="Occurs every {0} weeks on Saturday.`n" -f $recPattern.interval } } } } 2 { switch($recPattern.Instance){ 1 { $instance = "first" } 2 { $instance = "second" } 3 { $instance = "third" } 4 { $instance = "fourth" } 5 { $instance = "fifth" } 6 { $instance = "sixth" } } switch($recPattern.DayOfWeekMask) { 1 { $strDay = "Sunday" } 2 { $strDay = "Monday" } 4 { $strDay = "Tuesday" } 8 { $strDay = "Wednesday" } 16 { $strDay = "Thursday" } 32 { $strDay = "Friday" } 64 { $strDay = "Saturday" } } $int = $recPattern.Interval if ($int -eq 1) { $payload += "Occurs on the {0} {1} of each month.`n" -f $instance, $strDay } else { $payload +="Occurs on the {0} {1} every {2} months`n" -f $instance, $strDay, $int } } 3 { if($recPattern.interval -eq 1) { $payload +="Recurs each month`n" } else { $payload +="Recurs every {0} month`n" -f $recPattern.interval } switch($recPattern.Instance){ 1 { $instance = "first" } 2 { $instance = "second" } 3 { $instance = "third" } 4 { $instance = "fourth" } 5 { $instance = "fifth" } 6 { $instance = "sixth" } } switch($recPattern.DayOfWeekMask) { 1 { $strDay = "Sunday" } 2 { $strDay = "Monday" } 4 { $strDay = "Tuesday" } 8 { $strDay = "Wednesday" } 16 { $strDay = "Thursday" } 32 { $strDay = "Friday" } 64 { $strDay = "Saturday" } } $payload +="Occurs on the {0} {1} of the month `n" -f $instance, $strDay } 5 { $a = new-object system.globalization.datetimeformatinfo $month = $a.MonthNames[$recPattern.MonthOfYear+1] $payload += "Occurs each year on {0} {1}`n" -f $month, $recPattern.DayofMonth } 6 { switch($recPattern.Instance){ 1 { $instance = "first" } 2 { $instance = "second" } 3 { $instance = "third" } 4 { $instance = "fourth" } 5 { $instance = "fifth" } 6 { $instance = "sixth" } } switch($recPattern.DayOfWeekMask) { 1 { $strDay = "Sunday" } 2 { $strDay = "Monday" } 4 { $strDay = "Tuesday" } 8 { $strDay = "Wednesday" } 16 { $strDay = "Thursday" } 32 { $strDay = "Friday" } 64 { $strDay = "Saturday" } } $a = new-object system.globalization.datetimeformatinfo $month = $a.MonthNames[$recPattern.MonthOfYear+1] $payload +="Occurs on the {0} {1} of {2} each year`n" -f $recPattern.Instance, $strDay, $month } } $payload += "From: {0:hh:mm tt} - {1:hh:mm tt}`n" -f [DateTime]$recPattern.StartTime, [DateTime]$recPattern.EndTime if ($dict.ContainsValue($appt.Organizer)) { $dict.Set_Item($appt.Organizer, ($dict[$appt.Organizer] += $payload)) } else { $dict.Set_Item($appt.Organizer, $payload) } } } $outlook = $session = $null; foreach ($e in $dict.GetEnumerator()) { "Person: {0}`n" -f $e.Name "Events:`n{0}" -f $e.Value "--------------------------`n`n" } "End report for {0}`n----------------------" -f[Environment]::UserName
PowerShellCorpus/PoshCode/Get-Netstat 1,1.ps1
Get-Netstat 1,1.ps1
$null, $null, $null, $null, $netstat = netstat -a -n -o [regex]$regexTCP = '(?<Protocol>\\S+)\\s+((?<LAddress>(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?))|(?<LAddress>\\[?[0-9a-fA-f]{0,4}(\\:([0-9a-fA-f]{0,4})){1,7}\\%?\\d?\\]))\\:(?<Lport>\\d+)\\s+((?<Raddress>(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?))|(?<RAddress>\\[?[0-9a-fA-f]{0,4}(\\:([0-9a-fA-f]{0,4})){1,7}\\%?\\d?\\]))\\:(?<RPort>\\d+)\\s+(?<State>\\w+)\\s+(?<PID>\\d+$)' [regex]$regexUDP = '(?<Protocol>\\S+)\\s+((?<LAddress>(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.(2[0-4]\\d|25[0-5]|[01]?\\d\\d?))|(?<LAddress>\\[?[0-9a-fA-f]{0,4}(\\:([0-9a-fA-f]{0,4})){1,7}\\%?\\d?\\]))\\:(?<Lport>\\d+)\\s+(?<RAddress>\\*)\\:(?<RPort>\\*)\\s+(?<PID>\\d+)' [psobject]$process = "" | Select-Object Protocol, LocalAddress, Localport, RemoteAddress, Remoteport, State, PID, ProcessName foreach ($net in $netstat) { switch -regex ($net.Trim()) { $regexTCP { $process.Protocol = $matches.Protocol $process.LocalAddress = $matches.LAddress $process.Localport = $matches.LPort $process.RemoteAddress = $matches.RAddress $process.Remoteport = $matches.RPort $process.State = $matches.State $process.PID = $matches.PID $process.ProcessName = ( Get-Process -Id $matches.PID ).ProcessName } $regexUDP { $process.Protocol = $matches.Protocol $process.LocalAddress = $matches.LAddress $process.Localport = $matches.LPort $process.RemoteAddress = $matches.RAddress $process.Remoteport = $matches.RPort $process.State = $matches.State $process.PID = $matches.PID $process.ProcessName = ( Get-Process -Id $matches.PID ).ProcessName } } $process }
PowerShellCorpus/PoshCode/Start-Encryption_3.ps1
Start-Encryption_3.ps1
## Start-Encryption ################################################################################################## ## Rijndael symmetric key encryption ... with no passes on the key. Very lazy. ## USAGE: ## $encrypted = Encrypt-String "Oisin Grehan is a genius" "P@ssw0rd" ## Decrypt-String $encrypted "P@ssw0rd" ## ## You can choose to return an array by passing -arrayOutput to Encrypt-String ## I chose to use Base64 encoded strings because they're easier to save ... [Reflection.Assembly]::LoadWithPartialName("System.Security") function Encrypt-String($String, $Passphrase, $salt="My Voice is my P455W0RD!", $init="Yet another key", [switch]$arrayOutput) { $r = new-Object System.Security.Cryptography.RijndaelManaged $pass = [Text.Encoding]::UTF8.GetBytes($Passphrase) $salt = [Text.Encoding]::UTF8.GetBytes($salt) $r.Key = (new-Object Security.Cryptography.PasswordDeriveBytes $pass, $salt, "SHA1", 5).GetBytes(32) #256/8 $r.IV = (new-Object Security.Cryptography.SHA1Managed).ComputeHash( [Text.Encoding]::UTF8.GetBytes($init) )[0..15] $c = $r.CreateEncryptor() $ms = new-Object IO.MemoryStream $cs = new-Object Security.Cryptography.CryptoStream $ms,$c,"Write" $sw = new-Object IO.StreamWriter $cs $sw.Write($String) $sw.Close() $cs.Close() $ms.Close() $r.Clear() [byte[]]$result = $ms.ToArray() if($arrayOutput) { return $result } else { return [Convert]::ToBase64String($result) } } function Decrypt-String($Encrypted, $Passphrase, $salt="My Voice is my P455W0RD!", $init="Yet another key") { if($Encrypted -is [string]){ $Encrypted = [Convert]::FromBase64String($Encrypted) } $r = new-Object System.Security.Cryptography.RijndaelManaged $pass = [System.Text.Encoding]::UTF8.GetBytes($Passphrase) $salt = [System.Text.Encoding]::UTF8.GetBytes($salt) $r.Key = (new-Object Security.Cryptography.PasswordDeriveBytes $pass, $salt, "SHA1", 5).GetBytes(32) #256/8 $r.IV = (new-Object Security.Cryptography.SHA1Managed).ComputeHash( [Text.Encoding]::UTF8.GetBytes($init) )[0..15] $d = $r.CreateDecryptor() $ms = new-Object IO.MemoryStream @(,$Encrypted) $cs = new-Object Security.Cryptography.CryptoStream $ms,$d,"Read" $sr = new-Object IO.StreamReader $cs Write-Output $sr.ReadToEnd() $sr.Close() $cs.Close() $ms.Close() $r.Clear() }
PowerShellCorpus/PoshCode/Update-SysinternalsSuite.ps1
Update-SysinternalsSuite.ps1
<# .Synopsis Update Sysinternals Suite. .DESCRIPTION Use PowerShell v3's Invoke-WebRequest do download the latest Sysinternals Tools from: http://live.sysinternals.com. Supports -AsJob .EXAMPLE Update-SysinternalsSuite -Path C:\\tools\\sysinterals This Example downloads all sysinternals tools to C:\\tools\\sysinternals. .EXAMPLE Update-SysinternalsSuite -Path C:\\tools\\sysinterals -AsJob This Example downloads all sysinternals tools to C:\\tools\\sysinternals, it creates a background job to keep your command line usable! #> function Update-SysinternalsSuite { [CmdletBinding(DefaultParameterSetName='Parameter Set 1', SupportsShouldProcess=$true, ConfirmImpact='Medium')] Param ( # Path specifies where to save the tools [Parameter(Mandatory=$true, Position=0, ParameterSetName='Parameter Set 1')] [ValidateNotNull()] [ValidateNotNullOrEmpty()] $Path, # AsJob, start a job [Parameter(Mandatory=$false)] [switch] $AsJob ) Begin { # check if folder exists, if not create folder if (Test-Path $Path) { Write-Verbose "Path exists, updating $Path" } else { Write-Verbose "Path does not exist, creating folder $path" try { New-Item -Path $Path -ItemType Directory -ErrorAction Stop } catch { Write-Error "Could not create Folder" } } # Define Scriptblock $myscriptblock = { param ($path) Invoke-WebRequest -Uri live.sysinternals.com | Select-Object -ExpandProperty Links | ForEach-Object { if ($_.href -like '*.exe' -or $_.href -like '*.chm' -or $_.href -like '*.hlp' -or $_.href -like '*.sys' -or $_.href -like '*.txt' -or $_.href -like '*.cnt'){ $str = "http://live.sysinternals.com"+$($_.href) Invoke-WebRequest -Uri $str -OutFile $path$($_.href) } else { Write-Output "Skipped: $($_.href)" } } } # end Scriptblock } Process { if ($AsJob) { Write-Verbose "AsJob is $AsJob - Creating a background job" # using -ArgumentList (,$Array) to pass an array to the ScriptBlock Start-Job -ScriptBlock $myscriptblock -ArgumentList ($path) } else { Write-Verbose "AsJob is $AsJob - Running script normally" # using -ArgumentList (,$Array) to pass an array to the ScriptBlock Invoke-Command -ScriptBlock $myscriptblock -ArgumentList ($path) } } End { } }
PowerShellCorpus/PoshCode/Get-HostEntry.ps1
Get-HostEntry.ps1
param ( [parameter(Mandatory=$true, ValueFromPipeline=$true)] [String[]]$HostnameOrIPs ) process { ForEach ($HostnameOrIP in $HostnameOrIPs) { try { $result = [System.Net.Dns]::GetHostEntry($HostnameOrIP) "" | select @{Name='HostName'; Expression={$result.HostName}}, @{Name='AddressList'; Expression={$result.AddressList}} } catch { Write-Warning ("[{0}] Lookup failed: {1}" -f $HostnameOrIP, $_.exception.InnerException.message) } } }
PowerShellCorpus/PoshCode/Get-WebFile 1.0.ps1
Get-WebFile 1.0.ps1
# --------------------------------------------------------------------------- ### <Script> ### <Author> ### Joel "Jaykul" Bennett ### </Author> ### <Description> ### Downloads a file from the web to the specified file path. ### </Description> ### <Usage> ### Get-URL http://huddledmasses.org/downloads/RunOnlyOne.exe RunOnlyOne.exe ### Get-URL http://huddledmasses.org/downloads/RunOnlyOne.exe C:\\Users\\Joel\\Documents\\WindowsPowershell\\RunOnlyOne.exe ### </Usage> ### </Script> # --------------------------------------------------------------------------- param([string]$url, [string]$path) if(!(Split-Path -parent $path) -or !(Test-Path -pathType Container (Split-Path -parent $path))) { $path = Join-Path $pwd (Split-Path -leaf $path) } "Downloading [$url]`nSaving at [$path]" $client = new-object System.Net.WebClient $client.DownloadFile( $url, $path ) $path
PowerShellCorpus/PoshCode/VBScript from cmd__bat.ps1
VBScript from cmd__bat.ps1
@set @script=0 /* @echo off set @script= cscript //nologo //e:jscript "%~dpnx0" exit /b */ //extracting VBScript source code from Source() function ExtractCode(text, index) { try { return text.toString().split(/\\/\\*|\\*\\//)[index * 2 + 1]; } catch (e) {} } //this execute VBScript code by using MSScriptControl function ExecuteCode(index) { with (new ActiveXObject('MSScriptControl.ScriptControl')) { language = 'VBScript'; try { addobject('WScript', WScript, true); addcode(ExtractCode(Source, index)); } catch (e) {} } } //place your VBScript code inside this function function Source() { /* This section has index = 0 To execute this section you should put 'ExecuteCode(0);' in the end of current script. */ /* 'This section has index = 1 'and it has a real code intBig = 100 intLow = 1 For i = 0 To 5 Randomize intNum = Int((intBig - intLow + 1) * Rnd + intLow) WScript.Echo intNum Next */ } ExecuteCode(1);
PowerShellCorpus/PoshCode/Resizer of pictures_1.ps1
Resizer of pictures_1.ps1
[reflection.assembly]::LoadWithPartialName("System.Drawing") $SizeLimit=1280 # required size of picture's long side $logfile="resizelog.txt" # log file for errors $toresize=$args[0] # list of directories to find and resize images. can be empty if ([string]$toresize -eq &#8220;&#8221;) { # if script startup parameter empty, use some default values $toresize=@("n:\\path1", "n:\\path2\\", "s:\\path3") } echo $toresize # visual control #Write-Host -NoNewLine ("Press any key.") # Optional "Press any key" #$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") #Write-Host &"" $error.clear() # first part. find and resize jpgs Get-ChildItem -recurse $toresize -include *.jpg | foreach { $OldBitmap = new-object System.Drawing.Bitmap $_.FullName # open found jpg if ($error.count -ne 0) { # error handling $error | out-file $logfile -append -encoding default $error[($error.count-1)].TargetObject | out-file $logfile -append -encoding default echo $_>>$logfile $error.clear() } $LongSide=$OldBitmap.Width # locating long side of picture if ($OldBitmap.Width -lt $OldBitmap.Height) { $LongSide=$OldBitmap.Height } if ($LongSide -gt $SizeLimit) { # if long side is greater than our limit, process jpg if ($OldBitmap.Width -lt $OldBitmap.Height) { # calculate dimensions of picture resize to $newH=$SizeLimit $newW=[int]($OldBitmap.Width*$SizeLimit/$OldBitmap.Height) } else { $newW=$SizeLimit $newH=[int]($OldBitmap.Height*$newW/$OldBitmap.Width) } $NewBitmap = new-object System.Drawing.Bitmap $newW,$newH # create new bitmap $g=[System.Drawing.Graphics]::FromImage($NewBitmap) $g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic # use high quality resize algorythm $g.DrawImage($OldBitmap, 0, 0, $newW, $newH) # resize our picture $name=$_.DirectoryName+"\\"+$_.name+".new" # generating name for new picture $NewBitmap.Save($name, ([system.drawing.imaging.imageformat]::jpeg)) # save newly created resized jpg $NewBitmap.Dispose() # cleaning up our mess $OldBitmap.Dispose() $n=get-childitem $name if ($n.length -ge $_.length) { # if resized jpg has greater size than original Write-host -NoNewLine "+" # draw "+" $n.delete() # and delete it } else { # if resized jpg is smaller than original if ($n.Exists -and $_.Exists) { $name=$_.FullName $_.Delete() # delete original $n.MoveTo($name) # rename new file to original name (replace old file with new) echo ($Name + " " + $LongSide) # write its name for visual control } } } else { # if long side is smaller than limit, draw dot for visual Write-host -NoNewLine "." $OldBitmap.Dispose() } } #second part. process other than jpgs bitmaps Get-ChildItem -recurse $toresize -include *.bmp, *.tif, *.gif | foreach { $OldBitmap = new-object System.Drawing.Bitmap $_.FullName # open picture if ($error.count -ne 0) { # handle errors if any $error | out-file $logfile -append -encoding default $error[($error.count-1)].TargetObject | out-file $logfile -append -encoding default $error.clear() } $LongSide=$OldBitmap.Width # find picture's long side if ($OldBitmap.Width -lt $OldBitmap.Height) { $LongSide=$OldBitmap.Height } if ($LongSide -gt $SizeLimit) { # if long side is greater than our limit, process picture if ($OldBitmap.Width -lt $OldBitmap.Height) { # calculating new dimensions $newH=$SizeLimit $newW=[int]($OldBitmap.Width*$SizeLimit/$OldBitmap.Height) } else { $newW=$SizeLimit $newH=[int]($OldBitmap.Height*$newW/$OldBitmap.Width) } $NewBitmap = new-object System.Drawing.Bitmap $newW,$newH # create new bitmap $g=[System.Drawing.Graphics]::FromImage($NewBitmap) $g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic $g.DrawImage($OldBitmap, 0, 0, $newW, $newH) # copy resized image to it $name=$_.DirectoryName+"\\"+$_.name.substring(0, $_.name.indexof($_.extension))+".jpg" # generating new name, jpg extension $NewBitmap.Save($name, ([system.drawing.imaging.imageformat]::jpeg)) # save new file $NewBitmap.Dispose() $OldBitmap.Dispose() $n=get-childitem $name if ($n.length -ge $_.length) { # if new file is longer than original, $n.delete() # delete new file Write-host -NoNewLine "+" # and draw "+" for beauty } else { # if new file is shorter than original (as we expect) echo ($Name + " " + $LongSide) # draw its name $_.Delete() # delete oroginal } } else { # if long side is less than our limit, try to recompress it to jpg $name=$_.DirectoryName+"\\"+$_.name.substring(0, $_.name.indexof($_.extension))+".jpg" $OldBitmap.Save($name, ([system.drawing.imaging.imageformat]::jpeg)) $OldBitmap.Dispose() $n=get-childitem $name if ($n.length -ge $_.length) { # if new jpg is greater than original $n.delete() # delete new jpg Write-host -NoNewLine "-" # draw "-" for visual control } else { echo ($Name + " " + $LongSide) # draw new file name $_.Delete() # delete original } } }
PowerShellCorpus/PoshCode/Get-User_9.ps1
Get-User_9.ps1
function Get-User($user) { # this function should be passed the CN of the user to be returned $dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() $root = [ADSI] "LDAP://$($dom.Name)" $searcher = New-Object System.DirectoryServices.DirectorySearcher $root $searcher.filter = "(&(objectCategory=person)(objectClass=user)(cn=$user))" $user = $searcher.FindOne() [System.Collections.Arraylist]$names = $user.Properties.PropertyNames [System.Collections.Arraylist]$props = $user.Properties.Values $userobj = New-Object System.Object for ($i = 0; $i -lt $names.Count) { $userobj | Add-Member -type NoteProperty -Name $($names[$i]) -Value $($props[$i]) $i++ } $userobj.pwdlastset = [System.DateTime]::FromFileTime($userobj.pwdlastset) $userobj.lastlogontimestamp = [System.DateTime]::FromFileTime($userobj.lastlogontimestamp) return $userobj }
PowerShellCorpus/PoshCode/validate an IP address_2.ps1
validate an IP address_2.ps1
# validate given IP address in $ip1 variable $ip1=read-host "Enter any IP Address" ($ip1.split(".") | where-object { ([int]$_) -ge 1 -and ([int]$_) -le 255 } | Where-Object { $_ -match "\\d{1,3}"} | Measure-Object).count -eq 4
PowerShellCorpus/PoshCode/WriteFileName_2.ps1
WriteFileName_2.ps1
# functions to print overwriting multi-line messages. Test script will accept a file/filespec/dir and iterate through all files in all subdirs printing a test message + file name to demostrate. # e.g. PS>.\\writefilename.ps1 c:\\ # call WriteFileName [string] # after done writing series of overwriting messages, call WriteFileNameEnd function WriteFileName ( [string]$writestr ) # this function prints multiline messages on top of each other, good for iterating through filenames without filling { # the console with a huge wall of text. Call this function to print each of the filename messages, then call WriteFileNameEnd when done # before printing anything else, so that you are not printing into a long file name with extra characters from it visible. if ($Host.Name -match 'ise') { write-host $writestr; return } if ($global:lastlen -eq $null) {$global:lastlen=0} $ctop=[console]::cursortop [console]::cursorleft=0 $oldwritestrlen=$writestr.length $spaces = "" if ($global:lastlen -gt $writestr.length) { $spaces = " " * ($global:lastlen-$writestr.length) } $writelines = [math]::divrem($writestr.length, [console]::bufferwidth, [ref]$null) $cwe = ($writelines-([console]::bufferheight-$ctop))+1 # calculate where text has scroll back to. if ($cwe -gt 0) {$ctop-=($cwe)} write-host "$writestr" -nonewline $global:oldctop=[console]::cursortop if ([console]::cursorleft -ne 0) {$global:oldctop+=1} write-host "$spaces" -nonewline $global:lastlen = $oldwritestrlen [console]::cursortop=$ctop [console]::cursorleft=0 } function WriteFileNameEnd ( ) # call this function when you are done overwriting messages on top of each other { # and before printing something else if ($Host.Name -match 'ise') { return } if ($global:oldctop -ne $null) { [console]::cursortop=$global:oldctop [console]::cursorleft=0 } $global:oldctop=$null $global:lastlen=$null } dir $args -recurse -ea 0 -force | %{$string="Test String. "*(get-random(100));$string+="Checking $($_.fullname) ..."; WriteFileName $string;sleep -seconds 1} #WriteFileName "Final Test String." WriteFileNameEnd write-host "Done! exiting."
PowerShellCorpus/PoshCode/Write-Log_5.ps1
Write-Log_5.ps1
function Write-Log { #region Parameters [cmdletbinding()] Param( [Parameter(ValueFromPipeline=$true,Mandatory=$true)] [ValidateNotNullOrEmpty()] [string] $Message, [Parameter()] [ValidateSet(ōErrorö, ōWarnö, ōInfoö)] [string] $Level = ōInfoö, [Parameter()] [Switch] $NoConsoleOut, [Parameter()] @@ [ValidateSet("Black", "DarkMagenta", "DarkRed", "DarkBlue", "DarkGreen", "DarkCyan", "DarkYellow", "Red", "Blue", "Green", "Cyan", "Magenta", "Yellow", "DarkGray", "Gray", "White")] [String] $ConsoleForeground = 'White', [Parameter()] [ValidateRange(1,30)] [Int16] $Indent = 0, [Parameter()] [IO.FileInfo] $Path = ö$env:temp\\PowerShellLog.txtö, [Parameter()] [Switch] $Clobber, [Parameter()] @@ [ValidateSet("Application","System","Security")] [String] $EventLogName, [Parameter()] [String] $EventSource, [Parameter()] [Int32] $EventID = 1, [Parameter()] [String] $LogEncoding = "ASCII" ) #endregion Begin {} Process { try { @@ $msg = '{0} : {1} : {2}{3}' -f (Get-Date -Format "yyyy-MM-dd HH:mm:ss"), $Level.ToUpper(), (" " * $Indent), $Message if ($NoConsoleOut -eq $false) { switch ($Level) { 'Error' { Write-Error $Message } 'Warn' { Write-Warning $Message } 'Info' { Write-Host ('{0}{1}' -f (" " * $Indent), $Message) -ForegroundColor $ConsoleForeground} } } if (-not $Path.Exists) { New-Item -Path $Path.FullName -ItemType File -Force | Out-Null } if ($Clobber) { $msg | Out-File -FilePath $Path -Encoding $LogEncoding -Force } else { $msg | Out-File -FilePath $Path -Encoding $LogEncoding -Append } if ($EventLogName) { if (-not $EventSource) { $EventSource = ([IO.FileInfo] $MyInvocation.ScriptName).Name } if(-not [Diagnostics.EventLog]::SourceExists($EventSource)) { [Diagnostics.EventLog]::CreateEventSource($EventSource, $EventLogName) } $log = New-Object System.Diagnostics.EventLog $log.set_log($EventLogName) $log.set_source($EventSource) switch ($Level) { ōErrorö { $log.WriteEntry($Message, 'Error', $EventID) } ōWarnö { $log.WriteEntry($Message, 'Warning', $EventID) } ōInfoö { $log.WriteEntry($Message, 'Information', $EventID) } } } } catch { throw ōFailed to create log entry in: æ$PathÆ. The error was: æ$_Æ.ö } } End {} <# .SYNOPSIS Writes logging information to screen and log file simultaneously. .DESCRIPTION Writes logging information to screen and log file simultaneously. Supports multiple log levels. .PARAMETER Message The message to be logged. .PARAMETER Level The type of message to be logged. .PARAMETER NoConsoleOut Specifies to not display the message to the console. .PARAMETER ConsoleForeground Specifies what color the text should be be displayed on the console. Ignored when switch 'NoConsoleOut' is specified. .PARAMETER Indent The number of spaces to indent the line in the log file. .PARAMETER Path The log file path. .PARAMETER Clobber Existing log file is deleted when this is specified. .PARAMETER EventLogName The name of the system event log, e.g. 'Application'. .PARAMETER EventSource The name to appear as the source attribute for the system event log entry. This is ignored unless 'EventLogName' is specified. .PARAMETER EventID The ID to appear as the event ID attribute for the system event log entry. This is ignored unless 'EventLogName' is specified. .PARAMETER LogEncoding The text encoding for the log file. Default is ASCII. .EXAMPLE PS C:\\> Write-Log -Message "It's all good!" -Path C:\\MyLog.log -Clobber -EventLogName 'Application' .EXAMPLE PS C:\\> Write-Log -Message "Oops, not so good!" -Level Error -EventID 3 -Indent 2 -EventLogName 'Application' -EventSource "My Script" .INPUTS System.String .OUTPUTS No output. .NOTES Revision History: 2011-03-10 : Andy Arismendi - Created. 2011-07-23 : Will Steele - Updated. 2011-07-23 : Andy Arismendi - Added missing comma in param block. - Added support for creating missing directories in log file path. 2012-03-10 : Pat Richard - Added validation sets to $ConsoleForeground and $EventLogName - Changed formatting of $msg so that only $message is indented instead of entire line (looks cleaner) - suppressed output when creating path/file #> }
PowerShellCorpus/PoshCode/Monitor ESX with WS-MAN_1.ps1
Monitor ESX with WS-MAN_1.ps1
function Get-VMHostWSManInstance { param ( [Parameter(Mandatory=$TRUE,HelpMessage="VMHosts to probe")] [VMware.VimAutomation.Client20.VMHostImpl[]] $VMHost, [Parameter(Mandatory=$TRUE,HelpMessage="Class Name")] [string] $class, [switch] $ignoreCertFailures, [System.Management.Automation.PSCredential] $credential=$null ) $omcBase = "http://schema.omc-project.org/wbem/wscim/1/cim-schema/2/" $dmtfBase = "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/" $vmwareBase = "http://schemas.vmware.com/wbem/wscim/1/cim-schema/2/" if ($ignoreCertFailures) { $option = New-WSManSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck } else { $option = New-WSManSessionOption } foreach ($H in $VMHost) { if ($credential -eq $null) { $hView = $H | Get-View -property Value $ticket = $hView.AcquireCimServicesTicket() $password = convertto-securestring $ticket.SessionId -asplaintext -force $credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $ticket.SessionId, $password } $uri = "https`://" + $h.Name + "/wsman" if ($class -cmatch "^CIM") { $baseUrl = $dmtfBase } elseif ($class -cmatch "^OMC") { $baseUrl = $omcBase } elseif ($class -cmatch "^VMware") { $baseUrl = $vmwareBase } else { throw "Unrecognized class" } Get-WSManInstance -Authentication basic -ConnectionURI $uri -Credential $credential -Enumerate -Port 443 -UseSSL -SessionOption $option -ResourceURI "$baseUrl/$class" } } # Examples (make sure you are connected to an ESX server.) # Get-VMHostWSManInstance -VMHost (Get-VMHost) -class CIM_Fan -ignoreCertFailures # Get-VMHostWSManInstance -VMHost (Get-VMHost) -class VMware_Role -ignoreCertFailures # Get-VMHostWSManInstance -VMHost (Get-VMHost) -class OMC_Card -ignoreCertFailures # See http`://www.vmware.com/support/developer/cim-sdk/smash/u2/ga/apirefdoc/ for a list of classes.
PowerShellCorpus/PoshCode/IE Proxy Toggle (Silent)_1.ps1
IE Proxy Toggle (Silent)_1.ps1
# Process command line parameter (if present). [bool] $DISABLE_PROXY = $false; foreach ($param in $MyInvocation.UnboundArguments) { if ($param -like 'disable') { $DISABLE_PROXY = $true; } } # Apply/refresh the organization's default proxy settings. [string] $proxyServer = '###.###.###.###:####'; [string] $proxyOverride = '*.local;192.168.*;<local>'; [int] $migrateProxy = 1; [int] $proxyHttp11 = 1; REG ADD """HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"" /v ""ProxyServer"" /t REG_SZ /d ""$proxyServer"" /f" | Out-Null; REG ADD """HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"" /v ""ProxyOverride"" /t REG_SZ /d ""$proxyOverride"" /f" | Out-Null; REG ADD """HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"" /v ""MigrateProxy"" /t REG_DWORD /d $migrateProxy /f" | Out-Null; REG ADD """HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"" /v ""ProxyHttp1.1"" /t REG_DWORD /d $proxyHttp11 /f" | Out-Null; <# Define a function to start a 'hidden' Internet Explorer process. This is needed since there is no easy way to programmatically 'refresh' the user's proxy settings after they have been changed in the registry. #> function Start-HiddenIEProcess () { [object] $ieProcess = $null; # Launch Internet Explorer (use 32-bit version only) in a hidden window. if (Test-Path "$env:PROGRAMFILES(X86)\\Internet Explorer\\iexplore.exe") { $ieProcess = Start-Process -Passthru -FilePath "$env:PROGRAMFILES(X86)\\Internet Explorer\\iexplore.exe" -WindowStyle Hidden ; } else { $ieProcess = Start-Process -Passthru -FilePath "$env:PROGRAMFILES\\Internet Explorer\\iexplore.exe" -WindowStyle Hidden; } # Wait for Internet Explorer to load fully. [int] $count = 10; do { if (($ieProcess.WaitForInputIdle())) { $waiting = $false; # IE is ready. $count = 0; } else { Start-Sleep 1; # Sleep for another second. $count--; # Decrement wait counter. } } while ($waiting -or ($count -gt 0)); # Check to see if our new process exists. if ((Get-Process -Name iexplore -ErrorAction SilentlyContinue)) { return $true; } else { return $false; } } # END <# Define a function to toggle the user's proxy settings by altering the required registry entry and then forcing a 'refresh' of the proxy status by utilizing a hidden/temporary Internet Explorer process. #> function Set-ProxyState ([bool] $disable) { # Kill existing IE processes. Stop-Process -Name iexplore -Force -ErrorAction SilentlyContinue; # Toggle proxy state. if ($disable) { Write-Host 'DISABLING user''s proxy settings...'; REG ADD '"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v "ProxyEnable" /t REG_DWORD /d 0 /f' | Out-Null; # Disable proxy. } else { Write-Host 'ENABLING user''s proxy settings...'; REG ADD '"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings" /v "ProxyEnable" /t REG_DWORD /d 1 /f' | Out-Null; # Enable proxy. } # Start a new/hidden IE process temporarily. Start-HiddenIEProcess; # Kill existing IE processes. Stop-Process -Name iexplore -Force -ErrorAction SilentlyContinue; Write-Host '[DONE]'; return $null; } # END # Toggle the user's proxy settings. $null = Set-ProxyState $DISABLE_PROXY;
PowerShellCorpus/PoshCode/Watch-Process.ps1
Watch-Process.ps1
## Watch-Process.ps1 ## Continuously display a process list, sorted ## by the desired criteria. ## ## usage: poll-process [sortCriteria] [pollInterval] ## ## sortCriteria must be one of "Id", "ProcessName", "MainWindowTitle", ## "Processor", "Disk", or "WorkingSet" ## pollInterval is specified in milliseconds ## param( [string] $sortCriteria = "Processor", [int] $pollInterval = 750 ) ## As a heuristic, gets the total IO and Data operations per second, and ## returns their sum. function get-diskActivity ( $process = $(throw "Please specify a process for which to get disk usage.") ) { $processName = get-processName $process ## We store the performance counter objects in a hashtable. If we don't, ## then they fail to return any information for a few seconds. if(-not $ioOtherOpsPerfCounters[$processName]) { $ioOtherOpsPerfCounters[$processName] = ` new-object System.Diagnostics.PerformanceCounter ` "Process","IO Other Operations/sec",$processName } if(-not $ioOtherBytesPerfCounters[$processName]) { $ioOtherBytesPerfCounters[$processName] = ` new-object System.Diagnostics.PerformanceCounter ` "Process","IO Other Bytes/sec",$processName } if(-not $ioDataOpsPerfCounters[$processName]) { $ioDataOpsPerfCounters[$processName] = ` new-object System.Diagnostics.PerformanceCounter ` "Process","IO Data Operations/sec",$processName } if(-not $ioDataBytesPerfCounters[$processName]) { $ioDataBytesPerfCounters[$processName] = ` new-object System.Diagnostics.PerformanceCounter ` "Process","IO Data Bytes/sec",$processName } ## If a process exits between the time we capture the processes and now, ## then we will be unable to get its NextValue(). This trap simply ## catches the error and continues. trap { continue; } ## Get the performance counter values $ioOther = (100 * $ioOtherOpsPerfCounters[$processName].NextValue()) + ` ($ioOtherBytesPerfCounters[$processName].NextValue()) $ioData = (100 * $ioDataOpsPerfCounters[$processName].NextValue()) + ` ($ioDataBytesPerfCounters[$processName].NextValue()) return [int] ($ioOther + $ioData) } ## Get the percentage of time spent by a process. ## Note: this is multiproc "unaware." We need to divide the ## result by the number of processors. function get-cpuPercent ( $process = $(throw "Please specify a process for which to get CPU usage.") ) { $processName = get-processName $process ## We store the performance counter objects in a hashtable. If we don't, ## then they fail to return any information for a few seconds. if(-not $cpuPerfCounters[$processName]) { $cpuPerfCounters[$processName] = ` new-object System.Diagnostics.PerformanceCounter ` "Process","% Processor Time",$processName } ## If a process exits between the time we capture the processes and now, ## then we will be unable to get its NextValue(). This trap simply ## catches the error and continues. trap { continue; } ## Get the performance counter values $cpuTime = ($cpuPerfCounters[$processName].NextValue() / $env:NUMBER_OF_PROCESSORS) return [int] $cpuTime } ## Performance counters are keyed by process name. However, ## processes may share the same name, so duplicates are named ## <process>#1, <process>#2, etc. function get-processName ( $process = $(throw "Please specify a process for which to get the name.") ) { ## If a process exits between the time we capture the processes and now, ## then we will be unable to get its information. This simply ## ignores the error. $errorActionPreference = "SilentlyContinue" $processName = $process.ProcessName $localProcesses = get-process -ProcessName $processName | sort Id if(@($localProcesses).Count -gt 1) { ## Determine where this one sits in the list $processNumber = -1 for($counter = 0; $counter -lt $localProcesses.Count; $counter++) { if($localProcesses[$counter].Id -eq $process.Id) { break } } ## Append its unique identifier, if required $processName += "#$counter" } return $processName } ## Store the performance counters we need ## for the CPU, and Disk I/O numbers $cpuPerfCounters = @{} $ioOtherOpsPerfCounters = @{} $ioOtherBytesPerfCounters = @{} $ioDataOpsPerfCounters = @{} $ioDataBytesPerfCounters = @{} $processes = $null $lastPoll = get-date $lastSnapshotCount = 0 $lastWindowHeight = 0 ## The coordinates to which we position the output $coords = new-object System.Management.Automation.Host.Coordinates 0,0 clear-host while(-not $host.UI.RawUI.KeyAvailable) { ## Set the cursor position, get the processes, and store ## the time of the snapshot $host.UI.RawUI.CursorPosition = $coords $processes = get-process | sort Id ## Go through all of the processes we captured foreach($process in $processes) { ## Get the disk activity, based on I/O Perf Counters, ## for the process in question. Then, add it as a note. $activity = get-diskActivity $process $process | add-member NoteProperty Disk $activity $cpuPercent = get-cpuPercent $process $process | add-member NoteProperty Processor $cpuPercent } $windowHeight = $host.Ui.RawUi.WindowSize.Height ## Since clear-host makes the screen flash, we only do so when ## we have fewer processes than we did the last time if(($processes.Count -lt $lastSnapshotCount) -or ` (-not ($lastWindowHeight -eq $windowHeight))) { clear-host } ## Tailor the length of the list to the height of the ## window. If the window is to short, show no output. if($windowHeight -le 7) { $output = $null } else { $output = $processes | sort -desc $sortCriteria | ` select-object -First ($windowHeight - 7) } ## Display the results $output | format-table Id,ProcessName,MainWindowTitle,Processor,Disk,WorkingSet if($processes.Count -gt ($windowHeight - 7)) { $notDisplayed = ($processes.Count - $output.Count) "[ $notDisplayed process(es) not shown ]" } $lastSnapshotCount = $processes.Count $lastWindowHeight = $windowHeight ## Sleep for their desired amount of elapsed time, ## adjusted for how much time we've actually spent working. $elapsed = [int] (get-date).Subtract($lastPoll).TotalMilliseconds $lastPoll = get-date if($pollInterval -gt $elapsed) { start-sleep -m ($pollInterval - $elapsed) } }
PowerShellCorpus/PoshCode/PowerShell Template_3.ps1
PowerShell Template_3.ps1
Function New-Script { $strName = $env:username $date = get-date -format d $name = Read-Host "Filename" if ($name -eq "") { $name="NewTemplate" } $email = Read-Host "eMail Address" if ($email -eq "") { $email="genemagerr@hotmail.com" } $comment=@(); while($s = (Read-Host "Comment").Trim()){$comment+="$s`r`n#"} $file = New-Item -type file "$name.ps1" -force $template=@" ########################################################################### # # NAME: $name.ps1 # # AUTHOR: $strName # EMAIL: $email # # COMMENT: $comment # # You have a royalty-free right to use, modify, reproduce, and # distribute this script file in any way you find useful, provided that # you agree that the creator, owner above has no warranty, obligations, # or liability for such use. # # VERSION HISTORY: # 1.0 $date - Initial release # ########################################################################### "@ | out-file $file ii $file } Set-Alias new New-Script
PowerShellCorpus/PoshCode/ScriptTransforms module_3.ps1
ScriptTransforms module_3.ps1
function New-ParameterTransform { #.Synopsis # Generates Parameter Transformation Attributes in simple PowerShell syntax #.Description # New-ParameterTransform allows the creation of .Net Attribute classes which can be applied to PowerShell parameters to transform or manipulate data as it's being passed in. #.Example # Transform TrimBraces { # param($string) # if($string -is [String] -and $string.Length -gt 2 -and $string[0] -eq '[' -and $string[-1] -eq ']') { # $string.SubString(1, $string.Length-2) # } else { # $string # } # } # # function Where-Type { # param( # [Type][TrimBraces()][String] # [Parameter(Mandatory=$true, Position=0)] # $Type, # # [Parameter(ValueFromPipeline=$true)] # $InputObject # ) # process { # if($InputObject -is $Type) { $InputObject } # } # } # # Description # ----------- # This example allows us to pass the "Type" to Where-Type with or without the [Braces] which would normally cause an exception when casting to a type: # # Get-ChildItem | Where-Type IO.FileInfo # # Get-ChildItem | Where-Type [IO.FileInfo] # # Get-ChildItem | Where-Type ([IO.FileInfo]) # #.Notes # It is now possible to redefine transforms by name by running the New-ParameterTransform command again, but type aliases that are generated are bound at function definition time, so any functions that are using the transform before it is redefined must also be redefined to take advantage of the new transform definition. [cmdletbinding()] param( # The name of the parameter transform to generate [Parameter(Mandatory=$true,Position=0)] [string] $name, # The script definition of the parameter transform [Parameter(Mandatory=$true, Position=1)] [scriptblock] $script ) end { $className = [Convert]::ToBase64String( ([Guid]::NewGuid().ToByteArray()) ).Replace('+',([char]241)).Replace('/',([char]223)).TrimEnd('=') $Type = Add-Type -Passthru -TypeDefinition @" using System; using System.ComponentModel; using System.Management.Automation; using System.Collections.ObjectModel; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class ${name}Attribute${className} : ArgumentTransformationAttribute { private ScriptBlock _scriptblock; private string _noOutputMessage = "Transform Script had no output."; public ${name}Attribute${className}() { this.Script = ScriptBlock.Create( @" $($script.ToString() -replace '"','""' ) " ); } public override string ToString() { return Script.ToString(); } public override Object Transform( EngineIntrinsics engine, Object inputData) { try { Collection<PSObject> output = engine.InvokeCommand.InvokeScript( engine.SessionState, Script, inputData ); if(output.Count > 1) { Object[] transformed = new Object[output.Count]; for(int i =0; i < output.Count;i++) { transformed[i] = output[i].BaseObject; } return transformed; } else if(output.Count == 1) { return output[0].BaseObject; } else { throw new ArgumentTransformationMetadataException(NoOutputMessage); } } catch (ArgumentTransformationMetadataException) { throw; } catch (Exception e) { throw new ArgumentTransformationMetadataException(string.Format("Transform Script threw an exception ('{0}'). See `$Error[0].Exception.InnerException.InnerException for more details.",e.Message), e); } } public ScriptBlock Script { get { return _scriptblock; } set { _scriptblock = value; } } public string NoOutputMessage { get { return _noOutputMessage; } set { _noOutputMessage = value; } } } "@ $xlr8r = [psobject].assembly.gettype("System.Management.Automation.TypeAccelerators") if($xlr8r::AddReplace) { $xlr8r::AddReplace( ${name}, $Type) } else { $null = $xlr8r::Remove( ${name} ) $xlr8r::Add( ${name}, $Type) } }} New-Alias -Name Transform -Value New-ParameterTransform; Export-ModuleMember -Alias Transform -Function * # SIG # Begin signature block # MIIRDAYJKoZIhvcNAQcCoIIQ/TCCEPkCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUuPtERnV5sVWNUIGE0Yl9W7+M # r4Wggg5CMIIHBjCCBO6gAwIBAgIBFTANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQG # EwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERp # Z2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2Vy # dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDcxMDI0MjIwMTQ1WhcNMTIxMDI0MjIw # MTQ1WjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzAp # BgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRlIFNpZ25pbmcxODA2BgNV # BAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJbnRlcm1lZGlhdGUgT2JqZWN0 # IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyiOLIjUemqAbPJ1J # 0D8MlzgWKbr4fYlbRVjvhHDtfhFN6RQxq0PjTQxRgWzwFQNKJCdU5ftKoM5N4YSj # Id6ZNavcSa6/McVnhDAQm+8H3HWoD030NVOxbjgD/Ih3HaV3/z9159nnvyxQEckR # ZfpJB2Kfk6aHqW3JnSvRe+XVZSufDVCe/vtxGSEwKCaNrsLc9pboUoYIC3oyzWoU # TZ65+c0H4paR8c8eK/mC914mBo6N0dQ512/bkSdaeY9YaQpGtW/h/W/FkbQRT3sC # pttLVlIjnkuY4r9+zvqhToPjxcfDYEf+XD8VGkAqle8Aa8hQ+M1qGdQjAye8OzbV # uUOw7wIDAQABo4ICfzCCAnswDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAQYwHQYD # VR0OBBYEFNBOD0CZbLhLGW87KLjg44gHNKq3MIGoBgNVHSMEgaAwgZ2AFE4L7xqk # QFulF2mHMMo0aEPQQa7yoYGBpH8wfTELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0 # YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRl # IFNpZ25pbmcxKTAnBgNVBAMTIFN0YXJ0Q29tIENlcnRpZmljYXRpb24gQXV0aG9y # aXR5ggEBMAkGA1UdEgQCMAAwPQYIKwYBBQUHAQEEMTAvMC0GCCsGAQUFBzAChiFo # dHRwOi8vd3d3LnN0YXJ0c3NsLmNvbS9zZnNjYS5jcnQwYAYDVR0fBFkwVzAsoCqg # KIYmaHR0cDovL2NlcnQuc3RhcnRjb20ub3JnL3Nmc2NhLWNybC5jcmwwJ6AloCOG # IWh0dHA6Ly9jcmwuc3RhcnRzc2wuY29tL3Nmc2NhLmNybDCBggYDVR0gBHsweTB3 # BgsrBgEEAYG1NwEBBTBoMC8GCCsGAQUFBwIBFiNodHRwOi8vY2VydC5zdGFydGNv # bS5vcmcvcG9saWN5LnBkZjA1BggrBgEFBQcCARYpaHR0cDovL2NlcnQuc3RhcnRj # b20ub3JnL2ludGVybWVkaWF0ZS5wZGYwEQYJYIZIAYb4QgEBBAQDAgABMFAGCWCG # SAGG+EIBDQRDFkFTdGFydENvbSBDbGFzcyAyIFByaW1hcnkgSW50ZXJtZWRpYXRl # IE9iamVjdCBTaWduaW5nIENlcnRpZmljYXRlczANBgkqhkiG9w0BAQUFAAOCAgEA # UKLQmPRwQHAAtm7slo01fXugNxp/gTJY3+aIhhs8Gog+IwIsT75Q1kLsnnfUQfbF # pl/UrlB02FQSOZ+4Dn2S9l7ewXQhIXwtuwKiQg3NdD9tuA8Ohu3eY1cPl7eOaY4Q # qvqSj8+Ol7f0Zp6qTGiRZxCv/aNPIbp0v3rD9GdhGtPvKLRS0CqKgsH2nweovk4h # fXjRQjp5N5PnfBW1X2DCSTqmjweWhlleQ2KDg93W61Tw6M6yGJAGG3GnzbwadF9B # UW88WcRsnOWHIu1473bNKBnf1OKxxAQ1/3WwJGZWJ5UxhCpA+wr+l+NbHP5x5XZ5 # 8xhhxu7WQ7rwIDj8d/lGU9A6EaeXv3NwwcbIo/aou5v9y94+leAYqr8bbBNAFTX1 # pTxQJylfsKrkB8EOIx+Zrlwa0WE32AgxaKhWAGho/Ph7d6UXUSn5bw2+usvhdkW4 # npUoxAk3RhT3+nupi1fic4NG7iQG84PZ2bbS5YxOmaIIsIAxclf25FwssWjieMwV # 0k91nlzUFB1HQMuE6TurAakS7tnIKTJ+ZWJBDduUbcD1094X38OvMO/++H5S45Ki # 3r/13YTm0AWGOvMFkEAF8LbuEyecKTaJMTiNRfBGMgnqGBfqiOnzxxRVNOw2hSQp # 0B+C9Ij/q375z3iAIYCbKUd/5SSELcmlLl+BuNknXE0wggc0MIIGHKADAgECAgFR # MA0GCSqGSIb3DQEBBQUAMIGMMQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRD # b20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2ln # bmluZzE4MDYGA1UEAxMvU3RhcnRDb20gQ2xhc3MgMiBQcmltYXJ5IEludGVybWVk # aWF0ZSBPYmplY3QgQ0EwHhcNMDkxMTExMDAwMDAxWhcNMTExMTExMDYyODQzWjCB # qDELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5ldyBZb3JrMRcwFQYDVQQHEw5XZXN0 # IEhlbnJpZXR0YTEtMCsGA1UECxMkU3RhcnRDb20gVmVyaWZpZWQgQ2VydGlmaWNh # dGUgTWVtYmVyMRUwEwYDVQQDEwxKb2VsIEJlbm5ldHQxJzAlBgkqhkiG9w0BCQEW # GEpheWt1bEBIdWRkbGVkTWFzc2VzLm9yZzCCASIwDQYJKoZIhvcNAQEBBQADggEP # ADCCAQoCggEBAMfjItJjMWVaQTECvnV/swHQP0FTYUvRizKzUubGNDNaj7v2dAWC # rAA+XE0lt9JBNFtCCcweDzphbWU/AAY0sEPuKobV5UGOLJvW/DcHAWdNB/wRrrUD # dpcsapQ0IxxKqpRTrbu5UGt442+6hJReGTnHzQbX8FoGMjt7sLrHc3a4wTH3nMc0 # U/TznE13azfdtPOfrGzhyBFJw2H1g5Ag2cmWkwsQrOBU+kFbD4UjxIyus/Z9UQT2 # R7bI2R4L/vWM3UiNj4M8LIuN6UaIrh5SA8q/UvDumvMzjkxGHNpPZsAPaOS+RNmU # Go6X83jijjbL39PJtMX+doCjS/lnclws5lUCAwEAAaOCA4EwggN9MAkGA1UdEwQC # MAAwDgYDVR0PAQH/BAQDAgeAMDoGA1UdJQEB/wQwMC4GCCsGAQUFBwMDBgorBgEE # AYI3AgEVBgorBgEEAYI3AgEWBgorBgEEAYI3CgMNMB0GA1UdDgQWBBR5tWPGCLNQ # yCXI5fY5ViayKj6xATCBqAYDVR0jBIGgMIGdgBTQTg9AmWy4SxlvOyi44OOIBzSq # t6GBgaR/MH0xCzAJBgNVBAYTAklMMRYwFAYDVQQKEw1TdGFydENvbSBMdGQuMSsw # KQYDVQQLEyJTZWN1cmUgRGlnaXRhbCBDZXJ0aWZpY2F0ZSBTaWduaW5nMSkwJwYD # VQQDEyBTdGFydENvbSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eYIBFTCCAUIGA1Ud # IASCATkwggE1MIIBMQYLKwYBBAGBtTcBAgEwggEgMC4GCCsGAQUFBwIBFiJodHRw # Oi8vd3d3LnN0YXJ0c3NsLmNvbS9wb2xpY3kucGRmMDQGCCsGAQUFBwIBFihodHRw # Oi8vd3d3LnN0YXJ0c3NsLmNvbS9pbnRlcm1lZGlhdGUucGRmMIG3BggrBgEFBQcC # AjCBqjAUFg1TdGFydENvbSBMdGQuMAMCAQEagZFMaW1pdGVkIExpYWJpbGl0eSwg # c2VlIHNlY3Rpb24gKkxlZ2FsIExpbWl0YXRpb25zKiBvZiB0aGUgU3RhcnRDb20g # Q2VydGlmaWNhdGlvbiBBdXRob3JpdHkgUG9saWN5IGF2YWlsYWJsZSBhdCBodHRw # Oi8vd3d3LnN0YXJ0c3NsLmNvbS9wb2xpY3kucGRmMGMGA1UdHwRcMFowK6ApoCeG # JWh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL2NydGMyLWNybC5jcmwwK6ApoCeGJWh0 # dHA6Ly9jcmwuc3RhcnRzc2wuY29tL2NydGMyLWNybC5jcmwwgYkGCCsGAQUFBwEB # BH0wezA3BggrBgEFBQcwAYYraHR0cDovL29jc3Auc3RhcnRzc2wuY29tL3N1Yi9j # bGFzczIvY29kZS9jYTBABggrBgEFBQcwAoY0aHR0cDovL3d3dy5zdGFydHNzbC5j # b20vY2VydHMvc3ViLmNsYXNzMi5jb2RlLmNhLmNydDAjBgNVHRIEHDAahhhodHRw # Oi8vd3d3LnN0YXJ0c3NsLmNvbS8wDQYJKoZIhvcNAQEFBQADggEBACY+J88ZYr5A # 6lYz/L4OGILS7b6VQQYn2w9Wl0OEQEwlTq3bMYinNoExqCxXhFCHOi58X6r8wdHb # E6mU8h40vNYBI9KpvLjAn6Dy1nQEwfvAfYAL8WMwyZykPYIS/y2Dq3SB2XvzFy27 # zpIdla8qIShuNlX22FQL6/FKBriy96jcdGEYF9rbsuWku04NqSLjNM47wCAzLs/n # FXpdcBL1R6QEK4MRhcEL9Ho4hGbVvmJES64IY+P3xlV2vlEJkk3etB/FpNDOQf8j # RTXrrBUYFvOCv20uHsRpc3kFduXt3HRV2QnAlRpG26YpZN4xvgqSGXUeqRceef7D # dm4iTdHK5tIxggI0MIICMAIBATCBkjCBjDELMAkGA1UEBhMCSUwxFjAUBgNVBAoT # DVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBEaWdpdGFsIENlcnRpZmlj # YXRlIFNpZ25pbmcxODA2BgNVBAMTL1N0YXJ0Q29tIENsYXNzIDIgUHJpbWFyeSBJ # bnRlcm1lZGlhdGUgT2JqZWN0IENBAgFRMAkGBSsOAwIaBQCgeDAYBgorBgEEAYI3 # AgEMMQowCKACgAChAoAAMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3AgEEMBwGCisG # AQQBgjcCAQsxDjAMBgorBgEEAYI3AgEWMCMGCSqGSIb3DQEJBDEWBBRwXWZDNpNi # 610AMYX0IABK3chR3TANBgkqhkiG9w0BAQEFAASCAQAjQh+y+Avtqg0AUE4YwQuw # InQPMRD6M1w2+Gl8v89lJ/+X0bgAFafCvxMsXy4ENJ/AReImBjPwqGiiG4IoRyzL # zIPRNyEUVAMDYQRaorpYvi8z635mhpw2owpDPbtOl3Ljh+wiv7CtPVlDq/tGzh6S # lwjEDHro4SkKMMS2ZUQYc+fxyb2OCt4FkiNTisudpr1/R30CG4KEuLxSi/uUMUK8 # SrBddBF82GNyzA9eFs9Ep2+6quseIIFiKizdV1bIgWtknQKn6l9F9SDYnMyZ/MAD # EWq7GkNqKStiVAAzHU/vzHTNhhrem4Bbo13hA8cuiGd5iyFiHlYTpORGjsr1VO60 # SIG # End signature block
PowerShellCorpus/PoshCode/Check Chromium Build.ps1
Check Chromium Build.ps1
# Name : Check-LatestChromium.ps1 # Author: David "Makovec" Moravec # Web : http://www.powershell.cz # Email : powershell.cz@googlemail.com # # Description: Check latest Chromium build # : Uses HttpRest http://poshcode.org/787 # # Version: 0.1 # History: # v0.1 - (add) build check # - (add) split to handle more return values # # ToDo: download file # unzip # check installed version of Chromium # # Usage: Check-LatestChromium # ################################################################# function Check-LatestChromium { $url = 'http://build.chromium.org/buildbot/snapshots/chromium-rel-xp/' $XPathRelDate = "//tr[position()=last()-2]//td[3]" $XPathBuild = "//tr[position()=last()-2]//td[2]//a" $page = Invoke-Http get $url $releaseDate = $page | Receive-Http text $XPathRelDate ($page | Receive-Http text $XPathBuild) -match "(?<build>\\d*)" | Out-Null "Latest Build is: {0}, released at {1}" -f $matches.build, $releaseDate }
PowerShellCorpus/PoshCode/Start-Cassini_1.ps1
Start-Cassini_1.ps1
function Start-Cassini([string]$physical_path=((@(Coalesce-Args (Find-File Global.asax).DirectoryName "."))[0]), [int]$port=12372, [switch]$dontOpenBrowser) { $serverLocation = Resolve-Path "C:\\Program Files (x86)\\Common Files\\Microsoft Shared\\DevServer\\10.0\\WebDev.WebServer40.EXE"; $full_app_path = Resolve-Path $physical_path $url = "http://localhost:$port" &($serverLocation.Path) /port:$port /path:"""$($full_app_path.Path)""" Write-Host "Started $($full_app_path.Path) on $url" Write-Host "Remember you can kill processes with kill -name WebDev*" if($dontOpenBrowser -eq $false) { [System.Diagnostics.Process]::Start($url) } }
PowerShellCorpus/PoshCode/Invoke-NamedParameter.ps1
Invoke-NamedParameter.ps1
Function Invoke-NamedParameter { <# .SYNOPSIS Invokes a method using named parameters. .DESCRIPTION A function that simplifies calling methods with named parameters to make it easier to deal with long signatures and optional parameters. This is particularly helpful for COM objects. .PARAMETER Object The object that has the method. .PARAMETER Method The name of the method. .PARAMETER Parameter A hashtable with the names and values of parameters to use in the method call. .PARAMETER Argument An array of arguments without names to use in the method call. .NOTES Name: Invoke-NamedParameter Author: Jason Archer DateCreated: 2011-04-06 1.0 - 2011-04-06 - Jason Archer Initial release. .EXAMPLE $shell = New-Object -ComObject Shell.Application Invoke-NamedParameters $Shell "Explore" @{"vDir"="$pwd"} Description ----------- Invokes a method named "Explore" with the named parameter "vDir." #> [CmdletBinding(DefaultParameterSetName = "Named")] param( [Parameter(ParameterSetName = "Named", Position = 0, Mandatory = $true)] [Parameter(ParameterSetName = "Positional", Position = 0, Mandatory = $true)] [ValidateNotNull()] [System.Object]$Object , [Parameter(ParameterSetName = "Named", Position = 1, Mandatory = $true)] [Parameter(ParameterSetName = "Positional", Position = 1, Mandatory = $true)] [ValidateNotNullOrEmpty()] [String]$Method , [Parameter(ParameterSetName = "Named", Position = 2, Mandatory = $true)] [ValidateNotNull()] [Hashtable]$Parameter , [Parameter(ParameterSetName = "Positional")] [Object[]]$Argument ) end { ## Just being explicit that this does not support pipelines if ($PSCmdlet.ParameterSetName -eq "Named") { ## Invoke method with parameter names ## Note: It is ok to use a hashtable here because the keys (parameter names) and values (args) ## will be output in the same order. We don't need to worry about the order so long as ## all parameters have names $Object.GetType().InvokeMember($Method, [System.Reflection.BindingFlags]::InvokeMethod, $null, ## Binder $Object, ## Target ([Object[]]($Parameter.Values)), ## Args $null, ## Modifiers $null, ## Culture ([String[]]($Parameter.Keys)) ## NamedParameters ) } else { ## Invoke method without parameter names $Object.GetType().InvokeMember($Method, [System.Reflection.BindingFlags]::InvokeMethod, $null, ## Binder $Object, ## Target $Argument, ## Args $null, ## Modifiers $null, ## Culture $null ## NamedParameters ) } } } <# Examples Calling a method with named parameters. $shell = New-Object -ComObject Shell.Application Invoke-NamedParameters $Shell "Explore" @{"vDir"="$pwd"} The syntax for more than one would be @{"First"="foo";"Second"="bar"} Calling a method that takes no parameters (you can also use -Argument with $null). $shell = New-Object -ComObject Shell.Application Invoke-NamedParameters $Shell "MinimizeAll" @{} #>
PowerShellCorpus/PoshCode/Export-CSV -Append.ps1
Export-CSV -Append.ps1
#Requires -Version 2.0 <# This Export-CSV behaves exactly like native Export-CSV However it has one optional switch -Append Which lets you append new data to existing CSV file: e.g. Get-Process | Select ProcessName, CPU | Export-CSV processes.csv -Append For details, see http://dmitrysotnikov.wordpress.com/2010/01/19/export-csv-append/ (c) Dmitry Sotnikov #> function Export-CSV { [CmdletBinding(DefaultParameterSetName='Delimiter', SupportsShouldProcess=$true, ConfirmImpact='Medium')] param( [Parameter(Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [System.Management.Automation.PSObject] ${InputObject}, [Parameter(Mandatory=$true, Position=0)] [Alias('PSPath')] [System.String] ${Path}, #region -Append (added by Dmitry Sotnikov) [Switch] ${Append}, #endregion [Switch] ${Force}, [Switch] ${NoClobber}, [ValidateSet('Unicode','UTF7','UTF8','ASCII','UTF32','BigEndianUnicode','Default','OEM')] [System.String] ${Encoding}, [Parameter(ParameterSetName='Delimiter', Position=1)] [ValidateNotNull()] [System.Char] ${Delimiter}, [Parameter(ParameterSetName='UseCulture')] [Switch] ${UseCulture}, [Alias('NTI')] [Switch] ${NoTypeInformation}) begin { # This variable will tell us whether we actually need to append # to existing file $AppendMode = $false try { $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Export-Csv', [System.Management.Automation.CommandTypes]::Cmdlet) #String variable to become the target command line $scriptCmdPipeline = '' # Add new parameter handling #region Dmitry: Process and remove the Append parameter if it is present if ($Append) { $PSBoundParameters.Remove('Append') | Out-Null if ($Path) { if (Test-Path $Path) { # Need to construct new command line $AppendMode = $true if ($Encoding.Length -eq 0) { # ASCII is default encoding for Export-CSV $Encoding = 'ASCII' } # For Append we use ConvertTo-CSV instead of Export $scriptCmdPipeline += 'ConvertTo-Csv -NoTypeInformation ' # Inherit other CSV convertion parameters if ( $UseCulture ) { $scriptCmdPipeline += ' -UseCulture ' } if ( $Delimiter ) { $scriptCmdPipeline += " -Delimiter '$Delimiter' " } # Skip the first line (the one with the property names) $scriptCmdPipeline += ' | Foreach-Object {$start=$true}' $scriptCmdPipeline += '{if ($start) {$start=$false} else {$_}} ' # Add file output $scriptCmdPipeline += " | Out-File -FilePath '$Path' -Encoding '$Encoding' -Append " if ($Force) { $scriptCmdPipeline += ' -Force' } if ($NoClobber) { $scriptCmdPipeline += ' -NoClobber' } } } } $scriptCmd = {& $wrappedCmd @PSBoundParameters } if ( $AppendMode ) { # redefine command line $scriptCmd = $ExecutionContext.InvokeCommand.NewScriptBlock( $scriptCmdPipeline ) } else { # execute Export-CSV as we got it because # either -Append is missing or file does not exist $scriptCmd = $ExecutionContext.InvokeCommand.NewScriptBlock( [string]$scriptCmd ) } # standard pipeline initialization $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } <# .ForwardHelpTargetName Export-Csv .ForwardHelpCategory Cmdlet #> }
PowerShellCorpus/PoshCode/Get-NestedGroups_1.ps1
Get-NestedGroups_1.ps1
<# .SYNOPSIS Enumerate all AD group memberships of an account (including nested membership). .DESCRIPTION This script will return all the AD groups an account is member of. .PARAMETER UserName The username whose group memberships to find. .EXAMPLE .\\Get-NestedGroups.ps1 'johndoe' Name DistinguishedName ---- ----------------- Domain Users CN=Domain Users,CN=Users,DC=contoso,DC=com Finance CN=Finance,OU=Department,OU=Groups,DC=contos... .NOTES ScriptName : Get-NestedGroups Created By : Gilbert van Griensven Date Coded : 06/17/2012 The script iterates through all nested groups and skips circular nested groups. .LINK #> Param ( [Parameter(Mandatory=$true)]$UserName ) Begin { Function LoadADModule { If (!(Get-Module ActiveDirectory)) { If (Get-Module -ListAvailable | ? {$_.Name -eq "ActiveDirectory"}) { Import-Module ActiveDirectory Return $True } Else { Return $False } } Else { Return $True } } Function GetNestedGroups ($strGroupDN) { $currentGroupmemberships = (Get-ADGroup $strGroupDN �Properties MemberOf | Select-Object MemberOf).MemberOf foreach ($groupDN in $currentGroupmemberships) { if (!(($Script:UserGroupMembership | Select-Object -ExpandProperty DistinguishedName) -contains $groupDN)) { $arrProps = @{ Name = (Get-ADGroup $groupDN).Name DistinguishedName = $groupDN } $Script:UserGroupMembership += (New-Object psobject -Property $arrProps) GetNestedGroups $groupDN } } } Function FindGroupMembership ($strUsername) { $Script:UserGroupMembership = @() $arrProps = @{ Name = "Domain Users" DistinguishedName = (Get-ADGroup "Domain Users").DistinguishedName } $Script:UserGroupMembership += (New-Object psobject -Property $arrProps) GetNestedGroups (Get-ADGroup "Domain Users").DistinguishedName $directMembershipGroups = (Get-ADUser $strUsername �Properties MemberOf | Select-Object MemberOf).MemberOf foreach ($groupDN in $directMembershipGroups) { $arrProps = @{ Name = (Get-ADGroup $groupDN).Name DistinguishedName = $groupDN } $Script:UserGroupMembership += (New-Object psobject -Property $arrProps) GetNestedGroups $groupDN } } } Process { If (!(LoadADModule)) { Write-Host "Could not load module ActiveDirectory!" Return } If ($UserName) { FindGroupMembership $UserName Return $Script:UserGroupMembership } } End { Remove-Module ActiveDirectory -ErrorAction SilentlyContinue }
PowerShellCorpus/PoshCode/Set-SendAs_1.ps1
Set-SendAs_1.ps1
# NAME # Set-SendAs # # SYNOPSIS # Use the Set-SendAs cmdlet to grant or Remove SendAs permissions on a mailbox # # SYNTAX # Set-SendAs -Identity <MailboxIdParameter> -SendAs <MailboxIdParameter> -ou <OrganizationalUnit> [-Remove <SwitchParameter> [-Confirm [<SwitchParameter>]]] [-DomainController <Fqdn>] Function Set-SendAs ($Identity, $SendAs, $ou, [Switch]$Remove, $DomainController = "dc01", [switch]$Confirm = $true) { PROCESS { if(!$ou) {throw 'Required paramater $ou is missing.'} # Use pipeline input when parameter is not specified if($_) { if($_.Identity -and !$Identity) {$Identity = $_.Identity} if($_.SendAs -and !$SendAs) {$SendAs = $_.SendAs} if($_.ou -and !$ou) {$ou = $_.ou} if($_.remove -and !$remove) {$remove = $_.remove} } # Verify admin and user are both available $IdentityMbx = $Identity $SendAsMbx = $SendAs if([string]$Identity.GetType() -ne "Microsoft.Exchange.Data.Directory.Management.Mailbox" -and !($IdentityMbx = Get-Mailbox $Identity -DomainController $DomainController -OrganizationalUnit $ou -ErrorAction SilentlyContinue)) {throw "The operation could not be performed becaues the object '$Identity' could not be found in the organization '$ou'"} if([string]$SendAs.GetType() -ne "Microsoft.Exchange.Data.Directory.Management.Mailbox" -and !($SendAsMbx = Get-Mailbox $SendAs -DomainController $DomainController -OrganizationalUnit $ou -ErrorAction SilentlyContinue)) {throw "The operation could not be performed becaues the object '$SendAs' could not be found in the organization '$ou'"} # Make changes If(!$Remove) {$null = Add-ADPermission -Identity $IdentityMbx.DistinguishedName -User $SendAsMbx.DistinguishedName -ExtendedRights Send-As} Else {$null = Remove-ADPermission -Identity $IdentityMbx.DistinguishedName -User $SendAsMbx.DistinguishedName -ExtendedRights Send-As -Confirm:$Confirm} } }
PowerShellCorpus/PoshCode/Spin-Busy.ps1
Spin-Busy.ps1
function Spin-Busy { param( [Int] $msWait = 0, [String] $spinStr = '-\\|/. ', [Char[]] $spinChars = [Char[]] ($spinStr.ToCharArray()), [System.Management.Automation.Host.PSHostRawUserInterface] $rawUI = (Get-Host).UI.RawUI, [ConsoleColor] $bgColor = $rawUI.BackgroundColor, [ConsoleColor] $fgColor = $rawUI.ForegroundColor, [System.Management.Automation.Host.Coordinates] $curPos = $rawUI.Get_CursorPosition(), [Int32] $startX = $curPos.X, [Int32] $maxX = $rawUI.WindowSize.Width, [Switch] $trails ) begin { $trailCell = $rawUI.NewBufferCellArray(@($spinChars[-2]), $fgColor, $bgColor); $blankCell = $rawUI.NewBufferCellArray(@($spinChars[-1]), $fgColor, $bgColor); $spinCells = $spinChars[0..($spinChars.Count - 3)]; for ($i=0; $i -lt ($spinCells.Count); ++$i) { $spinCells[$i] = $rawUI.NewBufferCellArray(@($spinCells[$i]), $fgColor, $bgColor) } $charNdx = 0; } process { if ($charNdx -lt $spinCells.Count) { $rawUI.SetBufferContents($curPos, $spinCells[$charNdx++]); } else { $charNdx = 0; $rawUI.SetBufferContents($curPos, $trailCell); if ($trails) { if (++$curPos.X -gt $maxX) { do { --$curPos.X; $rawUI.SetBufferContents($curPos, $blankCell) } until ($curPos.X -le $startX) } } } Start-Sleep -milliseconds $msWait $_ } end { do { $rawUI.SetBufferContents($curPos, $blankCell); } until (--$curPos.X -le $startX) } }
PowerShellCorpus/PoshCode/Twitter Module v0.2b.ps1
Twitter Module v0.2b.ps1
<# ------------------------------------------------------------------------------- Name: Social Media Scripting Framework Module: Twitter Version: 0.2 BETA Date: 2013/02/03 Author: Carlos Veira Lorenzo e-mail: cveira [at] thinkinbig [dot] org blog: thinkinbig.org twitter: @cveira facebook: www.facebook.com/cveira Google+: gplus.to/cveira LinkedIn: es.linkedin.com/in/cveira/ ------------------------------------------------------------------------------- Support: http://thinkinbig.org/oms/ Forums & Communities: facebook.com/ThinkInBig gplus.to/ThinkInBig http://bit.ly/SMSF-Forum ------------------------------------------------------------------------------- Code Mirror Sites: https://smsf.codeplex.com/ https://github.com/cveira/social-media-scripting-framework https://code.google.com/p/social-media-scripting-framework/ http://sourceforge.net/projects/smsf/ ------------------------------------------------------------------------------- Social Media Scripting Framework. Copyright (C) 2013 Carlos Veira Lorenzo. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ------------------------------------------------------------------------------- #> [Reflection.Assembly]::LoadWithPartialName("System.Security") | Out-Null [Reflection.Assembly]::LoadWithPartialName("System.Net") | Out-Null [string] $TweetContentPattern = '((?s)<p[^>]*js-tweet-text tweet-text[^>]*>(?<TweetContent>.*?)</p>.*?' + ` '<li[^>]*js-stat-count js-stat-retweets stat-count[^>]*>(?<ReTweetStats>.*?)</li>.*?' + ` '<li[^>]*js-stat-count js-stat-favorites stat-count[^>]*>(?<FavoritesStats>.*?)</li>)|' + ` '((?s)<p[^>]*js-tweet-text tweet-text[^>]*>(?<TweetContent>.*?)</p>.*?' + ` '<li[^>]*js-stat-count js-stat-retweets stat-count[^>]*>(?<ReTweetStats>.*?)</li>)|' + ` '((?s)<p[^>]*js-tweet-text tweet-text[^>]*>(?<TweetContent>.*?)</p>.*?' + ` '<li[^>]*js-stat-count js-stat-favorites stat-count[^>]*>(?<FavoritesStats>.*?)</li>)|' + ` '((?s)<p[^>]*js-tweet-text tweet-text[^>]*>(?<TweetContent>.*?)</p>)' $TwitterTimeOut = 3 * 60 * 1000 # seconds $TwitterUserAgent = "PowerShell" # -------------------------------------------------------------------------------------------------- function Get-TweetRetweetsFromPage( [ref] $PageSourceCode ) { # $SourceCode = Get-PageSourceCode https://twitter.com/cveira/status/275929500183830529 # Get-TweetRetweetsFromPage ([ref] $SourceCode) [string] $RetweetsCountPattern = '<strong[^>]*[^>]*>(?<RetweetsCount>.*?)</strong>' if ( $PageSourceCode.Value -match $TweetContentPattern ) { if ( $Matches.ReTweetStats -match $RetweetsCountPattern ) { $Matches.RetweetsCount } else { 0 } } else { 0 } } function Get-TweetFavoritesFromPage( [ref] $PageSourceCode ) { # $SourceCode = Get-PageSourceCode https://twitter.com/cveira/status/275929500183830529 # Get-TweetFavoritesFromPage ([ref] $SourceCode) [string] $FavoritesCountPattern = '<strong[^>]*[^>]*>(?<FavoritesCount>.*?)</strong>' if ( $PageSourceCode.Value -match $TweetContentPattern ) { if ( $Matches.FavoritesStats -match $FavoritesCountPattern ) { $Matches.FavoritesCount } else { 0 } } else { 0 } } function Get-TweetContentFromPage( [ref] $PageSourceCode ) { # $SourceCode = Get-PageSourceCode https://twitter.com/cveira/status/275929500183830529 # Get-TweetContentFromPage ([ref] $SourceCode) if ( $PageSourceCode.Value -match $TweetContentPattern ) { $Matches.TweetContent } else { "N/D" } } function Get-TweetLinksFromPage( [ref] $PageSourceCode ) { # $SourceCode = Get-PageSourceCode https://twitter.com/cveira/status/275929500183830529 # Get-TweetLinksFromPage ([ref] $SourceCode) [RegEx] $LinksPattern = '(data-expanded-url="(.*?)")+' [string[]] $TweetLinks = @() if ( $PageSourceCode.Value -match $TweetContentPattern ) { $CurrentMatch = $LinksPattern.match($Matches.TweetContent) if (!$CurrentMatch.Success) { $TweetLinks += "N/D" } while ($CurrentMatch.Success) { $TweetLinks += $CurrentMatch.Value.Split('"')[1] $CurrentMatch = $CurrentMatch.NextMatch() } } else { $TweetLinks += "N/D" } $TweetLinks } function Get-TweetHashTagsFromPage( [ref] $PageSourceCode ) { # $SourceCode = Get-PageSourceCode https://twitter.com/cveira/status/275929500183830529 # Get-TweetHashTagsFromPage ([ref] $SourceCode) [string] $HashTagNamePattern = "%23(?<HashTag>.*?)&amp" [RegEx] $LinksPattern = '(href="(.*?)")+' [string[]] $TweetLinks = @() if ( $PageSourceCode.Value -match $TweetContentPattern ) { $CurrentMatch = $LinksPattern.match($Matches.TweetContent) if (!$CurrentMatch.Success) { $TweetLinks += "N/D" } while ($CurrentMatch.Success) { if ( $CurrentMatch.Value -match $HashTagNamePattern ) { $TweetLinks += $Matches.HashTag } $CurrentMatch = $CurrentMatch.NextMatch() } } else { $TweetLinks += "N/D" } $TweetLinks } # -------------------------------------------------------------------------------------------------- function EscapeDataStringRfc3986( [string] $text ) { [string[]] $Rfc3986CharsToEscape = @( "!", "*", "'", "(", ")" ) [string] $EscapedText = [System.Uri]::EscapeDataString($text) for ( $i = 0; $i -lt $Rfc3986CharsToEscape.Length; $i++ ) { $EscapedText = $EscapedText.Replace( $Rfc3986CharsToEscape[$i], [System.Uri]::HexEscape($Rfc3986CharsToEscape[$i]) ) } $EscapedText } function Set-OAuthSignature( [string] $HttpRequestType, [string] $HttpEndpoint, [string] $HttpQueryString, [string] $OAuthNonce, [string] $OAuthTimeStamp, [string] $OAuthConsumerKey, [string] $OAuthConsumerSecret, [string] $OAuthToken, [string] $OAuthTokenSecret ) { [string[]] $HttpQueryStringParameters $ParameterString = @{} if ( $HttpQueryString.Length -gt 0 ) { $HttpQueryStringParameters = $HttpQueryString.Split("&") $HttpQueryStringParameters | ForEach-Object { $ParameterString.Add( $_.Split("=")[0], $_.Split("=")[1] ) } } $ParameterString.Add( "oauth_consumer_key", $OAuthConsumerKey ) $ParameterString.Add( "oauth_nonce", $OAuthNonce ) $ParameterString.Add( "oauth_signature_method", "HMAC-SHA1" ) $ParameterString.Add( "oauth_timestamp", $OAuthTimeStamp ) $ParameterString.Add( "oauth_token", $OAuthToken ) $ParameterString.Add( "oauth_version", "1.0" ) $signature = $HttpRequestType + "&" # 1. The URL in the signature string HAS NO QUERY_STRING PARAMETERS $signature += [System.Uri]::EscapeDataString($HttpEndpoint) + "&" # 2. All the parameters included in the QUERY_STRING {when calling [System.Net.WebRequest]::Create()} have to be included in the signature # 3. When building the signature string, parameters must be in alphabetical order. $ParameterString.Keys | Sort-Object | ForEach-Object { # [System.Uri]::EscapeDataString($_ + "=" + $ParameterString.$_ + "&") is not RFC3986 compliant in .NET < 4.x! # RFC3986 compliancy is documented in OAuth 1.0A, not in Twitter documentation! $signature += EscapeDataStringRfc3986 $($_ + "=" + $ParameterString.$_ + "&") } $signature = $signature.Substring(0, $signature.Length - 3) $SignatureKey = [System.Uri]::EscapeDataString($OAuthConsumerSecret) + "&" + [System.Uri]::EscapeDataString($OAuthTokenSecret) $Hasher = New-Object System.Security.Cryptography.HMACSHA1 $Hasher.Key = [System.Text.Encoding]::ASCII.GetBytes($SignatureKey) $OAuthSignature = [System.Convert]::ToBase64String($Hasher.ComputeHash([System.Text.Encoding]::ASCII.GetBytes($signature))) $OAuthSignature } function Set-OAuthHeader( [string] $OAuthConsumerKey, [string] $OAuthNonce, [string] $OAuthSignature, [string] $OAuthTimeStamp, [string] $OAuthToken ) { $OAuthHeader = 'OAuth ' $OAuthHeader += 'oauth_consumer_key="' + [System.Uri]::EscapeDataString($OAuthConsumerKey) + '", ' $OAuthHeader += 'oauth_nonce="' + [System.Uri]::EscapeDataString($OAuthNonce) + '", ' $OAuthHeader += 'oauth_signature="' + [System.Uri]::EscapeDataString($OAuthSignature) + '", ' $OAuthHeader += 'oauth_signature_method="HMAC-SHA1", ' $OAuthHeader += 'oauth_timestamp="' + [System.Uri]::EscapeDataString($OAuthTimeStamp) + '", ' $OAuthHeader += 'oauth_token="' + [System.Uri]::EscapeDataString($OAuthToken) + '", ' $OAuthHeader += 'oauth_version="1.0"' $OAuthHeader } function Get-RawTweetRetweetedByAsXml( [string] $TweetPermaLink ) { # Get-RawTweetRetweetedByAsXml https://twitter.com/cveira/status/275929500183830529 [string] $HttpRequestType = "GET" [string] $HttpEndpoint = "" [string] $HttpQueryString = "" [string] $TwitterRawResponse = "" [string] $ApiURL = "http://api.twitter.com/1/statuses/" + $TweetPermaLink.Split("/")[5] + "/retweeted_by.xml" $HttpEndpoint = $ApiURL $HttpQueryString = "" $OAuthConsumerKey = $TwitterConsumerKey $OAuthConsumerSecret = $TwitterConsumerSecret $OAuthToken = $TwitterAccessToken $OAuthTokenSecret = $TwitterAccessTokenSecret $OAuthNonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString())) $TimeStamp = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null).ToUniversalTime() $OAuthTimeStamp = [System.Convert]::ToInt64($TimeStamp.TotalSeconds).ToString() $OAuthSignature = Set-OAuthSignature $HttpRequestType $HttpEndpoint $HttpQueryString $OAuthNonce $OAuthTimeStamp $OAuthConsumerKey $OAuthConsumerSecret $OAuthToken $OAuthTokenSecret $OAuthHeader = Set-OAuthHeader $OAuthConsumerKey $OAuthNonce $OAuthSignature $OAuthTimeStamp $OAuthToken [System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create($ApiURL) $request.Method = $HttpRequestType $request.UserAgent = $TwitterUserAgent $request.Timeout = $TwitterTimeOut $request.ContentType = "application/x-www-form-urlencoded" $request.Headers.Add("Authorization", $OAuthHeader) try { [System.Net.HttpWebResponse] $response = $request.GetResponse() if ( $response -ne $null ) { $ResponseStream = New-Object System.IO.StreamReader($response.GetResponseStream()) $ResponseStream.ReadToEnd().Trim() | Select-String -NotMatch "api.twitter.com" | ForEach-Object { $TwitterRawResponse += $_ } | Out-Null $TwitterRawResponse } $response.Close() } catch { $_.Exception.Message } } function Get-RawTweetRetweetedBy( [string] $TweetPermaLink ) { # Get-RawTweetRetweetedBy https://twitter.com/cveira/status/275929500183830529 [string] $HttpRequestType = "GET" [string] $HttpEndpoint = "" [string] $HttpQueryString = "" [string] $TwitterRawResponse = "" [string] $ApiURL = "http://api.twitter.com/1/statuses/" + $TweetPermaLink.Split("/")[5] + "/retweeted_by.xml" $HttpEndpoint = $ApiURL $HttpQueryString = "" $OAuthConsumerKey = $TwitterConsumerKey $OAuthConsumerSecret = $TwitterConsumerSecret $OAuthToken = $TwitterAccessToken $OAuthTokenSecret = $TwitterAccessTokenSecret $OAuthNonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString())) $TimeStamp = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null).ToUniversalTime() $OAuthTimeStamp = [System.Convert]::ToInt64($TimeStamp.TotalSeconds).ToString() $OAuthSignature = Set-OAuthSignature $HttpRequestType $HttpEndpoint $HttpQueryString $OAuthNonce $OAuthTimeStamp $OAuthConsumerKey $OAuthConsumerSecret $OAuthToken $OAuthTokenSecret $OAuthHeader = Set-OAuthHeader $OAuthConsumerKey $OAuthNonce $OAuthSignature $OAuthTimeStamp $OAuthToken [System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create($ApiURL) $request.Method = $HttpRequestType $request.UserAgent = $TwitterUserAgent $request.Timeout = $TwitterTimeOut $request.ContentType = "application/x-www-form-urlencoded" $request.Headers.Add("Authorization", $OAuthHeader) try { [System.Net.HttpWebResponse] $response = $request.GetResponse() if ( $response -ne $null ) { $ResponseStream = New-Object System.IO.StreamReader($response.GetResponseStream()) $ResponseStream.ReadToEnd().Trim() | Select-String -NotMatch "api.twitter.com" | ForEach-Object { $TwitterRawResponse += $_ } | Out-Null [xml] $TwitterRawResponse | ForEach-Object { $_.users.user } | ForEach-Object { New-Object PSObject -Property @{ Name = $_.name ScreenName = $_.screen_name Description = $_.description URL = $_.url Friends = $_.friends_count Followers = $_.followers_count Tweets = $_.statuses_count Listed = $_.listed_count } } } $response.Close() } catch { $_.Exception.Message } } function Get-RawTwitterMentionsAsJson { # https://dev.twitter.com/docs/api/1.1/get/statuses/mentions_timeline # Get-RawTwitterMentionsAsJson | ConvertFrom-Json [string] $HttpRequestType = "GET" [string] $HttpEndpoint = "" [string] $HttpQueryString = "" [string] $TwitterRawResponse = "" [string] $ApiURL = "http://api.twitter.com/1.1/statuses/mentions_timeline.json?count=20&include_entities=true&include_rts=true" if ( $ApiURL.IndexOf("?") -ne -1 ) { $HttpEndpoint = $ApiURL.Split("?")[0] $HttpQueryString = $ApiURL.Split("?")[1] } else { $HttpEndpoint = $ApiURL $HttpQueryString = "" } $OAuthConsumerKey = $TwitterConsumerKey $OAuthConsumerSecret = $TwitterConsumerSecret $OAuthToken = $TwitterAccessToken $OAuthTokenSecret = $TwitterAccessTokenSecret $OAuthNonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString())) $TimeStamp = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null).ToUniversalTime() $OAuthTimeStamp = [System.Convert]::ToInt64($TimeStamp.TotalSeconds).ToString() $OAuthSignature = Set-OAuthSignature $HttpRequestType $HttpEndpoint $HttpQueryString $OAuthNonce $OAuthTimeStamp $OAuthConsumerKey $OAuthConsumerSecret $OAuthToken $OAuthTokenSecret $OAuthHeader = Set-OAuthHeader $OAuthConsumerKey $OAuthNonce $OAuthSignature $OAuthTimeStamp $OAuthToken [System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create($ApiURL) $request.Method = $HttpRequestType $request.UserAgent = $TwitterUserAgent $request.Timeout = $TwitterTimeOut $request.ContentType = "application/x-www-form-urlencoded" $request.Headers.Add("Authorization", $OAuthHeader) try { [System.Net.HttpWebResponse] $response = $request.GetResponse() if ( $response -ne $null ) { $ResponseStream = New-Object System.IO.StreamReader($response.GetResponseStream()) $ResponseStream.ReadToEnd().Trim() } $response.Close() } catch { $_.Exception.Message } } function Get-RawTweetRetweetsAsJson( [string] $TweetPermaLink ) { # https://dev.twitter.com/docs/api/1.1/get/statuses/retweets/%3Aid # Get-RawTweetRetweetsAsJson https://twitter.com/cveira/status/275929500183830529 | ConvertFrom-Json # Get-RawTweetRetweetsAsJson http://twitter.com/TechCrunch/status/282712924752060417 | ConvertFrom-Json [string] $HttpRequestType = "GET" [string] $HttpEndpoint = "" [string] $HttpQueryString = "" [string] $TwitterRawResponse = "" [string] $ApiURL = "http://api.twitter.com/1.1/statuses/retweets/" + $TweetPermaLink.Split("/")[5] + ".json?count=100" if ( $ApiURL.IndexOf("?") -ne -1 ) { $HttpEndpoint = $ApiURL.Split("?")[0] $HttpQueryString = $ApiURL.Split("?")[1] } else { $HttpEndpoint = $ApiURL $HttpQueryString = "" } $OAuthConsumerKey = $TwitterConsumerKey $OAuthConsumerSecret = $TwitterConsumerSecret $OAuthToken = $TwitterAccessToken $OAuthTokenSecret = $TwitterAccessTokenSecret $OAuthNonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString())) $TimeStamp = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null).ToUniversalTime() $OAuthTimeStamp = [System.Convert]::ToInt64($TimeStamp.TotalSeconds).ToString() $OAuthSignature = Set-OAuthSignature $HttpRequestType $HttpEndpoint $HttpQueryString $OAuthNonce $OAuthTimeStamp $OAuthConsumerKey $OAuthConsumerSecret $OAuthToken $OAuthTokenSecret $OAuthHeader = Set-OAuthHeader $OAuthConsumerKey $OAuthNonce $OAuthSignature $OAuthTimeStamp $OAuthToken [System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create($ApiURL) $request.Method = $HttpRequestType $request.UserAgent = $TwitterUserAgent $request.Timeout = $TwitterTimeOut $request.ContentType = "application/x-www-form-urlencoded" $request.Headers.Add("Authorization", $OAuthHeader) try { [System.Net.HttpWebResponse] $response = $request.GetResponse() if ( $response -ne $null ) { $ResponseStream = New-Object System.IO.StreamReader($response.GetResponseStream()) $ResponseStream.ReadToEnd().Trim() } $response.Close() } catch { $_.Exception.Message } } function Get-RawTwitterUserAsJson( [string] $UserName ) { # https://dev.twitter.com/docs/api/1.1/get/users/show # Get-RawTwitterUserAsJson cveira | ConvertFrom-Json [string] $HttpRequestType = "GET" [string] $HttpEndpoint = "" [string] $HttpQueryString = "" [string] $TwitterRawResponse = "" [string] $ApiURL = "http://api.twitter.com/1.1/users/show.json?screen_name=" + $UserName.Trim() + "&include_entities=true" if ( $ApiURL.IndexOf("?") -ne -1 ) { $HttpEndpoint = $ApiURL.Split("?")[0] $HttpQueryString = $ApiURL.Split("?")[1] } else { $HttpEndpoint = $ApiURL $HttpQueryString = "" } $OAuthConsumerKey = $TwitterConsumerKey $OAuthConsumerSecret = $TwitterConsumerSecret $OAuthToken = $TwitterAccessToken $OAuthTokenSecret = $TwitterAccessTokenSecret $OAuthNonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString())) $TimeStamp = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null).ToUniversalTime() $OAuthTimeStamp = [System.Convert]::ToInt64($TimeStamp.TotalSeconds).ToString() $OAuthSignature = Set-OAuthSignature $HttpRequestType $HttpEndpoint $HttpQueryString $OAuthNonce $OAuthTimeStamp $OAuthConsumerKey $OAuthConsumerSecret $OAuthToken $OAuthTokenSecret $OAuthHeader = Set-OAuthHeader $OAuthConsumerKey $OAuthNonce $OAuthSignature $OAuthTimeStamp $OAuthToken [System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create($ApiURL) $request.Method = $HttpRequestType $request.UserAgent = $TwitterUserAgent $request.Timeout = $TwitterTimeOut $request.ContentType = "application/x-www-form-urlencoded" $request.Headers.Add("Authorization", $OAuthHeader) try { [System.Net.HttpWebResponse] $response = $request.GetResponse() if ( $response -ne $null ) { $ResponseStream = New-Object System.IO.StreamReader($response.GetResponseStream()) $ResponseStream.ReadToEnd().Trim() } $response.Close() } catch { $_.Exception.Message } } function Get-RawTweetAsJson( [string] $TweetPermaLink ) { # https://dev.twitter.com/docs/api/1.1/get/statuses/show/%3Aid # Get-RawTweetAsJson https://twitter.com/cveira/status/275929500183830529 | ConvertFrom-Json [string] $HttpRequestType = "GET" [string] $HttpEndpoint = "" [string] $HttpQueryString = "" [string] $TwitterRawResponse = "" [string] $ApiURL = "http://api.twitter.com/1.1/statuses/show.json?id=" + $TweetPermaLink.Split("/")[5] + "&include_entities=true" if ( $ApiURL.IndexOf("?") -ne -1 ) { $HttpEndpoint = $ApiURL.Split("?")[0] $HttpQueryString = $ApiURL.Split("?")[1] } else { $HttpEndpoint = $ApiURL $HttpQueryString = "" } $OAuthConsumerKey = $TwitterConsumerKey $OAuthConsumerSecret = $TwitterConsumerSecret $OAuthToken = $TwitterAccessToken $OAuthTokenSecret = $TwitterAccessTokenSecret $OAuthNonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString())) $TimeStamp = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null).ToUniversalTime() $OAuthTimeStamp = [System.Convert]::ToInt64($TimeStamp.TotalSeconds).ToString() $OAuthSignature = Set-OAuthSignature $HttpRequestType $HttpEndpoint $HttpQueryString $OAuthNonce $OAuthTimeStamp $OAuthConsumerKey $OAuthConsumerSecret $OAuthToken $OAuthTokenSecret $OAuthHeader = Set-OAuthHeader $OAuthConsumerKey $OAuthNonce $OAuthSignature $OAuthTimeStamp $OAuthToken [System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create($ApiURL) $request.Method = $HttpRequestType $request.UserAgent = $TwitterUserAgent $request.Timeout = $TwitterTimeOut $request.ContentType = "application/x-www-form-urlencoded" $request.Headers.Add("Authorization", $OAuthHeader) try { [System.Net.HttpWebResponse] $response = $request.GetResponse() if ( $response -ne $null ) { $ResponseStream = New-Object System.IO.StreamReader($response.GetResponseStream()) $ResponseStream.ReadToEnd().Trim() } $response.Close() } catch { $_.Exception.Message } } function Get-RawTwitterFavoritesAsJson( [string] $UserName ) { # https://dev.twitter.com/docs/api/1.1/get/favorites/list # Get-RawTwitterFavoritesAsJson cveira | ConvertFrom-Json [string] $HttpRequestType = "GET" [string] $HttpEndpoint = "" [string] $HttpQueryString = "" [string] $TwitterRawResponse = "" [string] $ApiURL = "http://api.twitter.com/1.1/favorites/list.json?count=20&screen_name=" + $UserName.Trim() + "&include_entities=true" if ( $ApiURL.IndexOf("?") -ne -1 ) { $HttpEndpoint = $ApiURL.Split("?")[0] $HttpQueryString = $ApiURL.Split("?")[1] } else { $HttpEndpoint = $ApiURL $HttpQueryString = "" } $OAuthConsumerKey = $TwitterConsumerKey $OAuthConsumerSecret = $TwitterConsumerSecret $OAuthToken = $TwitterAccessToken $OAuthTokenSecret = $TwitterAccessTokenSecret $OAuthNonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString())) $TimeStamp = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null).ToUniversalTime() $OAuthTimeStamp = [System.Convert]::ToInt64($TimeStamp.TotalSeconds).ToString() $OAuthSignature = Set-OAuthSignature $HttpRequestType $HttpEndpoint $HttpQueryString $OAuthNonce $OAuthTimeStamp $OAuthConsumerKey $OAuthConsumerSecret $OAuthToken $OAuthTokenSecret $OAuthHeader = Set-OAuthHeader $OAuthConsumerKey $OAuthNonce $OAuthSignature $OAuthTimeStamp $OAuthToken [System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create($ApiURL) $request.Method = $HttpRequestType $request.UserAgent = $TwitterUserAgent $request.Timeout = $TwitterTimeOut $request.ContentType = "application/x-www-form-urlencoded" $request.Headers.Add("Authorization", $OAuthHeader) try { [System.Net.HttpWebResponse] $response = $request.GetResponse() if ( $response -ne $null ) { $ResponseStream = New-Object System.IO.StreamReader($response.GetResponseStream()) $ResponseStream.ReadToEnd().Trim() } $response.Close() } catch { $_.Exception.Message } } function Get-RawTweetsFromUserAsJson( [string] $UserName, [int] $results = 20, [string] $FirstId = "", [string] $LastId = "" ) { # https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline # Get-RawTweetsFromUserAsJson cveira | ConvertFrom-Json [string] $HttpRequestType = "GET" [string] $HttpEndpoint = "" [string] $HttpQueryString = "" [string] $TwitterRawResponse = "" [string] $FilterParameters = "" if ( ( $FirstId -ne "" ) -and ( $FirstId -match "\\d+" ) ) { $FilterParameters += "&max_id=" + $FirstId } if ( ( $LastId -ne "" ) -and ( $LastId -match "\\d+" ) ) { $FilterParameters += "&since_id=" + $LastId } [string] $ApiURL = "http://api.twitter.com/1.1/statuses/user_timeline.json?include_entities=true&include_rts=true&exclude_replies=true&count=" + $results + $FilterParameters + "&screen_name=" + $UserName.Trim() if ( $ApiURL.IndexOf("?") -ne -1 ) { $HttpEndpoint = $ApiURL.Split("?")[0] $HttpQueryString = $ApiURL.Split("?")[1] } else { $HttpEndpoint = $ApiURL $HttpQueryString = "" } $OAuthConsumerKey = $TwitterConsumerKey $OAuthConsumerSecret = $TwitterConsumerSecret $OAuthToken = $TwitterAccessToken $OAuthTokenSecret = $TwitterAccessTokenSecret $OAuthNonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString())) $TimeStamp = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null).ToUniversalTime() $OAuthTimeStamp = [System.Convert]::ToInt64($TimeStamp.TotalSeconds).ToString() $OAuthSignature = Set-OAuthSignature $HttpRequestType $HttpEndpoint $HttpQueryString $OAuthNonce $OAuthTimeStamp $OAuthConsumerKey $OAuthConsumerSecret $OAuthToken $OAuthTokenSecret $OAuthHeader = Set-OAuthHeader $OAuthConsumerKey $OAuthNonce $OAuthSignature $OAuthTimeStamp $OAuthToken [System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create($ApiURL) $request.Method = $HttpRequestType $request.UserAgent = $TwitterUserAgent $request.Timeout = $TwitterTimeOut $request.ContentType = "application/x-www-form-urlencoded" $request.Headers.Add("Authorization", $OAuthHeader) try { [System.Net.HttpWebResponse] $response = $request.GetResponse() if ( $response -ne $null ) { $ResponseStream = New-Object System.IO.StreamReader($response.GetResponseStream()) $ResponseStream.ReadToEnd().Trim() } $response.Close() } catch { $_.Exception.Message } } function Get-RawTwitterTimeLineAsJson { # https://dev.twitter.com/docs/api/1.1/get/statuses/home_timeline # Get-RawTwitterTimeLineAsJson | ConvertFrom-Json [string] $HttpRequestType = "GET" [string] $HttpEndpoint = "" [string] $HttpQueryString = "" [string] $TwitterRawResponse = "" [string] $ApiURL = "http://api.twitter.com/1.1/statuses/home_timeline.json?include_entities=true&count=20" if ( $ApiURL.IndexOf("?") -ne -1 ) { $HttpEndpoint = $ApiURL.Split("?")[0] $HttpQueryString = $ApiURL.Split("?")[1] } else { $HttpEndpoint = $ApiURL $HttpQueryString = "" } $OAuthConsumerKey = $TwitterConsumerKey $OAuthConsumerSecret = $TwitterConsumerSecret $OAuthToken = $TwitterAccessToken $OAuthTokenSecret = $TwitterAccessTokenSecret $OAuthNonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString())) $TimeStamp = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null).ToUniversalTime() $OAuthTimeStamp = [System.Convert]::ToInt64($TimeStamp.TotalSeconds).ToString() $OAuthSignature = Set-OAuthSignature $HttpRequestType $HttpEndpoint $HttpQueryString $OAuthNonce $OAuthTimeStamp $OAuthConsumerKey $OAuthConsumerSecret $OAuthToken $OAuthTokenSecret $OAuthHeader = Set-OAuthHeader $OAuthConsumerKey $OAuthNonce $OAuthSignature $OAuthTimeStamp $OAuthToken [System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create($ApiURL) $request.Method = $HttpRequestType $request.UserAgent = $TwitterUserAgent $request.Timeout = $TwitterTimeOut $request.ContentType = "application/x-www-form-urlencoded" $request.Headers.Add("Authorization", $OAuthHeader) try { [System.Net.HttpWebResponse] $response = $request.GetResponse() if ( $response -ne $null ) { $ResponseStream = New-Object System.IO.StreamReader($response.GetResponseStream()) $ResponseStream.ReadToEnd().Trim() } $response.Close() } catch { $_.Exception.Message } } function Get-RawTwitterSearchAsJson( [string] $query, [int] $ResultsPerPage = 20, [string] $Language = "", [string] $ResultType = "", [string] $StartDate = "", [string] $GeoCode = "", [int64] $SinceId = 0, [int64] $MaxId = 0 ) { # https://dev.twitter.com/docs/api/1.1/get/search/tweets # https://dev.twitter.com/docs/using-search # https://dev.twitter.com/docs/working-with-timelines # Get-RawTwitterSearchAsJson cveira | ConvertFrom-Json [string] $HttpRequestType = "GET" [string] $HttpEndpoint = "" [string] $HttpQueryString = "" [string] $TwitterRawResponse = "" [string] $SearchParameters = "include_entities=true" if ( $ResultType -eq "" ) { $SearchParameters += "&result_type=mixed" } else { switch ( $ResultType ) { "mixed" { $SearchParameters += "&result_type=mixed" } "recent" { $SearchParameters += "&result_type=recent" } "popular" { $SearchParameters += "&result_type=popular" } default { $SearchParameters += "&result_type=mixed" } } } if ( ( $StartDate -ne "" ) -and ( $StartDate -match "\\d{4}-\\d{2}-\\d{2}" ) ) { $SearchParameters += "&until=" + $StartDate } if ( ( $GeoCode -ne "" ) -and ( $GeoCode -match "(\\-*[\\d\\.]+),(\\-*[\\d\\.]+),(\\d+)(km|mi)" ) ) { $SearchParameters += "&geocode=" + $GeoCode } if ( $SinceId -ne 0 ) { $SearchParameters += "&since_id=" + $SinceId } if ( $MaxId -ne 0 ) { $SearchParameters += "&max_id=" + $MaxId } $SearchParameters += "&count=" + $ResultsPerPage + "&q=" [string] $ApiURL = "http://api.twitter.com/1.1/search/tweets.json?" + $SearchParameters + [System.Uri]::EscapeDataString($query.Trim()) if ( $ApiURL.IndexOf("?") -ne -1 ) { $HttpEndpoint = $ApiURL.Split("?")[0] $HttpQueryString = $ApiURL.Split("?")[1] } else { $HttpEndpoint = $ApiURL $HttpQueryString = "" } $OAuthConsumerKey = $TwitterConsumerKey $OAuthConsumerSecret = $TwitterConsumerSecret $OAuthToken = $TwitterAccessToken $OAuthTokenSecret = $TwitterAccessTokenSecret $OAuthNonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString())) $TimeStamp = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null).ToUniversalTime() $OAuthTimeStamp = [System.Convert]::ToInt64($TimeStamp.TotalSeconds).ToString() $OAuthSignature = Set-OAuthSignature $HttpRequestType $HttpEndpoint $HttpQueryString $OAuthNonce $OAuthTimeStamp $OAuthConsumerKey $OAuthConsumerSecret $OAuthToken $OAuthTokenSecret $OAuthHeader = Set-OAuthHeader $OAuthConsumerKey $OAuthNonce $OAuthSignature $OAuthTimeStamp $OAuthToken [System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create($ApiURL) $request.Method = $HttpRequestType $request.UserAgent = $TwitterUserAgent $request.Timeout = $TwitterTimeOut $request.ContentType = "application/x-www-form-urlencoded" $request.Headers.Add("Authorization", $OAuthHeader) try { [System.Net.HttpWebResponse] $response = $request.GetResponse() if ( $response -ne $null ) { $ResponseStream = New-Object System.IO.StreamReader($response.GetResponseStream()) $ResponseStream.ReadToEnd().Trim() } $response.Close() } catch { $_.Exception.Message } } function Send-Tweet ( [string] $TweetMessage ) { # https://dev.twitter.com/docs/api/1.1/post/statuses/update # Send-Tweet "This is my first Tweet from #PowerShell using, raw #DotNet and #OAuth!" [string] $HttpRequestType = "POST" [string] $HttpEndpoint = "" [string] $HttpQueryString = "" [string] $TwitterRawResponse = "" [string] $ApiURL = "http://api.twitter.com/1.1/statuses/update.json" if ( $TweetMessage.Length -gt 140 ) { $TweetMessage = $TweetMessage.Substring(0,140) } # Body POST Data format is NOT documented! # look at how the supplied example looks like @ https://dev.twitter.com/docs/api/1.1/post/statuses/update [byte[]] $HttpPostBody = [System.Text.Encoding]::UTF8.GetBytes( "status=" + ( EscapeDataStringRfc3986 ($TweetMessage) ) ) $HttpEndpoint = $ApiURL # The 'status' parameter gets encoded TWICE in the OAuth signature. This detail is NOT documented! # Run an example with the OAuth Tool and look at the results for the OAuth signature. # [System.Uri]::EscapeDataString() is not RFC3986 compliant in .NET < 4.x! # RFC3986 compliancy is documented in OAuth 1.0A, not in Twitter documentation! $HttpQueryString = "status=" + (EscapeDataStringRfc3986 $TweetMessage) $OAuthConsumerKey = $TwitterConsumerKey $OAuthConsumerSecret = $TwitterConsumerSecret $OAuthToken = $TwitterAccessToken $OAuthTokenSecret = $TwitterAccessTokenSecret $OAuthNonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString())) $TimeStamp = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null).ToUniversalTime() $OAuthTimeStamp = [System.Convert]::ToInt64($TimeStamp.TotalSeconds).ToString() $OAuthSignature = Set-OAuthSignature $HttpRequestType $HttpEndpoint $HttpQueryString $OAuthNonce $OAuthTimeStamp $OAuthConsumerKey $OAuthConsumerSecret $OAuthToken $OAuthTokenSecret $OAuthHeader = Set-OAuthHeader $OAuthConsumerKey $OAuthNonce $OAuthSignature $OAuthTimeStamp $OAuthToken [System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create($ApiURL) $request.Method = $HttpRequestType $request.UserAgent = $TwitterUserAgent $request.Timeout = $TwitterTimeOut $request.ContentType = "application/x-www-form-urlencoded" $request.ContentLength = $HttpPostBody.Length $request.ServicePoint.Expect100Continue = $false $request.Headers.Add("Authorization", $OAuthHeader) try { [System.IO.Stream] $RequestBody = $request.GetRequestStream() $RequestBody.Write($HttpPostBody, 0, $HttpPostBody.Length) # $RequestBody.Flush() $RequestBody.Close() [System.Net.HttpWebResponse] $response = $request.GetResponse() if ( $response -ne $null ) { $ResponseStream = New-Object System.IO.StreamReader($response.GetResponseStream()) $ResponseStream.ReadToEnd().Trim() } $response.Close() } catch { $_.Exception.Message } } function Get-RawTwitterListSubscribersAsJson( [string] $TweetPermaLink, [string] $PageId = "-1" ) { # https://dev.twitter.com/docs/api/1.1/get/lists/subscribers # Get-RawTwitterListSubscribersAsJson https://twitter.com/cveira/cloud | ConvertFrom-Json [string] $HttpRequestType = "GET" [string] $HttpEndpoint = "" [string] $HttpQueryString = "" [string] $TwitterRawResponse = "" [string] $ApiURL = "http://api.twitter.com/1.1/lists/subscribers.json?slug=" + $TweetPermaLink.Split("/")[4] + "&owner_screen_name=" + $TweetPermaLink.Split("/")[3] + "&include_entities=true&cursor=" + $PageId + "&skip_status=true" if ( $ApiURL.IndexOf("?") -ne -1 ) { $HttpEndpoint = $ApiURL.Split("?")[0] $HttpQueryString = $ApiURL.Split("?")[1] } else { $HttpEndpoint = $ApiURL $HttpQueryString = "" } $OAuthConsumerKey = $TwitterConsumerKey $OAuthConsumerSecret = $TwitterConsumerSecret $OAuthToken = $TwitterAccessToken $OAuthTokenSecret = $TwitterAccessTokenSecret $OAuthNonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString())) $TimeStamp = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null).ToUniversalTime() $OAuthTimeStamp = [System.Convert]::ToInt64($TimeStamp.TotalSeconds).ToString() $OAuthSignature = Set-OAuthSignature $HttpRequestType $HttpEndpoint $HttpQueryString $OAuthNonce $OAuthTimeStamp $OAuthConsumerKey $OAuthConsumerSecret $OAuthToken $OAuthTokenSecret $OAuthHeader = Set-OAuthHeader $OAuthConsumerKey $OAuthNonce $OAuthSignature $OAuthTimeStamp $OAuthToken [System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create($ApiURL) $request.Method = $HttpRequestType $request.UserAgent = $TwitterUserAgent $request.Timeout = $TwitterTimeOut $request.ContentType = "application/x-www-form-urlencoded" $request.Headers.Add("Authorization", $OAuthHeader) try { [System.Net.HttpWebResponse] $response = $request.GetResponse() if ( $response -ne $null ) { $ResponseStream = New-Object System.IO.StreamReader($response.GetResponseStream()) $ResponseStream.ReadToEnd().Trim() } $response.Close() } catch { $_.Exception.Message } } function Get-RawTwitterListMembersAsJson( [string] $TweetPermaLink, [string] $PageId = "-1" ) { # https://dev.twitter.com/docs/api/1.1/get/lists/members # Get-RawTwitterListMembersAsJson https://twitter.com/cveira/cloud | ConvertFrom-Json [string] $HttpRequestType = "GET" [string] $HttpEndpoint = "" [string] $HttpQueryString = "" [string] $TwitterRawResponse = "" [string] $ApiURL = "http://api.twitter.com/1.1/lists/members.json?slug=" + $TweetPermaLink.Split("/")[4] + "&owner_screen_name=" + $TweetPermaLink.Split("/")[3] + "&include_entities=true&cursor=" + $PageId + "&skip_status=true" if ( $ApiURL.IndexOf("?") -ne -1 ) { $HttpEndpoint = $ApiURL.Split("?")[0] $HttpQueryString = $ApiURL.Split("?")[1] } else { $HttpEndpoint = $ApiURL $HttpQueryString = "" } $OAuthConsumerKey = $TwitterConsumerKey $OAuthConsumerSecret = $TwitterConsumerSecret $OAuthToken = $TwitterAccessToken $OAuthTokenSecret = $TwitterAccessTokenSecret $OAuthNonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString())) $TimeStamp = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null).ToUniversalTime() $OAuthTimeStamp = [System.Convert]::ToInt64($TimeStamp.TotalSeconds).ToString() $OAuthSignature = Set-OAuthSignature $HttpRequestType $HttpEndpoint $HttpQueryString $OAuthNonce $OAuthTimeStamp $OAuthConsumerKey $OAuthConsumerSecret $OAuthToken $OAuthTokenSecret $OAuthHeader = Set-OAuthHeader $OAuthConsumerKey $OAuthNonce $OAuthSignature $OAuthTimeStamp $OAuthToken [System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create($ApiURL) $request.Method = $HttpRequestType $request.UserAgent = $TwitterUserAgent $request.Timeout = $TwitterTimeOut $request.ContentType = "application/x-www-form-urlencoded" $request.Headers.Add("Authorization", $OAuthHeader) try { [System.Net.HttpWebResponse] $response = $request.GetResponse() if ( $response -ne $null ) { $ResponseStream = New-Object System.IO.StreamReader($response.GetResponseStream()) $ResponseStream.ReadToEnd().Trim() } $response.Close() } catch { $_.Exception.Message } } function Get-RawTwitterListTimeLineAsJson( [string] $TweetPermaLink, [int] $ResultsPerPage = 20 ) { # https://dev.twitter.com/docs/api/1.1/get/lists/statuses # Get-RawTwitterListTimeLineAsJson https://twitter.com/cveira/cloud | ConvertFrom-Json [string] $HttpRequestType = "GET" [string] $HttpEndpoint = "" [string] $HttpQueryString = "" [string] $TwitterRawResponse = "" [string] $ApiURL = "http://api.twitter.com/1.1/lists/statuses.json?slug=" + $TweetPermaLink.Split("/")[4] + "&owner_screen_name=" + $TweetPermaLink.Split("/")[3] + "&count=" + $ResultsPerPage + "&include_entities=true&include_rts=true" if ( $ApiURL.IndexOf("?") -ne -1 ) { $HttpEndpoint = $ApiURL.Split("?")[0] $HttpQueryString = $ApiURL.Split("?")[1] } else { $HttpEndpoint = $ApiURL $HttpQueryString = "" } $OAuthConsumerKey = $TwitterConsumerKey $OAuthConsumerSecret = $TwitterConsumerSecret $OAuthToken = $TwitterAccessToken $OAuthTokenSecret = $TwitterAccessTokenSecret $OAuthNonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString())) $TimeStamp = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null).ToUniversalTime() $OAuthTimeStamp = [System.Convert]::ToInt64($TimeStamp.TotalSeconds).ToString() $OAuthSignature = Set-OAuthSignature $HttpRequestType $HttpEndpoint $HttpQueryString $OAuthNonce $OAuthTimeStamp $OAuthConsumerKey $OAuthConsumerSecret $OAuthToken $OAuthTokenSecret $OAuthHeader = Set-OAuthHeader $OAuthConsumerKey $OAuthNonce $OAuthSignature $OAuthTimeStamp $OAuthToken [System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create($ApiURL) $request.Method = $HttpRequestType $request.UserAgent = $TwitterUserAgent $request.Timeout = $TwitterTimeOut $request.ContentType = "application/x-www-form-urlencoded" $request.Headers.Add("Authorization", $OAuthHeader) try { [System.Net.HttpWebResponse] $response = $request.GetResponse() if ( $response -ne $null ) { $ResponseStream = New-Object System.IO.StreamReader($response.GetResponseStream()) $ResponseStream.ReadToEnd().Trim() } $response.Close() } catch { $_.Exception.Message } } function Get-RawTwitterUserFriendsFromUserAsJson( [string] $UserName, [string] $PageId = "-1" ) { # https://dev.twitter.com/docs/api/1.1/get/friends/list # Get-RawTwitterUserFriendsFromUserAsJson cveira | ConvertFrom-Json [string] $HttpRequestType = "GET" [string] $HttpEndpoint = "" [string] $HttpQueryString = "" [string] $TwitterRawResponse = "" [string] $ApiURL = "http://api.twitter.com/1.1/friends/list.json?screen_name=" + $UserName.Trim() + "&include_entities=true&cursor=" + $PageId + "&skip_status=true" if ( $ApiURL.IndexOf("?") -ne -1 ) { $HttpEndpoint = $ApiURL.Split("?")[0] $HttpQueryString = $ApiURL.Split("?")[1] } else { $HttpEndpoint = $ApiURL $HttpQueryString = "" } $OAuthConsumerKey = $TwitterConsumerKey $OAuthConsumerSecret = $TwitterConsumerSecret $OAuthToken = $TwitterAccessToken $OAuthTokenSecret = $TwitterAccessTokenSecret $OAuthNonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString())) $TimeStamp = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null).ToUniversalTime() $OAuthTimeStamp = [System.Convert]::ToInt64($TimeStamp.TotalSeconds).ToString() $OAuthSignature = Set-OAuthSignature $HttpRequestType $HttpEndpoint $HttpQueryString $OAuthNonce $OAuthTimeStamp $OAuthConsumerKey $OAuthConsumerSecret $OAuthToken $OAuthTokenSecret $OAuthHeader = Set-OAuthHeader $OAuthConsumerKey $OAuthNonce $OAuthSignature $OAuthTimeStamp $OAuthToken [System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create($ApiURL) $request.Method = $HttpRequestType $request.UserAgent = $TwitterUserAgent $request.Timeout = $TwitterTimeOut $request.ContentType = "application/x-www-form-urlencoded" $request.Headers.Add("Authorization", $OAuthHeader) try { [System.Net.HttpWebResponse] $response = $request.GetResponse() if ( $response -ne $null ) { $ResponseStream = New-Object System.IO.StreamReader($response.GetResponseStream()) $ResponseStream.ReadToEnd().Trim() } $response.Close() } catch { $_.Exception.Message } } function Get-RawTwitterFollowersFromUserAsJson( [string] $UserName, [string] $PageId = "-1" ) { # https://dev.twitter.com/docs/api/1.1/get/followers/list # Get-RawTwitterFollowersFromUserAsJson cveira | ConvertFrom-Json [string] $HttpRequestType = "GET" [string] $HttpEndpoint = "" [string] $HttpQueryString = "" [string] $TwitterRawResponse = "" [string] $ApiURL = "http://api.twitter.com/1.1/followers/list.json?screen_name=" + $UserName.Trim() + "&include_entities=true&cursor=" + $PageId + "&skip_status=true" if ( $ApiURL.IndexOf("?") -ne -1 ) { $HttpEndpoint = $ApiURL.Split("?")[0] $HttpQueryString = $ApiURL.Split("?")[1] } else { $HttpEndpoint = $ApiURL $HttpQueryString = "" } $OAuthConsumerKey = $TwitterConsumerKey $OAuthConsumerSecret = $TwitterConsumerSecret $OAuthToken = $TwitterAccessToken $OAuthTokenSecret = $TwitterAccessTokenSecret $OAuthNonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString())) $TimeStamp = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null).ToUniversalTime() $OAuthTimeStamp = [System.Convert]::ToInt64($TimeStamp.TotalSeconds).ToString() $OAuthSignature = Set-OAuthSignature $HttpRequestType $HttpEndpoint $HttpQueryString $OAuthNonce $OAuthTimeStamp $OAuthConsumerKey $OAuthConsumerSecret $OAuthToken $OAuthTokenSecret $OAuthHeader = Set-OAuthHeader $OAuthConsumerKey $OAuthNonce $OAuthSignature $OAuthTimeStamp $OAuthToken [System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create($ApiURL) $request.Method = $HttpRequestType $request.UserAgent = $TwitterUserAgent $request.Timeout = $TwitterTimeOut $request.ContentType = "application/x-www-form-urlencoded" $request.Headers.Add("Authorization", $OAuthHeader) try { [System.Net.HttpWebResponse] $response = $request.GetResponse() if ( $response -ne $null ) { $ResponseStream = New-Object System.IO.StreamReader($response.GetResponseStream()) $ResponseStream.ReadToEnd().Trim() } $response.Close() } catch { $_.Exception.Message } } function Get-RawTwitterUserAsJson( [string] $UserName ) { # https://dev.twitter.com/docs/api/1.1/get/users/show # Get-RawTwitterUserAsJson cveira | ConvertFrom-Json [string] $HttpRequestType = "GET" [string] $HttpEndpoint = "" [string] $HttpQueryString = "" [string] $TwitterRawResponse = "" [string] $ApiURL = "http://api.twitter.com/1.1/users/show.json?screen_name=" + $UserName.Trim() + "&include_entities=true" if ( $ApiURL.IndexOf("?") -ne -1 ) { $HttpEndpoint = $ApiURL.Split("?")[0] $HttpQueryString = $ApiURL.Split("?")[1] } else { $HttpEndpoint = $ApiURL $HttpQueryString = "" } $OAuthConsumerKey = $TwitterConsumerKey $OAuthConsumerSecret = $TwitterConsumerSecret $OAuthToken = $TwitterAccessToken $OAuthTokenSecret = $TwitterAccessTokenSecret $OAuthNonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString())) $TimeStamp = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null).ToUniversalTime() $OAuthTimeStamp = [System.Convert]::ToInt64($TimeStamp.TotalSeconds).ToString() $OAuthSignature = Set-OAuthSignature $HttpRequestType $HttpEndpoint $HttpQueryString $OAuthNonce $OAuthTimeStamp $OAuthConsumerKey $OAuthConsumerSecret $OAuthToken $OAuthTokenSecret $OAuthHeader = Set-OAuthHeader $OAuthConsumerKey $OAuthNonce $OAuthSignature $OAuthTimeStamp $OAuthToken [System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create($ApiURL) $request.Method = $HttpRequestType $request.UserAgent = $TwitterUserAgent $request.Timeout = $TwitterTimeOut $request.ContentType = "application/x-www-form-urlencoded" $request.Headers.Add("Authorization", $OAuthHeader) try { [System.Net.HttpWebResponse] $response = $request.GetResponse() if ( $response -ne $null ) { $ResponseStream = New-Object System.IO.StreamReader($response.GetResponseStream()) $ResponseStream.ReadToEnd().Trim() } $response.Close() } catch { $_.Exception.Message } } # -------------------------------------------------------------------------------------------------- function Get-TwitterProfile( [string] $UserName ) { Get-RawTwitterUserAsJson $UserName | ConvertFrom-JSON } function Get-UnpagedFollowerList( [object[]] $PagedFollowersList ) { $UnpagedFollowers = @() $PagedFollowersList | ForEach-Object { $UnpagedFollowers += $_.users } $UnpagedFollowers = $UnpagedFollowers | Select-Object * -unique $UnpagedFollowers } function Get-TwitterFollowers( [string] $UserName ) { begin { [PSCustomObject[]] $RawFollowersPages = @() $CurrentPage = $null $TimeToWait = 66 $FollowersPerPage = 20 $PageCount = 0 [int] $TotalFollowers = ( Get-RawTwitterUserAsJson $UserName | ConvertFrom-JSON ).followers_count } process { try { $PageCount = 1 $CurrentPage = Get-RawTwitterFollowersFromUserAsJson $UserName | ConvertFrom-JSON $RawFollowersPages += $CurrentPage do { Write-Progress -Activity "Retrieving Followers ..." -Status "Progress: " -PercentComplete ( (($PageCount * $FollowersPerPage) / $TotalFollowers) * 100 ) $PageCount++ $RawFollowersPages += $CurrentPage Start-Sleep -Seconds $TimeToWait $CurrentPage = Get-RawTwitterFollowersFromUserAsJson $UserName -PageId $CurrentPage.next_cursor | ConvertFrom-JSON } until ( $CurrentPage.next_cursor -eq 0 ) } catch { [PSCustomObject[]] $RawFollowersPages = @() $_.Exception.Message } } end { Get-UnpagedFollowerList $RawFollowersPages # $RawFollowersPages } } function Get-TweetsFromUser( [string] $UserName, [int] $results = 20, [switch] $quick, [switch] $IncludeAll ) { # Get-TweetsFromUser cveira -results 250 -quick # $DebugPreference = "Continue" [PSObject[]] $TimeLine = @() [PSObject[]] $tweets = @() $SourcePattern = '((?s)<a[^>]*[^>]*>(?<TweetSource>.*?)</a>)' $TwitterMaxResults = 100 $TimeToWait = 6 $ExtendedTimeToWait = 0 $TimeToWaitForRTs = 66 $TimeToWaitForFavs = 66 $IncludeRTs = $false $IncludeFavorites = $false if ( $quick ) { $IncludeAll = $false $IncludeRTs = $false $IncludeFavorites = $false } elseif ( $IncludeAll ) { $IncludeRTs = $true $IncludeFavorites = $true } if ( $TimeToWaitForRTs -ge $TimeToWaitForFavs ) { $ExtendedTimeToWait = $TimeToWaitForRTs } else { $ExtendedTimeToWait = $TimeToWaitForFavs } if ( $results -lt $TwitterMaxResults ) { $tweets = Get-RawTweetsFromUserAsJson -UserName $UserName -results $results | ConvertFrom-Json } else { do { Write-Progress -Activity "Retrieving Tweets ..." -Status "Progress: $($tweets.Count) / $results" -PercentComplete ( ( $($tweets.Count) / $results ) * 100 ) $CurrentTweets = Get-RawTweetsFromUserAsJson -UserName $UserName -results $TwitterMaxResults -FirstId $LastId | ConvertFrom-Json Write-Debug "[INFO] Retrieved Tweets: $($tweets.Count)" Write-Debug "[INFO] CurrentTweets count: $($CurrentTweets.Count)" Write-Debug "[INFO] LastId: $LastId" Write-Debug "[INFO] FirstId: $($CurrentTweets[0].id)" if ( $CurrentTweets[0].id -eq $LastId ) { $FirstTweet = 1 } else { $FirstTweet = 0 } $LastId = $CurrentTweets[ ( $CurrentTweets.Count - 1 ) ].id $tweets += $CurrentTweets[ $FirstTweet..($CurrentTweets.Count - 1) ] Start-Sleep -Seconds $TimeToWait } until ( $tweets.Count -gt $results ) $tweets = $tweets[0..( $results - 1 )] } if ( $quick ) { $tweets } else { $i = 1 $tweets | ForEach-Object { if ( $IncludeAll ) { Write-Progress -Activity "Normalizing Information ..." -Status "Progress: $i / $results - ETC: $( (( $results - $i ) * ( $TimeToWaitForRTs + $TimeToWaitForFavs )) / 60 ) minutes - Time Elapsed: $( (( $i - 1 ) * ( $TimeToWaitForRTs + $TimeToWaitForFavs )) / 60 ) minutes" -PercentComplete ( ( $i / $results ) * 100 ) } else { Write-Progress -Activity "Normalizing Information ..." -Status "Progress: $i / $results" -PercentComplete ( ( $i / $results ) * 100 ) } $NewTweet = $_ $NewTweet.user = $NewTweet.user.screen_name if ( $NewTweet.source -match $SourcePattern ) { $NewTweet.source = $Matches.TweetSource } Write-Debug ".Links not exists: $( $NewTweet.Links -eq $null )" if ( $NewTweet.Links -eq $null ) { $NewTweet | Add-Member -NotePropertyName Links -NotePropertyValue $NewTweet.entities.urls.expanded_url } else { $NewTweet.Links = $NewTweet.entities.urls.expanded_url } Write-Debug ".HashTags not exists: $( $null -eq $NewTweet.HashTags )" if ( $null -eq $NewTweet.HashTags ) { $NewTweet | Add-Member -NotePropertyName HashTags -NotePropertyValue $NewTweet.entities.hashtags.text -force } else { $NewTweet.HashTags = $NewTweet.entities.hashtags.text } Write-Debug ".Mentions not exists: $( $null -eq $NewTweet.Mentions )" if ( $null -eq $NewTweet.Mentions ) { $NewTweet | Add-Member -NotePropertyName Mentions -NotePropertyValue $NewTweet.entities.user_mentions.screen_name -force } else { $NewTweet.Mentions = $NewTweet.entities.user_mentions.screen_name } Write-Debug ".PermaLink not exists: $( $NewTweet.PermaLink -eq $null )" if ( $NewTweet.retweeted_status.user.screen_name -eq $null ) { if ( $NewTweet.PermaLink -eq $null ) { $NewTweet | Add-Member -NotePropertyName PermaLink -NotePropertyValue "https://twitter.com/$($NewTweet.user)/status/$($NewTweet.id)" } else { $NewTweet.PermaLink = "https://twitter.com/$($NewTweet.user)/status/$($NewTweet.id)" } } else { if ( $NewTweet.PermaLink -eq $null ) { $NewTweet | Add-Member -NotePropertyName PermaLink -NotePropertyValue "https://twitter.com/$($NewTweet.retweeted_status.user.screen_name)/status/$($NewTweet.retweeted_status.id)" } else { $NewTweet.PermaLink = "https://twitter.com/$($NewTweet.retweeted_status.user.screen_name)/status/$($NewTweet.retweeted_status.id)" } } Write-Debug "[INFO] PermaLink: $($NewTweet.PermaLink)" if ( $IncludeRTs ) { if ( $IncludeAll ) { Write-Progress -Activity "Retrieving Retweets ..." -Status "Progress: $i / $results - ETC: $( (( $results - $i ) * ( $TimeToWaitForRTs + $TimeToWaitForFavs )) / 60 ) minutes - Time Elapsed: $( (( $i - 1 ) * ( $TimeToWaitForRTs + $TimeToWaitForFavs )) / 60 ) minutes" -PercentComplete ( ( $i / $results ) * 100 ) } else { Write-Progress -Activity "Retrieving Retweets ..." -Status "Progress: $i / $results" -PercentComplete ( ( $i / $results ) * 100 ) } Write-Debug ".retweets not exists: $( $NewTweet.entities.retweets -eq $null )" if ( $NewTweet.entities.retweets -eq $null ) { $NewTweet.entities | Add-Member -NotePropertyName retweets -NotePropertyValue @() } else { $NewTweet.entities.retweets = @() } Write-Debug ".Interactions not exists: $( $NewTweet.Interactions -eq $null )" if ( $NewTweet.Interactions -eq $null ) { $NewTweet | Add-Member -NotePropertyName Interactions -NotePropertyValue @() } else { $NewTweet.Interactions = @() } $NewTweet.entities.retweets = Get-RawTweetRetweetsAsJson $NewTweet.PermaLink | ConvertFrom-Json # $NewTweet.retweet_count = $NewTweet.entities.retweets.Count $NewTweet.Interactions += $NewTweet.entities.retweets | ForEach-Object { New-Object PSObject -Property @{ screen_name = $_.user.screen_name location = $_.user.location } } Write-Debug "[INFO] Retrieved Retweets: $($NewTweet.entities.retweets.Count)" Write-Debug "[INFO] Interactions: $($NewTweet.Interactions.Count)" } if ( $IncludeFavorites ) { if ( $IncludeAll ) { Write-Progress -Activity "Retrieving Favorites ..." -Status "Progress: $i / $results - ETC: $( (( $results - $i ) * ( $TimeToWaitForRTs + $TimeToWaitForFavs )) / 60 ) minutes - Time Elapsed: $( (( $i - 1 ) * ( $TimeToWaitForRTs + $TimeToWaitForFavs )) / 60 ) minutes" -PercentComplete ( ( $i / $results ) * 100 ) } else { Write-Progress -Activity "Retrieving Favorites ..." -Status "Progress: $i / $results" -PercentComplete ( ( $i / $results ) * 100 ) } Write-Debug ".favorites_count not exists: $( $NewTweet.favorites_count -eq $null )" if ( $NewTweet.favorites_count -eq $null ) { $NewTweet | Add-Member -NotePropertyName favorites_count -NotePropertyValue 0 } else { $NewTweet.favorites_count = 0 } $SourceCode = Get-PageSourceCode $NewTweet.PermaLink $NewTweet.favorites_count = Get-TweetFavoritesFromPage ([ref] $SourceCode) Write-Debug "[INFO] Retrieved Favorites: $($NewTweet.favorites_count)" } if ( $IncludeAll ) { Start-Sleep -Seconds $ExtendedTimeToWait } $TimeLine += $NewTweet $i++ } $TimeLine } # $DebugPreference = "SilentlyContinue" } function Normalize-TwitterTimeLine( [PSObject[]] $TimeLine, [switch] $IncludeAll ) { # $TimeLine = Normalize-TwitterTimeLine $tweets -IncludeAll # $DebugPreference = "Continue" [PSObject[]] $NewTimeLine = @() $TimeToWait = 0 $TimeToWaitForRTs = 66 $TimeToWaitForFavs = 66 $SourcePattern = '((?s)<a[^>]*[^>]*>(?<TweetSource>.*?)</a>)' $i = 1 $IncludeRTs = $false $IncludeFavorites = $false if ( $IncludeAll ) { $IncludeRTs = $true $IncludeFavorites = $true } if ( $TimeToWaitForRTs -ge $TimeToWaitForFavs ) { $TimeToWait = $TimeToWaitForRTs } else { $TimeToWait = $TimeToWaitForFavs } $TimeLine | ForEach-Object { $NewTweet = $_ if ( $IncludeAll ) { Write-Progress -Activity "Normalizing Information ..." -Status "Progress: $i / $($TimeLine.Count) - ETC: $( (( $TimeLine.Count - $i ) * ( $TimeToWaitForRTs + $TimeToWaitForFavs )) / 60 ) minutes - Time Elapsed: $( (( $i - 1 ) * ( $TimeToWaitForRTs + $TimeToWaitForFavs )) / 60 ) minutes" -PercentComplete ( ( $i / $TimeLine.Count ) * 100 ) } else { Write-Progress -Activity "Normalizing Information ..." -Status "Progress: $i / $($TimeLine.Count)" -PercentComplete ( ( $i / $TimeLine.Count ) * 100 ) } $NewTweet.user = $NewTweet.user.screen_name if ( $NewTweet.source -match $SourcePattern ) { $NewTweet.source = $Matches.TweetSource } Write-Debug ".Links not exists: $( $NewTweet.Links -eq $null )" if ( $NewTweet.Links -e
PowerShellCorpus/PoshCode/Get_Set Signature (CTP2)_4.ps1
Get_Set Signature (CTP2)_4.ps1
#Requires -version 2.0 ## Authenticode.psm1 updated for CTP 3 #################################################################################################### ## Wrappers for the Get-AuthenticodeSignature and Set-AuthenticodeSignature cmdlets ## These properly parse paths, so they don't kill your pipeline and script if you include a folder ## ## Usage: ## ls | Get-AuthenticodeSignature ## Get all the signatures ## ## ls | Select-Signed -Mine -Broken | Set-AuthenticodeSignature ## Re-sign anything you signed before that has changed ## ## ls | Select-Signed -NotMine -ValidOnly | Set-AuthenticodeSignature ## Re-sign scripts that are hash-correct but not signed by me or by someone trusted ## #################################################################################################### ## History: ## 1.5 - Moved the default certificate setting into the module info Authenticode.psd1 file ## Note: If you get this off PoshCode, you'll have to create it yourself, see below: ## 1.4 - Moved the default certificate setting into an external psd1 file. ## 1.3 - Fixed some bugs in If-Signed and renamed it to Select-Signed ## - Added -MineOnly and -NotMineOnly switches to Select-Signed ## 1.2 - Added a hack workaround to make it appear as though we can sign and check PSM1 files ## It's important to remember that the signatures are NOT checked by PowerShell yet... ## 1.1 - Added a filter "If-Signed" that can be used like: ls | If-Signed ## - With optional switches: ValidOnly, InvalidOnly, BrokenOnly, TrustedOnly, UnsignedOnly ## - commented out the default Certificate which won't work for "you" ## 1.0 - first working version, includes wrappers for Get and Set ## #################################################################################################### ## README! README! README! README! ################################################################# ## README! README! README! README! ################################################################# ## ## You should set the location to your default signing certificate. The permanent way to do that is ## to modify (or create) the .psd1 file to set the PrivateData member variable. Otherwise you'll be ## prompted to provide a cert path whenever you try to sign a script without passing a certificate. ## ## The PrivateData variable should point at your code-signing certificate either with a full path ## or with the THUMBPRINT of a certificate you have available in your Cert:\\CurrentUser\\My\\ provider ## ## EG: ## F05F583BB5EA4C90E3B9BF1BDD0B657701245BD5 ## OR: ## "Cert:\\CurrentUser\\My\\F05F583BB5EA4C90E3B9BF1BDD0B657701245BD5" ## OR a file name: ## "C:\\Users\\Joel\\Documents\\WindowsPowerShell\\PoshCerts\\Joel-Bennett_Code-Signing.pfx" ## ## The simplest thing is to just create a new PSD1 ## ## New-ModuleManifest .\\Authenticode.psd1 -Nested .\\Authenticode.psm1 ` ## -Author "" -COmpany "" -Copy "" -Desc "" ` ## -Types @() -Formats @() -RequiredMod @() -RequiredAs @() -Other @() ` ## -PrivateData F05F583BB5EA4C90E3B9BF1BDD0B657701245BD5 ## #################################################################################################### function Get-UserCertificate { [CmdletBinding()] PARAM () PROCESS { trap { Write-Host "The authenticode script module requires configuration to function fully!" Write-Host Write-Host "You must put the path to your default signing certificate in the module metadata"` "file before you can use the module's Set-Authenticode cmdlet or to the 'mine'"` "feature of the Select-Signed or Test-Signature. To set it up, you can do this:" Write-Host Write-Host "PrivateData = 'C:\\Users\\${Env:UserName}\\Documents\\WindowsPowerShell\\PoshCerts\\Code-Signing.pfx'" Write-Host Write-Host "If you load your certificate into your 'CurrentUser\\My' store, or put the .pfx file"` "into the folder with the Authenthenticode module script, you can just specify it's"` "thumprint or filename, respectively. Otherwise, it should be a full path." Write-Error $_ return } # Import-LocalizedData -bindingVariable CertificatePath -EA "STOP" if(!$ExecutionContext.SessionState.Module.PrivateData) { $ExecutionContext.SessionState.Module.PrivateData = $(Read-Host "Please specify a user certificate") } # Write-Host "CertificatePath: $ExecutionContext.SessionState.Module.PrivateData" -fore cyan $ResolvedPath = $Null $ResolvedPath = Resolve-Path $ExecutionContext.SessionState.Module.PrivateData -ErrorAction "SilentlyContinue" if(!$ResolvedPath -or !(Test-Path $ResolvedPath -ErrorAction "SilentlyContinue")) { # Write-Host "ResolvedPath: $ResolvedPath" -fore green $ResolvedPath = Resolve-Path (Join-Path $PsScriptRoot $ExecutionContext.SessionState.Module.PrivateData -ErrorAction "SilentlyContinue") -ErrorAction "SilentlyContinue" } if(!$ResolvedPath -or !(Test-Path $ResolvedPath -ErrorAction "SilentlyContinue")) { # Write-Host "ResolvedPath: $ResolvedPath" -fore yellow $ResolvedPath = Resolve-Path (Join-Path "Cert:\\CurrentUser\\My" $ExecutionContext.SessionState.Module.PrivateData -ErrorAction "SilentlyContinue") -ErrorAction "SilentlyContinue" } $Certificate = get-item $ResolvedPath -ErrorAction "SilentlyContinue" if($Certificate -is [System.IO.FileInfo]) { $Certificate = Get-PfxCertificate $Certificate -ErrorAction "SilentlyContinue" } Write-Verbose "Certificate: $($Certificate | Out-String)" return $Certificate } } function Test-Signature { [CmdletBinding()] PARAM ( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)] # We can't actually require the type, or we won't be able to check the fake ones # [System.Management.Automation.Signature] $Signature , [Alias("Valid")] [Switch]$ForceValid ) return ( $Signature.Status -eq "Valid" -or ( !$ForceValid -and ($Signature.Status -eq "UnknownError") -and ($_.SignerCertificate.Thumbprint -eq $(Get-UserCertificate).Thumbprint) ) ) } function Set-AuthenticodeSignature{ [CmdletBinding()] PARAM ( [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [ValidateScript({ if((resolve-path $_).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } if(!(Test-Path -PathType Leaf $_)) { throw "Specified Path is not a File: '$_'" } return $true })] [string] $Path , ## TODO: you should CHANGE THIS to a method which gets *your* default certificate [Parameter(Position=2, Mandatory=$false)] $Certificate = $(Get-UserCertificate) ) PROCESS { Write-Verbose "Set Authenticode Signature on $Path with $($Certificate | Out-String)" Microsoft.PowerShell.Security\\Set-AuthenticodeSignature -Certificate $Certificate -FilePath $Path } } New-Alias sign Set-AuthenticodeSignature function Get-AuthenticodeSignature { [CmdletBinding()] PARAM ( [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [ValidateScript({ if((resolve-path $_).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } if(!(Test-Path -PathType Leaf $_)) { throw "Specified Path is not a File: '$_'" } return $true })] [string] $Path ) PROCESS { Microsoft.PowerShell.Security\\Get-AuthenticodeSignature -FilePath $Path } } function Select-Signed { [CmdletBinding()] PARAM ( [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [Alias("FullName")] [ValidateScript({ if((resolve-path $_).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } return $true })] [string] $Path , [Parameter()] [switch]$MineOnly , [Parameter()] [switch]$NotMineOnly , [Parameter()] [switch]$BrokenOnly , [Parameter()] [switch]$TrustedOnly , [Parameter()] [switch]$ValidOnly , [Parameter()] [switch]$InvalidOnly , [Parameter()] [switch]$UnsignedOnly ) if(!(Test-Path -PathType Leaf $Path)) { # if($ErrorAction -ne "SilentlyContinue") { # Write-Error "Specified Path is not a File: '$Path'" # } } else { $sig = Get-AuthenticodeSignature $Path # Broken only returns ONLY things which are HashMismatch if($BrokenOnly -and $sig.Status -ne "HashMismatch") { Write-Debug "$($sig.Status) - Not Broken: $Path" return } # Trusted only returns ONLY things which are Valid if($TrustedOnly -and $sig.Status -ne "Valid") { Write-Debug "$($sig.Status) - Not Trusted: $Path" return } # AllValid returns only things that are SIGNED and not HashMismatch if($ValidOnly -and (($sig.Status -ne "HashMismatch") -or !$sig.SignerCertificate) ) { Write-Debug "$($sig.Status) - Not Valid: $Path" return } # NOTValid returns only things that are SIGNED and not HashMismatch if($InvalidOnly -and ($sig.Status -eq "Valid")) { Write-Debug "$($sig.Status) - Valid: $Path" return } # Unsigned returns only things that aren't signed # NOTE: we don't test using NotSigned, because that's only set for .ps1 or .exe files?? if($UnsignedOnly -and $sig.SignerCertificate ) { Write-Debug "$($sig.Status) - Signed: $Path" return } # Mine returns only things that were signed by MY CertificateThumbprint if($MineOnly -and (!($sig.SignerCertificate) -or ($sig.SignerCertificate.Thumbprint -ne $((Get-UserCertificate).Thumbprint)))) { Write-Debug "Originally signed by someone else, thumbprint: $($sig.SignerCertificate.Thumbprint)" Write-Debug "Does not match your default certificate print: $((Get-UserCertificate).Thumbprint)" Write-Debug " $Path" return } # NotMine returns only things that were signed by MY CertificateThumbprint if($NotMineOnly -and (!($sig.SignerCertificate) -or ($sig.SignerCertificate.Thumbprint -eq $((Get-UserCertificate).Thumbprint)))) { if($sig.SignerCertificate) { Write-Debug "Originally signed by you, thumbprint: $($sig.SignerCertificate.Thumbprint)" Write-Debug "Matches your default certificate print: $((Get-UserCertificate).Thumbprint)" Write-Debug " $Path" } return } if(!$BrokenOnly -and !$TrustedOnly -and !$ValidOnly -and !$InvalidOnly -and !$UnsignedOnly -and !($sig.SignerCertificate) ) { Write-Debug "$($sig.Status) - Not Signed: $Path" return } get-childItem $sig.Path } } Export-ModuleMember Set-AuthenticodeSignature, Get-AuthenticodeSignature, Test-Signature, Select-Signed, Get-UserCertificate
PowerShellCorpus/PoshCode/ESXi Config Backup Scrip_1.ps1
ESXi Config Backup Scrip_1.ps1
**********EDIT: See Carter's Example, it's way simpler: http://poshcode.org/1559********** ###ESXi Configuration Backup Script #DESCRIPION: This Script takes a CSV file with the hostname, username, and password of a list of ESXi servers, and backs up their configurations to a specified Destination #USAGE: This script is meant to be run as a regular scheduled task or a pre-script for a backup job. There is no version control, so it is recommended to use an external backup program (Such as Backup Exec) to scan this. #LAST MODIFIED: 15 Dec 2009 by JGrote <jgrote AT enpointe NOSPAMDOT-com> #REQUIREMENTS: #VMWare Remote CLI (Tested with 4.0U1) ### SETTINGS #Location of the VMWare Remote CLI vicfg-cfgbackup.pl command (will be different for 32-bit systems) $vSphereCLIPath = "C:\\Program Files (x86)\\VMware\\VMware vSphere CLI\\" #Backup Destination Folder $BackupDest = "E:\\Backup\\ESXi" #Path to ESXi CSV File. APPLY STRICT PERMISSIONS TO THIS FILE SO THAT ONLY THE SCRIPTAND ADMINISTRATORS CAN READ IT! #Format: #1st Field - HOSTNAME - ESXi IP Address or Hostname #2nd Field - USERNAME - Local Username (usually root) #3rd Field - PASSWORD - Password # #Example: #HOSTNAME,USERNAME,PASSWORD #server1,root,password #server2,root,password2 #It is recommended to create and edit this file using Excel (Save as CSV) $ESXiCSV = "C:\\Scripts\\ESXiBackupList.csv" ### PREPARATION #Create an ESXi Backup Event Source if it doesn't already exist $eventsource = "Backup-ESXi" $eventlog = "Application" if (!(get-eventlog -logname $eventlog -source $eventsource)) {new-eventlog -logname $eventlog -source $eventsource} #Write an error and exit the script if an exception is ever thrown trap {write-eventlog -logname $eventlog -eventID 1 -source $eventsource -EntryType "Error" -Message "An Error occured during $($eventsource): $_ . Script run from $($MyInvocation.MyCommand.Definition)"; exit} #Verify the Destination Directory Exists: #Verify that the import XML file was created. If it is not there, it will throw an exception caught by the trap above that will exit the script. $ESXiCSVIsPresentTest = Get-Item $ESXiCSV ### SCRIPT #Read Each Host from the File and back up the config to the backup directory import-csv $ESXiCSV | ForEach-Object { $BackupResult = invoke-expression "& '$vSphereCLIPath\\perl\\bin\\perl.exe' '$vSphereCLIPath\\bin\\vicfg-cfgbackup.pl' --server $($_.HOSTNAME) --username $($_.USERNAME) --password $($_.PASSWORD) --save $($BackupDest)\\$($_.HOSTNAME)-cfgbackup.tgz" if ($LastExitCode -ne 0) {throw "An Error occurred while executing $BackupBin for $($_.HOSTNAME): $BackupResult"} } #Compose and Write Success Event $successText = "ESXi Configurations were successfully backed up to $BackupDest. Script run from $($MyInvocation.MyCommand.Definition)"" write-eventlog -logname $eventlog -eventID 1 -source $eventsource -EntryType "Information" -Message $successText
PowerShellCorpus/PoshCode/Register-TemporaryEvent..ps1
Register-TemporaryEvent..ps1
##############################################################################\n##\n## Register-TemporaryEvent\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\nRegisters an event action for an object, and automatically unregisters\nitself afterward.\n\n.EXAMPLE\n\nPS >$timer = New-Object Timers.Timer\nPS >Register-TemporaryEvent $timer Disposed { [Console]::Beep(100,100) }\nPS >$timer.Dispose()\nPS >Get-EventSubscriber\nPS >Get-Job\n\n#>\n\nparam(\n ## The object that generates the event\n $Object,\n\n ## The event to subscribe to\n $Event,\n\n ## The action to invoke when the event arrives\n [ScriptBlock] $Action\n)\n\nSet-StrictMode -Version Latest\n\n$actionText = $action.ToString()\n$actionText += @'\n\n$eventSubscriber | Unregister-Event\n$eventSubscriber.Action | Remove-Job\n'@\n\n$eventAction = [ScriptBlock]::Create($actionText)\n$null = Register-ObjectEvent $object $event -Action $eventAction
PowerShellCorpus/PoshCode/Quest Dynamic Group 005.ps1
Quest Dynamic Group 005.ps1
<# 2012.07.06 Information will be uploaded shortly. #>
PowerShellCorpus/PoshCode/List AD Users CSV_3.ps1
List AD Users CSV_3.ps1
$NumDays = 0 $LogDir = ".\\User-Accounts.csv" $currentDate = [System.DateTime]::Now $currentDateUtc = $currentDate.ToUniversalTime() $lltstamplimit = $currentDateUtc.AddDays(- $NumDays) $lltIntLimit = $lltstampLimit.ToFileTime() $adobjroot = [adsi]'' $objstalesearcher = New-Object System.DirectoryServices.DirectorySearcher($adobjroot) $objstalesearcher.filter = "(&(objectCategory=person)(objectClass=user)(lastLogonTimeStamp<=" + $lltIntLimit + "))" $users = $objstalesearcher.findall() | select ` @{e={$_.properties.cn};n='Display Name'},` @{e={$_.properties.samaccountname};n='Username'},` @{e={[datetime]::FromFileTimeUtc([int64]$_.properties.lastlogontimestamp[0])};n='Last Logon'},` @{e={[string]$adspath=$_.properties.adspath;$account=[ADSI]$adspath;$account.psbase.invokeget('AccountDisabled')};n='Account Is Disabled'} $users | Export-CSV -NoType $LogDir
PowerShellCorpus/PoshCode/Save-Credentials_5.ps1
Save-Credentials_5.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/New-ComplexPassword.ps1
New-ComplexPassword.ps1
# $Id: New-ComplexPassword.ps1 170 2008-09-05 19:49:48Z jon $ # $Revision: 170 $ Function New-ComplexPassword ([int]$Length=8, $digits=$null, $alphaUpper=$null, $alphaLower=$null, $special=$null) { # ASCII data taken from http://msdn2.microsoft.com/en-us/library/60ecse8t(VS.80).aspx # Make sure the password is long enough to meet complexity requirements if($digits+$alphaUpper+$alphaLower+$special -gt $Length) { throw "Password too short for specified complexity" } # Define character groups and the number of each required by passwords # In case this is used in a DCPromo answer files, theres a few chars to # avoid: Ampersand, Less than, double quote and back slash # (34,38,60,92) $groups = @() $group = New-Object System.Object Add-Member -In $group -Type NoteProperty -Name "Group" -Value "0123456789" # 48..57 Add-Member -In $group -Type NoteProperty -Name "Count" -Value $Digits $groups += $group $group = New-Object System.Object Add-Member -In $group -Type NoteProperty -Name "Group" -Value "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # 65..90 Add-Member -In $group -Type NoteProperty -Name "Count" -Value $alphaUpper $groups += $group $group = New-Object System.Object Add-Member -In $group -Type NoteProperty -Name "Group" -Value "abcdefghijklmnopqrstuvwxyk" # 97..122 Add-Member -In $group -Type NoteProperty -Name "Count" -Value $alphaLower $groups += $group $group = New-Object System.Object Add-Member -In $group -Type NoteProperty -Name "Group" -Value '~`!@#$%^&*()-_={}[]\\|;:"<>?,./'' ' # 32..47, 58..64, 91..96, 123..126 Add-Member -In $group -Type NoteProperty -Name "Count" -Value $special $groups += $group # initilize random number generator $ran = New-Object Random # make sure password meets complexity requirements foreach ($req in $groups) { if ($req.count) { $charsAllowed += $req.group for ($i=0; $i -lt $req.count; $i++) { $r = $ran.Next(0,$req.group.length) $password += $req.group[$r] } } elseif ($req.count -eq 0) { $charsAllowed += $req.group } } # make sure password meets length requirement if(!$charsAllowed) { $groups |% { $charsAllowed += $_.group } } for($i=$password.length; $i -lt $length; $i++) { $r = $ran.Next(0,$charsAllowed.length) $password += $charsAllowed[$r] } # randomize the password return [string]::join('',($password.ToCharArray()|sort {$ran.next()})) }
PowerShellCorpus/PoshCode/Connect-WebService.ps1
Connect-WebService.ps1
##############################################################################\n##\n## Connect-WebService\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n## Connect to a given web service, and create a type that allows you to\n## interact with that web service. In PowerShell version two, use the\n## New-WebserviceProxy cmdlet.\n##\n## Example:\n##\n## $wsdl = "http://terraservice.net/TerraService.asmx?WSDL"\n## $terraServer = Connect-WebService $wsdl\n## $place = New-Object Place\n## $place.City = "Redmond"\n## $place.State = "WA"\n## $place.Country = "USA"\n## $facts = $terraserver.GetPlaceFacts($place)\n## $facts.Center\n##\n##############################################################################\n\nparam(\n ## The URL that contains the WSDL\n [string] $WsdlLocation = $(throw "Please specify a WSDL location"),\n\n ## The namespace to use to contain the web service proxy\n [string] $Namespace,\n\n ## Switch to identify web services that require authentication\n [Switch] $RequiresAuthentication\n)\n\n## Create the web service cache, if it doesn't already exist\nif(-not (Test-Path Variable:\\Lee.Holmes.WebServiceCache))\n{\n ${GLOBAL:Lee.Holmes.WebServiceCache} = @{}\n}\n\n## Check if there was an instance from a previous connection to\n## this web service. If so, return that instead.\n$oldInstance = ${GLOBAL:Lee.Holmes.WebServiceCache}[$wsdlLocation]\nif($oldInstance)\n{\n $oldInstance\n return\n}\n\n## Load the required Web Services DLL\nAdd-Type -Assembly System.Web.Services\n\n## Download the WSDL for the service, and create a service description from\n## it.\n$wc = New-Object System.Net.WebClient\n\nif($requiresAuthentication)\n{\n $wc.UseDefaultCredentials = $true\n}\n\n$wsdlStream = $wc.OpenRead($wsdlLocation)\n\n## Ensure that we were able to fetch the WSDL\nif(-not (Test-Path Variable:\\wsdlStream))\n{\n return\n}\n\n$serviceDescription =\n [Web.Services.Description.ServiceDescription]::Read($wsdlStream)\n$wsdlStream.Close()\n\n## Ensure that we were able to read the WSDL into a service description\nif(-not (Test-Path Variable:\\serviceDescription))\n{\n return\n}\n\n## Import the web service into a CodeDom\n$serviceNamespace = New-Object System.CodeDom.CodeNamespace\nif($namespace)\n{\n $serviceNamespace.Name = $namespace\n}\n\n$codeCompileUnit = New-Object System.CodeDom.CodeCompileUnit\n$serviceDescriptionImporter =\n New-Object Web.Services.Description.ServiceDescriptionImporter\n$serviceDescriptionImporter.AddServiceDescription(\n $serviceDescription, $null, $null)\n[void] $codeCompileUnit.Namespaces.Add($serviceNamespace)\n[void] $serviceDescriptionImporter.Import(\n $serviceNamespace, $codeCompileUnit)\n\n## Generate the code from that CodeDom into a string\n$generatedCode = New-Object Text.StringBuilder\n$stringWriter = New-Object IO.StringWriter $generatedCode\n$provider = New-Object Microsoft.CSharp.CSharpCodeProvider\n$provider.GenerateCodeFromCompileUnit($codeCompileUnit, $stringWriter, $null)\n\n## Compile the source code.\n$references = @("System.dll", "System.Web.Services.dll", "System.Xml.dll")\n$compilerParameters = New-Object System.CodeDom.Compiler.CompilerParameters\n$compilerParameters.ReferencedAssemblies.AddRange($references)\n$compilerParameters.GenerateInMemory = $true\n\n$compilerResults =\n $provider.CompileAssemblyFromSource($compilerParameters, $generatedCode)\n\n## Write any errors if generated.\nif($compilerResults.Errors.Count -gt 0)\n{\n $errorLines = ""\n foreach($error in $compilerResults.Errors)\n {\n $errorLines += "`n`t" + $error.Line + ":`t" + $error.ErrorText\n }\n\n Write-Error $errorLines\n return\n}\n## There were no errors. Create the webservice object and return it.\nelse\n{\n ## Get the assembly that we just compiled\n $assembly = $compilerResults.CompiledAssembly\n\n ## Find the type that had the WebServiceBindingAttribute.\n ## There may be other "helper types" in this file, but they will\n ## not have this attribute\n $type = $assembly.GetTypes() |\n Where-Object { $_.GetCustomAttributes(\n [System.Web.Services.WebServiceBindingAttribute], $false) }\n\n if(-not $type)\n {\n Write-Error "Could not generate web service proxy."\n return\n }\n\n ## Create an instance of the type, store it in the cache,\n ## and return it to the user.\n $instance = $assembly.CreateInstance($type)\n\n ## Many services that support authentication also require it on the\n ## resulting objects\n if($requiresAuthentication)\n {\n if(@($instance.PsObject.Properties |\n where { $_.Name -eq "UseDefaultCredentials" }).Count -eq 1)\n {\n $instance.UseDefaultCredentials = $true\n }\n }\n\n ${GLOBAL:Lee.Holmes.WebServiceCache}[$wsdlLocation] = $instance\n\n $instance\n}
PowerShellCorpus/PoshCode/Get-Characteristics.ps1
Get-Characteristics.ps1
##############################################################################\n##\n## Get-Characteristics\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nGet the file characteristics of a file in the PE Executable File Format.\n\n.EXAMPLE\n\nGet-Characteristics $env:WINDIR\\notepad.exe\nIMAGE_FILE_LOCAL_SYMS_STRIPPED\nIMAGE_FILE_RELOCS_STRIPPED\nIMAGE_FILE_EXECUTABLE_IMAGE\nIMAGE_FILE_32BIT_MACHINE\nIMAGE_FILE_LINE_NUMS_STRIPPED\n\n#>\n\nparam(\n ## The path to the file to check\n [Parameter(Mandatory = $true)]\n [string] $Path\n)\n\nSet-StrictMode -Version Latest\n\n## Define the characteristics used in the PE file file header.\n## Taken from:\n## http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx\n$characteristics = @{}\n$characteristics["IMAGE_FILE_RELOCS_STRIPPED"] = 0x0001\n$characteristics["IMAGE_FILE_EXECUTABLE_IMAGE"] = 0x0002\n$characteristics["IMAGE_FILE_LINE_NUMS_STRIPPED"] = 0x0004\n$characteristics["IMAGE_FILE_LOCAL_SYMS_STRIPPED"] = 0x0008\n$characteristics["IMAGE_FILE_AGGRESSIVE_WS_TRIM"] = 0x0010\n$characteristics["IMAGE_FILE_LARGE_ADDRESS_AWARE"] = 0x0020\n$characteristics["RESERVED"] = 0x0040\n$characteristics["IMAGE_FILE_BYTES_REVERSED_LO"] = 0x0080\n$characteristics["IMAGE_FILE_32BIT_MACHINE"] = 0x0100\n$characteristics["IMAGE_FILE_DEBUG_STRIPPED"] = 0x0200\n$characteristics["IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP"] = 0x0400\n$characteristics["IMAGE_FILE_NET_RUN_FROM_SWAP"] = 0x0800\n$characteristics["IMAGE_FILE_SYSTEM"] = 0x1000\n$characteristics["IMAGE_FILE_DLL"] = 0x2000\n$characteristics["IMAGE_FILE_UP_SYSTEM_ONLY"] = 0x4000\n$characteristics["IMAGE_FILE_BYTES_REVERSED_HI"] = 0x8000\n\n## Get the content of the file, as an array of bytes\n$fileBytes = Get-Content $path -ReadCount 0 -Encoding byte\n\n## The offset of the signature in the file is stored at location 0x3c.\n$signatureOffset = $fileBytes[0x3c]\n\n## Ensure it is a PE file\n$signature = [char[]] $fileBytes[$signatureOffset..($signatureOffset + 3)]\nif([String]::Join('', $signature) -ne "PE`0`0")\n{\n throw "This file does not conform to the PE specification."\n}\n\n## The location of the COFF header is 4 bytes into the signature\n$coffHeader = $signatureOffset + 4\n\n## The characteristics data are 18 bytes into the COFF header. The\n## BitConverter class manages the conversion of the 4 bytes into an integer.\n$characteristicsData = [BitConverter]::ToInt32($fileBytes, $coffHeader + 18)\n\n## Go through each of the characteristics. If the data from the file has that\n## flag set, then output that characteristic.\nforeach($key in $characteristics.Keys)\n{\n $flag = $characteristics[$key]\n if(($characteristicsData -band $flag) -eq $flag)\n {\n $key\n }\n}
PowerShellCorpus/PoshCode/Get-MWSOrder.ps1
Get-MWSOrder.ps1
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="GetOrderCmdlet.cs" company="Huddled Masses"> // Copyright (c) 2011 Joel Bennett // </copyright> // <summary> // Defines the Get-Order Cmdlet for Amazon Marketplace Orders WebService. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace PoshOrders { using System; using System.Management.Automation; // I'm using Amazon's MarketplaceWebServiceOrders Apache-licensed web-service access code. using MarketplaceWebServiceOrders; using MarketplaceWebServiceOrders.Model; /// <summary> /// Get Amazon Marketplace Orders from the WebService /// </summary> [Cmdlet(VerbsCommon.Get, "Order")] public class GetOrderCmdlet : Cmdlet { // Access Key ID and Secret Access Key ID for the Amazon MWS /// <summary>The Amazon Access Key ID</summary> private const string AccessKeyId = "INSERT YOUR MWS ACCESS KEY HERE"; /// <summary>The Amazon Secret Key</summary> private const string SecretAccessKey = "INSERT YOUR MWS SECRET ACCESS KEY HERE"; /// <summary>The Application Name is sent to MWS as part of the HTTP User-Agent header</summary> private const string ApplicationName = "INSERT YOUR APPLICATION NAME HERE"; /// <summary>The Application Version is sent to MWS as part of the HTTP User-Agent header</summary> private const string ApplicationVersion = "1.0"; /// <summary>Default value for the service URL is for the USA</summary> private string serviceUrl = "https://mws.amazonservices.com/Orders/2011-01-01"; /// <summary>The web service client</summary> private MarketplaceWebServiceOrdersClient marketplaceWebServiceOrdersClient; /// <summary>Default value for "Created After" is 1 day ago.</summary> private DateTime createdAfter = DateTime.MinValue; /// <summary>Default value for "Created Before" is infinitely in the future</summary> private DateTime createdBefore = DateTime.MaxValue; /// <summary>The Default order status is Unshipped or PartiallyShipped</summary> private OrderStatusEnum[] orderStatus = new[] { OrderStatusEnum.Unshipped, OrderStatusEnum.PartiallyShipped }; /// <summary> /// Gets or sets the merchant id. /// </summary> /// <value> /// The merchant id. /// </value> [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true)] public string MerchantId { get; set; } /// <summary> /// Gets or sets the marketplace id. /// </summary> /// <value> /// The marketplace id. /// </value> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true)] public string[] Marketplace { get; set; } /// <summary> /// Gets or sets the service URL. /// Defaults to the USA service URL. /// </summary> /// <value> /// The service URL. /// </value> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)] public string ServiceUrl { get { return this.serviceUrl; } set { this.serviceUrl = value; } } /// <summary> /// Gets or sets a date orders must prescede. /// </summary> /// <value> /// The date. /// </value> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)] public DateTime CreatedBefore { get { return this.createdBefore; } set { this.createdBefore = value; } } /// <summary> /// Gets or sets a date the orders must come aftercreated after. /// </summary> /// <value> /// The created after. /// </value> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)] public DateTime CreatedAfter { get { return this.createdAfter; } set { this.createdAfter = value; } } /// <summary> /// Gets or sets the order status. /// </summary> /// <value> /// The order status. /// </value> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)] public OrderStatusEnum[] OrderStatus { get { return orderStatus; } set { orderStatus = value; } } /// <summary> /// Gets or sets the buyer email. /// </summary> /// <value> /// The buyer email. /// </value> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)] public string BuyerEmail { get; set; } /// <summary> /// Gets or sets the seller order id. /// </summary> /// <value> /// The seller order id. /// </value> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)] public string SellerOrderId { get; set; } /// <summary> /// Gets or sets whether to include the Order Items /// </summary> /// <value> /// True to included the Order Items /// </value> [Parameter(Mandatory = false)] public SwitchParameter IncludeItems { get; set; } /// <summary> /// Implement the Begin step for PowerShell Cmdlets /// </summary> protected override void BeginProcessing() { base.BeginProcessing(); var config = new MarketplaceWebServiceOrdersConfig { ServiceURL = "https://mws.amazonservices.com/Orders/2011-01-01" }; this.marketplaceWebServiceOrdersClient = new MarketplaceWebServiceOrdersClient( ApplicationName, ApplicationVersion, AccessKeyId, SecretAccessKey, config); } /// <summary> /// Implement the Process step for PowerShell Cmdlets /// </summary> protected override void ProcessRecord() { base.ProcessRecord(); /* // If no dates are specificied, start a day ago ... if (CreatedBefore == DateTime.MaxValue && CreatedAfter == DateTime.MinValue) { CreatedAfter = DateTime.UtcNow.AddDays(-1); } */ // Amazon's policy doesn't allow calling with a CreatedBefore after two minutes before the request time if (CreatedBefore == DateTime.MaxValue) { CreatedBefore = DateTime.Now.AddMinutes(-2); } var orderRequest = new ListOrdersRequest { MarketplaceId = new MarketplaceIdList(), OrderStatus = new OrderStatusList(), BuyerEmail = this.BuyerEmail, SellerId = this.MerchantId, SellerOrderId = this.SellerOrderId, CreatedAfter = this.CreatedAfter, CreatedBefore = this.CreatedBefore }; orderRequest.OrderStatus.Status.AddRange(OrderStatus); orderRequest.MarketplaceId.Id.AddRange(Marketplace); var response = marketplaceWebServiceOrdersClient.ListOrders(orderRequest); foreach (var order in response.ListOrdersResult.Orders.Order) { var output = new PSObject(order); if (IncludeItems.ToBool()) { var itemRequest = new ListOrderItemsRequest { AmazonOrderId = order.AmazonOrderId, SellerId = this.MerchantId, }; var items = marketplaceWebServiceOrdersClient.ListOrderItems(itemRequest); output.Properties.Add(new PSNoteProperty("Items", items.ListOrderItemsResult.OrderItems.OrderItem)); } WriteObject(output); } } } }
PowerShellCorpus/PoshCode/Users_Contacts from CSV.ps1
Users_Contacts from CSV.ps1
#=============================================================================# #=============================================================================# #=============================================================================# # # SCRIPT : CreateOrUpdateUsersOrContacts.ps1 # LAST UPDATE : 9/18/2009 # VERSION : 1.00 # # # DESCRIPTION: # PowerShell script for creating/updating mail-enabled Users or Contact objects # in Active Directory for Exchange 2003. Uses a CSV source file. # # # TO DO: # * Logging. # * Roll-back # * Eliminate need to hard-code LDAP fields, use CSV header instead. # * Confirm required LDAP fields are present and populated. # * Incorporate command-line argument functionality # # (NOTE: NONE OF THESE HAVE BEEN IMPLEMENTED YET!!!) # # CSV input path and file name # $File = $args[0] # -f <CSV File Name> # # Type of Active Directory object to target # $ADObject = $args[1] # -a <AD Object Type> # # Where the Contacts should be created # $OUPath = $args[2] # -o <Target OU Path> # # Which Exchange environment to create contacts in (CHI or LA) # $Affiliate = $args[3] # -e <Exchange Environment> # # Test only -- Add 'what if' to New-QADObject # $TestFlag = $args[4] # -t # # Domain and username of authentication credentials # $UserName = $args[5] # -u <domain\\sAMAccountName> # # Password for above credentials # $Password = $args[6] # -p <password> # # # VERSION HISTORY: # 1.00 - 8/18/2009 # * Initial Release. # # # AUTHOR: # Ken Knicker - kenknicker@gmail.com # #=============================================================================# #=============================================================================# #=============================================================================# #=============================================================================# #=============================================================================# # Functions #=============================================================================# #=============================================================================# #=============================================================================# Function Set_People_Attributes { #=============================================================================# $Input | Set-QADObject -ObjectAttributes @{ c = ($_.c); co = ($_.co); countryCode = ($_.countryCode); comment = ($_.comment); company = ($_.company); description = ($_.description); division = ($_.division); employeeID = ($_.employeeID); employeeType = ($_.employeeType); extensionAttribute1 = ($_.extensionAttribute1); extensionAttribute2 = ($_.extensionAttribute2); extensionAttribute3 = ($_.extensionAttribute3); extensionAttribute4 = ($_.extensionAttribute4); extensionAttribute5 = ($_.extensionAttribute5); extensionAttribute6 = ($_.extensionAttribute6); extensionAttribute7 = ($_.extensionAttribute7); extensionAttribute8 = ($_.extensionAttribute8); extensionAttribute9 = ($_.extensionAttribute9); extensionAttribute10 = ($_.extensionAttribute10); extensionAttribute11 = ($_.extensionAttribute11); extensionAttribute12 = ($_.extensionAttribute12); extensionAttribute13 = ($_.extensionAttribute13); extensionAttribute14 = ($_.extensionAttribute14); extensionAttribute15 = ($_.extensionAttribute15); facsimileTelephoneNumber = ($_.facsimileTelephoneNumber); givenName = ($_.givenName); info = ($_.info); initials = ($_.initials); l = ($_.l); # memberOf = ($_.memberOf); # Group memberships mobile = ($_.mobile); physicalDeliveryOfficeName = ($_.physicalDeliveryOfficeName); postalCode = ($_.postalCode); sn = ($_.sn); st = ($_.st); streetAddress = ($_.streetAddress); telephoneNumber = ($_.telephoneNumber); title = ($_.title) } -Verbose } #=============================================================================# Function Set_User_Attributes { #=============================================================================# $Input | Set-QADUser -ObjectAttributes @{ homeDirectory = ($_.homeDirectory); homeDrive = ($_.homeDrive); # manager = ($_.manager); mobile = ($_.mobile); profilePath = ($_.profilePath); sAMAccountName = ($_.sAMAccountName); scriptPath = ($_.scriptPath); userPrincipalName = ($_.sAMAccountName + $Domain); wWWHomePage = ($_.wWWHomePage) } -Verbose } #=============================================================================# Function Set_Mail_Attributes { #=============================================================================# $Input | Set-QADObject -ObjectAttributes @{ legacyExchangeDN = ($Root_LegacyExchangeDN + $_.mailNickname); mail = ($_.mail); mailNickname = ($_.mailNickname); # msExchHideFromAddressLists = ($_.msExchHideFromAddressLists); # # msExchHomeServerName = ($_.msExchHomeServerName); # Only for User objects targetAddress = ($_.targetAddress) } -Verbose } #=============================================================================# #=============================================================================# # Script Setup #=============================================================================# #=============================================================================# #=============================================================================# # Load snap-in for Quest ActiveRoles cmdlets #=============================================================================# If (-not (Get-PSSnapin Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue)) { Add-PSSnapin Quest.ActiveRoles.ADManagement -Verbose } #=============================================================================# # Initialize variables #=============================================================================# $CSVPath = "\\\\SERVER\\SharePath\\ListOfPeople.csv" $PeopleList = Import-Csv $CSVPath -Verbose # CSV file containing people info $MailEnable = $false # Set these all to null to clear from last execution. $ObjectType = $null $Domain = $null $OU = $null $Root_LegacyExchangeDN = $null $Server = $null $UserName = $null #=============================================================================# # Affiliate Number 1 attributes #=============================================================================# $Affiliate1_Contact_OU = "OU=Contacts,DC=affiliate1,DC=com" $Affiliate1_User_OU = "OU=Users,DC=affiliate1,DC=com" $Affiliate1_Root_LegacyExchangeDN = "/O=Affiliate 1/OU=AFFILIATE1/cn=Recipients/cn=" $Affiliate1_Domain = "@affiliate1.com" $Affiliate1_Server = "domaincontroller.affiliate1.com" #=============================================================================# # Affiliate Number 2 attributes #=============================================================================# $Affiliate2_Contact_OU = "OU=Contacts,DC=affiliate2,DC=com" $Affiliate2_User_OU = "OU=Users,DC=affiliate2,DC=com" $Affiliate2_Root_LegacyExchangeDN = "/O=Affiliate 2/OU=AFFILIATE2/cn=Recipients/cn=" $Affiliate2_Domain = "@affiliate2.com" $Affiliate2_Server = "domaincontroller.affiliate2.com" #=============================================================================# # Credentials #=============================================================================# $Location = Read-Host "Affiliate location: ''A1'' for Affiliate 1, ''A2'' for Affiliate 2:" $ObjectType = Read-Host "Object type? ''Contact'' or ''User'':" If ($Location -eq "AF1") { If ($ObjectType -eq "User") { $OU = $Affiliate1_User_OU } Else { $OU = $CHI_Contact_OU } $Root_LegacyExchangeDN = $Affiliate1_Root_LegacyExchangeDN $Domain = $Affiliate1_Domain $Server = $Affiliate1_Server $UserName = $Affiliate1_UserName } If ($Location -eq "AF2") { If ($ObjectType -eq "User") { $OU = $Affiliate2_User_OU } Else { $OU = $CHI_Contact_OU } $Root_LegacyExchangeDN = $Affiliate2_Root_LegacyExchangeDN $Domain = $Affiliate2_Domain $Server = $Affiliate2_Server $UserName = $Affiliate2_UserName } $UserName = Read-Host "Enter username for the domain you are connecting to (''DOMAIN\\username''):" $Password = Read-Host "Enter password for"$UserName -AsSecureString Connect-QADService -Service $Server -ConnectionAccount $UserName -ConnectionPassword $Password -Verbose #=============================================================================# #=============================================================================# # Main Script #=============================================================================# #=============================================================================# #=============================================================================# # Create or update Contact or User objects from CSV records #=============================================================================# $PeopleList | ForEach-Object { $Person = Get-QADObject -DisplayName $_.displayName -LdapFilter "(&(objectClass=$ObjectType))" -Verbose If ($Person -eq $Null){ Write-Host "Creating Object for" $_.displayName -ForegroundColor Green -Verbose If ($ObjectType -eq "Contact") { $Person = New-QADObject -ParentContainer $OU -Name $_.cn -Type $ObjectType -DisplayName $_.displayName -Verbose } ElseIf ($ObjectType -eq "User") { $Person = New-QADUser -ParentContainer $OU -Name $_.cn -DisplayName $_.displayName -SamAccountName $_.sAMAccountName -UserPrincipalName ($_.sAMAccountName+"$Domain") -Verbose $Person | Set_User_Attributes } $Person | Set_People_Attributes } Else { Write-Host "Updating Properties for" $_.displayName -ForegroundColor Red -Verbose $Person | Set_People_Attributes } If ($MailEnable -eq $true) { $Person | Set_Mail_Attributes } } #=============================================================================# # END SCRIPT #=============================================================================#
PowerShellCorpus/PoshCode/Sybase Error Log Check.ps1
Sybase Error Log Check.ps1
# Description # =========== # This script is to check the Sybase ASE Server errorlog for certain strings indicating errors and other issues # a DBA should know about, and mails the results to a list of recipients. When the server is running, the # script will figure out the errorlog filename itself, though you can also specify the file name explicitly. # This script can be run as a daily 'Scheduled Task' job, so that the DBA receives a list of all new suspect errorlog # messages by email every day. By default, an email will always be sent after each run of this script, even # when no error messages have been found. # # # The script will look for the following strings in the Sybase error log: # # String Pattern To Search: "error","warning","severity","fail","full", "couldn","not found","not valid","invalid", # "threshold","unmirror","mirror","deadlock", "allow","NO_LOG","logsegment","syslogs # # Alternate String Pattern To Search: "error","warning" # # Usage: Job Should Be Scheduled Hourly # # powershell -command G:\\YourScriptDirectory\\SybaseErrorLogCheck.ps1 >G:\\SCRIPTDirectory\\Scripts\\SybErrLog.Err # # Note: Enter Command string above when creating a Scheduled Task # # Author: Victor Flores # Date Written: 05/01/2011 # Date Revised: # Program: SybaseErrorLogCheck.ps1 # Email: rattler69@gmail.com # Language: Powershell V2 # Copyright Note and Disclaimer # This software is provided "as is"; there is no warranty of any kind. While this software is believed to work # accurately, it may not work correctly and/or reliably in a production environment. In no event shall # Victor Flores be liable for any damages resulting from the use of this software. # # # Change Log: # Date Programmer Change(s) # # # # # # ################### This program is written in Windows Powershell Version 2 ################### Install Powershell V2 and configure powershell to allow you to run scripts ################### Log Files used in the execution of the SybaseErrorLogCheck.ps1 program ################### Change to your script directory del G:\\YourScriptDirectory\\ErrorsFound.log del G:\\YourScriptDirectory\\errlogfile.txt ################### Email Function to Email Error Log Results to The Sybase DBA's ################### Usage: Change Recieving Account in $mailmesssage.To.Add ################### Change $SMTPClient. To reference your sending SMTP Server ################### Change $SMTPClient.Credentials to reference your sending email acct ################### Change $SMTPClient.Credentials to reference your sending email password # function EmailResults { $mailmessage = New-Object system.net.mail.mailmessage $mailmessage.from = ("YourDBASendingAccount@YourCompanyEmailServer,com") $mailmessage.To.add("DBA1@your.company.com,DBA2@your.company.com") $mailmessage.Subject = $Subject $mailmessage.Body = $EmailBody $mailmessage.IsBodyHTML = $true $SMTPClient = New-Object Net.Mail.SmtpClient("YourCompanySMTPServer.com", 25) $SMTPClient.Credentials = New-Object System.Net.NetworkCredential("YourDBASendingAccount@YourCompanyEmailServer.com", "password") $SMTPClient.Send($mailmessage) } ################### Sybase Error Log Filtering. Logs can be filetered by Days or Hours ################### Alternate Log Filter in Days #####$today = Get-Date #####$daysback = New-Timespan -days 17 #####$cutoff = $today - $daysback ################### Alternate Log Filter in Hours $hoursback = New-Timespan -hours 12 $cutoff = $today - $hoursback ################### Parsing Thru Sybase Error Log For Errors ################### Sybase Error Log Location: E:\\sybase\\ASE-15_0\\install\\cbstest.log $LogFileByDate = Get-Content E:\\sybase\\ASE-15_0\\install\\cbstest.log | Foreach-Object { $elements = $_.Split("`t");` $rv = 1 | Select-Object date, message;$rv.date = if($elements[0] -notmatch "^\\d\\d:\\d{5}:\\d{5}:\\d{4}/\\d\\d/\\d\\d\\s\\d\\d:\\d\\d:\\d\\d\\.\\d\\d"){$elements >> G:\\YourScriptDirectory\\errlogfile.txt;"UNKNOWN"}else{ [DateTime]($elements[0].SubString(15,10))}` #$rv.Date = [DateTime]($elements[0].SubString(15,10));` $rv.Message = $elements[1]; $elements } | Where-Object { $rv.Date -gt $cutoff } ################### Errors Encountered in Sybase Error Log Output file based on date filter ################### File Created in your script directory $LogFileByDate| out-file G:\\YourScriptDirectory\\LogFileByDate.txt $ErrorsFound= Select-String -Path G:\\YourScriptDirectory\\LogFileByDate.txt -pattern "error","warning","severity",` "fail","full", "couldn","not found","not valid","invalid", "threshold","unmirror",` "mirror","deadlock", "allow","NO_LOG","logsegment","syslogs" ################### Errors Found in Your Sybase Error Log $ErrorsFound | out-file G:\\YourScriptDirectory\\ErrorsFound.log ################### Errors Found in Your Sybase Error Log Emailed to DBA ################### Change Subject Line to Something of your liking $EmailBody = (gc G:\\YourScriptDirectory\\ErrorsFound.log | out-string) $Subject = 'Sybase Error Log Report for YourSybaseServerName - Sybase Errors Have Been Encountered on YourSybaseServerName' if ($emailbody.Length -gt 0) { EmailResults $Subject $Body }
PowerShellCorpus/PoshCode/Send-HTMLFormattedEmail_6.ps1
Send-HTMLFormattedEmail_6.ps1
################################################## # cmdlets ################################################## #------------------------------------------------- # Send-HTMLFormattedEmail #------------------------------------------------- # Usage: Send-HTMLFormattedEmail -? #------------------------------------------------- function Send-HTMLFormattedEmail { <# .Synopsis Used to send an HTML Formatted Email. .Description Used to send an HTML Formatted Email that is based on an XSLT template. .Parameter To Email address or addresses for whom the message is being sent to. Addresses should be seperated using ;. .Parameter ToDisName Display name for whom the message is being sent to. .Parameter CC Email address if you want CC a recipient. Addresses should be seperated using ;. .Parameter BCC Email address if you want BCC a recipient. Addresses should be seperated using ;. .Parameter From Email address for whom the message comes from. .Parameter FromDisName Display name for whom the message comes from. .Parameter Subject The subject of the email address. .Parameter Content The content of the message (to be inserted into the XSL Template). .Parameter Relay FQDN or IP of the SMTP relay to send the message to. .XSLPath The full path to the XSL template that is to be used. #> param( [Parameter(Mandatory=$True)][String]$To, [Parameter(Mandatory=$True)][String]$ToDisName, [String]$CC, [String]$BCC, [Parameter(Mandatory=$True)][String]$From, [Parameter(Mandatory=$True)][String]$FromDisName, [Parameter(Mandatory=$True)][String]$Subject, [Parameter(Mandatory=$True)][String]$Content, [Parameter(Mandatory=$True)][String]$Relay, [Parameter(Mandatory=$True)][String]$XSLPath ) try { # Load XSL Argument List $XSLArg = New-Object System.Xml.Xsl.XsltArgumentList $XSLArg.Clear() $XSLArg.AddParam("To", $Null, $ToDisName) $XSLArg.AddParam("Content", $Null, $Content) # Load Documents $BaseXMLDoc = New-Object System.Xml.XmlDocument $BaseXMLDoc.LoadXml("<root/>") $XSLTrans = New-Object System.Xml.Xsl.XslCompiledTransform $XSLTrans.Load($XSLPath) #Perform XSL Transform $FinalXMLDoc = New-Object System.Xml.XmlDocument $MemStream = New-Object System.IO.MemoryStream $XMLWriter = [System.Xml.XmlWriter]::Create($MemStream) $XSLTrans.Transform($BaseXMLDoc, $XSLArg, $XMLWriter) $XMLWriter.Flush() $MemStream.Position = 0 # Load the results $FinalXMLDoc.Load($MemStream) $Body = $FinalXMLDoc.Get_OuterXML() # Create Message Object $Message = New-Object System.Net.Mail.MailMessage # Now Populate the Message Object. $Message.Subject = $Subject $Message.Body = $Body $Message.IsBodyHTML = $True # Add From $MessFrom = New-Object System.Net.Mail.MailAddress $From, $FromDisName $Message.From = $MessFrom # Add To $To = $To.Split(";") # Make an array of addresses. $To | foreach {$Message.To.Add((New-Object System.Net.Mail.Mailaddress $_.Trim()))} # Add them to the message object. # Add CC if ($CC){ $CC = $CC.Split(";") # Make an array of addresses. $CC | foreach {$Message.CC.Add((New-Object System.Net.Mail.Mailaddress $_.Trim()))} # Add them to the message object. } # Add BCC if ($BCC){ $BCC = $BCC.Split(";") # Make an array of addresses. $BCC | foreach {$Message.BCC.Add((New-Object System.Net.Mail.Mailaddress $_.Trim()))} # Add them to the message object. } # Create SMTP Client $Client = New-Object System.Net.Mail.SmtpClient $Relay # Send The Message $Client.Send($Message) } catch { throw $_ } } ################################################## # Main ################################################## Export-ModuleMember Send-HTMLFormattedEmail ### XSLT Template Example <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output media-type="xml" omit-xml-declaration="yes" /> <xsl:param name="To"/> <xsl:param name="Content"/> <xsl:template match="/"> <html> <head> <title>My First Formatted Email</title> </head> <body> <div width="400px"> <p>Dear <xsl:value-of select="$To" />,</p> <p></p> <p><xsl:value-of select="$Content" /></p> <p></p> <p><strong>Please do not respond to this email!</strong><br /> An automated system sent this email, if any point you have any questions or concerns please open a help desk ticket.</p> <p></p> <Address> Many thanks from your:<br /> Really Cool IT Team<br /> </Address> </div> </body> </html> </xsl:template> </xsl:stylesheet>
PowerShellCorpus/PoshCode/Write-Log System Center.ps1
Write-Log System Center.ps1
function Write-Log { <# .Synopsis Write a message to a log file in a format compatible with Trace32 and Config Manager logs. .Description This cmdlet takes a given message and formats that message such that it's compatible with the Trace32 log viewer tool used for reading/parsing System Center log files. The date and time (to the millisecond) is determined at the time that this cmdlet is called. Several optional arguments can be provided, to define the Component generating the log message, the File that is generating the message, the Thread ID, and the Context under which the log entry is being made. .Parameter Message The actual message to be logged. .Parameter Component The Component generating the logging event. .Parameter File The File generating the logging event. .Parameter Thread The Thread ID of the thread generating the logging event. .Parameter Context .Parameter FilePath The path to the log file to be generated/written to. By default this cmdlet looks for a variable called "WRITELOGFILEPATH" and uses whatever path is there. This variable can be set in the script prior to calling this cmdlet. Alternatively a path to a file may be provided. .Parameter Type The type of event being logged. Valid values are 1, 2 and 3. Each number corresponds to a message type: 1 - Normal messsage (default) 2 - Warning message 3 - Error message #> [CmdletBinding()] param( [Parameter( Mandatory = $true )] [string] $Message, [string] $Component="", [string] $File="", [string] $Thread="", [string] $Context="", [string] $FilePath=$WRITELOGFILEPATH, [ValidateSet(1,2,3)] [int] $Type=1 ) begin { $TZBias = (Get-WmiObject -Query "Select Bias from Win32_TimeZone").bias } process { $Time = Get-Date -Format "HH:mm:ss.fff" $Date = Get-Date -Format "MM-dd-yyyy" $Output = "<![LOG[$($Message)]LOG]!><time=`"$($Time)+$($TZBias)`" date=`"$($Date)`" " $Output += "component=`"$($Component)`" context=`"$($Context)`" type=`"$($Type)`" " $Output += "thread=`"$($Thread)`" file=`"$($File)`">" Write-Verbose "$Time $Date`t$Message" Out-File -InputObject $Output -Append -NoClobber -Encoding Default -FilePath $FilePath } }
PowerShellCorpus/PoshCode/Select-Alive_1.ps1
Select-Alive_1.ps1
## this filer passes through only objects that are pingable ## it takes any object as input, but the property containing the hostname ## to ping must be specified if the object is not a string function Select-Alive {param( [object]$InputObject, [string]$Property, [int32]$Requests = 3, [switch]$Verbose) PROCESS { if ($InputObject -eq $null) {$In = $_} else {$In = $InputObject} if ($In.GetType().Name -eq "String") { $HostName = $In } elseif (($In | Get-Member | Where-Object {$In.Name -eq $Property}) -ne $null) { $HostName = $In.$Property } else {return $null} if ($Verbose) {Write-Host "Pinging $HostName..." -NoNewline} for ($i = 1; $i -le $Requests; $i++) { $Result = Get-WmiObject -Class Win32_PingStatus -ComputerName . -Filter "Address='$HostName'" Start-Sleep -Seconds 1 if ($Result.StatusCode -ne 0) { if ($Verbose) {Write-Host "No response." -ForegroundColor "Red"} return $null } } if ($Verbose) {Write-Host "Success." -ForegroundColor "Green"} return $In } }
PowerShellCorpus/PoshCode/Get-User_11.ps1
Get-User_11.ps1
function Get-User($user) { # this function should be passed the CN of the user to be returned $dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() $root = [ADSI] "LDAP://$($dom.Name)" $searcher = New-Object System.DirectoryServices.DirectorySearcher $root $searcher.filter = "(&(objectCategory=person)(objectClass=user)(cn=$user))" $user = $searcher.FindOne() [System.Collections.Arraylist]$names = $user.Properties.PropertyNames [System.Collections.Arraylist]$props = $user.Properties.Values $userobj = New-Object System.Object for ($i = 0; $i -lt $names.Count) { $userobj | Add-Member -type NoteProperty -Name $($names[$i]) -Value $($props[$i]) $i++ } $userobj.pwdlastset = [System.DateTime]::FromFileTime($userobj.pwdlastset) $userobj.lastlogontimestamp = [System.DateTime]::FromFileTime($userobj.lastlogontimestamp) return $userobj }
PowerShellCorpus/PoshCode/Create VApps in vSphere.ps1
Create VApps in vSphere.ps1
<# .SYNOPSIS Creates VApps within DevStack with reservations for CPU & RAM .DESCRIPTION Creates VApps within DevStack vSphere Environment, available parameters are: -VIServer (Optional, defaults to DevStack) {FQDN of VCentre Server} -AppName (Required) {VApp Label} -Location (Required) {Managed | Un-managed} -CPUReservation (Optional, defaults to 0) {Amount in MHz} -RAMReservation (Optional, defaults to 0) {Amount in MB} .EXAMPLE The example below creates a VApp named "Test VApp" in the Un-Managed Resource Pool with a RAM reservation of 512MB Create-VApp -AppName "Test VApp" -Location Un-managed -RAMReservation 512 .EXAMPLE The example below shows the minimum required parameters, this VApp will be created with no reserved resources! Create-VApp -AppName "Test VApp1" -Location "Un-Managed" #> #Author: Ant B 2012 Param( [String]$VIServer = "<Your default VCentre Server>", [parameter(Mandatory=$true)][String]$AppName, [parameter(Mandatory=$true)][String]$Location, [Int]$CPURes, [Int]$RamRes ) #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 #Get a list of existing VApps to check for name conflicts. $Apps = Get-VApp | Select Name $i = 0 ForEach ($App in $Apps) { If ($Apps[$i].Name -like $AppName) { Throw "There is already a VApp with the name $AppName" } Else{ $i++ }} #Now we know the proposed VApp name is free we can create it New-vapp -Location $Location -Name $AppName -CpuExpandableReservation 0 -CpuReservationMhz $CPURes -CpuSharesLevel Normal -MemExpandableReservation 0 -MemReservationMB $RamRes -MemSharesLevel Normal #Close our connection to VCentre Disconnect-VIServer -Server * -Force -Confirm:$False
PowerShellCorpus/PoshCode/Get-DiskSizeInfo_1.ps1
Get-DiskSizeInfo_1.ps1
Function Get-DiskSizeInfo { <# .DESCRIPTION Check the Disk(s) Size and remaining freespace. .PARAMETER ComputerName Specify the computername(s) .INPUTS System.String .OUTPUTS System.Management.Automation.PSObject .EXAMPLE Get-DiskSizeInfo Get the drive(s), Disk(s) space, and the FreeSpace (GB and Percentage) .EXAMPLE Get-DiskSizeInfo -ComputerName SERVER01,SERVER02 Get the drive(s), Disk(s) space, and the FreeSpace (GB and Percentage) on the Computers SERVER01 and SERVER02 .EXAMPLE Get-Content Computers.txt | Get-DiskSizeInfo Get the drive(s), Disk(s) space, and the FreeSpace (GB and Percentage) for each computers listed in Computers.txt .NOTES NAME : Get-DiskSizeInfo AUTHOR: Francois-Xavier Cat EMAIL : fxcat@LazyWinAdmin.com DATE : 2013/02/05 .LINK http://lazywinadmin.com #> [CmdletBinding()] param( [Parameter(ValueFromPipeline=$True)] [string[]]$ComputerName = $env:COMPUTERNAME ) BEGIN {# Setup } PROCESS { Foreach ($Computer in $ComputerName) { Write-Verbose -Message "ComputerName: $Computer - Getting Disk(s) information..." try { # Set all the parameters required for our query $params = @{'ComputerName'=$Computer; 'Class'='Win32_LogicalDisk'; 'Filter'="DriveType=3"; 'ErrorAction'='SilentlyContinue'} $TryIsOK = $True # Run the query against the current $Computer $Disks = Get-WmiObject @params }#Try Catch { "$Computer" | Out-File -Append -FilePath c:\\Errors.txt $TryIsOK = $False }#Catch if ($TryIsOK) { Write-Verbose -Message "ComputerName: $Computer - Formating information for each disk(s)" foreach ($disk in $Disks) { # Prepare the Information output Write-Verbose -Message "ComputerName: $Computer - $($Disk.deviceid)" $output = @{'ComputerName'=$computer; 'Drive'=$disk.deviceid; 'FreeSpace(GB)'=("{0:N2}" -f($disk.freespace/1GB)); 'Size(GB)'=("{0:N2}" -f($disk.size/1GB)); 'PercentFree'=("{0:P2}" -f(($disk.Freespace/1GB) / ($disk.Size/1GB)))} # Create a new PowerShell object for the output $object = New-Object -TypeName PSObject -Property $output $object.PSObject.TypeNames.Insert(0,'Report.DiskSizeInfo') # Output the disk information Write-Output -InputObject $object }#foreach ($disk in $disks) }#if ($TryIsOK) }#Foreach ($Computer in $ComputerName) }#PROCESS END {# Cleanup } }#Function Get-DiskSizeInfo
PowerShellCorpus/PoshCode/Get-PipeLineObject_1.ps1
Get-PipeLineObject_1.ps1
# For TabExpansion.ps1 # this requires latest TabExpansion.ps1 in a same directory function Get-PipeLineObject { $i = -2 $property = $null do { $str = $line.Split("|") # extract the command name from the string # first split the string into statements and pipeline elements # This doesn't handle strings however. $_cmdlet = [regex]::Split($str[$i], '[|;=]')[-1] # take the first space separated token of the remaining string # as the command to look up. Trim any leading or trailing spaces # so you don't get leading empty elements. $_cmdlet = $_cmdlet.Trim().Split()[0] if ( $_cmdlet -eq "?" ) { $_cmdlet = "Where-Object" } $global:_exp = $_cmdlet # now get the info object for it... $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0] } if ( "Select-Object" -eq $_cmdlet ) { if ( $str[$i] -match '\\s+-Exp\\w*[\\s:]+(\\w+)' ) { $property = $Matches[1] + ";" + $property } } $i-- } while ( "Get-Unique", "Select-Object", "Sort-Object", "Tee-Object", "Where-Object" -contains $_cmdlet ) if ( $global:_forgci -eq $null ) { $a = @(ls "Alias:\\")[0] $e = @(ls "Env:\\")[0] $f = @(ls "Function:\\")[0] $h = @(ls "HKCU:\\")[0] $v = @(ls "Variable:\\")[0] $c = @(ls "cert:\\")[0] $global:_forgci = gi $PSHOME\\powershell.exe | Add-Member -Name CommandType -MemberType 'NoteProperty' -Value $f.CommandType -PassThru | Add-Member -Name Definition -MemberType 'NoteProperty' -Value $a.Definition -PassThru | Add-Member -Name Description -MemberType 'NoteProperty' -Value $a.Description -PassThru | Add-Member -Name Key -MemberType 'NoteProperty' -Value $e.Key -PassThru | Add-Member -Name Location -MemberType 'NoteProperty' -Value $c.Location -PassThru | Add-Member -Name LocationName -MemberType 'NoteProperty' -Value $c.LocationName -PassThru | Add-Member -Name Options -MemberType 'NoteProperty' -Value $a.Options -PassThru | Add-Member -Name ReferencedCommand -MemberType 'NoteProperty' -Value $a.ReferencedCommand -PassThru | Add-Member -Name ResolvedCommand -MemberType 'NoteProperty' -Value $a.ResolvedCommand -PassThru | Add-Member -Name ScriptBlock -MemberType 'NoteProperty' -Value $f.ScriptBlock -PassThru | Add-Member -Name StoreNames -MemberType 'NoteProperty' -Value $c.StoreNames -PassThru | Add-Member -Name SubKeyCount -MemberType 'NoteProperty' -Value $h.SubKeyCount -PassThru | Add-Member -Name Value -MemberType 'NoteProperty' -Value $e.Value -PassThru | Add-Member -Name ValueCount -MemberType 'NoteProperty' -Value $h.ValueCount -PassThru | Add-Member -Name Visibility -MemberType 'NoteProperty' -Value $a.Visibility -PassThru | Add-Member -Name Property -MemberType 'NoteProperty' -Value $h.Property -PassThru | Add-Member -Name ResolvedCommandName -MemberType 'NoteProperty' -Value $a.ResolvedCommandName -PassThru | Add-Member -Name Close -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name CreateSubKey -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name DeleteSubKey -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name DeleteSubKeyTree -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name DeleteValue -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Flush -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetSubKeyNames -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetValue -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetValueKind -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetValueNames -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsValidValue -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name OpenSubKey -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name SetValue -MemberType 'ScriptMethod' -Value {} -PassThru } if ( $global:_mix -eq $null ) { $f = gi $PSHOME\\powershell.exe $t = [type] $s = "" $global:_mix = ` Add-Member -InputObject (New-Object PSObject) -Name Mode -MemberType 'NoteProperty' -Value $f.Mode -PassThru | Add-Member -Name Assembly -MemberType 'NoteProperty' -Value $t.Assembly -PassThru | Add-Member -Name AssemblyQualifiedName -MemberType 'NoteProperty' -Value $t.AssemblyQualifiedName -PassThru | Add-Member -Name Attributes -MemberType 'NoteProperty' -Value $f.Attributes -PassThru | Add-Member -Name BaseType -MemberType 'NoteProperty' -Value $t.BaseType -PassThru | Add-Member -Name ContainsGenericParameters -MemberType 'NoteProperty' -Value $t.ContainsGenericParameters -PassThru | Add-Member -Name CreationTime -MemberType 'NoteProperty' -Value $f.CreationTime -PassThru | Add-Member -Name CreationTimeUtc -MemberType 'NoteProperty' -Value $f.CreationTimeUtc -PassThru | Add-Member -Name DeclaringMethod -MemberType 'NoteProperty' -Value $t.DeclaringMethod -PassThru | Add-Member -Name DeclaringType -MemberType 'NoteProperty' -Value $t.DeclaringType -PassThru | Add-Member -Name Exists -MemberType 'NoteProperty' -Value $f.Exists -PassThru | Add-Member -Name Extension -MemberType 'NoteProperty' -Value $f.Extension -PassThru | Add-Member -Name FullName -MemberType 'NoteProperty' -Value $f.FullName -PassThru | Add-Member -Name GenericParameterAttributes -MemberType 'NoteProperty' -Value $t.GenericParameterAttributes -PassThru | Add-Member -Name GenericParameterPosition -MemberType 'NoteProperty' -Value $t.GenericParameterPosition -PassThru | Add-Member -Name GUID -MemberType 'NoteProperty' -Value $t.GUID -PassThru | Add-Member -Name HasElementType -MemberType 'NoteProperty' -Value $t.HasElementType -PassThru | Add-Member -Name IsAbstract -MemberType 'NoteProperty' -Value $t.IsAbstract -PassThru | Add-Member -Name IsAnsiClass -MemberType 'NoteProperty' -Value $t.IsAnsiClass -PassThru | Add-Member -Name IsArray -MemberType 'NoteProperty' -Value $t.IsArray -PassThru | Add-Member -Name IsAutoClass -MemberType 'NoteProperty' -Value $t.IsAutoClass -PassThru | Add-Member -Name IsAutoLayout -MemberType 'NoteProperty' -Value $t.IsAutoLayout -PassThru | Add-Member -Name IsByRef -MemberType 'NoteProperty' -Value $t.IsByRef -PassThru | Add-Member -Name IsClass -MemberType 'NoteProperty' -Value $t.IsClass -PassThru | Add-Member -Name IsCOMObject -MemberType 'NoteProperty' -Value $t.IsCOMObject -PassThru | Add-Member -Name IsContextful -MemberType 'NoteProperty' -Value $t.IsContextful -PassThru | Add-Member -Name IsEnum -MemberType 'NoteProperty' -Value $t.IsEnum -PassThru | Add-Member -Name IsExplicitLayout -MemberType 'NoteProperty' -Value $t.IsExplicitLayout -PassThru | Add-Member -Name IsGenericParameter -MemberType 'NoteProperty' -Value $t.IsGenericParameter -PassThru | Add-Member -Name IsGenericType -MemberType 'NoteProperty' -Value $t.IsGenericType -PassThru | Add-Member -Name IsGenericTypeDefinition -MemberType 'NoteProperty' -Value $t.IsGenericTypeDefinition -PassThru | Add-Member -Name IsImport -MemberType 'NoteProperty' -Value $t.IsImport -PassThru | Add-Member -Name IsInterface -MemberType 'NoteProperty' -Value $t.IsInterface -PassThru | Add-Member -Name IsLayoutSequential -MemberType 'NoteProperty' -Value $t.IsLayoutSequential -PassThru | Add-Member -Name IsMarshalByRef -MemberType 'NoteProperty' -Value $t.IsMarshalByRef -PassThru | Add-Member -Name IsNested -MemberType 'NoteProperty' -Value $t.IsNested -PassThru | Add-Member -Name IsNestedAssembly -MemberType 'NoteProperty' -Value $t.IsNestedAssembly -PassThru | Add-Member -Name IsNestedFamANDAssem -MemberType 'NoteProperty' -Value $t.IsNestedFamANDAssem -PassThru | Add-Member -Name IsNestedFamily -MemberType 'NoteProperty' -Value $t.IsNestedFamily -PassThru | Add-Member -Name IsNestedFamORAssem -MemberType 'NoteProperty' -Value $t.IsNestedFamORAssem -PassThru | Add-Member -Name IsNestedPrivate -MemberType 'NoteProperty' -Value $t.IsNestedPrivate -PassThru | Add-Member -Name IsNestedPublic -MemberType 'NoteProperty' -Value $t.IsNestedPublic -PassThru | Add-Member -Name IsNotPublic -MemberType 'NoteProperty' -Value $t.IsNotPublic -PassThru | Add-Member -Name IsPointer -MemberType 'NoteProperty' -Value $t.IsPointer -PassThru | Add-Member -Name IsPrimitive -MemberType 'NoteProperty' -Value $t.IsPrimitive -PassThru | Add-Member -Name IsPublic -MemberType 'NoteProperty' -Value $t.IsPublic -PassThru | Add-Member -Name IsSealed -MemberType 'NoteProperty' -Value $t.IsSealed -PassThru | Add-Member -Name IsSerializable -MemberType 'NoteProperty' -Value $t.IsSerializable -PassThru | Add-Member -Name IsSpecialName -MemberType 'NoteProperty' -Value $t.IsSpecialName -PassThru | Add-Member -Name IsUnicodeClass -MemberType 'NoteProperty' -Value $t.IsUnicodeClass -PassThru | Add-Member -Name IsValueType -MemberType 'NoteProperty' -Value $t.IsValueType -PassThru | Add-Member -Name IsVisible -MemberType 'NoteProperty' -Value $t.IsVisible -PassThru | Add-Member -Name LastAccessTime -MemberType 'NoteProperty' -Value $f.LastAccessTime -PassThru | Add-Member -Name LastAccessTimeUtc -MemberType 'NoteProperty' -Value $f.LastAccessTimeUtc -PassThru | Add-Member -Name LastWriteTime -MemberType 'NoteProperty' -Value $f.LastWriteTime -PassThru | Add-Member -Name LastWriteTimeUtc -MemberType 'NoteProperty' -Value $f.LastWriteTimeUtc -PassThru | Add-Member -Name MemberType -MemberType 'NoteProperty' -Value $t.MemberType -PassThru | Add-Member -Name MetadataToken -MemberType 'NoteProperty' -Value $t.MetadataToken -PassThru | Add-Member -Name Module -MemberType 'NoteProperty' -Value $t.Module -PassThru | Add-Member -Name Name -MemberType 'NoteProperty' -Value $t.Name -PassThru | Add-Member -Name Namespace -MemberType 'NoteProperty' -Value $t.Namespace -PassThru | Add-Member -Name Parent -MemberType 'NoteProperty' -Value $f.Parent -PassThru | Add-Member -Name ReflectedType -MemberType 'NoteProperty' -Value $t.ReflectedType -PassThru | Add-Member -Name Root -MemberType 'NoteProperty' -Value $f.Root -PassThru | Add-Member -Name StructLayoutAttribute -MemberType 'NoteProperty' -Value $t.StructLayoutAttribute -PassThru | Add-Member -Name TypeHandle -MemberType 'NoteProperty' -Value $t.TypeHandle -PassThru | Add-Member -Name TypeInitializer -MemberType 'NoteProperty' -Value $t.TypeInitializer -PassThru | Add-Member -Name UnderlyingSystemType -MemberType 'NoteProperty' -Value $t.UnderlyingSystemType -PassThru | Add-Member -Name PSChildName -MemberType 'NoteProperty' -Value $f.PSChildName -PassThru | Add-Member -Name PSDrive -MemberType 'NoteProperty' -Value $f.PSDrive -PassThru | Add-Member -Name PSIsContainer -MemberType 'NoteProperty' -Value $f.PSIsContainer -PassThru | Add-Member -Name PSParentPath -MemberType 'NoteProperty' -Value $f.PSParentPath -PassThru | Add-Member -Name PSPath -MemberType 'NoteProperty' -Value $f.PSPath -PassThru | Add-Member -Name PSProvider -MemberType 'NoteProperty' -Value $f.PSProvider -PassThru | Add-Member -Name BaseName -MemberType 'NoteProperty' -Value $f.BaseName -PassThru | Add-Member -Name Clone -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name CompareTo -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Contains -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name CopyTo -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Create -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name CreateObjRef -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name CreateSubdirectory -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Delete -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name EndsWith -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name FindInterfaces -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name FindMembers -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetAccessControl -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetArrayRank -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetConstructor -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetConstructors -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetCustomAttributes -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetDefaultMembers -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetDirectories -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetElementType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetEnumerator -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetEvent -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetEvents -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetField -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetFields -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetFiles -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetFileSystemInfos -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetGenericArguments -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetGenericParameterConstraints -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetGenericTypeDefinition -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetInterface -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetInterfaceMap -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetInterfaces -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetLifetimeService -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetMember -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetMembers -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetMethod -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetMethods -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetNestedType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetNestedTypes -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetObjectData -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetProperties -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetProperty -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name GetTypeCode -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IndexOf -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IndexOfAny -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name InitializeLifetimeService -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Insert -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name InvokeMember -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsAssignableFrom -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsDefined -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsInstanceOfType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsNormalized -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name IsSubclassOf -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name LastIndexOf -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name LastIndexOfAny -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name MakeArrayType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name MakeByRefType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name MakeGenericType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name MakePointerType -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name MoveTo -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Normalize -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name PadLeft -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name PadRight -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Refresh -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Remove -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Replace -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name SetAccessControl -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Split -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name StartsWith -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Substring -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name ToCharArray -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name ToLower -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name ToLowerInvariant -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name ToUpper -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name ToUpperInvariant -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Trim -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name TrimEnd -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name TrimStart -MemberType 'ScriptMethod' -Value {} -PassThru | Add-Member -Name Chars -MemberType 'NoteProperty' -Value $s.Chars -PassThru } if ( "Add-Member" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Compare-Object" -eq $_cmdlet ) { $global:_dummy = (Compare-Object 1 2)[0] } if ( "ConvertFrom-SecureString" -eq $_cmdlet ) { $global:_dummy = $null } if ( "ConvertTo-SecureString" -eq $_cmdlet ) { $global:_dummy = convertto-securestring "P@ssW0rD!" -asplaintext -force } if ( "ForEach-Object" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Acl" -eq $_cmdlet ) { $global:_dummy = Get-Acl } if ( "Get-Alias" -eq $_cmdlet ) { $global:_dummy = (Get-Alias)[0] } if ( "Get-AuthenticodeSignature" -eq $_cmdlet ) { $global:_dummy = Get-AuthenticodeSignature $PSHOME\\powershell.exe } if ( "Get-ChildItem" -eq $_cmdlet ) { $global:_dummy = $global:_forgci } if ( "Get-Command" -eq $_cmdlet ) { $global:_dummy = gcm Add-Content } if ( "Get-Content" -eq $_cmdlet ) { $global:_dummy = (type $PSHOME\\profile.ps1)[0] } if ( "Get-Credential" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Culture" -eq $_cmdlet ) { $global:_dummy = Get-Culture } if ( "Get-Date" -eq $_cmdlet ) { $global:_dummy = Get-Date } if ( "Get-Event" -eq $_cmdlet ) { $global:_dummy = (Get-Event)[0] } if ( "Get-EventLog" -eq $_cmdlet ) { $global:_dummy = Get-EventLog Windows` PowerShell -Newest 1 } if ( "Get-ExecutionPolicy" -eq $_cmdlet ) { $global:_dummy = Get-ExecutionPolicy } if ( "Get-Help" -eq $_cmdlet ) { $global:_dummy = Get-Help Add-Content } if ( "Get-History" -eq $_cmdlet ) { $global:_dummy = Get-History -Count 1 } if ( "Get-Host" -eq $_cmdlet ) { $global:_dummy = Get-Host } if ( "Get-Item" -eq $_cmdlet ) { $global:_dummy = $global:_forgci } if ( "Get-ItemProperty" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Location" -eq $_cmdlet ) { $global:_dummy = Get-Location } if ( "Get-Member" -eq $_cmdlet ) { $global:_dummy = (1|Get-Member)[0] } if ( "Get-Module" -eq $_cmdlet ) { $global:_dummy = (Get-Module)[0] } if ( "Get-PfxCertificate" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Process" -eq $_cmdlet ) { $global:_dummy = ps powershell } if ( "Get-PSBreakpoint" -eq $_cmdlet ) { $global:_dummy = Add-Member -InputObject (New-Object PSObject) -Name Action -MemberType 'NoteProperty' -Value '' -PassThru | Add-Member -Name Command -MemberType 'NoteProperty' -Value '' -PassThru | Add-Member -Name Enabled -MemberType 'NoteProperty' -Value '' -PassThru | Add-Member -Name HitCount -MemberType 'NoteProperty' -Value '' -PassThru | Add-Member -Name Id -MemberType 'NoteProperty' -Value '' -PassThru | Add-Member -Name Script -MemberType 'NoteProperty' -Value '' -PassThru } if ( "Get-PSCallStack" -eq $_cmdlet ) { $global:_dummy = Get-PSCallStack } if ( "Get-PSDrive" -eq $_cmdlet ) { $global:_dummy = Get-PSDrive Function } if ( "Get-PSProvider" -eq $_cmdlet ) { $global:_dummy = Get-PSProvider FileSystem } if ( "Get-PSSnapin" -eq $_cmdlet ) { $global:_dummy = Get-PSSnapin Microsoft.PowerShell.Core } if ( "Get-Service" -eq $_cmdlet ) { $global:_dummy = (Get-Service)[0] } if ( "Get-TraceSource" -eq $_cmdlet ) { $global:_dummy = Get-TraceSource AddMember } if ( "Get-UICulture" -eq $_cmdlet ) { $global:_dummy = Get-UICulture } if ( "Get-Variable" -eq $_cmdlet ) { $global:_dummy = Get-Variable _ } if ( "Get-WmiObject" -eq $_cmdlet ) { $global:_dummy = @(iex $str[$i+1])[0] } if ( "Group-Object" -eq $_cmdlet ) { $global:_dummy = 1 | group } if ( "Measure-Command" -eq $_cmdlet ) { $global:_dummy = Measure-Command {} } if ( "Measure-Object" -eq $_cmdlet ) { $global:_dummy = Measure-Object } if ( "New-PSDrive" -eq $_cmdlet ) { $global:_dummy = Get-PSDrive Alias } if ( "New-TimeSpan" -eq $_cmdlet ) { $global:_dummy = New-TimeSpan } if ( "Resolve-Path" -eq $_cmdlet ) { $global:_dummy = $PWD } if ( "Select-String" -eq $_cmdlet ) { $global:_dummy = " " | Select-String " " } if ( "Set-Date" -eq $_cmdlet ) { $global:_dummy = Get-Date } if ( $property -ne $null) { foreach ( $name in $property.Split(";", "RemoveEmptyEntries" -as [System.StringSplitOptions]) ) { $global:_dummy = @($global:_dummy.$name)[0] } } }
PowerShellCorpus/PoshCode/PowerShell Talk Chickens.ps1
PowerShell Talk Chickens.ps1
#The PowerShell Talk #Virtualization Congress 2009 # #The Chicken Counter Script #Get our cretendials #More on credential stores: http://professionalvmware.com/2009/04/09/posh-article-of-the-week-secure-credential-storage/ $credentials = Get-VICredentialStoreItem -File "c:\\scripts\\really_secure_file.xml" #Setup Our Counters $datacenters = @{ Name = "Datacenters" Expression = { Get-Datacenter | Measure-Object} } $hosts = @{ Name = "Hosts" Expression = { Get-VMHost | Measure-Object } } $vms = @{ Name = "VMs" Expression = { Get-VM | Measure-Object } } $clusters = @{ Name = "Clusters" Expression = { Get-Cluster | Measure-Object } } #Connect to each vCenter in the credentials file ForEach ($creds in $credentials) { #Connect, Count, Disconnect connect-viserver -Server $creds.Host -User $creds.User -Password $creds.Password $output = $datacenter | Select-Object $datacenters, $hosts, $vms, $clusters disconnect-viserver -confirm:$false #Add this to the mail $Body += "`nvCenter: " + $creds.Host $Body += "`nDatacenters: " + $output.Datacenterss.count $Body += "`nHosts: " + $output.Hosts.Count $Body += "`nVMs: " + $output.VM.Count $Body += "`nClusters: " + $output.Clusters.Count #Totals $totalHosts += $output.Hosts.count $totalVM += $output.VM.count $totalDatacenters += $output.Datacenters.count $totalClusters += $output.Clusters.count } #Setup & Send our Mail $SmtpClient = new-object Net.Mail.SmtpClient("localhost") $From = "The Farm Hand <chicken_counter@professionalvmware.com>" #Change these for your environment $To = "Your Pointy Haired Boss <The_Boss@professionalvmware.com>" #Change these for your environment $Title = "Direct from your local VC: Weekly Statistics" $Body += "`n`nTotals:`n" $Body += "`nDatacenters: " + $totalDatacenters $Body += "`nHosts: " + $totalHosts $Body += "`nVMs: " + $totalVM $Body += "`nClusters: " + $totalClusters $SmtpClient.Send($From, $To, $Title, $Body)
PowerShellCorpus/PoshCode/Set-PowerGUIWelcomePage_3.ps1
Set-PowerGUIWelcomePage_3.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-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.3 - May 27: made it compatible with PowerGUI 1.8 # 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" # If quest.powergui.xml not found - try new name of the file (PowerGUI 1.8 and later) if ( -not (Test-Path $cfgpath) ) { $cfgpath = "$($env:APPDATA)\\Quest Software\\PowerGUI\\config.xml" if ( -not (Test-Path $cfgpath) ) { throw "ERROR: PowerGUI configuration file not found" } } # 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/CreateSite_tmp.ps1
CreateSite_tmp.ps1
# the order of the set custom WSP template # &#1057;&#1087;&#1080;&#1089;&#1086;&#1082; &#1085;&#1077;&#1086;&#1073;&#1093;&#1086;&#1076;&#1080;&#1084;&#1086;&#1075;&#1086; &#1076;&#1083;&#1103; &#1080;&#1089;&#1087;&#1086;&#1083;&#1100;&#1079;&#1086;&#1074;&#1072;&#1085;&#1080;&#1103; &#1083;&#1080;&#1095;&#1085;&#1086;&#1075;&#1086; WSP &#1096;&#1072;&#1073;&#1083;&#1086;&#1085;&#1072; #Add-SPSolution D:\\tmp\\ps\\template\\test.wsp #Install-SPSolution -identity "test.wsp" #Install-SPSolution -Identity test.wsp -GACDeployment #Enable-SPFeature test -url http://spf # delete WSP #Remove-SPSolution -identity "test.wsp" #Uninstall-SPSolution -identity "Test.wsp" $site = Get-SPSite http://spf/ $web = $site.RootWeb $templates = "{055CF2A7-43A8-48E1-95CB-19DC393F0215}#kolam""" write-host "template = $templates ; web = $web " New-SPWeb -name 'KoKA2' -url http://spf/koka2 -UseParentTopNav -AddToTopNav -Template $templates # -UniquePermissions #kolam" #New-SPWeb -Url http://sps2010/sites/mynewsite -Name "my new site" -Template ""{E6BD7EFF-8336-4975-BA22-2256970781E2}#SubWebTemplate" #" -UseParentTopNav -UniquePermissions #>
PowerShellCorpus/PoshCode/New-SelfSignedCertificat.ps1
New-SelfSignedCertificat.ps1
##############################################################################\n##\n## New-SelfSignedCertificate\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\nGenerate a new self-signed certificate. The certificate generated by these\ncommands allow you to sign scripts on your own computer for protection\nfrom tampering. Files signed with this signature are not valid on other\ncomputers.\n\n.EXAMPLE\n\nNew-SelfSignedCertificate.ps1\nCreates a new self-signed certificate\n\n#>\n\nSet-StrictMode -Version Latest\n\n## Ensure we can find makecert.exe\nif(-not (Get-Command makecert.exe -ErrorAction SilentlyContinue))\n{\n $errorMessage = "Could not find makecert.exe. " +\n "This tool is available as part of Visual Studio, or the Windows SDK."\n\n Write-Error $errorMessage\n return\n}\n\n$keyPath = Join-Path ([IO.Path]::GetTempPath()) "root.pvk"\n\n## Generate the local certification authority\nmakecert -n "CN=PowerShell Local Certificate Root" -a sha1 `\n -eku 1.3.6.1.5.5.7.3.3 -r -sv $keyPath root.cer `\n -ss Root -sr localMachine\n\n## Use the local certification authority to generate a self-signed\n## certificate\nmakecert -pe -n "CN=PowerShell User" -ss MY -a sha1 `\n -eku 1.3.6.1.5.5.7.3.3 -iv $keyPath -ic root.cer\n\n## Remove the private key from the filesystem.\nRemove-Item $keyPath\n\n## Retrieve the certificate\nGet-ChildItem cert:\\currentuser\\my -codesign |\n Where-Object { $_.Subject -match "PowerShell User" }
PowerShellCorpus/PoshCode/Set-OCSUser_1.ps1
Set-OCSUser_1.ps1
###########################################################################" # # NAME: Set-OCSUser.ps1 # # AUTHOR: Jan Egil Ring # EMAIL: jan.egil.ring@powershell.no # # COMMENT: Requires Quest AD cmdlets. This script sets Active Directory user attributes for Microsoft Office Communications Server 2007. # For more info: http://janegilring.wordpress.com/2009/07/23/manage-ocs-users-with-windows-powershell # # You have a royalty-free right to use, modify, reproduce, and # distribute this script file in any way you find useful, provided that # you agree that the creator, owner above has no warranty, obligations, # or liability for such use. # # VERSION HISTORY: # 1.0 23.07.2009 - Initial release # ###########################################################################" $Username="demo.user" $Fullname="Demo User" $serverpool="pool01.ourdomain.com" $oa = @{'msRTCSIP-ArchivingEnabled'=0; 'msRTCSIP-FederationEnabled'=$true; 'msRTCSIP-InternetAccessEnabled'=$true; 'msRTCSIP-OptionFlags'=257; 'msRTCSIP-PrimaryHomeServer'=$serverpool; 'msRTCSIP-PrimaryUserAddress'=("sip:$Username@ourdomain.com"); 'msRTCSIP-UserEnabled'=$true } Set-QADUser $Fullname -oa $oa
PowerShellCorpus/PoshCode/viewAllTemplate.ps1
viewAllTemplate.ps1
<# view all template wsp on custom site url based on http://www.danielbrown.id.au/Lists/Posts/Post.aspx?ID=74 #> $site = Get-SPSite "http://spf" $web = $site.OpenWeb(); foreach($lang in $web.RegionalSettings.InstalledLanguages) { Write-Host "Displaying Sites for Langauge: " $lang.DisplayName; $site.GetWebTemplates($lang.LCID) | Format-Table -Property Title, Name } $web.Dispose(); $site.Dispose(); <# second view not all template #> <# function Get-SPWebTemplateWithId { $templates = Get-SPWebTemplate | Sort-Object "Name" $templates | ForEach-Object { $templateValues = @{ "Title" = $_.Title "Name" = $_.Name "ID" = $_.ID "Custom" = $_.Custom "LocaleId" = $_.LocaleId } New-Object PSObject -Property $templateValues | Select @("Name","Title","LocaleId","Custom","ID") } } Get-SPWebTemplateWithId | Format-Table #> <# $site = Get-SPSite "http://spf" foreach ($web in $site.AllWebs) { $web | Select-Object -Property Title,Url,WebTemplate } $site.Dispose() #>
PowerShellCorpus/PoshCode/ConvertTo-Hex_1.ps1
ConvertTo-Hex_1.ps1
# Ported from C# technique found here: http://forums.asp.net/p/1298956/2529558.aspx param ( [string]$SidString ) # Create SID .NET object using SID string provided $sid = New-Object system.Security.Principal.SecurityIdentifier $sidstring # Create a byte array of the proper length $sidBytes = New-Object byte[] $sid.BinaryLength #Convert to bytes $sid.GetBinaryForm( $sidBytes, 0 ) # Iterate through bytes, converting each to the hexidecimal equivalent $hexArr = $sidBytes | ForEach-Object { $_.ToString("X2") } # Join the hex array into a single string for output $hexArr -join ''
PowerShellCorpus/PoshCode/Pastebin Functions.ps1
Pastebin Functions.ps1
## Send-Paste (aka sprunge for Pastebin) ############################################################################################################## ## Uploads code to any pastebin.com based pastebin site and returns the url for you. ############################################################################################################## ## Usage: ## get-content myscript.ps1 | Send-Paste "An example for you" "This is just to show how to do it" ## would send the script with the specified title and description ## ls *.ps1 | Send-Paste -Keep Forever ## would flood the pastebin site with all your scripts, using filename as the title ## and a generic description, and mark them for storing indefinitely ## get-history -count 5 | % { $_.CommandLine } | Send-Paste ## would paste the last 5 commands in your history! ############################################################################################################## ## History: ## v 2.1 - Changed some defaults ## - Added "PermanentPosh" switch ( -P ) to switch the upload to the PowerShellCentral repository ## v 2.0 - works with "pastebin" (including posh.jaykul.com/p/ and PowerShellCentral.com/scripts/) ## v 1.0 - Worked with a special pastebin ############################################################################################################## function Send-Paste { param( $Title, $Description=$(Read-Host "Please enter a description for this script"), $KeepFor="d", $Language="posh", $Author = $(Read-Host "Your name"), $url="http`://posh.jaykul.com/p/", [switch]$PermanentPosh ) BEGIN { $null = [Reflection.Assembly]::LoadWithPartialName("System.Web") [string]$data = $null; [string]$meta = $null; if($PermanentPosh) { $url = "http`://PowerShellCentral.com/scripts/" $keepFor = "f" } if($language) { $meta = "format=" + [System.Web.HttpUtility]::UrlEncode($language) # $url = $url + "?" +$lang } else { $meta = "format=text" } do { switch -regex ($KeepFor) { "^d.*" { $meta += "&expiry=d" } "^m.*" { $meta += "&expiry=m" } "^f.*" { $meta += "&expiry=f" } default { $KeepFor = Read-Host "Invalid value for 'KeepFor' parameter. Please specify 'day', 'month', or 'forever'" } } } until ( $meta -like "*&expiry*" ) if($Description) { $meta += "&descrip=" + [System.Web.HttpUtility]::UrlEncode($Description) } else { $meta += "&descrip=" } $meta += "&poster=" + [System.Web.HttpUtility]::UrlEncode($Author) function PasteBin-Text ($meta, $title, $data) { $meta += "&paste=Send&posttitle=" + [System.Web.HttpUtility]::UrlEncode($Title) $data = $meta + "&code2=" + [System.Web.HttpUtility]::UrlEncode($data) Write-Host $url -fore yellow $request = [System.Net.WebRequest]::Create($url) $request.ContentType = "application/x-www-form-urlencoded" $request.ContentLength = $data.Length $request.Method = "POST" $post = new-object IO.StreamWriter $request.GetRequestStream() $post.Write($data,0,$data.Length) $post.Flush() $post.Close() # $reader = new-object IO.StreamReader $request.GetResponse().GetResponseStream() ##,[Text.Encoding]::UTF8 # write-output $reader.ReadToEnd() # $reader.Close() write-output $request.GetResponse().ResponseUri.AbsoluteUri $request.Abort() } } PROCESS { switch($_) { { $_ -is [System.IO.FileInfo] } { if(!$Title) { if ($_.Extension.Length -gt 0) { $Title = $_.Name.Remove($_.Name.Length - $_.Extension.Length) } else { $Title = $_.Name } } Write-Output $_.FullName Write-Output $(PasteBin-Text $meta $Title $([string]::join("`n",(Get-Content $_.FullName)))) } { $_ -is [String] } { if(!$data -and !$Title){ $Title = Read-Host "Give us a title for your post" } $data += "`n" + $_ } ## Todo, handle folders? default { Write-Error "Unable to process $_" } } } END { if($data) { Write-Output $(PasteBin-Text $meta $Title $data) } } } ## Find-Paste (search Pastebin) ############################################################################################################## ## Searches the powershellcentral.com/script site and returns lists of results ## All search terms are automatically surrounded with wildcards ## NOTE: powershellcentral.com currently uses MySql fulltext search syntax... ############################################################################################################## ## Usage: ## find-paste crypt ## would find scripts about encryption, decryption, cryptography, etc. ############################################################################################################## ## History: ## v 1.0 - Working against our special pastebin ############################################################################################################## function Find-Paste { param( [string]$query, $url="http`://powershellcentral.com/scripts/" ) $page = Get-WebFile "$($url)?q=*$($query)*" -passthru $start = $page.IndexOf("<body") $length = $page.indexOf("</html") - $start $doc = [xml]$page.Substring($start,$length) $doc.SelectNodes( "//div[@id='content']/*/tr[position() > 1]" ) | % { Select @{n="Id";e={$_.td[0].a.href -replace $url,''}}, @{n="Title";e={$_.td[0].a."#text"}}, @{n="Description";e={$_.td[3]}}, @{n="Author";e={$_.td[1]}}, @{n="Date";e={$_.td[2]}}, @{n="Link";e={$_.td[0].a.href}} -Input $_ } } ## Get-Paste (download Pastebin script) ############################################################################################################## ## Downloads a specified script from a Pastbin.com based site, by Id ############################################################################################################## ## Usage: ## Get-Paste 184 ## would download the original Get-Paste script to 184.ps1 ## Get-Paste 184 -Passthru ## would output the contents of Get-Paste to the pipeline ## Get-Paste 184 Get-Paste.ps1 ## would download Get-Paste to Get-Paste.ps1 in the current directory ############################################################################################################## ## History: ## v 1.0 - Working against our special pastebin ############################################################################################################## function Get-Paste { param( [int]$Id = (throw "You must specify the id of the paste to get"), [string]$SaveAs, [switch]$InBrowser, [switch]$Passthru, $url="http`://powershellcentral.com/scripts/" ) if(!$InBrowser) { if($SaveAs) { Get-WebFile "$($url)?dl=$id" -fileName $SaveAs } elseif($Passthru) { Get-WebFile "$($url)?dl=$id" -Passthru } else { Get-WebFile "$($url)?dl=$id" } } else { [Diagnostics.Process]::Start( "$($url)$id" ) } } ## Get-WebFile (aka wget for PowerShell) ############################################################################################################## ## Downloads a file or page from the web ## History: ## v3.6 - Add -Passthru switch to output TEXT files ## v3.5 - Add -Quiet switch to turn off the progress reports ... ## v3.4 - Add progress report for files which don't report size ## v3.3 - Add progress report for files which report their size ## v3.2 - Use the pure Stream object because StreamWriter is based on TextWriter: ## it was messing up binary files, and making mistakes with extended characters in text ## v3.1 - Unwrap the filename when it has quotes around it ## v3 - rewritten completely using HttpWebRequest + HttpWebResponse to figure out the file name, if possible ## v2 - adds a ton of parsing to make the output pretty ## added measuring the scripts involved in the command, (uses Tokenizer) ############################################################################################################## function Get-WebFile { param( $url = (Read-Host "The URL to download"), $fileName = $null, [switch]$Passthru, [switch]$quiet ) $req = [System.Net.HttpWebRequest]::Create($url); $res = $req.GetResponse(); if($fileName -and !(Split-Path $fileName)) { $fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName } elseif((!$Passthru -and ($fileName -eq $null)) -or (($fileName -ne $null) -and (Test-Path -PathType "Container" $fileName))) { [string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $res.Headers["Content-Disposition"] ).Groups[1].Value $fileName = $fileName.trim("\\/""'") if(!$fileName) { $fileName = $res.ResponseUri.Segments[-1] $fileName = $fileName.trim("\\/") if(!$fileName) { $fileName = Read-Host "Please provide a file name" } $fileName = $fileName.trim("\\/") if(!([IO.FileInfo]$fileName).Extension) { $fileName = $fileName + "." + $res.ContentType.Split(";")[0].Split("/")[1] } } $fileName = Join-Path (Get-Location -PSProvider "FileSystem") $fileName } if($Passthru) { $encoding = [System.Text.Encoding]::GetEncoding( $res.CharacterSet ) [string]$output = "" } if($res.StatusCode -eq 200) { [int]$goal = $res.ContentLength $reader = $res.GetResponseStream() if($fileName) { $writer = new-object System.IO.FileStream $fileName, "Create" } [byte[]]$buffer = new-object byte[] 4096 [int]$total = [int]$count = 0 do { $count = $reader.Read($buffer, 0, $buffer.Length); if($fileName) { $writer.Write($buffer, 0, $count); } if($Passthru){ $output += $encoding.GetString($buffer,0,$count) } elseif(!$quiet) { $total += $count if($goal -gt 0) { Write-Progress "Downloading $url" "Saving $total of $goal" -id 0 -percentComplete (($total/$goal)*100) } else { Write-Progress "Downloading $url" "Saving $total bytes..." -id 0 } } } while ($count -gt 0) $reader.Close() if($fileName) { $writer.Flush() $writer.Close() } if($Passthru){ $output } } $res.Close(); if($fileName) { ls $fileName } }
PowerShellCorpus/PoshCode/PowerChart _1.5.ps1
PowerChart _1.5.ps1
function New-PowerChart() { [CmdletBinding(DefaultParameterSetName='DataTemplate')] param( [Parameter(Position=0, Mandatory=$true)] [ValidateSet("Area","Bar","Bubble","Column","Line","Pie","Scatter")] [String[]] ${ChartType} , [Parameter(Position=1, Mandatory=$true, HelpMessage='The data for the chart ...')] [System.Management.Automation.ScriptBlock[]] ${ItemsSource} , [Parameter(Position=2, Mandatory=$true, HelpMessage='The property name for the independent values ...')] [String[]] ${IndependentValuePath} , [Parameter(Position=3, Mandatory=$true, HelpMessage='The property name for the dependent values ...')] [String[]] ${DependentValuePath} , [Parameter(Position=4, HelpMessage='The property name for the size values ...')] [String[]] ${SizeValuePath} , [TimeSpan] ${Interval} , [Switch] $Show ) begin { Write-Host "Interval: $Interval" Chart -ControlNale PowerChart -Tag @{Interval=$Interval; ItemsSource=$ItemsSource} -On_Loaded { $Interval = $this.Tag.Interval if($Interval) { Register-PowerShellCommand -ScriptBlock { $i=0 $Window.Content.Series | ForEach{ $_.ItemsSource = &$($Window.Content.Tag.ItemsSource[$i++]) } } -in $Interval -run } } -Series { $Series = @() # Write-Host "Three" -Fore Cyan for($c=0; $c -lt $ChartType.length; $c++) { $chartType = $ChartType[$c].ToLower() if($SizeValuePath -and $ChartType[$c] -eq "Bubble") { $Series += iex "$($chartType)Series -DependentValuePath $($DependentValuePath[$c]) -IndependentValuePath $($IndependentValuePath[$c]) -SizeValuePath $($SizeValuePath[$c]) -ItemsSource `$(&{$($ItemsSource[$c])})" #$Series[-1].DataPointStyle = $this.FindResource("$($chartType)DataPointTooltipsFix") } elseif($ChartType[$c] -eq "Pie") { $Series += iex "$($chartType)Series -DependentValuePath $($DependentValuePath[$c]) -IndependentValuePath $($IndependentValuePath[$c]) -ItemsSource `$(&{$($ItemsSource[$c])})" #$Series[-1].StylePalette = $this.FindResource("$($chartType)PaletteTooltipsFix") } else { Write-Verbose "$($chartType)Series -DependentValuePath $($DependentValuePath[$c]) -IndependentValuePath $($IndependentValuePath[$c]) -ItemsSource `$(&{$($ItemsSource[$c])})" $Series += iex "$($chartType)Series -DependentValuePath $($DependentValuePath[$c]) -IndependentValuePath $($IndependentValuePath[$c]) -ItemsSource `$(&{$($ItemsSource[$c])})" #A$Series[-1].DataPointStyle = $this.FindResource("$($chartType)DataPointTooltipsFix") } } Write-Verbose "There are $($Series.Count) Series!" $Series } -Background Transparent -BorderThickness 0 -Show:$Show } }
PowerShellCorpus/PoshCode/Get-ADGroupMembers_3.ps1
Get-ADGroupMembers_3.ps1
Function Get-ADGroupMembers { <# .SYNOPSIS Return a collection of users in an ActiveDirectory group. .DESCRIPTION This function returns an object that contains all the properties of a user object. This function works for small groups as well as groups in excess of 1000. .PARAMETER UserGroup The name of the group to get membership from. .PARAMETER UserDomain The LDAP URL of the domain that the group resides in. .EXAMPLE Get-ADGroupMembers -UserGroup Managers |Format-Table -Property name, distinguishedName, cn name distinguishedName cn ---- ----------------- -- {Steve Roberts} {CN=Steve Roberts,CN=Users,DC... {Steve Roberts} {S-1-5-21-57989841-1078081533... {CN=S-1-5-21-57989841-1078081... {S-1-5-21-57989841-1078081533... {S-1-5-21-57989841-1078081533... {CN=S-1-5-21-57989841-1078081... {S-1-5-21-57989841-1078081533... {Matt Temple} {CN=Matt Temple,CN=Users,DC=c... {Matt Temple} ... Description ----------- This example shows passing in a group name, but leaving the default domain name in place. .NOTES The context under which this script is run must have rights to pull infromation from ActiveDirectory. .LINK http://scripts.patton-tech.com/wiki/PowerShell/ActiveDirectoryManagement#Get-ADGroupMembers #> Param ( $UserGroup = "Domain Users", $UserDomain = ([ADSI]"LDAP://DC=company,DC=com") ) Begin { $DirectoryEntry = New-Object System.DirectoryServices.DirectoryEntry($UserDomain.Path) $DirectorySearcher = New-Object System.DirectoryServices.DirectorySearcher $LDAPFilter = "(&(objectCategory=Group)(name=$($UserGroup)))" $DirectorySearcher.SearchRoot = $DirectoryEntry $DirectorySearcher.PageSize = 1000 $DirectorySearcher.Filter = $LDAPFilter $DirectorySearcher.SearchScope = "Subtree" $SearchResult = $DirectorySearcher.FindAll() $UserAccounts = @() } Process { foreach ($Item in $SearchResult) { $Group = $Item.GetDirectoryEntry() $Members = $Group.member If ($Members -ne $Null) { foreach ($User in $Members) { $UserObject = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($User)") If ($UserObject.objectCategory.Value.Contains("Group")) { } Else { $ThisUser = New-Object -TypeName PSObject -Property @{ cn = $UserObject.cn distinguishedName = $UserObject.distinguishedName name = $UserObject.name nTSecurityDescriptor = $UserObject.nTSecurityDescriptor objectCategory = $UserObject.objectCategory objectClass = $UserObject.objectClass objectGUID = $UserObject.objectGUID objectSID = $UserObject.objectSID showInAdvancedViewOnly = $UserObject.showInAdvancedViewOnly } } $UserAccounts += $ThisUser } } } } End { Return $UserAccounts } }
PowerShellCorpus/PoshCode/New-CodeSigningCertifica.ps1
New-CodeSigningCertifica.ps1
##################################################################### # New-CodeSigningCertificate.ps1 # Version 1.0 # # Creates new self-signed code signing certificate and installs it to # current user's personal store. Supports Windows XP and higher. # # Initially script was developed for Quest PowerGUI ScriptEditor add-on. # # Vadims Podans (c) 2011 # http://en-us.sysadmins.lv/ ##################################################################### #requires -Version 2.0 function New-CodeSigningCertificate { [CmdletBinding()] param( [Security.Cryptography.X509Certificates.X500DistinguishedName]$Subject = "CN=PowerGUI User", [ValidateSet(1024,2048)] [int]$KeyLength = 2048, [DateTime]$ValidFrom = [datetime]::Now, [DateTime]$ValidTo = [datetime]::Now.AddYears(1) ) $signature = @" [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)] public static extern bool CryptAcquireContext( ref IntPtr phProv, string pszContainer, string pszProvider, uint dwProvType, Int64 dwFlags ); [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)] public static extern bool CryptReleaseContext( IntPtr phProv, int flags ); [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)] public static extern bool CryptGenKey( IntPtr phProv, int Algid, int dwFlags, ref IntPtr phKey ); [DllImport("Crypt32.dll", CharSet=CharSet.Auto, SetLastError=true)] public static extern bool CryptExportPublicKeyInfo( IntPtr phProv, int dwKeySpec, int dwCertEncodingType, IntPtr pbInfo, ref int pcbInfo ); [DllImport("Crypt32.dll", CharSet=CharSet.Auto, SetLastError=true)] public static extern bool CryptHashPublicKeyInfo( IntPtr phProv, int Algid, int dwFlags, int dwCertEncodingType, IntPtr pInfo, IntPtr pbComputedHash, ref int pcbComputedHash ); [DllImport("Crypt32.dll", SetLastError=true)] public static extern bool CryptEncodeObject( int dwCertEncodingType, [MarshalAs(UnmanagedType.LPStr)]string lpszStructType, ref CRYPTOAPI_BLOB pvStructInfo, byte[] pbEncoded, ref int pcbEncoded ); [DllImport("Crypt32.dll", CharSet=CharSet.Auto, SetLastError=true)] public static extern IntPtr CertCreateSelfSignCertificate( IntPtr phProv, CRYPTOAPI_BLOB pSubjectIssuerBlob, int flags, CRYPT_KEY_PROV_INFO pKeyProvInfo, IntPtr pSignatureAlgorithm, SystemTime pStartTime, SystemTime pEndTime, CERT_EXTENSIONS pExtensions ); [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)] public static extern bool CryptDestroyKey( IntPtr cryptKeyHandle ); [DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)] public static extern bool FileTimeToSystemTime( [In] ref long fileTime, out SystemTime SystemTime ); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct CRYPT_KEY_PROV_INFO { public string pwszContainerName; public string pwszProvName; public int dwProvType; public int dwFlags; public int cProvParam; public IntPtr rgProvParam; public int dwKeySpec; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct CERT_EXTENSIONS { public int cExtension; public IntPtr rgExtension; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct CERT_EXTENSION { [MarshalAs(UnmanagedType.LPStr)]public String pszObjId; public Boolean fCritical; public CRYPTOAPI_BLOB Value; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct CERT_BASIC_CONSTRAINTS2_INFO { public Boolean fCA; public Boolean fPathLenConstraint; public int dwPathLenConstraint; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct CRYPTOAPI_BLOB { public int cbData; public IntPtr pbData; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct CRYPT_BIT_BLOB { public uint cbData; public IntPtr pbData; public uint cUnusedBits; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct CERT_PUBLIC_KEY_INFO { public CRYPT_ALGORITHM_IDENTIFIER Algorithm; public CRYPT_BIT_BLOB PublicKey; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct CRYPT_ALGORITHM_IDENTIFIER { [MarshalAs(UnmanagedType.LPStr)]public String pszObjId; public CRYPTOAPI_BLOB Parameters; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct SystemTime { public short Year; public short Month; public short DayOfWeek; public short Day; public short Hour; public short Minute; public short Second; public short Milliseconds; } "@ Add-Type -MemberDefinition $signature -Namespace Quest -Name PowerGUI $pszContainer = [Guid]::NewGuid().ToString() [IntPtr]$phProv = [IntPtr]::Zero $Provider = "Microsoft Base Cryptographic Provider v1.0" $Result = [Quest.PowerGUI]::CryptAcquireContext([ref]$phProv,$pszContainer,$Provider,0x1,0x8) if (!$Result) {Write-Warning "Unable to create provider context!"; return} [IntPtr]$phKey = [IntPtr]::Zero if ($KeyLength -eq 2048) { $Result = [Quest.PowerGUI]::CryptGenKey($phProv,2,0x08000001,[ref]$phKey) } else { $Result = [Quest.PowerGUI]::CryptGenKey($phProv,2,0x04000001,[ref]$phKey) } if (!$Result) {Write-Warning "Unable to create key context!"; return} $dataHandle = [Runtime.InteropServices.GCHandle]::Alloc($Subject.RawData,"pinned") $ptrName = New-Object Quest.PowerGUI+CRYPTOAPI_BLOB -Property @{ cbData = $Subject.RawData.Count; pbData = $dataHandle.AddrOfPinnedObject() } $PrivateKey = New-Object Quest.PowerGUI+CRYPT_KEY_PROV_INFO -Property @{ pwszContainerName = $pszContainer; pwszProvName = $Provider; dwProvType = 1; dwKeySpec = 2 } $Extensions = New-Object Security.Cryptography.X509Certificates.X509ExtensionCollection # add Basic Constraints extension [void]$Extensions.Add((New-Object Security.Cryptography.X509Certificates.X509BasicConstraintsExtension $false,$false,0,$false)) # add Code Signing EKU $OIDs = New-Object Security.Cryptography.OidCollection [void]$OIDs.Add("code signing") [void]$Extensions.Add((New-Object Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension -ArgumentList $OIDs, $false)) # add SKI extension $pcbInfo = 0 if (([Quest.PowerGUI]::CryptExportPublicKeyInfo($phProv,2,1,[IntPtr]::Zero,[ref]$pcbInfo))) { $pbInfo = [Runtime.InteropServices.Marshal]::AllocHGlobal($pcbInfo) $Return = [Quest.PowerGUI]::CryptExportPublicKeyInfo($phProv,2,1,$pbInfo,[ref]$pcbInfo) $pcbComputedHash = 0 if (([Quest.PowerGUI]::CryptHashPublicKeyInfo([IntPtr]::Zero,0x00008004,0,1,$pbInfo,[IntPtr]::Zero,[ref]$pcbComputedHash))) { $pbComputedHash = [Runtime.InteropServices.Marshal]::AllocHGlobal($pcbComputedHash) [void][Quest.PowerGUI]::CryptHashPublicKeyInfo([IntPtr]::Zero,0x00008004,0,1,$pbInfo,$pbComputedHash,[ref]$pcbComputedHash) $pcbEncoded = 0 $uSKI = New-Object Quest.PowerGUI+CRYPTOAPI_BLOB -Property @{ cbData = $pcbComputedHash; pbData = $pbComputedHash } $pcbEncoded = 0 if (([Quest.PowerGUI]::CryptEncodeObject(1,"2.5.29.14",[ref]$uSKI,$null,[ref]$pcbEncoded))) { $pbEncoded = New-Object byte[] -ArgumentList $pcbEncoded $Return = [Quest.PowerGUI]::CryptEncodeObject(1,"2.5.29.14",[ref]$uSKI,$pbEncoded,[ref]$pcbEncoded) $AsnEncodedData = New-Object Security.Cryptography.AsnEncodedData -ArgumentList "2.5.29.14", $pbEncoded [void]$Extensions.Add((New-Object Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension -ArgumentList $AsnEncodedData, $false)) } } } # add KeyUsages extension [void]$Extensions.Add((New-Object Security.Cryptography.X509Certificates.X509KeyUsageExtension -ArgumentList "DigitalSignature", $true)) # transform managed extensions to unmanaged structures $uExtensionCollection = @() foreach ($mExt in $Extensions) { $uExtension = New-Object Quest.PowerGUI+CERT_EXTENSION $uExtension.pszObjId = $mExt.Oid.Value $uExtension.fCritical = $mExt.Critical $value = New-Object Quest.PowerGUI+CRYPTOAPI_BLOB $value.cbData = $mExt.RawData.Length $value.pbData = [Runtime.InteropServices.Marshal]::AllocHGlobal($value.cbData) [Runtime.InteropServices.Marshal]::Copy($mExt.RawData,0,$Value.pbData,$Value.cbData) $uExtension.Value = $value $uExtensionCollection += $uExtension } $uExtensions = New-Object Quest.PowerGUI+CERT_EXTENSIONS $ExtensionSize = [Runtime.InteropServices.Marshal]::SizeOf([Quest.PowerGUI+CERT_EXTENSION]) * $Extensions.Count $uExtensions.cExtension = $Extensions.Count $uExtensions.rgExtension = [Runtime.InteropServices.Marshal]::AllocHGlobal($ExtensionSize) for ($n = 0; $n -lt $Extensions.Count; ++$n) { $offset = $n * [Runtime.InteropServices.Marshal]::SizeOf([Quest.PowerGUI+CERT_EXTENSION]) $next = $offset + $uExtensions.rgExtension.ToInt64() [IntPtr]$NextAddress = New-Object IntPtr $next [Runtime.InteropServices.Marshal]::StructureToPtr($uExtensionCollection[$n],$NextAddress,$false) } $pStartTime = New-Object Quest.PowerGUI+SystemTime [void][Quest.PowerGUI]::FileTimeToSystemTime([ref]$ValidFrom.ToFileTime(),[ref]$pStartTime) $pEndTime = New-Object Quest.PowerGUI+SystemTime [void][Quest.PowerGUI]::FileTimeToSystemTime([ref]$ValidTo.ToFileTime(),[ref]$pEndTime) $pvContext = [Quest.PowerGUI]::CertCreateSelfSignCertificate($phProv,$ptrName,0,$PrivateKey,[IntPtr]::Zero,$pStartTime,$pEndTime,$uExtensions) if (!$pvContext.Equals([IntPtr]::Zero)) { New-Object Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList $pvContext } # release memory foreach ($uExt in $uExtensionCollection) { [void][Runtime.InteropServices.Marshal]::FreeHGlobal($uExt.Value.pbData) } [void][Runtime.InteropServices.Marshal]::FreeHGlobal($uExtensions.rgExtension) [void][Runtime.InteropServices.Marshal]::FreeHGlobal($pbInfo) [void][Runtime.InteropServices.Marshal]::FreeHGlobal($pbComputedHash) [void]$dataHandle.Free() [void][Quest.PowerGUI]::CryptDestroyKey($phKey) [void][Quest.PowerGUI]::CryptReleaseContext($phProv,0) }
PowerShellCorpus/PoshCode/Write-IseFile.ps1
Write-IseFile.ps1
function Write-IseFile($file, $msg) { $Editor = $file.Editor $Editor.SetCaretPosition($Editor.LineCount, 1) $Editor.InsertText(($msg + "`r`n")) }
PowerShellCorpus/PoshCode/Get-Gender_1.ps1
Get-Gender_1.ps1
## This script serves three purposes: ## 1) You can look up whether a name is masculine or feminine ## -- even for foreign names. ## 2) It demonstrates the use of the HttpRest functions ## 3) It demonstrates memory-caching: ## how to write a SCRIPT ... ## that becomes a FUNCTION the first time you use it. param([string]$name) ## note that this matches the params of the function function global:get-gender { ## note the "global:" pushes the function to the global scope param([string]$name) ## note that this matches the params above! if($name.Length -lt 2) { throw "You need at least two letters in the name" } $name = "$($name[0])".ToUpper() + $name.SubString(1).ToLower() ## All of this is actually a one-liner. You can delete all the carriage returns, ## and stick it all where the elipsis is: "Joel","Wendy" | % { ... } switch( Invoke-Http GET "http://www.babynameaddicts.com/cgi-bin/search.pl" @{ gender="ALL";searchfield="Names";origins="ALL";searchtype="matching";searchtext=$name } | Receive-Http Text "//font[b/font/text()='$name']/@color" ) { "fucshia" { "Femenine" } "#088dd0" { "Masculine" } } } get-gender $name ## All three sets of parameters match.... ## Note that this technique works with Advanced functions as well, ## But making it work IN the pipeline is way more work :)
PowerShellCorpus/PoshCode/628b551c-7932-48ee-843d-243be07d7546.ps1
628b551c-7932-48ee-843d-243be07d7546.ps1
function Set-Encoding{ <# .Synopsis Takes a Script file or any other text file into memory and Re-Encodes it in the format specified. .Parameter FilePath The path to the file to be re-encoded. .Parameter Unicode Outputs the file in Unicode format. .Parameter UTF7 Outputs the file in UTF7 format. .Parameter UTF8 Outputs the file in UTF8 format. .Parameter UTF32 Outputs the file in UTF32 format. .Parameter ASCII Outputs the file in ASCII format. .Parameter BigEndianUnicode Outputs the file in BigEndianUnicode format. .Parameter Default Uses the encoding of the system's current ANSI code page. .Parameter OEM Uses the current original equipment manufacturer code page identifier for the operating system. .Example ls *.ps1 | Set-Encoding -ASCII .Description Written to provide an easy method to perform easy batch encoding, calls on the command Out-File with the -Encoding parameter and the -Force switch. Primarily to fix UnknownError status received when trying to sign non-ascii format files with digital signatures. Don't use on your MP3's or other non-text files :) #> [CmdletBinding()] PARAM( [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)] [ValidateScript({ if((resolve-path $_).Provider.Name -ne "FileSystem") { throw "Specified Path is not in the FileSystem: '$_'" } return $true })] [Alias("Fullname","Path")] [string]$FilePath, [switch]$Unicode, [switch]$UTF7, [switch]$UTF8, [switch]$UTF32, [switch]$ASCII, [switch]$BigEndianUnicode, [switch]$Default, [switch]$OEM ) BEGIN{ $Encoding = "" switch( $Unicode, $UTF7, $UTF8, $UTF32, $ASCII, $BigEndianUnicode, $Default, $OEM ){ $Unicode{$Encoding = "Unicode"} $UTF7{$Encoding = "UTF7"} $UTF8{$Encoding = "UTF8"} $UTF32{$Encoding = "UTF32"} $ASCII{$Encoding = "ASCII"} $BigEndianUnicode{$Encoding = "BigEndianUnicode"} $Default{$Encoding = "Default"} $OEM{$Encoding = "OEM"} } } PROCESS{ (Get-Content $FilePath) | Out-File -FilePath $FilePath -Encoding $Encoding -Force } }
PowerShellCorpus/PoshCode/ShowUI Clock 5.ps1
ShowUI Clock 5.ps1
New-UIWidget { Grid { $shadow = DropShadowEffect -ShadowDepth 0 -BlurRadius 5 -Direction 0 Ellipse -Name Hour -Fill Transparent -Stroke Black -StrokeThickness 100 -Width 350 -Height 350 -StrokeDashArray 7.85,7.85 -RenderTransformOrigin "0.5,0.5" -RenderTransform { RotateTransform -Angle -90 } Ellipse -Name Minute -Fill Transparent -Stroke Gray -StrokeThickness 75 -Width 325 -Height 325 -StrokeDashArray 10.468,10.468 -RenderTransformOrigin "0.5,0.5" -RenderTransform { RotateTransform -Angle -90 } Ellipse -Name Second -Fill Transparent -Stroke White -StrokeThickness 50 -Width 300 -Height 300 -StrokeDashArray 15.71,15.71 -RenderTransformOrigin "0.5,0.5" -RenderTransform { RotateTransform -Angle -90 } } } -Refresh "00:00:00.2" { $now = Get-Date $Hour.StrokeDashArray[0] = $Hour.StrokeDashArray[1]/60 * $now.Hour * 5 $Minute.StrokeDashArray[0] = $Minute.StrokeDashArray[1]/60 * $now.Minute $Second.StrokeDashArray[0] = $Second.StrokeDashArray[1]/60 * $now.Second }
PowerShellCorpus/PoshCode/POC-adding custom PS job_1.ps1
POC-adding custom PS job_1.ps1
#this is just a quite proof of concept, totally useless in of itself, with functions not fleshed out function get-jobrepository { [CmdletBinding()] param() $pscmdlet.JobRepository } function add-job { [CmdletBinding()] param($job) $pscmdlet.JobRepository.add($job) } $src = @" using System; using System.Collections.Generic; using System.Text; using System.Management.Automation; namespace bkg2 { public class BackgroundJob : Job { public BackgroundJob(string command) : base(command) { } public string dummy = "hello"; public override bool HasMoreData { get { return false; } //version 1 won't stream results. no results at all until job is completed } public override string Location { get { return "localhost"; } //background jobs are always in memory on the same system } public override string StatusMessage { get { return "NO STATUS MESSAGES IMPLEMENTed YET"; } } public override void StopJob() { throw new NotImplementedException(); } } } "@ add-type -typedefinition $src 1..5 | % { add-job $(new-object bkg2.BackgroundJob {1..10}) } get-job
PowerShellCorpus/PoshCode/Move-FileSafely.ps1
Move-FileSafely.ps1
function global:Move-FileSafely { #.Synopsis # Moves files and folders from $source folder to $destination #.Description # Moves files from $source to $destination but if they already exist, it puts them in a parallel $BackupCopies folder instead #.Parameter Source # The path to the source directory #.Parameter Destination # The path to the destination. The CONTENTS of $source will be copied into this folder. #.Parameter BackupCopies # The path to an alternate folder where files will be moved to if they already exist in the destination. param($Source, $Destination, $BackupCopies=$(Join-Path $destination (Get-Date -f "backup yyyy-MM-dd"))) function Test-CreateablePath { param($path) try { # if we can resolve the parent, then we'll be able to create this ... return Join-Path (Resolve-Path (Split-Path $path) -ErrorAction STOP) (Split-Path $path -Leaf) } catch { # otherwise, if it's a full absolute path, we'll be able to create it... return (split-path $path -isabsolute) } } $source = Resolve-Path $source -ErrorAction Stop # throw if source folder doesn't exist if(!(Test-CreateablePath $Destination)) { throw "Destination ($Destination) path must be a full path, or a subfolder of an existing folder" } if(!(Test-CreateablePath $BackupCopies)) { throw "BackupCopies ($BackupCopies) path must be a full path, or a subfolder of an existing folder" } mkdir $destination -Force -ErrorAction SilentlyContinue | Out-Null Get-ChildItem $source -recurse -ErrorAction SilentlyContinue | Move-Item -Destination { split-path $_.FullName.Replace($Source, $Destination) } -ErrorVariable Problems -ErrorAction SilentlyContinue foreach($file in $Problems | Select -Expand TargetObject | Where { Test-Path $_.FullName -Type Leaf }) { $Target = $File.FullName.Replace($source, $backupCopies) mkdir (Split-Path $Target) -Force -ErrorAction SilentlyContinue | Out-Null move-item $File.FullName $Target } remove-item $source -Recurse -Force }
PowerShellCorpus/PoshCode/Cluster Windows.ps1
Cluster Windows.ps1
#Comprobacion del estado de los clusters# ######################################### # Add Exchange Admin module If ((Get-PSSnapin | where {$_.Name -match "Exchange.Management"}) -eq $null) { Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin } #Fichero donde estan los nombres de los cluster $activos= Get-content "F:\\Scripts\\Cluster\\activos.txt" #Creamos la tabla $notabla = @() $notabla += "<table width='200' border='2' cellspacing='0'>" $contador = 0 #Nos recorremos los activos foreach($activo in $activos) { $datos= gwmi -q "select * from MSCluster_ResourceGroup" -namespace root\\mscluster -computername $activo -Authentication PacketPrivacy | select Name,InternalState,State,__SERVER $name = gwmi -q "select * from MSCluster_ResourceGroup" -namespace root\\mscluster -computername $activo -Authentication PacketPrivacy | where {$_.name -like "*CLUS*"} | Select name $namecluster= $name.name foreach ( $propdatos in $datos) { #Miramos el servidor activo de dicho cluster $ClusterStatus = Get-ClusteredMailboxServerStatus -Identity $namecluster | Select -Expand OperationalMachines | ForEach {If($_ -like "*Owner*") {$_}} $ActiveNode = $ClusterStatus.Split(" ")[0] #miramos si coincide el activo con el que tiene que ser if ($ActiveNode -eq $propdatos.__SERVER) { #Miramos si algun recurso se encuentra offline if ($propdatos.name -ne "Available Storage") { if ($propdatos.internalstate -eq "Offline") { $notabla += "<tr><td>" + $propdatos.name + "</td><td><font color='red'>" + $propdatos.internalstate + "</font></td><td>" + $activeNode +"</td></tr>" $contador = $contador + 1 } #Todo está correcto else { if ($contador -gt 0) { $notabla += "<tr><TH COLSPAN=3> <font color='blue'>" + $namecluster + "</th></font></tr>" } } } } #Si no coincide else { $contador = $contador + 1 if ($propdatos.name -ne "Available Storage") { if ($propdatos.internalstate -eq "Offline") { $notabla += "<tr><td>" + $propdatos.name + "</td><td><font color='red'>" + $propdatos.internalstate + "</font></td><td BGCOLOR='red'>" + $activeNode +"</td></tr>" } else { $notabla += "<tr><td>" + $propdatos.name + "</td><td><font color='red'>" + $propdatos.internalstate + "</font></td><td BGCOLOR='red'>" + $activeNode +"</td></tr>" } } } } }#Cerramos los activos $notabla += "</table><br>" $notabla > estado.html if ($contador -gt 0) { #Terminada la recofida de datos, lo mandamos por email $smtpServer = "xx.xx.xx.xx" $smtpFrom = "Cluster Windows <email@dominio.es>" $smtpTo = "email2@dominio.es" $message = New-Object System.Net.Mail.MailMessage $smtpfrom, $smtpto $message.Subject = "Chequeo Cluster Windows" $message.IsBodyHTML = $true $message.Body = $notabla $smtp = New-Object Net.Mail.SmtpClient($smtpServer) $smtp.Send($message) }
PowerShellCorpus/PoshCode/9db524e2-1659-493b-ad36-3624e7796a76.ps1
9db524e2-1659-493b-ad36-3624e7796a76.ps1
## Simplest RSS Reader\n####################################################################################################\n## Save this file as Start-RssReader.ps1\n## Run it like:\n## .\\Start-RssReader "http://feeds.feedburner.com/powerscripting", "http://HuddledMasses.org/feed"\n## And then:\n## Get-RSS # to (re)fetch the feeds and view\n## Show-RSS # to view without re-fetching\n## Open-RSSItem 2 # to open an item in your browser\n####################################################################################################\nPARAM( \n [string[]]$RssReaderUrls = $(do{\n $k = Read-Host "Specify an RSS Feed URL (hit Enter when done)"\n if($k) {write-output $k}\n } while($k) )\n)\n\nfunction global:Get-RSS {\n $webClient = New-Object System.Net.WebClient\n $global:RssReaderNews = $RssReaderUrls | % { [xml]$webClient.DownloadString( $_ ) } | \n % { $_.rss.channel.item } | \n Sort { [DateTime]$_.pubDate } -Desc\n Show-RSS\n}\n\nfunction global:Show-RSS($days=7) {\n $script:index = -1\n $global:RssReaderNews | Where { ([DateTime]$_.pubDate).AddDays($days) -gt [DateTime]::Now } | \n ft @{l="Index";e={return $script:index++}},@{l="Day";e={$_.pubDate.split(",",2)[0]}}, title, link -auto\n}\n\nfunction global:Open-RssItem($index=0) {\n [Diagnostics.Process]::Start( $($global:RssReaderNews[$index].link) )\n}\n$global:RssReaderUrls = $RssReaderUrls\nGet-RSS
PowerShellCorpus/PoshCode/push-module function v2 .ps1
push-module function v2 .ps1
# v2.0 function Push-Module { param( [parameter(position=0, mandatory=$true)] [validatenotnullorempty()] [string]$ModuleName ) # find out what this module exports (and therefore what it overwrites) $metadata = new-module -ascustomobject { param([string]$ModuleName) # import targeted module $inner = import-module $ModuleName -PassThru function GetExportedFunctions() { $inner.ExportedFunctions.values } # prevent export of inner module's exports Export-ModuleMember -Cmdlet "" -Function GetExportedFunctions } -args $ModuleName # find out which global functions might get clobbered $test = new-module -ascustomobject { param($metadata) $clobbered = @{} # grab copies of functions that would get clobbered $metadata.GetExportedFunctions() | ? { Test-Path "function:$($_.name)" } | % { $clobbered[$_.name] = gc -path "function:$($_.name)" } function GetClobberedFunctions() { $clobbered } } -args $metadata # import module $m = import-module $ModuleName -PassThru # grab clobberable (!) functions $clobbered = $test.GetClobberedFunctions() # hook up function restore $m.onremove = { $clobbered.keys | % { si -path function:global:$_ $clobbered[$_] -force } }.getnewclosure() }
PowerShellCorpus/PoshCode/Get Twitter RSS Feed_5.ps1
Get Twitter RSS Feed_5.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/Get-HtmlHelp 3.0.ps1
Get-HtmlHelp 3.0.ps1
## Get-HtmlHelp - by Joel Bennett ## version 3.0 ##################################################################### ## Cool Example, using ShowUI: ## Import-Module HtmlHelp ## Import-Module ShowUI ## function Show-Help { [CmdletBinding()]param([String]$Name) ## Window { WebBrowser -Name wb } -On_Loaded { ## $wb.NavigateToString((Get-HtmlHelp $Name)) ## $this.Title = "Get-Help $Name" ## } -Show ## } ## Show-Help Get-Help ## ##################################################################### #Import System.Web in order to use HtmlEncode functionality Add-Type -Assembly System.Web function ConvertTo-Dictionary([hashtable]$ht) { $kvd = new-object "System.Collections.Generic.Dictionary``2[[System.String],[System.String]]" foreach($kv in $ht.GetEnumerator()) { $kvd.Add($kv.Key,$kv.Value) } return $kvd } function htmlEncode { param([Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true)][String]$Text) process{ [System.Web.HttpUtility]::HtmlEncode($Text) } } function trim { param([Parameter(ValueFromPipeline=$true,Mandatory=$true)][String]$string) process{ $string.Trim() } } function trimEncode{ param([Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true)][String]$Text) process{ [System.Web.HttpUtility]::HtmlEncode($Text).Trim() } } function HHSplit { param( $Separator="\\s*\\r?\\n", [Parameter(ValueFromPipeline=$true,Mandatory=$true)] [String]$inputObject ) process{ foreach($item in [regex]::Split($inputObject,$Separator)) { $item.Trim() | Where {$_.Length} } } } function HHjoin { param( [Parameter(Position=0)] $Separator=$ofs, [Parameter(ValueFromPipeline=$true,Mandatory=$true)] [String[]] $inputObject ) begin { [string[]]$array = $inputObject } process { $array += $inputObject } end { Write-Verbose $Array.Length if($array.Length -gt 1) { [string]::Join($Separator,$array) } else { $array } } } function Out-HtmlTag { param([Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true)][String]$Text, $Tag="p") process{ $html = $Text | out-string -width ([int]::MaxValue) | HHSplit | trimEncode | HHjoin "</$tag>`n<$tag>" $html = $html -replace '(\\S+)(http://.*?)([\\s\\p{P}](?:\\s|$))','<a href="$2">$1</a>$3' "<$tag>$html</$tag>" } } function Out-HtmlList { param([Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true)][String]$Text) process{ "<li>$($Text | out-string -width ([int]::MaxValue) | HHSplit | trimEncode | HHjoin "</li>`n<li>")</li>" } } function Out-HtmlDefList { param( [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true)]$Node, [String[]]$Term, [String[]]$Definition ) # begin { "<dl>"} process{ $tx = $Node foreach($t in $Term) { $tx = $tx.$t; Write-Verbose "${t}: $tx" } $dx = $Node foreach($d in $Definition) { $dx = $dx.$d; Write-Verbose "${t}: $dx" } "<dt>{0}</dt><dd>{1}</dd>" -f ($tx | trimEncode),($dx | trimEncode) } # end { "</dl>"} } function Out-HtmlBr { param([Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Mandatory=$true)][String]$Text) process{ $Text | out-string -width ([int]::MaxValue) | HHSplit | trimEncode | HHjoin "<br />" } } ## Utility Functions function Get-UtcTime { Param($Format="") [DateTime]::Now.ToUniversalTime().ToString($Format) } function Encode-Twice { param([Parameter(ValueFromPipeline=$true,Mandatory=$true)][String]$string) process { [System.Web.HttpUtility]::UrlEncode( [System.Web.HttpUtility]::UrlEncode( $string ) ) } } ## Get-HtmlHelp - A Helper function for generating help: ## Usage: Get-HtmlHelp Get-* function Get-HtmlHelp { param([string[]]$commands, [string]$baseUrl = "http://http://technet.microsoft.com/en-us/library/") $commands | Get-Command -EA "SilentlyContinue" | Get-Help -Full | Convert-HelpToHtml $baseUrl } function textile { param([string]$text) $text -replace '(?<=\\r\\n\\r\\n|^)\\*\\s(.*)(?=\\r\\n)',"<ul>`r`n<li>`$1</li>" <# start of a list #>` -replace '(?<=\\r\\n)\\*\\s+((?:.|\\r\\n(?![\\*\\r]))+)(?=\\r\\n\\r\\n|\\r\\n\\*|$)',"<li>`$1</li>" <# middle of a list #>` -replace '</li>(?=\\r\\n\\r\\n|$)',"</li>`r`n</ul>" <# end of the list #>` -replace '(?<=\\r\\n\\r\\n|^)([^\\n]*)(?=\\r\\n\\r\\n|$)',"<p>`r`n`$1`r`n</p>" <# regular paragraphs #>` -replace '(?<=\\r\\n\\r\\n)([^\\r\\n]*\\s+[^\\r\\n]*)\\r\\n(-+)(?=\\r\\n\\r\\n)',"<h3>`$1</h3>" <# headers #>` -replace '(?<=[^\\r\\n>])(\\r\\n)(?=[^\\r\\n]+)',"<br />`$1" <# remaining linebreaks #>` -replace " "," &nbsp;" # Because the content is originally for get-help, preserve whitespace } function Convert-ParameterHelp { param([Parameter(ValueFromPipeline=$true,Mandatory=$true)]$ParameterItem) process { $name = $( if($ParameterItem.position -ne "named") { "[-<strong>{0}</strong>]" -f $ParameterItem.name } else { "-<strong>{0}</strong>" -f $ParameterItem.name } ) if($ParameterItem.required -eq "false") { "<nobr>[{0} {1}]</nobr>" -f $name, $ParameterItem.parameterValue } else { "<nobr>{0} {1}</nobr>" -f $name, $ParameterItem.parameterValue } } } function Convert-SyntaxItem { param([Parameter(ValueFromPipeline=$true,Mandatory=$true)]$SyntaxItem) process { "<li>{0} {1}</li>" -f $SyntaxItem.name, $($SyntaxItem.parameter | Convert-ParameterHelp | join " ") } } function Convert-HelpToHtml { param( [string]$baseUrl, [Parameter(ValueFromPipeline=$true)] $Help ) PROCESS { # throw "Can only process -Full view help output" # Name isn't needed, since this is going as the body, but ... # $data = "<html><head><title>$(trimEncode($help.Name))</title></head><body>"; # $data += "<h1>$(trimEncode($help.Name))</h1>" $data = @" <html> <head> <title>$(trimEncode($help.Name))</title> <style type="text/css"> h1, h2, h3, h4, h5, h6 { color: #369 } ul.syntax { list-style: none outside; font-size: .9em; font-family: Consolas, "DejaVu Sans Mono", "Lucida Console", monospace; } ul.syntax li { margin: 3px 0px; } table.parameters th { text-align: left; } </style> </head> <body> <h1>$(trimEncode($help.Name))</h1> "@ # Synopsis $data += "<h2>Synopsis</h2>$($help.Synopsis | Out-HtmlTag -Tag p)" # Syntax $data += "<h2 class='syntax'>Syntax</h2><ul class='syntax'>$($help.Syntax.syntaxItem | Convert-SyntaxItem)</ul>" # Related Commands $data += "<h2>Related Commands</h2>" foreach ($relatedLink in $help.relatedLinks.navigationLink) { if($relatedLink.linkText -and !$relatedLink.linkText.StartsWith("about")) { $uri = "" if( $relatedLink.uri -ne "" ) { $uri = $relatedLink.uri } else { $uri = "$baseUrl/$((get-command $relatedLink.linkText -EA "SilentlyContinue").PSSnapin.Name)/$($relatedLink.linkText)" } $data += "<a href='$(trimEncode($uri))'>$(trimEncode($relatedLink.linkText))</a><br>" } } # Detailed Description $data += "<h2>Detailed Description</h2>$($help.Description | Out-HtmlTag -Tag p)" # Parameters $data += "<h2>Parameters</h2>" foreach($param in $help.parameters.parameter) { $data += "<h4>-$(trimEncode($param.Name)) [&lt;$(trimEncode($param.type.name))&gt;]</h4>" $data += $param.Description | Out-HtmlTag -Tag p $data += "<table class='parameters'>" $data += "<tr><th>Required? &nbsp;</th><td> $(trimEncode($param.Required))</td></tr>" $data += "<tr><th>Position? &nbsp;</th><td> $(trimEncode($param.Position))</td></tr>" if($param.DefaultValue) { $data += "<tr><th>Default value? &nbsp;</th><td> $(trimEncode($param.defaultValue))</td></tr>" } $data += "<tr><th>Accept pipeline input? &nbsp;</th><td> $(trimEncode($param.pipelineInput))</td></tr>" $data += "<tr><th>Accept wildcard characters? &nbsp;</th><td> $(trimEncode($param.globbing))</td></tr></table>" } if($help.inputTypes) { # Input Type $data += "<h3>Input Type</h3><dl class='input'>$( $help.inputTypes.inputType | Out-HtmlDefList -Term type, name -Definition description )</dl>" } if($help.returnValues) { # Return Type $data += "<h3>Output Type</h3><dl class='output'>$( $help.returnValues.returnValue | Out-HtmlDefList -Term type, name -Definition description )</dl>" } # Notes $data += "<h2>Notes</h2>$($help.alertSet.alert | Out-HtmlTag -Tag p)" # Examples if($help.Examples.example -and $help.Examples.example.Length) { $data += "<h2>Examples</h2>" foreach($example in $help.Examples.example){ if($example.title) { $data += "<h4>$(trimEncode($example.title.trim(' -')))</h4>" } $data += "<code><strong>C:\\PS&gt;</strong>&nbsp;$(($example.code | Out-HtmlBr) -replace "<br />C:\\\\PS&gt;","<br /><strong>C:\\PS&gt;</strong>&nbsp;")</code>" $data += "<p>$($example.remarks | out-string -width ([int]::MaxValue) | Out-HtmlTag -Tag p)</p>" } } $data += "</body></html>" write-output $data }} # Export-ModuleMember Get-HtmlHelp
PowerShellCorpus/PoshCode/WPFDiskSpace_1.ps1
WPFDiskSpace_1.ps1
#.Example # Get-WmiObject -computername Z002 Win32_LogicalDisk -filter "DriveType=3" | New-DiskSpace #.Note # Requires ShowUI 1.1 and Visifire (You must use Add-UIModule on the Visifire dll and then import it) function New-DiskSpace { param([Parameter(ValueFromPipeline=$true)]$InputObject) begin { $chart = Chart -MinHeight 100 -MinWidth 200 -Theme Theme2 -View3D ` -BorderBrush Gray -CornerRadius 5 -BorderThickness 0.5 ` -AnimationEnabled:$false -Series { DataSeries -RenderAs StackedBar -LegendText UsedSpace -LabelEnabled $true DataSeries -RenderAs StackedBar -LegendText FreeSpace -LabelEnabled $true # -RadiusX 5 -RadiusY 5 } } process { foreach ($disk in $InputObject) { [double]$free = [System.Math]::Round(($disk.FreeSpace/1GB),2) [int]$pFree = ([double]$disk.FreeSpace/[double]$disk.Size) * 100 [double]$used = [System.Math]::Round((([double]$disk.Size - [double]$disk.FreeSpace)/1GB),2) [int]$pUsed = (([double]$disk.Size - [double]$disk.FreeSpace)/[double]$disk.Size) * 100 $dp1 = DataPoint -AxisXLabel $disk.Name -YValue $used -LabelText "$pUsed%" - $chart.Series[0].DataPoints.Add($dp1) $dp2 = DataPoint -YValue $free -LabelText "$pFree%" $chart.Series[1].DataPoints.Add($dp2) } } end { Grid -ControlName "DiskSpace Chart" { $chart } -show } }
PowerShellCorpus/PoshCode/vibackup linux script.ps1
vibackup linux script.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.4" $scriptout = @() #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 | Measure-Object | select count).Count -ne "0") { Write-Host "VM has Snapshots. No Backup possible." return $false exit } #write script $scriptname = $vm.name + ".sh" $vmname = $vm.Name $vmhost = $vm.Host #generate Text $header = "#!/bin/bash" $user = "USER=`"${viUser}`"" $pass = "PASS=`"${viPass}`"" $dest = "DEST=`"${lxDest}`"" $lxVM = "VM=`"${vmname}`"" #region writefile $scriptout += $header $scriptout += $user $scriptout += $pass $scriptout += $dest $scriptout += $lxvm $scriptout += "" $scriptout += "BKUP=``vmrun -h https://${viserver}/sdk -u `${USER} -p `${PASS} list | grep `${VM}`` " $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. Arborting...' `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 $vifs = "vifs --server ${viserver} --dc 'KM' --username `${USER} --password `${PASS} --get `"``echo $hdname | sed 's/.vmdk/-flat.vmdk/g'```" `${DEST}/`${VM}.vmdk " $scriptout += $vifs } $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/Findup_6.ps1
Findup_6.ps1
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.Runtime.InteropServices; using Microsoft.Win32; using System.IO; namespace Findup { public class FileInfoExt { public FileInfoExt(FileInfo fi) { FI = fi; } public FileInfo FI { get; private set; } public bool Checked { get; set; } public string SHA512_1st1K { get; set; } public string SHA512_All { get; set; } } class Recurse // Add FileInfoExt objects of files matching filenames, file specifications (IE: *.*), and in directories in pathRec, to returnList { public void Recursive(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfoExt> returnList) { foreach (string d in pathRec) { Recursive(d, searchPattern, recursiveFlag, returnList); } return; } public void Recursive(string pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfoExt> returnList) { if (File.Exists(pathRec)) { try { returnList.Add(new FileInfoExt(new FileInfo(pathRec))); } catch (Exception e) { Console.WriteLine("Add file error: " + e.Message); } } else if (Directory.Exists(pathRec)) { try { DirectoryInfo Dir = new DirectoryInfo(pathRec); foreach (FileInfo addf in (Dir.GetFiles(searchPattern))) { returnList.Add(new FileInfoExt(addf)); } } catch (Exception e) { Console.WriteLine("Add files from Directory error: " + e.Message); } if (recursiveFlag == true) { try { foreach (string d in (Directory.GetDirectories(pathRec))) { Recursive(d, searchPattern, recursiveFlag, returnList); } } catch (Exception e) { Console.WriteLine("Add Directory error: " + e.Message); } } } else { try { string filePart = Path.GetFileName(pathRec); string dirPart = Path.GetDirectoryName(pathRec); if (filePart.IndexOfAny(new char[] { '?', '*' }) >= 0) { if ((dirPart == null) || (dirPart == "")) dirPart = Directory.GetCurrentDirectory(); if (Directory.Exists(dirPart)) { Recursive(dirPart, filePart, recursiveFlag, returnList); } else { Console.WriteLine("Invalid file path, directory path, file specification, or program option specified: " + pathRec); } } else { Console.WriteLine("Invalid file path, directory path, file specification, or program option specified: " + pathRec); } } catch (Exception e) { Console.WriteLine("Parse error on: " + pathRec); Console.WriteLine("Make sure you don't end a directory with a \\\\ when using quotes. The console arg parser doesn't accept that."); Console.WriteLine("Exception: " + e.Message); return; } } return; } } class Findup { public static void Main(string[] args) { Console.WriteLine("Findup.exe v1.0 - use -help for usage information. Created in 2010 by James Gentile."); Console.WriteLine(" "); string[] paths = new string[0]; System.Boolean recurse = false; System.Boolean delete = false; System.Boolean noprompt = false; List<FileInfoExt> fs = new List<FileInfoExt>(); long bytesInDupes = 0; // bytes in all the duplicates long numOfDupes = 0; // number of duplicate files found. long bytesRec = 0; // number of bytes recovered. long delFiles = 0; // number of files deleted. int c = 0; int i = 0; string deleteConfirm; for (i = 0; i < args.Length; i++) { if ((System.String.Compare(args[i], "-help", true) == 0) || (System.String.Compare(args[i], "-h", true) == 0)) { Console.WriteLine("Usage: findup.exe <file/directory #1> <file/directory #2> ... <file/directory #N> [-recurse] [-delete] [-noprompt]"); Console.WriteLine(" "); Console.WriteLine("Options: -help - displays this help infomration."); Console.WriteLine(" -recurse - recurses through subdirectories."); Console.WriteLine(" -delete - deletes duplicates with confirmation prompt."); Console.WriteLine(" -noprompt - when used with -delete option, deletes files without confirmation prompt."); Console.WriteLine(" "); Console.WriteLine("Examples: findup.exe c:\\\\finances -recurse"); Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data -recurse -delete -noprompt"); Console.WriteLine(" "); return; } if (System.String.Compare(args[i], "-recurse", true) == 0) { recurse = true; continue; } if (System.String.Compare(args[i], "-delete", true) == 0) { delete = true; continue; } if (System.String.Compare(args[i], "-noprompt", true) == 0) { noprompt = true; continue; } Array.Resize(ref paths, paths.Length + 1); paths[c] = args[i]; c++; } if (paths.Length == 0) { Console.WriteLine("No files specified, try findup.exe -help"); return; } Recurse recurseMe = new Recurse(); recurseMe.Recursive(paths, "*.*", recurse, fs); if (fs.Count < 2) { Console.WriteLine("Findup.exe needs at least 2 files to compare. try findup.exe -help"); return; } for (i = 0; i < fs.Count; i++) { if (fs[i].Checked == true) // If file was already matched, then skip to next. continue; for (c = i + 1; c < fs.Count; c++) { if (fs[c].Checked == true) // skip already matched inner loop files. continue; if (fs[i].FI.Length != fs[c].FI.Length) // If file size matches, then check hash. continue; if (System.String.Compare(fs[i].FI.FullName, fs[c].FI.FullName, true) == 0) // don't count the same file as a match. continue; if (fs[i].SHA512_1st1K == null) // check/hash first 1K first. fs[i].SHA512_1st1K = ComputeInitialHash(fs[i].FI.FullName); if (fs[c].SHA512_1st1K == null) fs[c].SHA512_1st1K = ComputeInitialHash(fs[c].FI.FullName); if (fs[i].SHA512_1st1K != fs[c].SHA512_1st1K) // if the 1st 1K has the same hash.. continue; if (fs[i].SHA512_1st1K == null) // if hash error, then skip to next file. continue; if (fs[i].FI.Length > 1024) // skip hashing the file again if < 1024 bytes. { if (fs[i].SHA512_All == null) // check/hash the rest of the files. fs[i].SHA512_All = ComputeFullHash(fs[i].FI.FullName); if (fs[c].SHA512_All == null) fs[c].SHA512_All = ComputeFullHash(fs[c].FI.FullName); if (fs[i].SHA512_All != fs[c].SHA512_All) continue; if (fs[i].SHA512_All == null) // check for hash fail before declairing a duplicate. continue; } Console.WriteLine(" Match: " + fs[i].FI.FullName); Console.WriteLine(" with: " + fs[c].FI.FullName); fs[c].Checked = true; // do not check or match against this file again. numOfDupes++; // increase count of matches. bytesInDupes += fs[c].FI.Length; // accumulate number of bytes in duplicates. if (delete != true) // if delete is specified, try to delete the duplicate file. continue; if (noprompt == false) { Console.Write("Delete the duplicate file <Y/n>?"); deleteConfirm = Console.ReadLine(); if ((deleteConfirm[0] != 'Y') && (deleteConfirm[0] != 'y')) continue; } try { File.Delete(fs[c].FI.FullName); Console.WriteLine("Deleted: " + fs[c].FI.FullName); bytesRec += fs[c].FI.Length; delFiles++; } catch (Exception e) { Console.WriteLine("File delete error: " + e.Message); } } } Console.WriteLine(" "); Console.WriteLine("Files checked : {0:N0}", fs.Count); Console.WriteLine("Duplicate files : {0:N0}", numOfDupes); Console.WriteLine("Duplicate bytes : {0:N0}", bytesInDupes); Console.WriteLine("Duplicates deleted : {0:N0}", delFiles); Console.WriteLine("Recovered bytes : {0:N0}", bytesRec); return; } private static readonly byte[] readBuf = new byte[1024]; private static string ComputeInitialHash(string path) { try { using (var stream = File.OpenRead(path)) { var length = stream.Read(readBuf, 0, readBuf.Length); var hash = SHA512.Create().ComputeHash(readBuf, 0, length); return BitConverter.ToString(hash); } } catch (Exception e) { Console.WriteLine("Hash Error: " + e.Message); return (null); } } private static string ComputeFullHash(string path) { try { using (var stream = File.OpenRead(path)) { return BitConverter.ToString(SHA512.Create().ComputeHash(stream)); } } catch (Exception e) { Console.WriteLine("Hash error: " + e.Message); return (null); } } } }
PowerShellCorpus/PoshCode/BufferBox 3.6.ps1
BufferBox 3.6.ps1
#################################################################################################### ## This script is just a demonstration of some of the things you can do with the buffer ## in the default PowerShell host... it serves as a reminder of how much work remains on ## PoshConsole, and as an inspiration to anyone who is thinking about trying to create ## "interactive" PowerShell applications. ## ## Try Test-DisplayBox and then Test-BufferBox (note it has tab completion and everything). #################################################################################################### $global:BoxChars = new-object PSObject -Property @{ 'HorizontalDouble' = ([char]9552).ToString() 'VerticalDouble' = ([char]9553).ToString() 'TopLeftDouble' = ([char]9556).ToString() 'TopRightDouble' = ([char]9559).ToString() 'BottomLeftDouble' = ([char]9562).ToString() 'BottomRightDouble' = ([char]9565).ToString() 'HorizontalDoubleSingleDown' = ([char]9572).ToString() 'HorizontalDoubleSingleUp' = ([char]9575).ToString() 'Horizontal' = ([char]9472).ToString() 'Vertical' = ([char]9474).ToString() 'TopLeft' = ([char]9484).ToString() 'TopRight' = ([char]9488).ToString() 'BottomLeft' = ([char]9492).ToString() 'BottomRight' = ([char]9496).ToString() 'Cross' = ([char]9532).ToString() 'VerticalDoubleRightSingle' = ([char]9567).ToString() 'VerticalDoubleLeftSingle' = ([char]9570).ToString() } $global:RectType = "system.management.automation.host.rectangle" function Show-ConsoleMenu { param( [Parameter(ValueFromPipeline=$true)] [PSObject[]]$choices, [Alias("Title")] [string]$Caption, [int]$indentLeft=8, [Switch]$Passthru, [Switch]$UseBufferBox ) begin { $allchoices = New-Object System.Collections.ArrayList } process { if($choices) { $allchoices.AddRange($choices) } } end { # Make a hashtable with keys for($i=0; $i -lt $allchoices.Count; $i++) { $allchoices[$i] | Add-Member NoteProperty ConsoleMenuKey $i } # output the menu to the screen $menu = $allchoices | Format-Table -HideTableHeader @{E="ConsoleMenuKey";A="Right";W=$indentLeft}, @{E={$_};A="Left"} | Out-String $menu = "`n" + (" " * ($indentLeft/2)) + $Caption + "`n" + $menu.TrimEnd() + "`n" if($UseBufferBox) { $menu -split "`n" | Out-Buffer } else { $menu } # get a choice from the user do { $Key = $Host.UI.RawUI.ReadKey("IncludeKeyDown,NoEcho").Character try { [int][string]$choice = $Key } catch { [int][char]$choice = $Key } } while(!$allchoices.Count -and !(13,27 -contains $Key)) if($Passthru) { $allchoices[$choice] } else { $choice } }} function Reset-Buffer { param( $Position = $Host.UI.RawUI.WindowPosition, [int]$Height = $Host.UI.RawUI.WindowSize.Height, [int]$Width = $Host.UI.RawUI.WindowSize.Width, # Note: all edges are padded by 1 for the box edges, but we also pad each side by this ammount: [int]$Padding = 1, $ForegroundColor = $Host.UI.RawUI.ForegroundColor, $BackgroundColor = $Host.UI.RawUI.BackgroundColor, $BorderColor = "Yellow", [switch]$NoBorder, [switch]$ShowInput, [string]$Title = "" ) $global:BufferHeight = $Height $global:BufferWidth = $Width $global:BufferPadding = $Padding $global:BufferForegroundColor = $ForegroundColor $global:BufferBackgroundColor = $BackgroundColor $global:BufferBorderColor = $BorderColor if($NoBorder) { $global:BufferBoxSides = 0 } else { $global:BufferBoxSides = 2 } if($ShowInput) { $global:BufferHeight -= 2 } $Host.UI.RawUI.SetBufferContents($Position,(New-BufferBox $BufferHeight $BufferWidth -Title:$Title -NoBorder:$NoBorder -ShowInput:$ShowInput -Background $BufferBackgroundColor -Border $BufferBorderColor)) $global:BufferPosition = $Position $global:BufferPosition.X += $global:BufferPadding + ($global:BufferBoxSides/2) # this gets set to the BOTTOM line, because I assume text will flow in from the bottom. $global:BufferPosition.Y += $global:BufferHeight - 2 # and this goes below that ... $global:BufferPromptPosition = $BufferPosition $global:BufferPromptPosition.Y += 2 $global:BufferPromptPosition.X += 2 - $global:BufferPadding # Prompt = "> " } function New-BufferBox { param( [int]$Height = $global:BufferHeight, [int]$Width = $global:BufferWidth, $Title = "", [switch]$NoBorder, [switch]$ShowInput, $BackgroundColor = $global:BufferBackgroundColor, $BorderColor = $global:BufferBorderColor ) $Width = $Width - $global:BufferBoxSides $LineTop =( $global:BoxChars.HorizontalDouble * 2) + $Title ` + $($global:BoxChars.HorizontalDouble * ($Width - ($Title.Length+2))) $LineField = ' ' * $Width $LineBottom = $global:BoxChars.HorizontalDouble * $Width $LineSeparator = $global:BoxChars.Horizontal * $Width $LinePrompt = '> ' + ' ' * ($Width-2) # Prompt = "> " if(!$NoBorder) { $LineField = $global:BoxChars.VerticalDouble + $LineField + $global:BoxChars.VerticalDouble $LinePrompt = $global:BoxChars.VerticalDouble + $LinePrompt + $global:BoxChars.VerticalDouble $LineBottom = $global:BoxChars.BottomLeftDouble + $LineBottom + $global:BoxChars.BottomRightDouble $LineTop = $global:BoxChars.TopLeftDouble + $LineTop + $global:BoxChars.TopRightDouble $LineSeparator = $global:BoxChars.VerticalDoubleRightSingle + $LineSeparator + $global:BoxChars.VerticalDoubleLeftSingle } if($ShowInput) { $box = &{$LineTop;1..($Height - 2) |% {$LineField};$LineSeparator;$LinePrompt;$LineBottom} } else { $box = &{$LineTop;1..($Height - 2) |% {$LineField};$LineBottom} } $boxBuffer = $Host.UI.RawUI.NewBufferCellArray($box,$BorderColor,$BackgroundColor) return ,$boxBuffer } function Move-Buffer { param( $Position = $global:BufferPosition, [int]$Left = $($global:BufferBoxSides/2), [int]$Top = (2 - $global:BufferHeight), [int]$Width = $global:BufferWidth - $global:BufferBoxSides, [int]$Height = $global:BufferHeight, [int]$Offset = -1 ) $Position.X += $Left $Position.Y += $Top $Rect = New-Object $RectType $Position.X, $Position.Y, ($Position.X + $width), ($Position.Y + $height -1) $Position.Y += $OffSet $Host.UI.RawUI.ScrollBufferContents($Rect, $Position, $Rect, (new-object System.Management.Automation.Host.BufferCell(' ',$global:BufferForegroundColor,$global:BufferBackgroundColor,'complete'))) } function Out-Buffer { param( [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] $Message, [Parameter(ValueFromPipelineByPropertyName=$true)] $ForegroundColor = $global:BufferForegroundColor, [Parameter(ValueFromPipelineByPropertyName=$true)] $BackgroundColor = $global:BufferBackgroundColor, [switch]$NoScroll, [Parameter(ValueFromPipelineByPropertyName=$true)] $Position = $global:BufferPosition, [Parameter(ValueFromPipelineByPropertyName=$true)] [int]$Left = 0, [Parameter(ValueFromPipelineByPropertyName=$true)] [int]$Top = $(3 - $global:BufferHeight), # Box Edge + New Lines [Parameter(ValueFromPipelineByPropertyName=$true)] [int]$Width = ($global:BufferWidth - $global:BufferBoxSides), # Box Edge [Parameter(ValueFromPipelineByPropertyName=$true)] [int]$Height = ($global:BufferHeight - $global:BufferBoxSides), # Box Edge [Parameter(ValueFromPipelineByPropertyName=$true)] [int]$Offset = $( 0 - ($Message.Split("`n").Count)) ) process { $lineCount = $Message.Split("`n").Count $Width = $Width - ($global:BufferPadding * 2) if(!$NoScroll){ Move-Buffer $Position $Left $Top $Width $Height $Offset } $MessageBuffer = New-Object "System.Management.Automation.Host.BufferCell[,]" $lineCount, $width $index = 0 foreach( $line in $Message.Split("`n") ) { $Buffer = $Host.UI.RawUI.NewBufferCellArray( @($line.Trim("`r").PadRight($Width)), $ForegroundColor, $BackgroundColor ) for($i = 0; $i -lt $width; $i++) { $MessageBuffer[$index,$i] = $Buffer[0,$i] } $index++ } $Y = $global:BufferPosition.Y $global:BufferPosition.Y -= $lineCount - 1 $Host.UI.RawUI.SetBufferContents($global:BufferPosition,$MessageBuffer) $global:BufferPosition.Y = $Y } } function Set-BufferInputLine { param([String]$Line = "") $PromptText = $line.PadRight(($global:BufferWidth - $line.Length - 3)) # Prompt = "> " $CursorPosition = $BufferPromptPosition $CursorPosition.X += $line.Length $Prompt = $Host.UI.RawUI.NewBufferCellArray( @($PromptText),$global:BufferForegroundColor, $global:BufferBackgroundColor) $Host.UI.RawUI.SetBufferContents( $BufferPromptPosition, $prompt ) $Host.UI.RawUI.CursorPosition = $CursorPosition } function Test-DisplayBox { $Position = $Host.UI.RawUI.WindowPosition $Position.X += 10 $Position.Y += 3 Reset-Buffer $Position 20 66 3 -ForegroundColor 'Gray' -BackgroundColor 'Black' -BorderColor 'Green' Out-Buffer 'Greetings!' 'Yellow' 'black' sleep -m 600 Out-Buffer '' 'Gray' 'black' sleep -m 600 Out-Buffer '- - - Thank you for running this simple demo script! - - -' 'Green' 'black' sleep -m 600 Out-Buffer '' 'Gray' 'black' sleep -m 600 Out-Buffer 'We are demonstrating how the scroll buffer works: you can add more than one line at a time, but you don''t really need to, since they add almost as fast one at a time.' 'white' 'black' sleep -m 3000 Out-Buffer '' 'Gray' 'black' Out-Buffer 'That is, as long as you don''t have any delay, you can just' 'white' 'black' Out-Buffer 'write out as many lines as you like, one-at-a-time, like' 'white' 'black' Out-Buffer 'this, and there is really no downside to doing that.' 'white' 'black' sleep -m 3000 Out-Buffer '' 'Gray' 'black' Out-Buffer 'Right? '.PadRight(58,"-") 'Red' 'black' Out-Buffer '' 'Gray' 'black' sleep -m 600 Out-Buffer 'It''s clearly not as slick to just pop in multiple lines' 'white' 'black' sleep -m 1200 Out-Buffer 'with absolutely no scroll delay, and it makes it a little ' 'white' 'black' sleep -m 1200 Out-Buffer 'hard to tell what you have read already, but that''s ok.' 'white' 'black' sleep -m 1200 Out-Buffer '' 'Gray' 'black' sleep -m 600 Out-Buffer 'If you delay between paragraphs.' 'Red' 'black' sleep -m 600 Out-Buffer '' 'Gray' 'black' sleep -m 600 Out-Buffer 'But: don''t scroll off-screen faster than I can read!' 'Yellow' 'black' sleep -m 600 Out-Buffer '' 'Gray' 'black' } ## Test-BufferBox 3.1 - Now with Tab completion #################################################################################################### ## Imagine it's a chat window: you can type, but the whole time, the ongoing conversation in the ## chat room you have joined is going on in the background. ## ## NOTE: because this is a "chat" demo, we treat your input as text, and to execute script in-line ## you have to enclose it inside $() braces. #################################################################################################### function Test-BufferBox { param( $title = "PowerShell Interactive Buffer Demo" ) Reset-Buffer -ShowInput -Title $Title ################################################################################################### ##### We only need this for the purposes of the demo... ##### In a real script you would, presumably, be getting stuff from somewhere else to display $noise = $MyInvocation.MyCommand.Definition -split "`n" $index = 0; $random = New-Object "Random" [regex]$chunker = @' [^ \\"']+|([\\"'])[^\\\\1]*?\\\\1[^ \\"']*|([\\"'])[^\\\\1]*$| $ '@ ##### Printing a "How to Exit" message Out-Buffer " " -Fore DarkGray -Back Cyan Out-Buffer " This is just a demo. " -Fore Black -Back Cyan Out-Buffer " We will stream in the source code of this script ... " -Fore Black -Back Cyan Out-Buffer " And you can type at the bottom while it's running. " -Fore Black -Back Cyan Out-Buffer " Imagine this as an n-way chat application like IRC, except that " -Fore Black -Back Cyan Out-Buffer " FOR THIS PERFORMANCE ONLY: " -Fore Black -Back Cyan Out-Buffer " The part of your chatting friends is played by my source code. " -Fore DarkGray -Back Cyan Out-Buffer " " -Fore DarkGray -Back Cyan Out-Buffer " Press ESC to exit, or enter 'exit' and hit Enter" -Fore Black -Back Cyan Out-Buffer " " -Fore DarkGray -Back Cyan ##### Setting the prompt Set-BufferInputLine ##### And initializing our two variables ... $line="" $exit = $false switch(Show-ConsoleMenu "Continue the demo","Stop the demo","Exit PowerShell" "What would you like to do now?" -UseBuffer) { 0 { <# do nothing, will continue #> } 1 { $exit = $true <#this script exits cleanly below#> } 2 { exit <# stop abruptly #> } } while(!$exit){ while(!$exit -and $Host.UI.RawUI.KeyAvailable) { $char = $Host.UI.RawUI.ReadKey("IncludeKeyUp,IncludeKeyDown,NoEcho"); # we don't want the key up events, but we do want to get rid of them if($char.KeyDown) { switch([int]$char.Character) { 13 { # Enter if($line.Trim() -eq "exit") { $exit = $true; break; } ################################################################################################### ################################################################################################### ############# WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING ############# ############# This executes the user input! ############# ############# Don't use this on, say, content you got from a web page or chat room ############# iex "Out-Buffer `"$line`" -Fore Red"; ############# ################################################################################################### ################################################################################################### $line = ""; Set-BufferInputLine break; } 27 { # Esc $exit = $true; break; } 9 { # Tab if($line.Length -gt 0) { [Array]$words = $chunker.Matches($line) if($words.Count -ge 1) { Out-Buffer ($Words | Out-String) -Fore Black -Back White $lastWord = $words[$($words.Count-1)].Value $trim = $lastWord.TrimEnd("`r","`n") ## This may return more than one ... in which case subsequent tabs should iterate through them ## But for demo purposes, this is more than enough work... $replacement = TabExpansion -Line $line -LastWord ($lastWord.Trim() -replace '"') Out-Buffer ($replacement | Out-String) -Fore Black -Back White $line = $line.SubString(0, $line.Length - $lastWord.Length) + @($replacement)[0] Set-BufferInputLine $line } } break; } 8 { # Backspace if($line.Length -gt 0) { $line = $line.SubString(0,$($line.Length-1)) } # $pos = $Host.UI.RawUI.CursorPosition Set-BufferInputLine $line break; } 0 { # Not actually a key # Out-Buffer $($Char | Out-String) break; } default { $line += $char.Character Set-BufferInputLine $line } } } } # Simulate doing useful things 25% of the time if($random.NextDouble() -gt 0.75) { $noise[($index)..($index++)] | Out-Buffer if($index -ge $noise.Length){$index = 0} } sleep -milli 100 } $CursorPosition = $BufferPromptPosition $CursorPosition.Y += 2 $CursorPosition.X = 0 $Host.UI.RawUI.CursorPosition = $CursorPosition }
PowerShellCorpus/PoshCode/disable local users 2k08.ps1
disable local users 2k08.ps1
################################################################################## # # Script name: Set-LocalAccount.ps1 # Author: niklas.goude@zipper.se # Homepage: www.powershell.nu # http://www.powershell.nu/wp-content/uploads/2009/07/set-localaccount.ps1 # start script - .\\set-localaccount.ps1 -DS user.csv -Add ################################################################################## #param([string]$DS, [switch]$Add, [switch]$Remove, [switch]$ResetPassword) param([string]$DS, [string]$UserName, [string]$Password, [string]$fio, [switch]$Add, [switch]$Remove, [switch]$disable, [switch]$ResetPassword) #param([string]$DS, [string]$dataSource,[string]$UserName, [string]$Password, [string]$fio, [switch]$Add, [switch]$Remove, [switch]$ResetPassword, [switch]$help) function AddRemove-LocalAccount ([string]$DS, [switch]$Add, [switch]$Remove, [switch]$disable, [switch]$ResetPassword) { #function AddRemove-LocalAccount ([string]$DS, [string]$dataSource, [string]$UserName, [string]$Password, [string]$fio, [switch]$Add, [switch]$Remove, [switch]$ResetPassword) { [string]$ComputerName = "$Env:COMPUTERNAME" if($Add) { # new $ADSI = [adsi]"WinNT://$Env:COMPUTERNAME" $dataSource = Import-Csv $DS -Delimiter ";" #$dataSource = Import-Csv user.csv -Delimiter ";" foreach ($dataRecord in $dataSource) { $UserName = $dataRecord.name $Password = $dataRecord.password $fio = $dataRecord.fio $User = $ADSI.Create("user",$UserName) $User.Put("Description", $Password) $User.Put("FullName", $fio) $User.SetPassword($Password) $User.SetInfo() } } if($Remove) { $ADSI = [adsi]"WinNT://$Env:COMPUTERNAME" #[string]$ConnectionString = "WinNT://$ComputerName" $ADSI = [adsi]$ConnectionString $ADSI.Delete("user",$UserName) #$User.SetInfo() } if($disable) { # Disable the account [string]$ConnectionString = "WinNT://" + $ComputerName + "/" + $UserName + ",user" $account=[ADSI]$ConnectionString $account.psbase.invokeset("AccountDisabled", "True") $account.setinfo() } if($ResetPassword) { [string]$ConnectionString = "WinNT://" + $ComputerName + "/" + $UserName + ",user" $Account = [adsi]$ConnectionString $User.Put("Description", $Password) $User.SetInfo() $Account.psbase.invoke("SetPassword", $Password) } } if($DS -AND !$ResetPassword) { AddRemove-LocalAccount -DS $DS -Add} if($UserName -AND $Password -AND $ResetPassword) { AddRemove-LocalAccount -UserName $UserName -Password $Password -ResetPassword } if($Username -AND $disable) {AddRemove-LocalAccount -UserName $UserName -disable } if($UserName -AND $Remove) { AddRemove-LocalAccount -UserName $UserName -Remove }
PowerShellCorpus/PoshCode/Roll-Dice.ps1
Roll-Dice.ps1
# Roll-Dice.ps1 # Cody Bunch # ProfessionalVMware.com Begin { $rand = New-Object System.Random $dice = $rand.next(1,3) } Process { if ( $_ -isnot [VMware.VimAutomation.Client20.ManagedObjectBaseImpl.SnapshotImpl] ) { continue } if ($dice > 1) { $_ | Remove-Snapshot -Confirm:$false Write-Host "$_.Name OH NOES! Has been deleted!`n" } else { Write-Host "$_.Name lives to fight again!`n" } }
PowerShellCorpus/PoshCode/Get-DellWarranty.ps1
Get-DellWarranty.ps1
function Get-DellWarranty { <# .Synopsis Provides warranty information for one or more Dell service tags. .Description Queries the Dell Website for a list of service tags and returns the warranty information as a custom object. If a service tag has multiple warranties, they are returned as multiple separate objects. If no service tag is specified, it will attempt to retrieve and lookup the local system's service tag. The service tag can be provided to the command in several ways: 1. Using the -servicetag parameter 2. By passing one or more Service Tags via the pipeline 3. By passing objects that have either servicetag or serialnumber defined as a property, such as win32_bios WMI objects See examples for details. .Parameter ServiceTag ALIAS: serialnumber The Dell service tag you wish to query. Example: XYZ12A3 .Example C:\\PS> Get-DellWarranty Service Tag : XXXX123 Description : 4 Hour On-Site Service Provider : UNY Warranty Extension Notice * : No Start Date : 6/19/2009 End Date : 6/20/2011 Days Left : 140 Description ----------- If no service tags are provided, the script retrieves the local computer's serial number from WMI and queries for it. .Example C:\\PS> Get-DellWarranty -ServiceTag XXXX123 Service Tag : XXXX123 Description : 4 Hour On-Site Service Provider : UNY Warranty Extension Notice * : No Start Date : 6/19/2009 End Date : 6/20/2011 Days Left : 140 Description ----------- You can pass the service tag as a parameter, or as the first positional parameter (e.g. Get-DellWarranty XXXX123) .Example C:\\PS> "XXXX123","XXXX124","XXXX125" | get-dellwarranty Service Tag : XXXX123 Description : 4 Hour On-Site Service Provider : UNY Warranty Extension Notice * : No Start Date : 6/19/2009 End Date : 6/20/2011 Days Left : 140 Service Tag : XXXX124 Description : 4 Hour On-Site Service Provider : UNY Warranty Extension Notice * : No Start Date : 6/14/2009 End Date : 6/15/2011 Days Left : 145 Service Tag : XXXX125 Description : NBD On-Site Service Provider : DELL Warranty Extension Notice * : No Start Date : 6/14/2008 End Date : 6/15/2010 Days Left : 0 Description ----------- You can pass serial numbers via the pipeline either directly or as a variable. .Example C:\\PS> get-wmiobject win32_bios -computername "computer1","computer2","1.2.3.4" | get-dellwarranty Service Tag : XXXX123 Description : 4 Hour On-Site Service Provider : UNY Warranty Extension Notice * : No Start Date : 6/19/2009 End Date : 6/20/2011 Days Left : 140 Service Tag : XXXX124 Description : 4 Hour On-Site Service Provider : UNY Warranty Extension Notice * : No Start Date : 6/14/2009 End Date : 6/15/2011 Days Left : 145 Service Tag : XXXX125 Description : NBD On-Site Service Provider : DELL Warranty Extension Notice * : No Start Date : 6/14/2008 End Date : 6/15/2010 Days Left : 0 Description ----------- You can also pass any object that has a "serialnumber" or "servicetag" property. In this example, we query computers directly for their serial numbers, and pass those results (which are WMI objects that have a serialnumber property) via pipeline directly to the command to obtain warranty information. .Notes AUTHOR: Justin Grote <jgrote NOSPAM-AT allieddigital NOSPAM-DOT net> WARNING: Since Dell does not provide a formal API, this script works by screen-scraping the HTML from the Dell product support site. Any future change to the layout or logic of this site will break the script or cause unpredictable results. HISTORY: v1.0 [31 Jan 2011] - Initial Module Creatio .Link http://support.dell.com/support/topics/global.aspx/support/my_systems_info #> [CmdletBinding()] param( [Parameter(Mandatory=$False,Position=0,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)] [alias("serialnumber")] [string[]]$ServiceTag ) PROCESS { # If nothing was passed, retrieve the local system service tag if ($ServiceTag -eq $null) { write-verbose "No Service Tags provided. Using Local Computer's Service Tag" write-verbose "START Obtaining Serial number via WMI for localhost" $ServiceTag = (get-wmiobject win32_bios).SerialNumber write-verbose "SUCCESS Obtaining Serial number via WMI for localhost - $ServiceTag" } # Detect if an array of service tags were passed via parameter and unwind them. foreach ($strServicetag in $servicetag) { write-verbose "START Querying Dell for Service Tag $_" Get-DellWarrantyWorker $strServicetag write-verbose "SUCCESS Querying Dell for Service Tag $_" } } } Function Get-DellWarrantyWorker { Param( [String]$serviceTag ) #Dell Warranty URL Path $URL = "http://support.dell.com/support/topics/global.aspx/support/my_systems_info/details?c=us&l=en&s=gen&ServiceTag=$serviceTag" trap [System.FormatException] { write-error -category invalidresult "The service tag $serviceTag was not found. This is either because you entered the tag incorrectly, it is not present in Dell's database, or Dell changed the format of their website causing this search to fail." -recommendedaction "Please check that you entered the service tag correctly" return; } #Screenscrape the HTML for the warranty Table $HTML = (New-Object Net.WebClient).DownloadString($URL) If ($HTML -Match '<table[\\w\\s\\d"=%]*contract_table">.+?</table>') { $htmltable = $Matches[0] } else { throw (New-Object System.FormatException) } $HtmlLines = $htmltable -Split "<tr" | Where-Object { $_ -Match '<td' } $Header = ($HtmlLines[0] -Split '<td') -Replace '[\\w\\s\\d"=%:;\\-]*>|</.*' | Where-Object { $_ -ne '' } #Convert the warranty table fields into a powershell object For ($i = 1; $i -lt $HtmlLines.Count; $i++) { $Output = New-Object PSObject $Output | Add-Member NoteProperty "Service Tag" -value $serviceTag $Values = ($HtmlLines[$i] -Split '<td') -Replace '[\\w\\s\\d"=%:;\\-]*>|</.*|<a.+?>' For ($j = 1; $j -lt $Values.Count; $j++) { $Output | Add-Member NoteProperty $Header[$j - 1] -Value $Values[$j] } #Minor formatting fix if days remaining on warranty is zero if ($output.'Days Left' -match '<<0') {write-host -fore darkgreen "match!";$output.'Days Left' = 0} return $Output } }
PowerShellCorpus/PoshCode/finddupe_12.ps1
finddupe_12.ps1
function Get-MD5([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]')) { $stream = $null; $cryptoServiceProvider = [System.Security.Cryptography.MD5CryptoServiceProvider]; $hashAlgorithm = new-object $cryptoServiceProvider $stream = $file.OpenRead(); $hashByteArray = $hashAlgorithm.ComputeHash($stream); $stream.Close(); ## We have to be sure that we close the file stream if any exceptions are thrown. trap { if ($stream -ne $null) { $stream.Close(); } break; } foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }} return [string]$result; } write-host "Usage: finddupe.ps1 <directory/file #1> <directory/file #2> ... <directory/file #N> [-delete] [-noprompt]" $matches = 0 # initialize number of matches for summary. $filesdeleted = 0 # number of files deleted. $bytesrec = 0 # Number of bytes recovered. $files=@() $del = $false # delete duplicates $noprompt = $false # delete without prompting toggle $currentdir = $true # work on current directory by default for ($i=0;$i -ne $args.count; $i++) { if ($args[$i] -eq "-delete") { $del=$true;continue } else { if ($args[$i] -eq "-noprompt") { $noprompt=$true;continue } else { $files+=(dir $args[$i] -recurse | ? {$_.psiscontainer -ne $true}) $currentdir=$false } } } if ($currentdir -eq $true) { $files=(dir -recurse | ? {$_.psiscontainer -ne $true})} if ($files -eq $null) {write-host "No files found."; exit} for ($i=0;$i -ne $files.count; $i++) # Cycle thru all files { if ($files[$i] -eq $null) {continue} $md5 = $null $filecheck = $files[$i] $files[$i] = $null for ($c=0;$c -ne $files.count; $c++) { if ($files[$c] -eq $null) {continue} # write-host "Comparing $filecheck and $($files[$c]) `r" -nonewline if ($filecheck.length -eq $files[$c].length) { #write-host "Comparing MD5 of $($filecheck.fullname) and $($files[$c].fullname) `r" -nonewline if ($md5 -eq $null) {$md5 = (get-md5 $filecheck)} if ($md5 -eq (get-md5 $files[$c])) { write-host "Size and MD5 match: " -fore red -nonewline write-host "`"$($filecheck.fullname)`"" -nonewline write-host " and " -nonewline write-host "`"$($files[$c].fullname)`"" $matches++ if ($del -eq $true) { if ($noprompt -eq $true) { del $files[$c].fullname write-host "Deleted duplicate: " -f red -nonewline write-host "$($files[$c].fullname)." } else { del $files[$c].fullname -confirm } if ((get-item -ea 0 $files[$c].fullname) -eq $null) { $filesdeleted += 1 $bytesrec += $files[$c].length } } $files[$c] = $null } } } } write-host "" write-host "Number of Files checked: $($files.count)." # Display useful info; files checked and matches found. write-host "Number of matches 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 ""
PowerShellCorpus/PoshCode/SharePoint UserID grab.ps1
SharePoint UserID grab.ps1
## .\\SharePoint_Users_Read.ps1 "http://some.urlname.com/" "User Information List" "" ## .\\SharePoint_Users_Read.ps1 "http://some.urlname.com/" "User Information List" "user, someone" param( [string] $rqurdstrPath = $(Throw "--SharePoint Core Path required."), #required parameter [string] $rqurdstrListName = $(Throw "--SharePoint List Name required."), #required parameter [string] $strTargetUser = "" #non-required user name for ID Return ) Write-Host "Beginning Processing--`n" ## Global Variables ## $strUserIDReturn = "" write-host "rqurdstrPath: $rqurdstrPath " write-host "rqurdstrListName: $rqurdstrListName " ## Load SharePoint .NET Libraries ## [void][System.reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") $site = new-object Microsoft.SharePoint.SPSite($rqurdstrPath) $userlist = $site.RootWeb.Lists[$rqurdstrListName] write-host "site: $site " write-host "userlist: $userlist`n" # Print the ID and Title of each list item #$userlist.Items | Format-List -property ID, Title if($strTargetUser -eq "") { Write-Host "--Displaying all Portal Users" foreach($strItem in $userlist.Items) { [string]$strItem.ID + "--"+$strItem.Title } } else { write-host "--Targeting specific user to return ID" $intUserIDReturn = -1 foreach($strItem in $userlist.Items) { $intUserID=[int]$strItem.ID $strUserName=$strItem.Title if($strUserName -eq $strTargetUser) { $intUserIDReturn = $intUserID break; } } $intUserIDReturn } ## NOTE: don't forget to dispose your .NET objects! ## $site.RootWeb.Dispose() $site.Dispose() ## End Processing ## Write-Host "`nEnd Processing--`n"
PowerShellCorpus/PoshCode/Check Server Health.ps1
Check Server Health.ps1
######################################################## # Created by Brian English # Brian.English@charlottefl.com # eddiephoenix@gmail.com # # for Charlotte County Government # No warranty suggested or implied ######################################################## # Purpose: Check Server Service Health ######################################################## # Notes: For checking Vmware to work you must have the VMWare ToolKit for windows installed # For checking Citrix to work you must have the MPSSDK intalled # For checking DNS to work you must have dcdiag in your path ######################################################## #input params param($Server) ################# #other variables ################# $GLOBAL:priority="normal" $FreePercent = 5 $date = date ################# #turn off error handling #$SavedEA=$Global:ErrorActionPreference #$Global:ErrorActionPreference="SilentlyContinue" $inAry = @($input) if($inAry.count -gt 0) {$server = $inary} ############# function checkSystem() { $status = "`nChecking Server Systems" for($i = 0; $i -lt @($Server).count; $i++ ) { $srv = @($Server)[$i] $checkVMWare = $false $checkDNS = $false $checkDHCP = $false $checkShares = $false $checkExc = $false $checkCitrix = $false $checkIIS = $false write-progress "Checking Server Systems: $srv "-> -perc ($i * (100/@($Server).count)) $status += "`n***$srv***" $errcnt = 0 $error.clear() if((ping-computer "$srv").protocoladdress -ne "") { if((gwmi -computername $srv win32_computersystem).dnshostname -ne $srv -or (gwmi -computername $srv win32_computersystem).name -ne $srv) { $status += "`n`t! ServerName does not match" $errcnt += 1 } foreach($drive in(gwmi win32_logicaldisk -computername $srv | where{$_.Drivetype -like "3"})) { if((($drive.freespace/1gb)/($drive.size/1gb) * 100 ) -lt $FreePercent) { $status += "`n`t! Drive: " + $drive.deviceid + " Free Space: " + ($drive.freespace/ 1GB) + "GB" $priority = "high" $errcnt += 1 } } foreach($svc in(gwmi win32_service -computername $srv | where{$_.StartMode -like "Auto" -and $_.name -ne "SysmonLog"})) { if($svc.state -ne "Running") { $status += "`n`t! Service: " + $svc.DisplayName + " is " + $svc.state $errcnt += 1 } if($svc.name -eq "vpxd" -and $svc.state -eq "Running") {$checkVMWare = $true} if($svc.name -eq "DNS" -and $svc.state -eq "Running") {$checkDNS = $true} if($svc.name -eq "DHCPServer" -and $svc.state -eq "Running") {$checkDHCP = $true} if($svc.name -eq "lanmanserver" -and $svc.state -eq "Running") {$checkShares = $true} if($svc.name -eq "MSExchangeIS" -and $svc.state -eq "Running") {$checkExc = $true} if($svc.name -eq "cpsvc" -and $svc.state -eq "Running") {$checkCitrix = $true} if($svc.name -eq "IISADMIN" -and $svc.state -eq "Running") {$checkIIS = $true} } if($checkVMWare) { $vi = get-esx $srv $status += "`nHosts" foreach($vmh in get-vmhost) { if($vmh.state -ne "Connected") { $status += "`n`t! Host: " + $vmh.Name + "; State: " + $vmh.state } } $status += "`nVMs" $vms = (get-vm -server $vi) $greenvms = 0 $status += "`n`tTotal VMs: " + $vms.count $status += "`n`tVMs powered Off: " + ($vms | where{$_.PowerState -eq "PoweredOff"}).count $status += "`n`tVMs powered On: " + ($vms | where{$_.PowerState -eq "PoweredOn"}).count foreach($vm in ($vms | where{$_.PowerState -eq "PoweredOn"})) { $vmv = get-view $vm.id if($vmv.Overallstatus -ne "green" -or $vmv.configstatus -ne "green") # -or $vmv.guestheartbeatstatus -ne "green") { $status += "`n`t`t" + $vm.name + " Overall: " + $vmv.overallStatus $status += "`n`t`t" + $vm.name + " Config: " + $vmv.configStatus $status += "`n`t`t" + $vm.name + " Heartbeat: " + $vmv.GuestHeartbeatStatus foreach($alrm in $vmv.triggeredAlarmState) { $av = get-view $alrm.alarm $status += "`n`t`t " + $vm.name + " Triggered: " + $av.info.Name } $priority = "high" } else {$greenvms += 1} }#for $status += "`n`tGreen VMs: " + $greenvms + "`n" } if($checkDNS) { foreach($ln in (dcdiag /test:DNS /s:$srv /v)) { if( $ln -like "*warning:*" -or $ln -like "*error:*") {$status += "`n`t" + $ln.trim()} } foreach($ln in (dcdiag /test:CheckSecurityError /s:$srv /v)) { if($ln -like "*warning:*" -or $ln -like "*error:*") {$status += "`n`t" + $ln.trim()} } }#checkdns if($checkDHCP) { ########################## #add code to check DHCP data }#checkDHCP if($checkShares) { foreach($share in (gwmi win32_share -computername $srv | where {$_.status -ne "OK"})) { $status += "`n`t! Share: " + $share.Name + " is " + $share.status $errcnt += 1 } }#checkShares if($checkExc) { foreach($exc in (gwmi ExchangeConnectorState -namespace "root\\cimv2\\applications\\exchange" -computername $srv | where {$_.IsUp -ne $true})) { $status += "`n`t! Exchange Connector: " + $exc.Name + " is DOWN" $errcnt += 1 } foreach($exc in (gwmi ExchangeQueue -namespace "root\\cimv2\\applications\\exchange" -computername $srv | where {$_.NumberOfMessages -gt 1})) { $status += "`n`t! Exchange Queue: " + $exc.QueueName + " has " + $exc.NumberofMessages $errcnt += 1 } foreach($exc in (gwmi Exchange_Logon -namespace "root\\microsoftexchangev2" -computername $srv | where {$_.Latency -gt 60000})) { $status += "`n`t! Exchange Logons: " + $exc.MailboxDisplayName + " in Store " + $exc.StoreName + " has a latency of " + $exc.Latency $errcnt += 1 } }#checkExc if($checkCitrix) { $mfserver = New-Object -com "MetaframeCom.MetaFrameServer" $mfserver.initialize(6,$srv) $status += "`n`t Sesion Count " + $mfserver.SessionCount switch($mfserver.WinServerObject.EnableLogon) { "0" { $status += "`n`t! Not Allowing Connections" $errcnt += 1 } "1" {} } }#checkCitrix if($checkIIS) { $pathToTest = "\\\\$srv\\c$\\windows\\system32\\inetsrv\\metabase.xml" if(test-path $pathToTest) { $mb=[xml](get-content $pathToTest) $WebSites = $mb.configuration.MBProperty.IIsWebServer $WebVDirs = $mb.configuration.MBProperty.IIsWebVirtualDir If(!($mb.configuration.MBProperty.IIsWebService.Custom | where {$_.name -eq "ServerComment"}).value) { $WebServerName = "[UNKNOWN]" } Else { $WebServerName = ($mb.configuration.MBProperty.IIsWebService.Custom | where {$_.name -eq "ServerComment"}).value } If($WebServerName -ne $srv) { $status += "`n`t! WebServer Name Mismatch $WebServerName, $srv" $errcnt += 1 } ForEach ($Site in $WebSites) { if($Site.ServerComment -notlike "Allows*") { $sitePath = "$srv" + ($site.location -replace "/LM","") $siteState = ([ADSI]("IIS://$sitepath")).serverstate if($siteState -ne "2") { switch($sitestate) { "1" {$siteState = "starting"} "2" {$siteState = "started"} "3" {$siteState = "stopping"} "4" {$siteState = "stopped"} "5" {$siteState = "pausing"} "6" {$siteState = "paused"} "7" {$siteState = "continuing"} } $status += "`n`t! " + $Site.ServerComment + " is not running: state " + $sitestate $errcnt += 1 } } } } else { $status += "`n`t! Unable to verify IIS Metabase" $errcnt += 1 } }#checkIIS } else { $status += "`n`t! Server Unreachable" $errcnt += 1 } if($error[0]) { $status += "`n`t Errors Occured: " foreach($err in $error) { $status += "`n`t`!" + $err } } elseif($errCnt -eq 0) {$status += "`n***$srv*** Healthy" } else {$status += "`n***$srv*** Unhealthy"} $status $status = "" }#for }#checkSystem ############# ######################################################## #Execute script ############ checkSystem ######################################################## #reset error handling #$Global:ErrorActionPreference=$SavedEA
PowerShellCorpus/PoshCode/8480db1c-b0f9-4a82-aa9a-17edc18cae00.ps1
8480db1c-b0f9-4a82-aa9a-17edc18cae00.ps1
<# Author: Matt Schmitt Date: 11/29/12 Version: 1.0 From: USA Email: ithink2020@gmail.com Website: http://about.me/schmittmatt Twitter: @MatthewASchmitt Description A script for checking the status of a service on a group of servers, from a list in a file. #> $serverList = Import-Csv 'c:\\serverList.csv' "Server" +"`t" + "Status" | Out-File c:\\ServerService.csv foreach ($element in $serverList) { $sStatus = get-service -Name "CPSVS" | Select-Object -expand Status $server = $element | Select-Object -expand Server $server + "`t" + $sStatus | Out-File -append c:\\ServerServiceStatus.csv } Send-MailMessage -From donotreply@test.com -To recipient@domain.com -subject "Spooler Service Report" -Body "Attached is Server Service report." -Attachments "c:\\ServerServiceStatus.csv" -SmtpServer "xxx.xxx.xxx.xxx"
PowerShellCorpus/PoshCode/LookUp-WirelessLocation.ps1
LookUp-WirelessLocation.ps1
function LookUp-Location { param([String] $mac) $mac = $mac.Replace(":","").Replace("-","") $wClient = New-Object System.Net.WebClient $body = "<?xml version='1.0'?><LocationRQ xmlns='http://skyhookwireless.com/wps/2005' version='2.6' street-address-lookup='full'><authentication version='2.0'><simple><username>beta</username><realm>js.loki.com</realm></simple></authentication><access-point><mac>#{mac}</mac><signal-strength>-50</signal-strength></access-point></LocationRQ>" $url = "https://api.skyhookwireless.com/wps2/location" $wClient.Headers.Add("Content-Type:text/xml") $body = $body.Replace("#{mac}", $mac) $response = $wClient.UploadString($url, $body) return $response }
PowerShellCorpus/PoshCode/Get-ShortURL.ps1
Get-ShortURL.ps1
Function Get-ShortURL { Param($longURL, $login, $apiKey) $url = "http://api.bit.ly/shorten?version=2.0.1&format=xml&longUrl=$longURL&login=$login&apiKey=$apikey" $request = [net.webrequest]::Create($url) $responseStream = new-object System.IO.StreamReader($request.GetResponse().GetResponseStream()) $response = $responseStream.ReadToEnd() $responseStream.Close() $result = [xml]$response Write-Output $result.bitly.results.nodeKeyVal.shortUrl }
PowerShellCorpus/PoshCode/Show-ColorizedContent.ps.ps1
Show-ColorizedContent.ps.ps1
##############################################################################\n##\n## Show-ColorizedContent\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\nDisplays syntax highlighting, line numbering, and range highlighting for\nPowerShell scripts.\n\n.EXAMPLE\n\nPS >Show-ColorizedContent Invoke-MyScript.ps1\n\n001 | function Write-Greeting\n002 | {\n003 | param($greeting)\n004 | Write-Host "$greeting World"\n005 | }\n006 |\n007 | Write-Greeting "Hello"\n\n.EXAMPLE\n\nPS >Show-ColorizedContent Invoke-MyScript.ps1 -highlightRange (1..3+7)\n\n001 > function Write-Greeting\n002 > {\n003 > param($greeting)\n004 | Write-Host "$greeting World"\n005 | }\n006 |\n007 > Write-Greeting "Hello"\n\n#>\n\nparam(\n ## The path to colorize\n [Parameter(Mandatory = $true)]\n $Path,\n\n ## The range of lines to highlight\n $HighlightRange = @(),\n\n ## Switch to exclude line numbers\n [Switch] $ExcludeLineNumbers\n)\n\nSet-StrictMode -Version Latest\n\n## Colors to use for the different script tokens.\n## To pick your own colors:\n## [Enum]::GetValues($host.UI.RawUI.ForegroundColor.GetType()) |\n## Foreach-Object { Write-Host -Fore $_ "$_" }\n$replacementColours = @{\n 'Attribute' = 'DarkCyan'\n 'Command' = 'Blue'\n 'CommandArgument' = 'Magenta'\n 'CommandParameter' = 'DarkBlue'\n 'Comment' = 'DarkGreen'\n 'GroupEnd' = 'Black'\n 'GroupStart' = 'Black'\n 'Keyword' = 'DarkBlue'\n 'LineContinuation' = 'Black'\n 'LoopLabel' = 'DarkBlue'\n 'Member' = 'Black'\n 'NewLine' = 'Black'\n 'Number' = 'Magenta'\n 'Operator' = 'DarkGray'\n 'Position' = 'Black'\n 'StatementSeparator' = 'Black'\n 'String' = 'DarkRed'\n 'Type' = 'DarkCyan'\n 'Unknown' = 'Black'\n 'Variable' = 'Red'\n}\n\n$highlightColor = "Red"\n$highlightCharacter = ">"\n$highlightWidth = 6\nif($excludeLineNumbers) { $highlightWidth = 0 }\n\n## Read the text of the file, and tokenize it\n$file = (Resolve-Path $Path).Path\n$content = [IO.File]::ReadAllText($file)\n$parsed = [System.Management.Automation.PsParser]::Tokenize(\n $content, [ref] $null) | Sort StartLine,StartColumn\n\n## Write a formatted line -- in the format of:\n## <Line Number> <Separator Character> <Text>\nfunction WriteFormattedLine($formatString, [int] $line)\n{\n if($excludeLineNumbers) { return }\n\n ## By default, write the line number in gray, and use\n ## a simple pipe as the separator\n $hColor = "DarkGray"\n $separator = "|"\n\n ## If we need to highlight the line, use the highlight\n ## color and highlight separator as the separator\n if($highlightRange -contains $line)\n {\n $hColor = $highlightColor\n $separator = $highlightCharacter\n }\n\n ## Write the formatted line\n $text = $formatString -f $line,$separator\n Write-Host -NoNewLine -Fore $hColor -Back White $text\n}\n\n## Complete the current line with filler cells\nfunction CompleteLine($column)\n{\n ## Figure how much space is remaining\n $lineRemaining = $host.UI.RawUI.WindowSize.Width -\n $column - $highlightWidth + 1\n\n ## If we have less than 0 remaining, we've wrapped onto the\n ## next line. Add another buffer width worth of filler\n if($lineRemaining -lt 0)\n {\n $lineRemaining += $host.UI.RawUI.WindowSize.Width\n }\n\n Write-Host -NoNewLine -Back White (" " * $lineRemaining)\n}\n\n\n## Write the first line of context information (line number,\n## highlight character.)\nWrite-Host\nWriteFormattedLine "{0:D3} {1} " 1\n\n## Now, go through each of the tokens in the input\n## script\n$column = 1\nforeach($token in $parsed)\n{\n $color = "Gray"\n\n ## Determine the highlighting colour for that token by looking\n ## in the hashtable that maps token types to their color\n $color = $replacementColours[[string]$token.Type]\n if(-not $color) { $color = "Gray" }\n\n ## If it's a newline token, write the next line of context\n ## information\n if(($token.Type -eq "NewLine") -or ($token.Type -eq "LineContinuation"))\n {\n CompleteLine $column\n WriteFormattedLine "{0:D3} {1} " ($token.StartLine + 1)\n $column = 1\n }\n else\n {\n ## Do any indenting\n if($column -lt $token.StartColumn)\n {\n $text = " " * ($token.StartColumn - $column)\n Write-Host -Back White -NoNewLine $text\n $column = $token.StartColumn\n }\n\n ## See where the token ends\n $tokenEnd = $token.Start + $token.Length - 1\n\n ## Handle the line numbering for multi-line strings and comments\n if(\n (($token.Type -eq "String") -or\n ($token.Type -eq "Comment")) -and\n ($token.EndLine -gt $token.StartLine))\n {\n ## Store which line we've started at\n $lineCounter = $token.StartLine\n\n ## Split the content of this token into its lines\n ## We use the start and end of the tokens to determine\n ## the position of the content, but use the content\n ## itself (rather than the token values) for manipulation.\n $stringLines = $(\n -join $content[$token.Start..$tokenEnd] -split "`n")\n\n ## Go through each of the lines in the content\n foreach($stringLine in $stringLines)\n {\n $stringLine = $stringLine.Trim()\n\n ## If we're on a new line, fill the right hand\n ## side of the line with spaces, and write the header\n ## for the new line.\n if($lineCounter -gt $token.StartLine)\n {\n CompleteLine $column\n WriteFormattedLine "{0:D3} {1} " $lineCounter\n $column = 1\n }\n\n ## Now write the text of the current line\n Write-Host -NoNewLine -Fore $color -Back White $stringLine\n $column += $stringLine.Length\n $lineCounter++\n }\n }\n ## Write out a regular token\n else\n {\n ## We use the start and end of the tokens to determine\n ## the position of the content, but use the content\n ## itself (rather than the token values) for manipulation.\n $text = (-join $content[$token.Start..$tokenEnd])\n Write-Host -NoNewLine -Fore $color -Back White $text\n }\n\n ## Update our position in the column\n $column = $token.EndColumn\n }\n}\n\nCompleteLine $column\nWrite-Host
PowerShellCorpus/PoshCode/Get-UcsServerVlan.ps1
Get-UcsServerVlan.ps1
function Get-UcsServerVlan { Get-UcsServiceProfile | Foreach-Object { $sp = $_ $sp | Get-UcsVnic | Foreach-Object { $vn = $_ $vn | Get-UcsVnicInterface | Foreach-Object { $output = New-Object psobject –property @{ Server = $sp.Name Vnic = $vn.name Vlan = $_.name } Write-Output $output } } } }
PowerShellCorpus/PoshCode/SQLPSX SSIS Demo.ps1
SQLPSX SSIS Demo.ps1
#Edit SSIS.psm1 and Comment/Uncomment 2005 or 2008 version of SSIS assembly #add-type -AssemblyName "Microsoft.SqlServer.ManagedDTS, Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" add-type -AssemblyName "Microsoft.SqlServer.ManagedDTS, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" #Import the SSIS module import-module SSIS #Work with SSIS packages stored on the file system $packages = dir "C:\\Program Files\\Microsoft SQL Server\\100\\DTS\\Packages\\*" | select -ExpandProperty Fullname | foreach {get-ispackage -path $_ } $packages | foreach {$package = $_; $_.Configurations | Select @{n='Package';e={$Package.DisplayName}}, Name,ConfigurationString} $packages | foreach {$package = $_; $_.Connections | Select @{n='Package';e={$Package.DisplayName}}, Name,ConnectionString} #Create a new folder on the SSIS server new-isitem "\\msdb" "sqlpsx" "Z002" #Copy SSIS packages from the file system to SQL Server and change the connection string for SSISCONFIG copy-isitemfiletosql -path "C:\\Program Files\\Microsoft SQL Server\\100\\DTS\\Packages\\*" -destination "msdb\\sqlpsx" -destinationServer "Z002" -connectionInfo @{SSISCONFIG=".\\SQLEXPRESS"} #Work with SSIS packages on SQL Server $packages = get-isitem -path '\\sqlpsx' -topLevelFolder 'msdb' -serverName "Z002\\SQL2K8" | where {$_.Flags -eq 'Package'} | foreach {get-ispackage -path $_.literalPath -serverName $_.Servername} $packages | foreach {$package = $_; $_.Configurations | Select @{n='Package';e={$Package.DisplayName}}, Name,ConfigurationString} $packages | foreach {$package = $_; $_.Connections | Select @{n='Package';e={$Package.DisplayName}}, Name,ConnectionString}
PowerShellCorpus/PoshCode/Progress Message popup.ps1
Progress Message popup.ps1
#Generated Form Function function ProgressMessage { ######################################################################## # Code Generated By: SAPIEN Technologies PrimalForms (Community Edition) v1.0.10.0 # Generated On: 29/01/2013 11:01 AM # Generated By: Denis St-Pierre, Ottawa, Canada #source http://poshcode.org/4020 ######################################################################## param( #parameters with default values assigned [String]$LabelText="Message", [String]$FormTitle="Form Title", # [int]$nSecondsToWait=3, # [int]$Buttons = 0, [int]$FontSize = 12, [String]$ICOpath="" ) If ( Get-Variable -Name ProgMsgForm1 -Scope Global -ErrorAction SilentlyContinue ) { $ProgMsgForm1.close() #Kill previous Progress Message to prevent lost handles } If ($LabelText -eq ""){ Return } $LabelText="`r`n "+$LabelText+" `r`n " #add space around the message #region Import the Assemblies [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null #endregion #region Generated Form Objects $global:ProgMsgForm1 = New-Object System.Windows.Forms.Form $ProgMsgLabel1 = New-Object System.Windows.Forms.Label $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState #endregion Generated Form Objects #region Generated Form Code $ProgMsgForm1.AutoSize = $True $ProgMsgForm1.AutoSizeMode = 0 # $System_Drawing_Size = New-Object System.Drawing.Size #$System_Drawing_Size.Height = 113 #$System_Drawing_Size.Width = 255 # $ProgMsgForm1.ClientSize = $System_Drawing_Size $ProgMsgForm1.DataBindings.DefaultDataSourceUpdateMode = 0 #add Icon to dialog If ( ($ICOpath -ne "") -and (Test-Path "$ICOpath") ) { Try { #If the ICO file is NFG, ignore and move on $ProgMsgForm1.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon("$ICOpath") } catch { } #use default ICO } $ProgMsgForm1.Name = "form1" $ProgMsgForm1.StartPosition = 1 #Center of the Screen $ProgMsgForm1.Text = "$FormTitle" # $ProgMsgLabel1.AutoEllipsis = $True #handle text that goes beyond width of Label control $ProgMsgLabel1.AutoSize = $True $ProgMsgLabel1.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Point = New-Object System.Drawing.Point # $System_Drawing_Point.X = 10 # $System_Drawing_Point.Y = 10 $ProgMsgLabel1.Location = $System_Drawing_Point $ProgMsgLabel1.Name = "label1" # $System_Drawing_Size = New-Object System.Drawing.Size ## $System_Drawing_Size.Height = 13 ## $System_Drawing_Size.Width = 35 # $ProgMsgLabel1.Size = $System_Drawing_Size $ProgMsgLabel1.TabIndex = 0 $ProgMsgLabel1.Text = "$LabelText" $ProgMsgLabel1.TextAlign = 2 $ProgMsgLabel1.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",$FontSize,1,3,1) $ProgMsgForm1.Controls.Add($ProgMsgLabel1) #endregion Generated Form Code #Save the initial state of the form $InitialFormWindowState = $ProgMsgForm1.WindowState #Init the OnLoad event to correct the initial state of the form $ProgMsgForm1.add_Load($OnLoadForm_StateCorrection) #Show the Form #$ProgMsgForm1.ShowDialog()| Out-Null #ShowDialog waits until it is closed $ProgMsgForm1.Show() #show forms and keep on going $ProgMsgForm1.activate() #Make sure its on top return $ProgMsgForm1 #need to do this to kill form later (now optional b/c $ProgMsgForm1 is made global) } #End Function #Call the Function $ProgressObj=ProgressMessage "this is text to display this is text to display this is text to display this is text to display this is text to display" "My title" Echo "doing other stuff" Start-Sleep -Second 2 Echo "doing other stuff" Start-Sleep -Second 2 #$ProgressObj.Close() #if you forget to close previous, it stays on the screen and you cant kill it! $ProgressObj=ProgressMessage "LEt's see if this works too" Echo "doing other stuff" Start-Sleep -Second 3 Echo "doing other stuff" Start-Sleep -Second 2 #$ProgressObj.Close() ProgressMessage "" #close progress message
PowerShellCorpus/PoshCode/Get-ScriptCoverage.ps1
Get-ScriptCoverage.ps1
#############################################################################\n##\n## Get-ScriptCoverage\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\nUses conditional breakpoints to obtain information about what regions of\na script are executed when run.\n\n.EXAMPLE\n\nPS >Get-Content c:\\temp\\looper.ps1\n\nparam($userInput)\n\nfor($count = 0; $count -lt 10; $count++)\n{\n "Count is: $count"\n}\n\nif($userInput -eq "One")\n{\n "Got 'One'"\n}\n\nif($userInput -eq "Two")\n{\n "Got 'Two'"\n}\n\nPS >$action = { c:\\temp\\looper.ps1 -UserInput 'One' }\nPS >$coverage = Get-ScriptCoverage c:\\temp\\looper.ps1 -Action $action\nPS >$coverage | Select Content,StartLine,StartColumn | Format-Table -Auto\n\nContent StartLine StartColumn\n------- --------- -----------\nparam 1 1\n( 1 6\nuserInput 1 7\n) 1 17\nGot 'Two' 15 5\n} 16 1\n\nThis example exercises a 'looper.ps1' script, and supplies it with some\nuser input. The output demonstrates that we didn't exercise the\n"Got 'Two'" statement.\n\n#>\n\nparam(\n ## The path of the script to monitor\n $Path,\n\n ## The command to exercise the script\n [ScriptBlock] $Action = { & $path }\n)\n\nSet-StrictMode -Version Latest\n\n## Determine all of the tokens in the script\n$scriptContent = Get-Content $path\n$ignoreTokens = "Comment","NewLine"\n$tokens = [System.Management.Automation.PsParser]::Tokenize(\n $scriptContent, [ref] $null) |\n Where-Object { $ignoreTokens -notcontains $_.Type }\n$tokens = $tokens | Sort-Object StartLine,StartColumn\n\n## Create a variable to hold the tokens that PowerShell actually hits\n$visited = New-Object System.Collections.ArrayList\n\n## Go through all of the tokens\n$breakpoints = foreach($token in $tokens)\n{\n ## Create a new action. This action logs the token that we\n ## hit. We call GetNewClosure() so that the $token variable\n ## gets the _current_ value of the $token variable, as opposed\n ## to the value it has when the breakpoints gets hit.\n $breakAction = { $null = $visited.Add($token) }.GetNewClosure()\n\n ## Set a breakpoint on the line and column of the current token.\n ## We use the action from above, which simply logs that we've hit\n ## that token.\n Set-PsBreakpoint $path -Line `\n $token.StartLine -Column $token.StartColumn -Action $breakAction\n}\n\n## Invoke the action that exercises the script\n$null = . $action\n\n## Remove the temporary breakpoints we set\n$breakpoints | Remove-PsBreakpoint\n\n## Sort the tokens that we hit, and compare them with all of the tokens\n## in the script. Output the result of that comparison.\n$visited = $visited | Sort-Object -Unique StartLine,StartColumn\nCompare-Object $tokens $visited -Property StartLine,StartColumn -PassThru\n\n## Clean up our temporary variable\nRemove-Item variable:\\visited
PowerShellCorpus/PoshCode/New-Shortcut.ps1
New-Shortcut.ps1
#requires -version 2.0 function New-Shortcut { <# .SYNOPSIS Creates a new shortcut (.lnk file) pointing at the specified file. .DESCRIPTION The New-Shortcut script creates a shortcut pointing at the target in the location you specify. You may specify the location as a folder path (which must exist), with a name for the new file (ending in .lnk), or you may specify one of the "SpecialFolder" names like "QuickLaunch" or "CommonDesktop" followed by the name. If you specify the path for the link file without a .lnk extension, the path is assumed to be a folder. .EXAMPLE New-Shortcut C:\\Windows\\Notepad.exe Will make a shortcut to notepad in the current folder named "Notepad.lnk" .EXAMPLE New-Shortcut C:\\Windows\\Notepad.exe QuickLaunch\\Editor.lnk -Description "Run Notepad" Will make a shortcut to notepad on the QuickLaunch bar with the name "Editor.lnk" and the tooltip "Run Notepad" .EXAMPLE New-Shortcut C:\\Windows\\Notepad.exe F:\\User\\ Will make a shortcut to notepad in the F:\\User\\ folder with the name "Notepad.lnk" .NOTE Partial dependency on Get-SpecialPath ( http://poshcode.org/858 ) #> [CmdletBinding()] param( [Param(Position=0,Mandatory=$true)] [string]$TargetPath, ## Put the shortcut where you want: "Special Folder" names allowed! [Param(Position=1,Mandatory=$true)] [string]$LinkPath, ## Extra parameters for the shortcut [string]$Arguments="", [string]$WorkingDirectory="", [string]$WindowStyle="Normal", [string]$IconLocation="", [string]$Hotkey="", [string]$Description="", [string]$Folder="" ) # Values for Window Style: # 1 - Normal -- Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. # 3 - Maximized -- Activates the window and displays it as a maximized window. # 7 - Minimized -- Minimizes the window and activates the next top-level window. if(!(Test-Path $TargetPath) -and !($TargetPath.Contains("://"))) { Write-Error "TargetPath must be an existing file for the link to point at (or a URL)" return } function New-ShortCutFile { param( [string]$TargetPath=$(throw "Please specify a TargetPath for link to point to"), [string]$LinkPath=$(throw "must pass a path for the shortcut file"), [string]$Arguments="", [string]$WorkingDirectory=$(Split-Path $TargetPath -parent), [string]$WindowStyle="Normal", [string]$IconLocation="", [string]$Hotkey="", [string]$Description=$(Split-Path $TargetPath -Leaf) ) if(-not ($TargetPath.Contains("://") -or (Test-Path (Split-Path (Resolve-Path $TargetPath) -parent)))) { Throw "Cannot create Shortcut: Parent folder does not exist" } if(-not (Test-Path variable:\\global:WshShell)) { $global:WshShell = New-Object -com "WScript.Shell" } $Link = $global:WshShell.CreateShortcut($LinkPath) $Link.TargetPath = $TargetPath [IO.FileInfo]$LinkInfo = $LinkPath ## Properties for file shortcuts only ## If the $LinkPath ends in .url you can't set the arguments, icon, etc ## if you make the same shortcut with a .lnk extension ## you can still point it at a URL, but you can set hotkeys, icons, etc if( $LinkInfo.Extension -ne ".url" ) { $Link.WorkingDirectory = $WorkingDirectory ## Validate $WindowStyle if($WindowStyle -is [string]) { if( $WindowStyle -like "Normal" ) { $WindowStyle = 1 } if( $WindowStyle -like "Maximized" ) { $WindowStyle = 3 } if( $WindowStyle -like "Minimized" ) { $WindowStyle = 7 } } if( $WindowStyle -ne 1 -and $WindowStyle -ne 3 -and $WindowStyle -ne 7) { $WindowStyle = 1 } $Link.WindowStyle = $WindowStyle if($Hotkey.Length -gt 0 ) { $Link.HotKey = $Hotkey } if($Arguments.Length -gt 0 ) { $Link.Arguments = $Arguments } if($Description.Length -gt 0 ) { $Link.Description = $Description } if($IconLocation.Length -gt 0 ) { $Link.IconLocation = $IconLocation } } $Link.Save() Write-Output (get-item $LinkPath) } ## If they didn't explicitly specify a folder if($Folder.Length -eq 0) { if($LinkPath.Length -gt 0) { $path = Split-Path $LinkPath -parent [IO.FileInfo]$LinkInfo = $LinkPath if( $LinkInfo.Extension.Length -eq 0 ) { $Folder = $LinkPath } else { # If the LinkPath is just a single word with no \\ or extension... if($path.Length -eq 0) { $Folder = $Pwd } else { $Folder = $path } } } else { $Folder = $Pwd } } ## If they specified a link path, check it for an extension if($LinkPath.Length -gt 0) { $LinkPath = Split-Path $LinkPath -leaf [IO.FileInfo]$LinkInfo = $LinkPath if( $LinkInfo.Extension.Length -eq 0 ) { # If there's no extension, it must be a folder $Folder = $LinkPath $LinkPath = "" } } ## If there's no Link name, make one up based on the target if($LinkPath.Length -eq 0) { if($TargetPath.Contains("://")) { $LinkPath = "$($TargetPath.split('/')[2]).url" } else { [IO.FileInfo]$LinkInfo = $TargetPath $LinkPath = "$(([IO.FileInfo]$TargetPath).BaseName).lnk" } } ## If the folder doesn't actually exist, maybe it's special... if( -not (Test-Path $Folder)) { $morepath = ""; if( $Folder.Contains("\\") ) { $morepath = $Folder.SubString($Folder.IndexOf("\\")) $Folder = $Folder.SubString(0,$Folder.IndexOf("\\")) } $Folder = Join-Path (Get-SpecialPath $Folder) $morepath # or maybe they just screwed up trap { throw new-object ArgumentException "Cannot create shortcut: parent folder does not exist" } } $LinkPath = (Join-Path $Folder $LinkPath) New-ShortCutFile $TargetPath $LinkPath $Arguments $WorkingDirectory $WindowStyle $IconLocation $Hotkey $Description }
PowerShellCorpus/PoshCode/695c148f-1099-41a1-abaf-8e0b163f9eff.ps1
695c148f-1099-41a1-abaf-8e0b163f9eff.ps1
#=================================================================================== # # Filename: AddExecuteInPowerShellToPS1Files.ps1 # # Author: Nigel Boulton # # Version: 1.00 # # Date: 9 Nov 2008 # # Mod dates: # # Purpose: To add context menu items for .ps1 files in Windows Explorer, to # allow PowerShell scripts to be executed by right-clicking them # # Action: Gets the path to PowerShell.exe by reading the Path property of # the process. If PowerShell is not running (e.g. if using a GUI/IDE), # prompts the user to enter the path. Quotes the path if it contains # any spaces # Gets the class key for .ps1 files from the registry and adds the # appropriate subkeys and values to it to add "Execute in PowerShell" # and "Execute in PowerShell (-NoExit)" context menu items # # Notes: USE AT YOUR OWN RISK! Backup your system first and all that... # Must be run as an administrator # #=================================================================================== # Get the full path to PowerShell.exe, or prompt if using a GUI $PoSH = Get-Process | Where-Object {$_.Name -eq "PowerShell"} | Select-Object -First 1 If ($PoSH -eq $null) { $PoSHPath = Read-Host "Please enter the full path to PowerShell.exe, or cancel and run this script in a PowerShell console session" If ($PoSHPath -eq $Null) {exit 1} } Else { $PoSHPath = $PoSH.Path } # Quote PowerShell path if it isn't already If ($PoSHPath.Substring(0,1) -ne "`"") {$PoSHPath = "`"" + $PoSHPath} If ($PoSHPath.Substring($PoSHPath.Length - 1,1) -ne "`"") {$PoSHPath += "`""} # Get class for .ps1 files $PS1Class = (Get-ItemProperty -Path HKLM:SOFTWARE\\Classes\\.ps1)."(Default)" # Build hash table of registry data to add # $_.Name is the registry key and $_.Value is the data for the "(Default)" value in that key $RegData = @{"HKLM:Software\\Classes\\$PS1Class\\shell\\Execute in PowerShell\\command" = $PoSHPath + " &'%1'";` "HKLM:Software\\Classes\\$PS1Class\\shell\\Execute in PowerShell (-NoExit)\\command" = $PoSHPath + " -NoExit &'%1'"} # Check for an existing "Open" action. If there isn't one we need to add one in to ensure that "Open" # remains the default. If we didn't do this, in future double-clicking .ps1 files would execute them! If ((Test-Path "HKLM:Software\\Classes\\$PS1Class\\shell\\open\\command") -eq $False) {$RegData.Add("HKLM:Software\\Classes\\$PS1Class\\shell\\open\\command", "notepad.exe `"%1`"")} # Iterate hash table to create registry keys and set values $RegData.GetEnumerator() | ForEach-Object { # Create registry path If ((Test-Path $_.Name) -eq $False) {New-Item -Path $_.Name -Force | Out-Null} # Set "(Default)" value Set-ItemProperty -Path $_.Name -Name "(Default)" -Value $_.Value } Write-Output "Processing complete"
PowerShellCorpus/PoshCode/Invoke-ComplexScript.ps1
Invoke-ComplexScript.ps1
#############################################################################\n##\n## Invoke-ComplexScript\n##\n## From Windows PowerShell Cookbook (O'Reilly)\n## by Lee Holmes (http://www.leeholmes.com/guide)\n##\n##############################################################################\n\n<#\n\n.SYNOPSIS\n\nDemonstrates the functionality of PowerShell's debugging support.\n\n#>\n\nSet-StrictMode -Version Latest\n\nWrite-Host "Calculating lots of complex information"\n\n$runningTotal = 0\n$runningTotal += [Math]::Pow(5 * 5 + 10, 2)\n\nWrite-Debug "Current value: $runningTotal"\n\nSet-PsDebug -Trace 1\n$dirCount = @(Get-ChildItem $env:WINDIR).Count\n\nSet-PsDebug -Trace 2\n$runningTotal -= 10\n$runningTotal /= 2\n\nSet-PsDebug -Step\n$runningTotal *= 3\n$runningTotal /= 2\n\n$host.EnterNestedPrompt()\n\nSet-PsDebug -off
PowerShellCorpus/PoshCode/Windows Startup Script_5.ps1
Windows Startup Script_5.ps1
<#====================================================================================== File Name : Startup.ps1 Original Author : Kenneth C. Mazie : Description : This is a Windows start-up script with pop-up notification and checks to : assure things are not executed if already running or set. It can be run : as a personal start-up script or as a domain start-up (with some editing). : It is intended to be executed from the Start Menu "All Programs\\Startup" folder. : : The script will Start programs, map shares, set routes, and can email the results : if desired. The email subroutine is commented out. You'll need to edit it yourself. : When run with the "debug" variable set to TRUE it also displays status in the : PowerShell command window. Other wise all operation statuses are displayed in pop-up : balloons near the system tray. : : To call the script use the following in a shortcut or in the RUN registry key. : "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -WindowStyle Hidden ¢Noninteractive -NoLogo -Command "&{C:\\Startup.ps1}" : Change the script name and path as needed to suit your environment. : : Be sure to edit all sections to suit your needs before executing. Be sure to : enable sections you wish to run by un-commenting them at the bottom of the script. : : Route setting is done as a function of selecting a specific Network Adapter with the intent : of manually altering your routes for hardline or WiFi connectivity. This section you will : need to customize to suit your needs or leave commented out. This allowed me to : alter the routing for my office (Wifi) or lab (hardline) by detecting whether my : laptop was docked or not. The hardline is ALWAYS favored as written. : : To identify process names to use run "get-process" by itself to list process : names that PowerShell will be happy with, just make sure each app you want to : identify a process name for is already running first. : : A 2 second sleep delay is added to smooth out processing but can be removed if needed. : Notes : Sample script is safe to run as written, it will only load task manager and Firefox. : All notification options are enabled. For silent operation change them to $FALSE. : Many commands are one-liner style, sorry if that causes you grief. : Warnings : Drive mapping passwords are clear text within the script. : : Last Update by : Kenneth C. Mazie (email kcmjr AT kcmjr.com for comments or to report bugs) Version History : v1.0 - 05-03-12 - Original Change History : v2.0 - 11-15-12 - Minor edits : v3.0 - 12-10-12 - Converted application commands to arrays : v4.0 - 02-14-13 - Converted all other sections to arrays : v4.1 - 02-17-13 - Corrected error with pop-up notifications : v5.0 - 03-05-13 - Changed notifications into functions as well as : load routines. Added extra load options. Fixed bugs. : =======================================================================================#> clear-host $ErrorActionPreference = "silentlycontinue" $Debug = $True #--[ Set to false to disable local console messages ]-- $PopUp = $True #--[ Set to false to disable pop-up messages ]-- $CloudStor = $True $ScriptName = "Mazie Startup Script" $UserPath = $env:userprofile $WinDir = $env:windir #--[ Prep Pop-up Notifications ]-- [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") $Icon = [System.Drawing.SystemIcons]::Information $Notify = new-object system.windows.forms.notifyicon $Notify.icon = $Icon #--[ NOTE: Available tooltip icons are = warning, info, error, and none $Notify.visible = $true Function Notifications { #--[ Arguements: 0=delay, 1=message, 2=debug message color, 3=debug message (if different) ]-- if ($Args[3] -eq ""){$Args[3] = $Args[1]} if ($PopUp){$Notify.ShowBalloonTip($Args[0],$ScriptName,$Args[1],[system.windows.forms.tooltipicon]::Info)} if ($debug){write-host $Args[3] -ForegroundColor $Args[2] } } #--[ Force to execute with admin priviledge ]-- $identity = [Security.Principal.WindowsIdentity]::GetCurrent() $principal = new-object Security.Principal.WindowsPrincipal $identity if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -eq $false) {$Args = '-noprofile -nologo -executionpolicy bypass -file "{0}"' -f $MyInvocation.MyCommand.Path;Start-Process -FilePath 'powershell.exe' -ArgumentList $Args -Verb RunAs;exit} Notifications "2500" "Script is running with full admin priviledges..." "DarkCyan" "`n------[ Running with Admin Privileges ]------`n" Notifications "2500" "Script is running in DEBUG mode..." "DarkCyan" "" Function Instances([string]$process) { @(Get-Process $process -ErrorAction 0).Count #--[ For Powershell v3 use $ps = get-process "processname";$ps.count ]-- } function Pause-Host { #--[ Only use if you need a countdown timer ]-- param($Delay = 10) $counter = 0; While(!$host.UI.RawUI.KeyAvailable -and ($Delay-- -ne $counter )) #--count down #While(!$host.UI.RawUI.KeyAvailable -and ($counter++ -lt $Delay )) #--count up { clear-host if ($debug){Write-Host "testing... $Delay"} #--count down #Write-Host "testing... $counter" #--count up [Threading.Thread]::Sleep(1000) } } Function SetRoutes { #--[ Array consists of Network, Mask ]-- $RouteArray = @() $RouteArray += , @("10.0.0.0","255.0.0.0") $RouteArray += , @("172.1.0.0","255.255.0.0") $RouteArray += , @("192.168.1.0","255.255.255.0") #--[ Add more route entries here... ]-- $Index = 0 Do { $RouteNet = $ShareArray[$Index][0] $RouteMask = $ShareArray[$Index][1] iex "route delete $RouteNet" Sleep (2) iex "route add $RouteNet mask $RouteMask $IP" Sleep (2) $Index++ } While ($Index -lt $RouteArray.length) } Function SetMappings { #--[ Array consists of Drive Letter, Path, User, and Password ]-- Notifications "10000" "Stand by, attempting to map drives..." "Yellow" "" $ShareArray = @() $ShareArray += , @("J:","\\\\192.168.1.250\\Share1","username","password") $ShareArray += , @("K:","\\\\192.168.1.250\\Share2","username","password") #--[ Add more mapping entries here... ]-- $Index = 0 Do { $MapDrive = $ShareArray[$Index][0] $MapPath = $ShareArray[$Index][1] $MapUser = $ShareArray[$Index][2] $MapPassword = $ShareArray[$Index][3] $net = $(New-Object -Com WScript.Network) if ( Exists-Drive $MapDrive){$Notify.ShowBalloonTip(2500,$ScriptName,"Drive $MapDrive is already mapped...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "Drive $MapDrive already mapped" -ForegroundColor DarkRed}}else{if (test-path $MapPath){$net.MapNetworkDrive($MapDrive, $MapPath, "False",$MapUser,$MapPassword);$Notify.ShowBalloonTip(2500,$ScriptName,"Mapping Drive $MapDrive...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "Mapping Drive $MapDrive" -ForegroundColor DarkGreen}}else{$Notify.ShowBalloonTip(2500,$ScriptName,"Cannot Map Drive $MapDrive - Target Not Found...",[system.windows.forms.tooltipicon]::Info);if ($debug){write-host "Cannot Map Drive $MapDrive - Target Not Found" -ForegroundColor DarkRed}}} Sleep (2) $Index++ }While ($Index -lt $ShareArray.length) } Function Exists-Drive { param($driveletter) (New-Object System.IO.DriveInfo($driveletter)).DriveType -ne 'NoRootDirectory' } Function LoadApps { #--[ Array consists of Process Name, File Path, Arguements, Title ]-- #--[ Single Instance Array ]-- $AppArray = @() $AppArray += , @("firefox","C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe","https://www.google.com","FireFox") #--[ Add more app entries here... ]-- #--[ Cloud Storage Provider Subsection ]-- if (!$CloudStor ){Notifications "2500" "Cloud Providers Bypassed..." "Magenta" ""} else { $AppArray += , @("googledrivesync","C:\\Program Files (x86)\\Google\\Drive\\googledrivesync.exe","/autostart","GoogleDrive") #--[ Add more cloud entries here... ]-- } $AppArray += , @("taskmgr","C:\\Windows\\System32\\taskmgr.exe","Ā","Task Manager") #--[ Add more app entries here... ]-- $Index = 0 Do { $AppProcess = $AppArray[$Index][0] $AppExe = $AppArray[$Index][1] $AppArgs = $AppArray[$Index][2] $AppName = $AppArray[$Index][3] If (Test-Path $AppExe){ If((get-process -Name $AppProcess -ea SilentlyContinue) -eq $Null){ if ($AppArgs -eq ""){ Notifications "2500" "$AppName is loading..." "DarkGreen" "";start-process -FilePath $AppExe} else { Notifications "2500" "$AppName is loading..." "DarkGreen" "";start-process -FilePath $AppExe -ArgumentList $AppArgs } Do {Sleep (2)} Until ((get-process -Name $AppProcess -ea SilentlyContinue) -ne $Null) Notifications "2500" " $AppName loaded..." "DarkGreen" "" }else{ Notifications "2500" "$AppName is already running..." "DarkRed" "" } sleep (2) }Else{ Notifications "2500" "$AppName was NOT found..." "Red" "" sleep (2) } $Index++ } Until ($Index -ge $AppArray.Count) #--[ Multiple Instance Array. No check for running process ]-- $AppArray = @() #$AppArray += , @("VpxClient","C:\\Program Files (x86)\\VMware\\Infrastructure\\Virtual Infrastructure Client\\Launcher\\VpxClient.exe","-s virtualcenter -passthroughAuth","MAIN vSphere Client") #$AppArray += , @("VpxClient","C:\\Program Files (x86)\\VMware\\Infrastructure\\Virtual Infrastructure Client\\Launcher\\VpxClient.exe","-s vwvirtualcenter -passthroughAuth","VIEW vSphere Client") #$AppArray += , @("VpxClient","C:\\Program Files (x86)\\VMware\\Infrastructure\\Virtual Infrastructure Client\\Launcher\\VpxClient.exe","-s drvirtualcenter -passthroughAuth","DR vSphere Client") $Index = 0 If ($AppArray.count -ge 1){ Do { $AppProcess = $AppArray[$Index][0] $AppExe = $AppArray[$Index][1] $AppArgs = $AppArray[$Index][2] $AppName = $AppArray[$Index][3] if ($AppArgs -eq ""){ Notifications "2500" "$AppName is loading..." "DarkGreen" "";start-process -FilePath $AppExe }else{ Notifications "2500" "$AppName is loading..." "DarkGreen" "";start-process -FilePath $AppExe -ArgumentList $AppArgs } Do {Sleep (2)} Until ((get-process -Name $AppProcess -ea SilentlyContinue) -ne $Null) Notifications "2500" " $AppName loaded..." "DarkGreen" "" Sleep (2) $Index++ } Until ($Index -ge $AppArray.Count) } } <# function SendMail { #param($strTo, $strFrom, $strSubject, $strBody, $smtpServer) param($To, $From, $Subject, $Body, $smtpServer) $msg = new-object Net.Mail.MailMessage $smtp = new-object Net.Mail.SmtpClient($smtpServer) $msg.From = $From $msg.To.Add($To) $msg.Subject = $Subject $msg.IsBodyHtml = 1 $msg.Body = $Body $smtp.Send($msg) } #> Function IdentifyNics { $Domain1 = "LabDomain.com" $Domain2 = "OfficeDomain.com" #--[ Detect Network Adapters ]-- $Wired = get-wmiobject -class "Win32_NetworkAdapterConfiguration" | where {$_.IPAddress -like "192.168.1.*" } #--[ Alternate detection methods]-- #$Wired = get-wmiobject -class "Win32_NetworkAdapterConfiguration" | where {$_.IPAddress -like "192.168.1.*" } | where {$_.DNSDomainSuffixSearchOrder -match $Domain2} #$Wired = get-wmiobject -class "Win32_NetworkAdapterConfiguration" | where {$_.Description -like "Marvell Yukon 88E8056 PCI-E Gigabit Ethernet Controller" } $WiredIP = ([string]$Wired.IPAddress).split(" ") $WiredDesc = $Wired.Description if ($debug){ write-host "Name: " $Wired.Description`n"DNS Domain: " $Wired.DNSDomainSuffixSearchOrder`n"IPv4: " $WiredIP[0]`n"IPv6: " $WiredIP[1]`n"" if ($WiredIP[0]){Notifications "2500" "Detected $WiredDesc" "DarkRed" ""}else{Notifications "2500" "Hardline not detected..." "Red" ""} } sleep (2) $WiFi = get-wmiobject -class "Win32_NetworkAdapterConfiguration" | where {$_.Description -like "Intel(R) Centrino(R) Advanced-N 6250 AGN" } $WiFiIP = ([string]$WiFi.IPAddress).split(" ") $WiFiDesc = $WiFi.Description write-host "Name: " $WiFi.Description`n"DNS Domain: " $WiFi.DNSDomainSuffixSearchOrder`n"IPv4: " $WiFiIP[0]`n"IPv6: " $WiFiIP[1] if ($WiFiIP[0]){Notifications "2500" "Detected $WiFiDesc" "DarkRed" ""}else{Notifications "2500" "WiFi not detected..." "Red" ""} sleep (2) #--[ Set Routes ]-- if ($WiredIP[0]) { #--[ The hardline is connected. Favor the hardline if both connected ]-- $IP = $WiredIP[0] if ($Wired.DNSDomainSuffixSearchOrder -like $Domain1 -or $Wired.DNSDomainSuffixSearchOrder -like $Domain2) { #--[ the hardline is connected ]-- write-host ""`n"Setting routes for hardline"`n"" Notifications "2500" "Setting routes for hardline..." "DarkRed" #SetRoutes $IP } } else { if ($WiFiIP[0]) { if ($WiFi.DNSDomainSuffixSearchOrder -like $Domain2) { #--[ The wifi is connected --] $IP = $WiFiIP[0] write-host ""`n"Setting routes for wifi"`n"" Notifications "2500" "Setting routes for wifi..." "DarkRed" #SetRoutes $IP } } } } #Write-Host $IP #IdentifyNics #SetMappings #Pause-Host LoadApps Notifications "2500" "Completed All Operations..." "DarkCyan" ""
PowerShellCorpus/PoshCode/Get-Hostname_1.ps1
Get-Hostname_1.ps1
# .SYNOPSIS # Print the hostname of the system. # .DESCRIPTION # This function prints the hostname of the system. You can additionally output the DNS # domain or the FQDN by using the parameters as described below. # .PARAMETER Short # (Default) Print only the computername, i.e. the same value as returned by $env:computername # .PARAMETER Domain # If set, print only the DNS domain to which the system belongs. Overrides the Short parameter. # .PARAMETER FQDN # If set, print the fully-qualified domain name (FQDN) of the system. Overrides the Domain parameter. param ( [switch]$Short = $true, [switch]$Domain = $false, [switch]$FQDN = $false ) $ipProperties = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties() if ( $FQDN ) { return "{0}.{1}" -f $ipProperties.HostName, $ipProperties.DomainName } if ( $Domain ) { return $ipProperties.DomainName } if ( $Short ) { return $ipProperties.HostName }
PowerShellCorpus/PoshCode/View-Process_v2.ps1
View-Process_v2.ps1
function View-Process(){ param( [string[]]$ComputerNames, [string[]]$ProcessNames, $User ) if ($User -is [String]){ $Connection = Get-Credential -Credential $User } if ($ProcessNames -eq $null){ if ($Connection -eq $null){ foreach ($int1 in $ComputerNames){ $View_Process = gwmi "win32_process" -ComputerName $int1 | select __SERVER,Name,Handle $View_Process } } else { foreach ($int1 in $ComputerNames){ $View_Process = gwmi "win32_process" -ComputerName $int1 -Credential $Connection | select __SERVER,Name,Handle $View_Process } } } else { if ($Connection -eq $null){ foreach ($int1 in $ComputerNames){ foreach ($int2 in $ProcessNames){ if ($int2 -notlike "*.exe") {$int2 = $int2 + '.exe'} $View_Process = gwmi "win32_process" -ComputerName $int1 -filter "name='$int2'" | select __SERVER,Name,Handle $View_Process } } } else { foreach ($int1 in $ComputerNames){ foreach ($int2 in $ProcessNames){ $View_Process = gwmi "win32_process" -ComputerName $int1 -filter "name='$int2'" -Credential $Connection | select __SERVER,Name,Handle $View_Process } } } } }
PowerShellCorpus/PoshCode/Run-Query (SharePoint)_1.ps1
Run-Query (SharePoint)_1.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" @@ @@