full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PoshCode/where-property.ps1
where-property.ps1
function where-property([string] $PropertyName,[string]$SubProperty , $is,$isnot,$contains,$in) { process { if ($is) { if ($_.$Propertyname -eq $is) { , $_ } } elseif ($isnot) { if ($_.$Propertyname -ne $is) { , $_ } } elseif($contains) { if ($subproperty) { foreach ($prop in $_.$propertyname ) { if ($prop) { $subpropertyvalue = $prop.$subproperty if ($subpropertyvalue -contains $contains ) { , $_ } } } } else { if ($_.$Propertyname -contains $contains) { , $_ } } } elseif($in) { if ($in -contains $_.$Propertyname) { , $_ } } } } #set-alias and-property where-property #get-processes with a specific name gps | where-property processname -is svchost #get-processes all but a specific name gps | where-property processname -isnot svchost #get-processes with the processname in a specific list gps | where-property processname -in iexplore,chrome #get verbs in a specific group get-verb | where-property group -in common #get-commands that have a specific named parameter get-command | where-property parameters -subproperty keys -contains Begin #and using an a lias to this for the and since it seems more HUMAN to say where X and Y, rather than Where x where y get-command | where-property parameters -subproperty keys -contains Name | and-property commandtype -is alias
PowerShellCorpus/PoshCode/Compare-DatabaseSchema.ps1
Compare-DatabaseSchema.ps1
param( $SqlServerOne = 'YourDatabaseServer', $FirstDatabase = 'FirstDatabaseToCompare', $SqlUsernameOne = 'SQL Login', $SqlPasswordOne = 'SQL Password', $SqlServerTwo = 'YourDatabaseServer', $SecondDatabase = 'SecondDatabaseToCompare', $SqlUsernameTwo = 'SQL Login', $SqlPasswordTwo = 'SQL Password', $FilePrefix = 'Log', [switch]$Log, [switch]$Column) $File = $FilePrefix + '{0}-{1}.csv' $TableQuery = @" select sysobjects.name as TableName from sysobjects where sysobjects.xtype like 'U' and --specify only user tables sysobjects.name not like 'dtproperties' --specify only user tables "@ function Run-Query() { param ( $SqlQuery, $SqlServer, $SqlCatalog, $SqlUser, $SqlPass ) $SqlConnString = "Server = $SqlServer; Database = $SqlCatalog; user = $SqlUser; password = $SqlPass" $SqlConnection = New-Object System.Data.SqlClient.SqlConnection $SqlConnection.ConnectionString = $SqlConnString $SqlCmd = New-Object System.Data.SqlClient.SqlCommand $SqlCmd.CommandText = $SqlQuery $SqlCmd.Connection = $SqlConnection $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter $SqlAdapter.SelectCommand = $SqlCmd $DataSet = New-Object System.Data.DataSet $a = $SqlAdapter.Fill($DataSet) $SqlConnection.Close() $DataSet.Tables | Select-Object -ExpandProperty Rows } $TablesDBOne = Run-Query -SqlQuery $TableQuery -SqlServer $SqlServerOne -SqlCatalog $FirstDatabase -SqlUser $SqlUsernameOne -SqlPass $SqlPasswordOne | Select-Object -Property TableName $TablesDBTwo = Run-Query -SqlQuery $TableQuery -SqlServer $SqlServerTwo -SqlCatalog $SecondDatabase -SqlUser $SqlUsernameTwo -SqlPass $SqlPasswordTwo | Select-Object -Property TableName Write-Host 'Differences in Tables: ' $Database = @{Name='Database';Expression={if ($_.SideIndicator -eq '<='){'{0} / {1}' -f $FirstDatabase, $SqlServerOne} else {'{0} / {1}' -f $SecondDatabase, $SqlServerTwo}}} $TableDifference = Compare-Object $TablesDBOne $TablesDBTwo -SyncWindow (($TablesDBOne.count + $TablesDBTwo.count)/2) -Property TableName | select TableName, $Database if ($log) { $TableDifference | Export-Csv -Path ($file -f $FirstDatabase, $SecondDatabase) -NoTypeInformation } $TableDifference | Sort-Object -Property TableName, Database if ($Column) { #Compare columns in matching tables in DB $SameTables = Compare-Object $TablesDBOne $TablesDBTwo -SyncWindow (($TablesDBOne.count + $TablesDBTwo.count)/2) -Property TableName -IncludeEqual -ExcludeDifferent $ColumnQuery = @" select sysobjects.name as TableName , syscolumns.name as ColumnName , systypes.name as Type , systypes.Length , systypes.XUserType from sysobjects, syscolumns, systypes where sysobjects.xtype like 'U' and --specify only user tables sysobjects.name not like 'dtproperties' and --specify only user tables syscolumns.xusertype= systypes.xusertype --get data type info and sysobjects.id=syscolumns.id and sysobjects.name = '{0}' order by sysobjects.name, syscolumns.name, syscolumns.type "@ Write-Host "`n`n" Read-Host 'Press Enter to Check for Column Differences' foreach ($Table in $SameTables) { $ColumnsDBOne = Run-Query -SqlQuery ($ColumnQuery -f $table.tablename) -SqlServer $SqlServerOne -SqlCatalog $FirstDatabase -SqlUser $SqlUsernameOne -SqlPass $SqlPasswordOne | Select-Object -Property TableName, ColumnName, Type, Length, XUserType $ColumnsDBTwo = Run-Query -SqlQuery ($ColumnQuery -f $table.tablename) -SqlServer $SqlServerTwo -SqlCatalog $SecondDatabase -SqlUser $SqlUsernameTwo -SqlPass $SqlPasswordTwo | Select-Object -Property TableName, ColumnName, Type, Length, XUserType $ColumnDifference = Compare-Object $ColumnsDBOne $ColumnsDBTwo -SyncWindow (($ColumnsDBOne.count + $ColumnsDBTwo.count)/2) -Property TableName, ColumnName, Type, Length, XUserType | Select-Object TableName, ColumnName, Type, Length, XUserType, $Database if ($log -and $ColumnDifference ) { $ColumnDifference | Export-Csv -Path ($file -f $Table.TableName,'Columns' ) -NoTypeInformation } $ColumnDifference | sort ColumnName, Database } }
PowerShellCorpus/PoshCode/pslauncher.ps1
pslauncher.ps1
/* * Compile this program by simply doing: * * csc.exe PSLauncher.cs * */ // Requires powershell V2 /* * The Problem: * .ps1 scripts do not integrate with the shell nicely. You cannot * simply associate powershell.exe with .ps1 and have them run when u * double click them. Also, the execution of script you click on may * be blocked by security policies. Thirdly, some powershell scripts * require ps to be launched with some command line arguments, to frequently * run such a script then requires keyboard entry or awkward batch files. * * The Solution: * Compile this program, and associate it as the default launcher for .ps1. * follow the usage details below, and you will be able to launch .ps1 scripts * from the shell with mouse alone, and as added benafit you get to put * ps cmd line options in your script, and you can run scripts invisible. * * USAGE: * Put the first two characters of your script as "#!" * Follow that with the full path to powershell.exe (incl fname) or * if powershell.exe is in the path you can just put #!powershell.exe * * The remainder part of that line will be passed to powershell.exe as * arguments. For example, -STA. The filename of the script is also * passed as "-file %1" along with "-ExecutionPolicy UnRestricted". * * The second line of the file, if it is prefixed by "#-" can contain "meta arguments" * for powershell. Currently the only one allowed is "Hidden" which will supress the * powershell window and discard any output from the script. * * If a .ps1 script without these magics #! is encountered, it will be passed * to powershell.exe as above, if powershell.exe is in the path or default location. * * Example: * #!powershell.exe -STA * #-Hidden * ...rest of script... * * * or * * * #!C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\powershell.exe -noexit * ...rest of a script you don't want to exit when it ends... */ using System; using System.Collections.Generic; using System.Windows.Forms; using System.Diagnostics; using System.IO; using System.Text.RegularExpressions; namespace PSLauncher { static class PSLauncher { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string [] args) { if (args.Length != 1) { throw new ArgumentException("Wrong number of arguments, there must be exactly one."); } if (!(new Regex(".ps1$")).Match(args[0]).Success) { psl_err("Must have extension of ps1 or powershell.exe will error."); return; } StreamReader fs; string line_1; string line_2; string exe_path; string cmd_line; string ps_args; Regex r; Match m; bool hidden = false; Process ps_proc; try { fs = new StreamReader(args[0]); } catch (FileNotFoundException) { psl_err("File Not Found."); return; } catch (FileLoadException) { psl_err("File found but could not be loaded."); return; } try { line_1 = fs.ReadLine(); line_2 = fs.ReadLine(); } catch (IOException) { psl_err("File may not have enough lines."); return; } fs.Close(); r = new Regex(@"^#!(.*)powershell\\.exe"); exe_path = ""; if ((m = r.Match(line_1)).Success) { line_1 = r.Replace(line_1, ""); exe_path = m.Groups[1].Value; if (exe_path != "") { if (!File.Exists(exe_path + "powershell.exe")) { psl_err("specified powershell.exe file not exist."); } } else { exe_path = find_powershell(); if (exe_path == "") { psl_err("powershell.exe is not found."); return; } } } else { line_1 = ""; exe_path = find_powershell(); if (exe_path == "") { psl_err("powershell.exe is not found."); return; } } cmd_line = exe_path + "\\\\" + "powershell.exe"; ps_args = line_1 + " -ExecutionPolicy UnRestricted -File \\"" + args[0] + "\\""; r = new Regex("^#-"); if ((m = r.Match(line_2)).Success) { line_2 = r.Replace(line_2, ""); if ((new Regex("Hidden")).Match(line_2).Success) { hidden = true; } } ps_proc = new Process(); if (hidden) { ps_proc.StartInfo.RedirectStandardError = true; ps_proc.StartInfo.RedirectStandardInput = true; ps_proc.StartInfo.RedirectStandardOutput = true; ps_proc.StartInfo.CreateNoWindow = true; ps_proc.StartInfo.UseShellExecute = false; } ps_proc.StartInfo.Arguments = ps_args; ps_proc.StartInfo.FileName = cmd_line; ps_proc.Start(); } private static void psl_err(string msg) { MessageBox.Show(msg, "PSLauncher Critical Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } private static string find_powershell() { string exe_path = ""; foreach (string test_path in Environment.GetEnvironmentVariable("Path").Split(';')) { if (File.Exists(test_path + "\\\\" + "powershell.exe")) exe_path = test_path; } if (exe_path == "" && File.Exists( "C:\\\\WINDOWS\\\\system32\\\\windowspowershell\\\\v1.0\\\\powershell.exe")) exe_path = "C:\\\\WINDOWS\\\\system32\\\\windowspowershell\\\\v1.0\\\\powershell.exe"; return exe_path; } } }
PowerShellCorpus/PoshCode/Product key_4.ps1
Product key_4.ps1
from System import Array, Char, Console from System.Collections import ArrayList from Microsoft.Win32 import Registry def DecodeProductKey(digitalProductID): map = ("BCDFGHJKMPQRTVWXY2346789").ToCharArray() key = Array.CreateInstance(Char, 29) raw = ArrayList() i = 52 while i < 67: raw.Add(digitalProductID[i]) i += 1 i = 28 while i >= 0: if (i + 1) % 6 == 0: key[i] = '-' else: k = 0 j = 14 while j >= 0: k = (k * 256) ^ raw[j] raw[j] = (k / 24) k %= 24 key[i] = map[k] j -= 1 i -= 1 return key reg = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion") val = reg.GetValue("DigitalProductId") Console.WriteLine(DecodeProductKey(val))
PowerShellCorpus/PoshCode/Decrypt Psi Password.ps1
Decrypt Psi Password.ps1
function decrypt-psi ($jid, $pw) { $OFS = ""; $u = 0; for($p=0;$p -lt $pw.Length;$p+=4) { [char]([int]"0x$($pw[$p..$($p+3)])" -bxor [int]$jid[$u++]) } } $accounts = ([xml](cat ~\\psidata\\profiles\\default\\accounts.xml))["accounts"]["accounts"] foreach($account in ($accounts | gm a[0-9]*)) { $a = $accounts.$($account.Name) "$($a.jid.'#text'):$( decrypt-psi $a.jid.'#text' $a.password.'#text' )" }
PowerShellCorpus/PoshCode/print-file.ps1
print-file.ps1
function print-file($file) { begin { function internal-printfile($thefile) { if ($thefile -is [string]) {$filename = $thefile } else { if ($thefile.FullName -is [string] ) { $filename = $THEfile.FullName } } $start = new-object System.Diagnostics.ProcessStartInfo $filename $start.Verb = "print" [System.Diagnostics.Process]::Start($start) } if ($file -ne $null) { $filespecified = $true; internal-printfile $file } } process{if (!$filespecified) { write-Host process ; internal-printfile $_ } } }
PowerShellCorpus/PoshCode/Hardware Inventory_1.ps1
Hardware Inventory_1.ps1
# Synopsis: # Windows Script to collect Hardware information on a local system # And Convert it to a JSON String and Upload that to a CouchDB # Database for newly installed servers. # Requirements: # -Local Admin Access in Powershell v2 # -ConvertTo-Json.ps1 Function # -SSL(443/TCP) allowed to CouchDB Host # -Proxy verified and communication to it Write-Host " ---------------------------------------------- _ _ _____ _ _ | \\ | |_ _| / \\ ___ ___ ___| |_ | \\| | | | / _ \\ / __/ __|/ _ \\ __| | |\\ | | | / ___ \\\\__ \\__ \\ __/ |_ |_| \\_| |_| /_/ \\_\\___/___/\\___|\\__| ___ _ |_ _|_ ____ _____ _ __ | |_ ___ _ __ _ _ | || '_ \\ \\ / / _ \\ '_ \\| __/ _ \\| '__| | | | | || | | \\ V / __/ | | | || (_) | | | |_| | |___|_| |_|\\_/ \\___|_| |_|\\__\\___/|_| \\__, | |___/ by VulcanX 2011-09-29 v1.1 ---------------------------------------------- " #Adding ConvertTo-JSON function for use later on in script Filter ConvertTo-JSON { Function New-JSONProperty ($name, $value) { @" "$name": $value "@ } $targetObject = $_ $jsonProperties = @() $properties = $_ | Get-Member -MemberType *property ForEach ($property in $properties) { #"$($property.Name)=$($targetObject.$($property.Name)) [$($($targetObject.$($property.Name)).GetType())]" #(($targetObject.($property.Name)).GetType()).Name $value = $targetObject.($property.Name) $dataType = (($targetObject.($property.Name)).GetType()).Name switch -regex ($dataType) { 'String' {$jsonProperties += New-JSONProperty $property.Name "`"$value`""} 'Int32|Double' {$jsonProperties += New-JSONProperty $property.Name $value} 'Object\\[\\]' { #$jsonProperties += "`t`"$($property.Name)`": [$($($targetObject.($property.Name)) -join ',')]" $str = "`t`"$($property.Name)`": [" $count = $targetObject.($property.Name).Count For($idx=0; $idx -lt $count; $idx++) { $v = $targetObject.($property.Name)[$idx] switch -regex ($v.GetType()) { 'String' {$v="`"$v`""} } if($idx+1 -lt $count) { $comma = "," } else { $comma = "" } $str += "$v$($comma)" } $jsonProperties += "$str]" } default {$_} } } "{`r`n $($jsonProperties -join ",`r`n") `r`n}" } #Get WMI Info #Declaring all variables for use later in JSON $HOSTNAME1 = Get-WmiObject win32_computersystem | Select-Object -ExpandProperty Name $HOSTNAME2 = Get-WmiObject win32_computersystem | Select-Object -ExpandProperty Domain $HOSTNAME = "$HOSTNAME1.$HOSTNAME2" $OS = Get-WmiObject win32_operatingsystem | Select-Object -ExpandProperty Caption $OS_RELEASE = Get-WmiObject win32_operatingsystem | Select-Object -ExpandProperty Version $IP_ADDRESS_1 = Get-WmiObject win32_NetworkAdapterConfiguration | Where { $_.IPAddress -and $_.IPAddress -notlike ':' } | Select -ExpandProperty IPAddress $IP_ADDRESS = $IP_ADDRESS_1 -join ' ' # Adding multiple address onto one line $MAC_ADDRESS_1 = Get-WmiObject win32_networkadapter | Where { $_.PhysicalAdapter -eq $TRUE -and $_.MacAddress -ne $null } | Select-Object -ExpandProperty MACAddress $MAC_ADDRESS = $MAC_ADDRESS_1 -join ' ' #Adding multiple addresses onto one line $MEMORY = Get-WmiObject win32_computersystem | Select-Object -ExpandProperty TotalPhysicalMemory $BIOS_VENDOR = Get-WmiObject win32_bios | Select-Object -ExpandProperty Manufacturer $BIOS_VERSION = Get-WmiObject win32_bios | Select-Object -ExpandProperty SMBIOSBIOSVersion $BIOS_RELEASE_DATE = Get-WmiObject win32_bios | Select-Object @{label='Release Date';expression={$_.ConvertToDateTime($_.releasedate).ToShortDateString()}} | Select-Object -ExpandProperty 'Release Date' $SYSTEM_MANUFACTURER = Get-WmiObject win32_computersystemproduct | Select-Object -ExpandProperty Vendor $SYSTEM_PRODUCT_NAME = Get-WmiObject win32_computersystemproduct | Select-Object -ExpandProperty Name $SYSTEM_VERSION = Get-WmiObject win32_computersystemproduct | Select-Object -ExpandProperty Version $SYSTEM_SERIAL_NUMBER = Get-WmiObject win32_computersystemproduct | Select-Object -ExpandProperty IdentifyingNumber $SYSTEM_UUID = Get-WmiObject win32_computersystemproduct | Select-Object -ExpandProperty UUID $BASEBOARD_MANUFACTURER = Get-WmiObject win32_baseboard | Select-Object -ExpandProperty Manufacturer $BASEBOARD_PRODUCT_NAME = Get-WmiObject win32_baseboard | Select-Object -ExpandProperty Product $BASEBOARD_VERSION = Get-WmiObject win32_baseboard | Select-Object -ExpandProperty Version $BASEBOARD_SERIAL_NUMBER = Get-WmiObject win32_baseboard | Select-Object -ExpandProperty SerialNumber $BASEBOARD_ASSET_TAG = Get-WmiObject win32_baseboard | Select-Object -ExpandProperty Tag $CHASSIS_MANUFACTURER = Get-WmiObject win32_systemenclosure | Select-Object -ExpandProperty Manufacturer $CHASSIS_TYPE = Get-WmiObject win32_systemenclosure | Select-Object -ExpandProperty ChassisTypes $CHASSIS_VERSION = Get-WmiObject win32_systemenclosure | Select-Object -ExpandProperty Version $CHASSIS_SERIAL_NUMBER = Get-WmiObject win32_systemenclosure | Select-Object -ExpandProperty SerialNumber $CHASSIS_ASSET_TAG = Get-WmiObject win32_systemenclosure | Select-Object -ExpandProperty SMBIOSAssetTag $PROCESSOR_FAMILY1 = Get-WmiObject win32_processor | Select-Object -ExpandProperty Family -First 1 # Storing this for switching depending on version $PROCESSOR_FAMILY = Switch ($PROCESSOR_FAMILY1) # Switching the PROCESSOR_FAMILY1 to a true value or defaulting to the number { 12 {"Pentium Pro"} 132 {"AMD Opteron"} 176 {"Pentium 3 Xeon"} 179 {"Intel Xeon"} 181 {"Intel Xeon MP"} Default {$PROCESSOR_FAMILY1} } $PROCESSOR_MANUFACTURER = Get-WmiObject win32_processor | Select-Object -ExpandProperty Manufacturer -First 1 $PROCESSOR_VERSION = Get-WmiObject win32_processor | Select-Object -ExpandProperty Name -First 1 $PROCESSOR_ARCH1 = Get-WmiObject win32_processor | Select-Object -ExpandProperty Architecture -First 1 # Storing this for switching depending on version $PROCESSOR_ARCH = Switch ($PROCESSOR_ARCH1) # Switching the PROCESSOR_ARCH1 to a true value or defaulting to the number { 0 {"x86"} 1 {"MIPS"} 2 {"Alpha"} 3 {"PowerPC"} 6 {"Itanium"} 9 {"x64"} Default {$PROCESSOR_ARCH1} } $PROCESSOR_FREQUENCY = Get-WmiObject win32_processor | Select-Object -ExpandProperty MaxClockSpeed -First 1 # Storing all the information in a variable to convert to JSON Later $RESULTS = (New-Object PSObject | add-member -pass noteproperty HOSTNAME "$HOSTNAME" | add-member -pass noteproperty OS "$OS" | add-member -pass noteproperty OS-RELEASE "$OS_RELEASE" | add-member -pass noteproperty IP-ADDRESS "$IP_ADDRESS" | add-member -pass noteproperty MAC-ADDRESS "$MAC_ADDRESS" | add-member -pass noteproperty MEMORY "$MEMORY" | add-member -pass noteproperty BIOS-VENDOR "$BIOS_VENDOR" | add-member -pass noteproperty BIOS-VERSION "$BIOS_VERSION" | add-member -pass noteproperty BIOS-RELEASE-DATE "$BIOS_RELEASE_DATE" | add-member -pass noteproperty SYSTEM-MANUFACTURER "$SYSTEM_MANUFACTURER" | add-member -pass noteproperty SYSTEM-PRODUCT-NAME "$SYSTEM_PRODUCT_NAME" | add-member -pass noteproperty SYSTEM-VERSION "$SYSTEM_VERSION" | add-member -pass noteproperty SYSTEM-SERIAL-NUMBER "$SYSTEM_SERIAL_NUMBER" | add-member -pass noteproperty SYSTEM-UUID "$SYSTEM_UUID" | add-member -pass noteproperty BASEBOARD-MANUFACTURER "$BASEBOARD_MANUFACTURER" | add-member -pass noteproperty BASEBOARD-PRODUCT-NAME "$BASEBOARD_PRODUCT_NAME" | add-member -pass noteproperty BASEBOARD-VERSION "$BASEBOARD_VERSION" | add-member -pass noteproperty BASEBOARD-SERIAL-NUMBER "$BASEBOARD_SERIAL_NUMBER" | add-member -pass noteproperty BASEBOARD-ASSET-TAG "$BASEBOARD_ASSET_TAG" | add-member -pass noteproperty CHASSIS-MANUFACTURER "$CHASSIS_MANUFACTURER" | add-member -pass noteproperty CHASSIS-TYPE "$CHASSIS_TYPE" | add-member -pass noteproperty CHASSIS-VERSION "$CHASSIS_VERSION" | add-member -pass noteproperty CHASSIS-SERIAL-NUMBER "$CHASSIS_SERIAL_NUMBER" | add-member -pass noteproperty CHASSIS-ASSET-TAG "$CHASSIS_ASSET_TAG" | add-member -pass noteproperty PROCESSOR-FAMILY "$PROCESSOR_FAMILY" | add-member -pass noteproperty PROCESSOR-MANUFACTURER "$PROCESSOR_MANUFACTURER" | add-member -pass noteproperty PROCESSOR-VERSION "$PROCESSOR_VERSION" | add-member -pass noteproperty PROCESSOR-ARCH "$PROCESSOR_ARCH" | add-member -pass noteproperty PROCESSOR-FREQUENCY "$PROCESSOR_FREQUENCY" ) | ConvertTo-Json # Converting $RESULTS to JSON Format # Double check the structure and layout is all correct echo $RESULTS # CouchDB Credentials $username = Read-Host "CouchDB Username" $password = Read-Host "CouchDB Password" # Creating the document on the CouchDB Database [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} ; $request = [System.Net.WebRequest]::Create("https://server.domain.com/database/$HOSTNAME1") #Set this to your CouchDB Database # Converting the Header and adding the username and password to it in base64 encoding $auth = [System.Text.Encoding]::UTF8.GetBytes("$username" + ":" + "$password") $base64 = [System.Convert]::ToBase64String($auth) $authorization = "Authorization: Basic " + $base64 $request.Headers.Add($authorization) # Adding credentials for the webrequest and address of the proxy $request.Credentials = New-Object System.Net.NetworkCredential($username, $password) $request.Proxy = New-Object -TypeName System.Net.WebProxy -ArgumentList "http://proxy.domain.com:3128" # http://*hostname*:*port* format $data = [Text.Encoding]::UTF8.GetBytes($RESULTS) # Specifying what method to use $request.ContentLength = $data.Length $request.Method = "PUT" # Be careful to set your content type appropriately... # This is what you're going to SEND THEM $request.ContentType = "application/json"; # 'text/xml;charset="utf-8"'; "application/x-www-form-urlencoded" # This is what you expect back $request.Accept = "application/json"; # "text/xml" # Executing the PUT request $put = new-object IO.StreamWriter $request.GetRequestStream() $put.Write($data,0,$data.Length) $put.Flush() $put.Close()
PowerShellCorpus/PoshCode/Invoke-ADMTUserMigration.ps1
Invoke-ADMTUserMigration.ps1
###########################################################################" # # NAME: Invoke-ADMTUserMigration.ps1 # # AUTHOR: Jan Egil Ring # EMAIL: jan.egil.ring@powershell.no # # COMMENT: This is an example on how to script the Active Directory Migration Tool (ADMT) using PowerShell. # It`s based on the sample templatescript.vbs which resides in the ADMT installation-directory. # NOTE: Since ADMT is a 32-bit application, this script must be run from Windows PowerShell (x86). # It also requires elevated privileges. # # For more details, see the following blog-post: # http://blog.powershell.no/2010/08/04/automate-active-directory-migration-tool-using-windows-powershell # # You have a royalty-free right to use, modify, reproduce, and # distribute this script file in any way you find useful, provided that # you agree that the creator, owner above has no warranty, obligations, # or liability for such use. # # VERSION HISTORY: # 1.0 04.08.2010 - Initial release # ###########################################################################" ### BEGIN ADMT Scripting Constants ### # PasswordOption constants $admtComplexPassword = "&H0001" $admtCopyPassword = "&H0002" $admtDoNotUpdatePasswordsForExisting = "&H0010" # ConflictOptions constants $admtIgnoreConflicting = "&H0000" $admtMergeConflicting = "&H0001" $admtRemoveExistingUserRights = "&H0010" $admtRemoveExistingMembers = "&H0020" $admtMoveMergedAccounts = "&H0040" # DisableOption constants $admtLeaveSource = "&H0000" $admtDisableSource = "&H0001" $admtTargetSameAsSource = "&H0000" $admtDisableTarget = "&H0010" $admtEnableTarget = "&H0020" # SourceExpiration constant $admtNoExpiration = "-1" # Translation Option $admtTranslateReplace = "0" $admtTranslateAdd = "1" $admtTranslateRemove = "2" # Report Type $admtReportMigratedAccounts = "0" $admtReportMigratedComputers = "1" $admtReportExpiredComputers = "2" $admtReportAccountReferences = "3" $admtReportNameConflicts = "4" # Option constants $admtNone = "0" $admtData = "1" $admtFile = "2" $admtDomain = "3" $admtRecurse = "&H0100" $admtFlattenHierarchy = "&H0000" $admtMaintainHierarchy = "&H0200" # Event related constants # Progress type $admtProgressObjectMigration = "0" $admtProgressAgentDispatch = "1" $admtProgressAgentOperation = "2" $admtProgressMailboxMigration = "3" # Event type $admtEventNone = "0" $admtEventObjectInputPreprocessed = "1" $admtEventTaskStart = "2" $admtEventTaskFinish = "3" $admtEventObjectProcessed = "4" $admtEventGroupMembershipProcessed = "5" $admtEventAgentStatusUpdate ="6" $admtEventAgentNotStarted = "7" $admtEventAgentFailedToStart = "8" $admtEventAgentWaitingForReboot = "9" $admtEventAgentRunning = "10" $admtEventAgentCancelled = "11" $admtEventAgentPassed = "12" $admtEventAgentFailed = "13" $admtEventAgentWaitingForRetry = "14" $admtEventAgentSuccessful = "15" $admtEventAgentCompletedWithWarnings = "16" $admtEventAgentCompletedWithErrors = "17" $admtEventTaskLogSaved = "18" $admtAgentPreCheckPhase = "&H100" $admtAgentAgentOperationPhase = "&H200" $admtAgentPostCheckPhase = "&H300" $admtAgentStatusMask = "&HFF" $admtAgentPhaseMask = "&H300" # Status type $admtStatusSuccess = "0" $admtStatusWarnings = "1" $admtStatusErrors = "2" ### END ADMT Scripting Constants ### #Creates an instance of an ADMT migration object using the COM-object provided with ADMT $Migration = New-Object -ComObject "ADMT.Migration" $Migration.IntraForest = $false $Migration.SourceDomain = "contoso-old.local" $Migration.SourceDomainController = "dc01.contoso-old.local" $Migration.SourceOU = "Europe/Norway/Oslo" $Migration.TargetDomain = "contoso-new.local" $Migration.TargetDomainController = "dc02.contoso-new.local" $Migration.TargetOU = "Europe/Norway/Oslo" $Migration.PasswordOption = $admtComplexPassword $Migration.PasswordServer = "dc01.contoso-old.local" $Migration.PasswordFile = "C:\\WINDOWS\\ADMT\\Logs\\Passwords.txt" $Migration.ConflictOptions = $admtIgnoreConflicting $Migration.UserPropertiesToExclude = "" $Migration.InetOrgPersonPropertiesToExclude = "" $Migration.GroupPropertiesToExclude = "" $Migration.ComputerPropertiesToExclude = "" $Migration.SystemPropertiesToExclude = "" $Migration.PerformPreCheckOnly = $false $Migration.AdmtEventLevel = $admtStatusWarnings $Migration.CommandLine = $false #Creates an user migration object $UserMigration = $Migration.CreateUserMigration() $UserMigration.DisableOption = $admtTargetSameAsSource $UserMigration.SourceExpiration = $admtNoExpiration $UserMigration.MigrateSIDs = $true $UserMigration.TranslateRoamingProfile = $false $UserMigration.UpdateUserRights = $false $UserMigration.MigrateGroups = $false $UserMigration.UpdatePreviouslyMigratedObjects = $false $UserMigration.FixGroupMembership = $true $UserMigration.MigrateServiceAccounts = $false #Initiates user migration. Logs are written to C:\\Windows\\ADMT\\Logs by default. $UserMigration.Migrate($admtDomain,$null,$null) #Creates a password migration object $PasswordMigration = $Migration.CreatePasswordMigration() #Initiates password migration. Logs are written to C:\\Windows\\ADMT\\Logs by default. $PasswordMigration.Migrate($admtDomain,$null,$null)
PowerShellCorpus/PoshCode/Copy-Shares.ps1
Copy-Shares.ps1
<# .SYNOPSIS Recreates shares and copies share permissions. .DESCRIPTION Recreates shares and copies share permissions. .NOTES Name: Copy-Shares Author: Sysiphus DateCreated: 2013:03:06 Inspiration: http://poshcode.org/935 http://gallery.technet.microsoft.com/scriptcenter/a231026a-3fdb-4190-9915-38d8cd827348 http://serverfault.com/questions/9011/creating-a-share-with-permissions-with-windows-powershell Info: This script "copies" shares and share permissions from one computer to another. The drive letter can change between computers, but the path(s) on the drive may not. This script does not copy the data; for that you will need another solution, such as xcopy or a decent SAN that can do it for you. It works on OSes as old as Windows 2000, and at least as new as Server 2008 R2. It probably has a hundred possible improvements. .EXAMPLE Copy-Shares -SourceComputer Oldbox -SourceDrive E -DestComputer Newbox -DestDrive K #> Param ( [Parameter( Position=0, ValueFromRemainingArguments=$true, HelpMessage="Name of computer to get shares from, with no domain or slashes." )] [Alias("Old")] [ValidatePattern("^[^\\\\]")] [ValidateNotNullOrEmpty()] [String]$SourceComputer = "OldAndBusted", [Parameter( Position=1, ValueFromRemainingArguments=$true, HelpMessage="Source drive letter, with no colon or slash." )] [ValidatePattern('[^:]$')] [ValidateNotNullOrEmpty()] [String]$SourceDrive = "D", [Parameter( Position=2, ValueFromRemainingArguments=$true, HelpMessage="Name of computer to create shares on, with no domain or slashes." )] [Alias("New")] [ValidatePattern("^[^\\\\]")] [ValidateNotNullOrEmpty()] [String]$DestComputer = "NewHotness", [Parameter( Position=3, ValueFromRemainingArguments=$true, HelpMessage="Destination drive letter, with no colon or slash." )] [ValidatePattern('[^:]$')] [ValidateNotNullOrEmpty()] [String]$DestDrive = "F" ) #Format the drives to include ":\\". I know there's a much better way to do it out there. $SourceDrive = $SourceDrive + ":\\" $DestDrive = $DestDrive + ":\\" #Some early WMI queries to establish what needs to be done [Array]$SourceShares = Get-WmiObject -ComputerName $SourceComputer -Class Win32_Share -Filter "Type = '0'" # To eliminate all admin and non-disk shares [Array]$SourcePerms = Get-WmiObject -ComputerName $SourceComputer -Class Win32_LogicalShareSecuritySetting [Array]$DestShares = Get-WmiObject -ComputerName $DestComputer -Class Win32_Share -Filter "Type = '0'" # see http://msdn.microsoft.com/en-us/library/windows/desktop/aa394435%28v=vs.85%29.aspx [Array]$DestPerms = Get-WmiObject -ComputerName $DestComputer -Class Win32_LogicalShareSecuritySetting #Region Limit to shares on specified source drive, warn on others $SourceShareWrongDrive = $SourceShares | Where {$_.Path -notlike "$SourceDrive*"} [Array]$SourceShares = $SourceShares | Where {$_.Path -like "$SourceDrive*"} If ($SourceShareWrongDrive) { Write-Host -Fore Cyan -No "`nThe following shares are on a different source drive than the one you specified ($SourceDrive):" $SourceShareWrongDrive Write-Host -Fore Cyan "You will need to either do these shares manually, skip them, or re-run the script again for each additional drive.`n" } #EndRegion #Region Limit to shares with security settings #This little line of voodoo gets just the names of $SourceShares, and selects only those which are not in just the names of $SourcePerms #Feel free to pick it apart and make it cleaner, I just didn't want four more free variables running amok. #I also confess that I do these lines sometimes just to see if they really work... [Array]$MissingPerms = $SourceShares | %{$_.Name} | %{ if (($SourcePerms | %{$_.Name}) -notcontains $_) {$_} } If ($MissingPerms) { Write-Host -Fore Yellow -No "`nThe following shares do not have share permissions that can be read by a script:" $SourceShares | Where {$MissingPerms -contains $_.Name} Write-Host -Fore Yellow "These shares cannot be processed and will be skipped. To fix this, for each share" ` "listed, manually open the Share permissions on the source computer, uncheck and recheck any box, and apply." ` "Rerun this script and it will read the share permissions and work properly. Sadly, I'm not sure why this works.`n" #Update, it works because http://qa.social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/e9e9c619-ef54-4ce6-a520-202c7a3ffabc #and could probably be scripted around. Ah, well. $SourceShares = $SourceShares | Where {$MissingPerms -notcontains $_.Name} } #EndRegion #Region Don't create shares that already exist #Like above, just go with the voodoo... [Array]$DuplicateShares = $SourceShares | %{$_.Name} | %{if (($DestShares | %{$_.Name}) -contains $_) {$_} } If ($DuplicateShares) { Write-Host -Fore Green "`nDuplicate share(s) found on source and destination computers. You need to fix these manually if this is a problem." ForEach ($Duplicate in $DuplicateShares) { Write-Host -Fore Green " Share :" $Duplicate Write-Host -Fore Green " Source path :" ($SourceShares | where {$_.Name -like $Duplicate}).Path Write-Host -Fore Green "Destination Path :" ($DestShares | where {$_.Name -like $Duplicate}).Path } $SourceShares = $SourceShares | where {$DuplicateShares -notcontains $_.Name} } #EndRegion #Main bit happens here ForEach ($SourceShare in $SourceShares) { #Get the perms that match the share... $SourcePerm = $SourcePerms | Where {$_.Name -like $SourceShare.Name} #And grab its SecurityDescriptor to re-use on the destination share $ShareSecurity = $SourcePerm.GetSecurityDescriptor().Descriptor #Then get the share info, like the (modified) path and other stuff $DestPath = $SourceShare.Path -replace "$SourceDrive\\", $DestDrive #The regex needed the extra "\\" in the replacement string and that really bugs me. :-( $ShareName = $SourceShare.Name If ($SourceShare.MaximumAllowed) {$ShareMax = $SourceShare.MaximumAllowed} Else {[Void]$ShareMax = $null} $ShareDescription = $SourceShare.Description #Then create a new share WMI object on the destination computer's runspace... [wmiclass]$NewShare = "\\\\$DestComputer\\root\\cimv2:win32_share" #And create the share there! (Oh, and snag the return value...) Write-Host "Attempting to create the share $ShareName..." $Return = $NewShare.Create($DestPath, $ShareName, 0, $ShareMax, $ShareDescription, $null, $ShareSecurity) #Hint about that line, it is Path, Name, Type (Disk Drive is 0), Max connections, Description, # Password (null because using user-level security), and Access (a Win32_SecurityDescriptor) #Filter the return value into something readable... Switch ($return.returnvalue) { 0 {$ReturnVal = "Success"} 2 {$ReturnVal = "Access Denied"} 8 {$ReturnVal = "Unknown Failure"} 9 {$ReturnVal = "Invalid Name"} 10 {$ReturnVal = "Invalid Level"} 21 {$ReturnVal = "Invalid Parameter"} 22 {$ReturnVal = "Duplicate Share"} 23 {$ReturnVal = "Redirected Path"} 24 {$ReturnVal = "Unknown Device or Directory"} 25 {$ReturnVal = "Net Name Not Found"} } If ($Return.ReturnValue -eq 0) { Write-Host -Fore Green "Success!" } Else { Write-Host -Fore Yellow "Error" $ReturnVal "creating share" $ShareName "on $DestComputer. Good luck." } }
PowerShellCorpus/PoshCode/Write-DataTable_1.ps1
Write-DataTable_1.ps1
####################### <# .SYNOPSIS Writes data only to SQL Server tables. .DESCRIPTION Writes data only to SQL Server tables. However, the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a DataTable instance or read with a IDataReader instance. .INPUTS None You cannot pipe objects to Write-DataTable .OUTPUTS None Produces no output .EXAMPLE $dt = Invoke-Sqlcmd2 -ServerInstance "Z003\\R2" -Database pubs "select * from authors" Write-DataTable -ServerInstance "Z003\\R2" -Database pubscopy -TableName authors -Data $dt This example loads a variable dt of type DataTable from query and write the datatable to another database .NOTES Write-DataTable uses the SqlBulkCopy class see links for additional information on this class. Version History v1.0 - Chad Miller - Initial release v1.1 - Chad Miller - Fixed error message .LINK http://msdn.microsoft.com/en-us/library/30c3y597%28v=VS.90%29.aspx #> function Write-DataTable { [CmdletBinding()] param( [Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance, [Parameter(Position=1, Mandatory=$true)] [string]$Database, [Parameter(Position=2, Mandatory=$true)] [string]$TableName, [Parameter(Position=3, Mandatory=$true)] $Data, [Parameter(Position=4, Mandatory=$false)] [string]$Username, [Parameter(Position=5, Mandatory=$false)] [string]$Password, [Parameter(Position=6, Mandatory=$false)] [Int32]$BatchSize=50000, [Parameter(Position=7, Mandatory=$false)] [Int32]$QueryTimeout=0, [Parameter(Position=8, Mandatory=$false)] [Int32]$ConnectionTimeout=15 ) $conn=new-object System.Data.SqlClient.SQLConnection if ($Username) { $ConnectionString = "Server={0};Database={1};User ID={2};Password={3};Trusted_Connection=False;Connect Timeout={4}" -f $ServerInstance,$Database,$Username,$Password,$ConnectionTimeout } else { $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerInstance,$Database,$ConnectionTimeout } $conn.ConnectionString=$ConnectionString try { $conn.Open() $bulkCopy = new-object ("Data.SqlClient.SqlBulkCopy") $connectionString $bulkCopy.DestinationTableName = $tableName $bulkCopy.BatchSize = $BatchSize $bulkCopy.BulkCopyTimeout = $QueryTimeOut $bulkCopy.WriteToServer($Data) $conn.Close() } catch { $ex = $_.Exception Write-Error "$ex.Message" continue } } #Write-DataTable
PowerShellCorpus/PoshCode/Import-Methods.ps1
Import-Methods.ps1
param([type]$type = $(throw "need a type!")) $type | Get-Member -static | Where {$_.membertype -eq "method" } | % { $func = "function:$($_.name)" if (test-path $func) { remove-item $func } new-item $func -value "[$($type.fullname)].InvokeMember('$($_.name)','Public,Static,InvokeMethod,DeclaredOnly', `$null, `$null, `$args[0])" }
PowerShellCorpus/PoshCode/Update-Ipod.ps1
Update-Ipod.ps1
function Update-Ipod { $start = Get-Date $iTunesCOM = New-Object -comObject iTunes.Application $iTunesCOM.UpdateIPod() $elapsedTime = (Get-Date) - $start Write-Host "Elapsed Time: $elapsedTime" }
PowerShellCorpus/PoshCode/format-custom.ps1
format-custom.ps1
## UI Automation v 1.8 -- REQUIRES the Reflection module (current version: http://poshcode.org/3174 ) ## # WASP 2.0 is getting closer, but this is still just a preview: # -- a lot of the commands have weird names still because they're being generated ignorantly # -- eg: Invoke-Toggle.Toggle and Invoke-Invoke.Invoke # v 1.7 - Fixes using multiple checks like: Select-UIElement Red: Edit # v 1.8 - Fixes .Net version problems: specifying CSharpVersion3 when in PowerShell 2 # IF your PowerShell is running in .Net 4 if($PSVersionTable.CLRVersion -gt "4.0") { $Language = "CSharp" # Version 4 Add-Type -AssemblyName "UIAutomationClient, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Add-Type -AssemblyName "UIAutomationTypes, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" } else { # In PowerShell 2, we need to use the .Net 3 version $Language = "CSharpVersion3" Add-Type -AssemblyName "UIAutomationClient, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Add-Type -AssemblyName "UIAutomationTypes, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" } $SWA = "System.Windows.Automation" # Add-Accelerator InvokePattern "$SWA.InvokePattern" -EA SilentlyContinue # Add-Accelerator ExpandPattern "$SWA.ExpandCollapsePattern" -EA SilentlyContinue # Add-Accelerator WindowPattern "$SWA.WindowPattern" -EA SilentlyContinue # Add-Accelerator TransformPattern "$SWA.TransformPattern" -EA SilentlyContinue # Add-Accelerator ValuePattern "$SWA.ValuePattern" -EA SilentlyContinue # Add-Accelerator TextPattern "$SWA.TextPattern" -EA SilentlyContinue # This is what requires the Reflection module: Add-Accelerator Automation "$SWA.Automation" -EA SilentlyContinue Add-Accelerator AutomationElement "$SWA.AutomationElement" -EA SilentlyContinue Add-Accelerator TextRange "$SWA.Text.TextPatternRange" -EA SilentlyContinue ##### Conditions Add-Accelerator Condition "$SWA.Condition" -EA SilentlyContinue Add-Accelerator AndCondition "$SWA.AndCondition" -EA SilentlyContinue Add-Accelerator OrCondition "$SWA.OrCondition" -EA SilentlyContinue Add-Accelerator NotCondition "$SWA.NotCondition" -EA SilentlyContinue Add-Accelerator PropertyCondition "$SWA.PropertyCondition" -EA SilentlyContinue ##### IDentifiers Add-Accelerator AutoElementIds "$SWA.AutomationElementIdentifiers" -EA SilentlyContinue Add-Accelerator TransformIds "$SWA.TransformPatternIdentifiers" -EA SilentlyContinue ##### Patterns: $patterns = Get-Type -Assembly UIAutomationClient -Base System.Windows.Automation.BasePattern #| Where { $_ -ne [System.Windows.Automation.InvokePattern] } Add-Type -Language $Language -ReferencedAssemblies UIAutomationClient, UIAutomationTypes -TypeDefinition @" using System; using System.ComponentModel; using System.Management.Automation; using System.Reflection; using System.Text.RegularExpressions; using System.Windows.Automation; using System.Runtime.InteropServices; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class StaticFieldAttribute : ArgumentTransformationAttribute { private Type _class; public override string ToString() { return string.Format("[StaticField(OfClass='{0}')]", OfClass.FullName); } public override Object Transform( EngineIntrinsics engineIntrinsics, Object inputData) { if(inputData is string && !string.IsNullOrEmpty(inputData as string)) { System.Reflection.FieldInfo field = _class.GetField(inputData as string, BindingFlags.Static | BindingFlags.Public); if(field != null) { return field.GetValue(null); } } return inputData; } public StaticFieldAttribute( Type ofClass ) { OfClass = ofClass; } public Type OfClass { get { return _class; } set { _class = value; } } } public static class UIAutomationHelper { [DllImport ("user32.dll", CharSet = CharSet.Auto)] static extern IntPtr FindWindow (string lpClassName, string lpWindowName); [DllImport ("user32.dll", CharSet = CharSet.Auto)] static extern bool AttachThreadInput (int idAttach, int idAttachTo, bool fAttach); [DllImport ("user32.dll", CharSet = CharSet.Auto)] static extern int GetWindowThreadProcessId (IntPtr hWnd, IntPtr lpdwProcessId); [DllImport ("user32.dll", CharSet = CharSet.Auto)] static extern IntPtr SetForegroundWindow (IntPtr hWnd); public static AutomationElement RootElement { get { return AutomationElement.RootElement; } } ///<synopsis>Using Win32 to set foreground window because AutomationElement.SetFocus() is unreliable</synopsis> public static bool SetForeground(this AutomationElement element) { if(element == null) { throw new ArgumentNullException("element"); } // Get handle to the element IntPtr other = FindWindow (null, element.Current.Name); // // Get the Process ID for the element we are trying to // // set as the foreground element // int other_id = GetWindowThreadProcessId (other, IntPtr.Zero); // // // Get the Process ID for the current process // int this_id = GetWindowThreadProcessId (Process.GetCurrentProcess().Handle, IntPtr.Zero); // // // Attach the current process's input to that of the // // given element. We have to do this otherwise the // // WM_SETFOCUS message will be ignored by the element. // bool success = AttachThreadInput(this_id, other_id, true); // Make the Win32 call IntPtr previous = SetForegroundWindow(other); return !IntPtr.Zero.Equals(previous); } } "@ ## TODO: Write Get-SupportedPatterns or rather ... ## Get-SupportedFunctions (to return the names of the functions for the supported patterns) ## TODO: Support all the "Properties" too ## TODO: Figure out why Notepad doesn't support SetValue ## TODO: Figure out where the menus support went ForEach($pattern in $patterns){ $pattern | Add-Accelerator $PatternFullName = $pattern.FullName $PatternName = $Pattern.Name -Replace "Pattern","." $newline = "`n`t`t" New-Item "Function:ConvertTo-$($Pattern.Name)" -Value " param( [Parameter(ValueFromPipeline=`$true)][Alias('Element','AutomationElement')][AutomationElement]`$InputObject ) process { trap { if(`$_.Exception.Message -like '*Unsupported Pattern.*') { Write-Error `"Cannot get ```"$($Pattern.Name)```" from that AutomationElement, `$(`$_)` You should try one of: `$(`$InputObject.GetSupportedPatterns()|%{```"'```" + (`$_.ProgrammaticName.Replace(```"PatternIdentifiers.Pattern```",```"```")) + ```"Pattern'```"})`"; continue; } } Write-Output `$InputObject.GetCurrentPattern([$PatternFullName]::Pattern).Current }" $pattern.GetMethods() | Where { $_.DeclaringType -eq $_.ReflectedType -and !$_.IsSpecialName } | ForEach { $FunctionName = "Function:Invoke-$PatternName$($_.Name)" $Position = 1 if (test-path $FunctionName) { remove-item $FunctionName } $Parameters = @("$newline[Parameter(ValueFromPipeline=`$true)]"+ "$newline[Alias('Parent','Element','Root','AutomationElement')]"+ "$newline[AutomationElement]`$InputObject" ) + @( "[Parameter()]$newline[Switch]`$Passthru" ) + @($_.GetParameters() | % { "[Parameter(Position=$($Position; $Position++))]$newline[$($_.ParameterType.FullName)]`$$($_.Name)" }) $Parameters = $Parameters -Join "$newline,$newline" $ParameterValues = '$' + (@($_.GetParameters() | Select-Object -Expand Name ) -Join ', $') $definition = @" param( $Parameters ) process { ## trap { Write-Warning "`$(`$_)"; break } `$pattern = `$InputObject.GetCurrentPattern([$PatternFullName]::Pattern) if(`$pattern) { `$Pattern.$($_.Name)($(if($ParameterValues.Length -gt 1){ $ParameterValues })) } if(`$passthru) { `$InputObject } } "@ trap { Write-Warning $_ Write-Host $definition -fore cyan } New-Item $FunctionName -value $definition } $pattern.GetProperties() | Where { $_.DeclaringType -eq $_.ReflectedType -and $_.Name -notmatch "Cached|Current"} | ForEach { $FunctionName = "Function:Get-$PatternName$($_.Name)".Trim('.') if (test-path $FunctionName) { remove-item $FunctionName } New-Item $FunctionName -value " param( [Parameter(ValueFromPipeline=`$true)] [AutomationElement]`$AutomationElement ) process { trap { Write-Warning `"$PatternFullName `$_`"; continue } `$pattern = `$AutomationElement.GetCurrentPattern([$PatternFullName]::Pattern) if(`$pattern) { `$pattern.'$($_.Name)' } }" } ## So far this seems to be restricted to Text (DocumentRange) elements $pattern.GetFields() | Where { $_.FieldType.Name -like "*TextAttribute"} | ForEach { $FunctionName = "Function:Get-Text$($_.Name -replace 'Attribute')" if (test-path $FunctionName) { remove-item $FunctionName } New-Item $FunctionName -value " param( [Parameter(ValueFromPipeline=`$true)] [AutomationElement]`$AutomationElement ) process { trap { Write-Warning `"$PatternFullName `$_`"; continue } `$AutomationElement.GetAttributeValue([$PatternFullName]::$($_.Name)) }" } $pattern.GetFields() | Where { $_.FieldType -eq [System.Windows.Automation.AutomationEvent] } | ForEach { $Name = $_.Name -replace 'Event$' $FunctionName = "Function:Register-$($PatternName.Trim('.'))$Name" if (test-path $FunctionName) { remove-item $FunctionName } New-Item $FunctionName -value " param( [Parameter(ValueFromPipeline=`$true)] [AutomationElement]`$AutomationElement , [System.Windows.Automation.TreeScope]`$TreeScope = 'Element' , [ScriptBlock]`$EventHandler ) process { trap { Write-Warning `"$PatternFullName `$_`"; continue } [Automation]::AddAutomationEventHandler( [$PatternFullName]::$Name, `$AutomationElement, `$TreeScope, `$EventHandler ) }" } } $FalseCondition = [Condition]::FalseCondition $TrueCondition = [Condition]::TrueCondition Add-Type -AssemblyName System.Windows.Forms Add-Accelerator SendKeys System.Windows.Forms.SendKeys -EA SilentlyContinue $AutomationProperties = [system.windows.automation.automationelement+automationelementinformation].GetProperties() Set-Alias Invoke-UIElement Invoke-Invoke.Invoke function formatter { END { $input | Format-Table @{l="Text";e={$_.Text.SubString(0,25)}}, ClassName, FrameworkId -Auto }} function Get-ClickablePoint { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] [Alias("Parent","Element","Root")] [AutomationElement]$InputObject ) process { $InputObject.GetClickablePoint() } } function Show-Window { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] [Alias("Parent","Element","Root")] [AutomationElement]$InputObject , [Parameter()] [Switch]$Passthru ) process { Set-UIFocus $InputObject if($passthru) { $InputObject } } } function Set-UIFocus { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] [Alias("Parent","Element","Root")] [AutomationElement]$InputObject , [Parameter()] [Switch]$Passthru ) process { try { [UIAutomationHelper]::SetForeground( $InputObject ) $InputObject.SetFocus() } catch { Write-Verbose "SetFocus fail, trying SetForeground" } if($passthru) { $InputObject } } } function Send-UIKeys { [CmdletBinding()] param( [Parameter(Position=0)] [string]$Keys , [Parameter(ValueFromPipeline=$true)] [Alias("Parent","Element","Root")] [AutomationElement]$InputObject , [Parameter()] [Switch]$Passthru , [Parameter()] [Switch]$Async ) process { if(!$InputObject.Current.IsEnabled) { Write-Warning "The Control is not enabled!" } if(!$InputObject.Current.IsKeyboardFocusable) { Write-Warning "The Control is not focusable!" } Set-UIFocus $InputObject if($Async) { [SendKeys]::Send( $Keys ) } else { [SendKeys]::SendWait( $Keys ) } if($passthru) { $InputObject } } } function Set-UIText { [CmdletBinding()] param( [Parameter(Position=0)] [string]$Text , [Parameter(ValueFromPipeline=$true)] [Alias("Parent","Element","Root")] [AutomationElement]$InputObject , [Parameter()] [Switch]$Passthru ) process { if(!$InputObject.Current.IsEnabled) { Write-Warning "The Control is not enabled!" } if(!$InputObject.Current.IsKeyboardFocusable) { Write-Warning "The Control is not focusable!" } $valuePattern = $null if($InputObject.TryGetCurrentPattern([ValuePattern]::Pattern,[ref]$valuePattern)) { Write-Verbose "Set via ValuePattern!" $valuePattern.SetValue( $Text ) } elseif($InputObject.Current.IsKeyboardFocusable) { Set-UIFocus $InputObject [SendKeys]::SendWait("^{HOME}"); [SendKeys]::SendWait("^+{END}"); [SendKeys]::SendWait("{DEL}"); [SendKeys]::SendWait( $Text ) } if($passthru) { $InputObject } } } function Select-UIElement { [CmdletBinding(DefaultParameterSetName="FromParent")] PARAM ( [Parameter(ParameterSetName="FromWindowHandle", Position="0", Mandatory=$true)] [Alias("MainWindowHandle","hWnd","Handle","Wh")] [IntPtr[]]$WindowHandle=[IntPtr]::Zero , [Parameter(ParameterSetName="FromPoint", Position="0", Mandatory=$true)] [System.Windows.Point[]]$Point , [Parameter(ParameterSetName="FromParent", ValueFromPipeline=$true, Position=100)] [System.Windows.Automation.AutomationElement]$Parent = [UIAutomationHelper]::RootElement , [Parameter(ParameterSetName="FromParent", Position="0")] [Alias("WindowName")] [String[]]$Name , [Parameter(ParameterSetName="FromParent", Position="1")] [Alias("Type","Ct")] [System.Windows.Automation.ControlType] [StaticField(([System.Windows.Automation.ControlType]))]$ControlType , [Parameter(ParameterSetName="FromParent")] [Alias("UId")] [String[]]$AutomationId , ## Removed "Id" alias to allow get-process | Select-Window pipeline to find just MainWindowHandle [Parameter(ParameterSetName="FromParent", ValueFromPipelineByPropertyName=$true )] [Alias("Id")] [Int[]]$PID , [Parameter(ParameterSetName="FromParent")] [Alias("Pn")] [String[]]$ProcessName , [Parameter(ParameterSetName="FromParent")] [Alias("Cn")] [String[]]$ClassName , [switch]$Recurse , [switch]$Bare ) process { Write-Debug "Parameters Found" Write-Debug ($PSBoundParameters | Format-Table | Out-String) $search = "Children" if($Recurse) { $search = "Descendants" } $condition = [System.Windows.Automation.Condition]::TrueCondition Write-Verbose $PSCmdlet.ParameterSetName switch -regex ($PSCmdlet.ParameterSetName) { "FromWindowHandle" { Write-Verbose "Finding from Window Handle $HWnd" $Element = $( foreach($hWnd in $WindowHandle) { [System.Windows.Automation.AutomationElement]::FromHandle( $hWnd ) } ) continue } "FromPoint" { Write-Verbose "Finding from Point $Point" $Element = $( foreach($pt in $Point) { [System.Windows.Automation.AutomationElement]::FromPoint( $pt ) } ) continue } "FromParent" { Write-Verbose "Finding from Parent!" ## [System.Windows.Automation.Condition[]]$conditions = [System.Windows.Automation.Condition]::TrueCondition [ScriptBlock[]]$filters = @() if($AutomationId) { [System.Windows.Automation.Condition[]]$current = $( foreach($aid in $AutomationId) { new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::AutomationIdProperty), $aid } ) if($current.Length -gt 1) { [System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current } elseif($current.Length -eq 1) { [System.Windows.Automation.Condition[]]$conditions += $current[0] } } if($PID) { [System.Windows.Automation.Condition[]]$current = $( foreach($p in $PID) { new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ProcessIdProperty), $p } ) if($current.Length -gt 1) { [System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current } elseif($current.Length -eq 1) { [System.Windows.Automation.Condition[]]$conditions += $current[0] } } if($ProcessName) { if($ProcessName -match "\\?|\\*|\\[") { [ScriptBlock[]]$filters += { $(foreach($p in $ProcessName){ (Get-Process -id $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ProcessIdProperty)).ProcessName -like $p }) -contains $true } } else { [System.Windows.Automation.Condition[]]$current = $( foreach($p in Get-Process -Name $ProcessName) { new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ProcessIdProperty), $p.id, "IgnoreCase" } ) if($current.Length -gt 1) { [System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current } elseif($current.Length -eq 1) { [System.Windows.Automation.Condition[]]$conditions += $current[0] } } } if($Name) { Write-Verbose "Name: $Name" if($Name -match "\\?|\\*|\\[") { [ScriptBlock[]]$filters += { $(foreach($n in $Name){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::NameProperty) -like $n }) -contains $true } } else { [System.Windows.Automation.Condition[]]$current = $( foreach($n in $Name){ new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::NameProperty), $n, "IgnoreCase" } ) if($current.Length -gt 1) { [System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current } elseif($current.Length -eq 1) { [System.Windows.Automation.Condition[]]$conditions += $current[0] } } } if($ClassName) { if($ClassName -match "\\?|\\*|\\[") { [ScriptBlock[]]$filters += { $(foreach($c in $ClassName){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ClassNameProperty) -like $c }) -contains $true } } else { [System.Windows.Automation.Condition[]]$current = $( foreach($c in $ClassName){ new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ClassNameProperty), $c, "IgnoreCase" } ) if($current.Length -gt 1) { [System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current } elseif($current.Length -eq 1) { [System.Windows.Automation.Condition[]]$conditions += $current[0] } } } if($ControlType) { if($ControlType -match "\\?|\\*|\\[") { [ScriptBlock[]]$filters += { $(foreach($c in $ControlType){ $_.GetCurrentPropertyValue([System.Windows.Automation.AutomationElement]::ControlTypeProperty) -like $c }) -contains $true } } else { [System.Windows.Automation.Condition[]]$current = $( foreach($c in $ControlType){ new-object System.Windows.Automation.PropertyCondition ([System.Windows.Automation.AutomationElement]::ControlTypeProperty), $c } ) if($current.Length -gt 1) { [System.Windows.Automation.Condition[]]$conditions += New-Object System.Windows.Automation.OrCondition $current } elseif($current.Length -eq 1) { [System.Windows.Automation.Condition[]]$conditions += $current[0] } } } if($conditions.Length -gt 1) { [System.Windows.Automation.Condition]$condition = New-Object System.Windows.Automation.AndCondition $conditions } elseif($conditions) { [System.Windows.Automation.Condition]$condition = $conditions[0] } else { [System.Windows.Automation.Condition]$condition = [System.Windows.Automation.Condition]::TrueCondition } If($VerbosePreference -gt "SilentlyContinue") { function Write-Condition { param([Parameter(ValueFromPipeline=$true)]$condition, $indent = 0) process { Write-Debug ($Condition | fl * | Out-String) if($condition -is [System.Windows.Automation.AndCondition] -or $condition -is [System.Windows.Automation.OrCondition]) { Write-Verbose ((" "*$indent) + $Condition.GetType().Name ) $condition.GetConditions().GetEnumerator() | Write-Condition -Indent ($Indent+4) } elseif($condition -is [System.Windows.Automation.PropertyCondition]) { Write-Verbose ((" "*$indent) + $Condition.Property.ProgrammaticName + " = '" + $Condition.Value + "' (" + $Condition.Flags + ")") } else { Write-Verbose ((" "*$indent) + $Condition.GetType().Name + " where '" + $Condition.Value + "' (" + $Condition.Flags + ")") } } } Write-Verbose "CONDITIONS =============" $global:LastCondition = $condition foreach($c in $condition) { Write-Condition $c } Write-Verbose "============= CONDITIONS" } if($filters.Count -gt 0) { $Element = $Parent.FindAll( $search, $condition ) | Where-Object { $item = $_; foreach($f in $filters) { $item = $item | Where $f }; $item } } else { $Element = $Parent.FindAll( $search, $condition ) } } } Write-Verbose "Element Count: $(@($Element).Count)" if($Element) { foreach($el in $Element) { if($Bare) { Write-Output $el } else { $e = New-Object PSObject $el foreach($prop in $e.GetSupportedProperties() | Sort ProgrammaticName) { ## TODO: make sure all these show up: [System.Windows.Automation.AutomationElement] | gm -sta -type Property $propName = [System.Windows.Automation.Automation]::PropertyName($prop) Add-Member -InputObject $e -Type ScriptProperty -Name $propName -Value ([ScriptBlock]::Create( "`$this.GetCurrentPropertyValue( [System.Windows.Automation.AutomationProperty]::LookupById( $($prop.Id) ))" )) -EA 0 } foreach($patt in $e.GetSupportedPatterns()| Sort ProgrammaticName) { Add-Member -InputObject $e -Type ScriptProperty -Name ($patt.ProgrammaticName.Replace("PatternIdentifiers.Pattern","") + "Pattern") -Value ([ScriptBlock]::Create( "`$this.GetCurrentPattern( [System.Windows.Automation.AutomationPattern]::LookupById( '$($patt.Id)' ) )" )) -EA 0 } Write-Output $e } } } } } # [Cmdlet(VerbsCommon.Add, "UIAHandler")] # public class AddUIAHandlerCommand : PSCmdlet # { # private AutomationElement _parent = AutomationElement.RootElement; # private AutomationEvent _event = WindowPattern.WindowOpenedEvent; # private TreeScope _scope = TreeScope.Children; # # [Parameter(ValueFromPipeline = true)] # [Alias("Parent", "Element", "Root")] # public AutomationElement InputObject { set { _parent = value; } get { return _parent; } } # # [Parameter()] # public AutomationEvent Event { set { _event = value; } get { return _event; } } # # [Parameter()] # public AutomationEventHandler ScriptBlock { set; get; } # # [Parameter()] # public SwitchParameter Passthru { set; get; } # # [Parameter()] # public TreeScope Scope { set { _scope = value; } get { return _scope; } } # # protected override void ProcessRecord() # { # Automation.AddAutomationEventHandler(Event, InputObject, Scope, ScriptBlock); # # if (Passthru.ToBool()) # { # WriteObject(InputObject); # } # # base.ProcessRecord(); # } # } Export-ModuleMember -cmdlet * -Function * -Alias *
PowerShellCorpus/PoshCode/Get-ADMetaData.ps1
Get-ADMetaData.ps1
Param($Domain,$objectDN,$property) $context = new-object System.DirectoryServices.ActiveDirectory.DirectoryContext("Domain",$domain) $dc = [System.DirectoryServices.ActiveDirectory.DomainController]::findOne($context) $meta = $dc.GetReplicationMetadata($objectDN) if($property){$meta | %{$_.$Property}}else{$meta}
PowerShellCorpus/PoshCode/Convert-MacAddress.ps1
Convert-MacAddress.ps1
function Convert-MacAddress { <# .SYNOPSIS Converts a MAC address from one valid format to another. .DESCRIPTION The Convert-MacAddress function takes a valid hex MAC address and converts it to another valid hex format. Valid formats include the colon, dash, and dot delimiters as well as a raw address with no delimiter. .PARAMETER MacAddress Specifies the MAC address to be converted. .PARAMETER Delimiter Specifies a valid MAC address delimiting character. The format specified by the delimiter determines the conversion of the input string. Default value: ':' .EXAMPLE Convert-MacAddress 012345abcdef Converts the MAC address '012345abcdef' to '01:23:45:ab:cd:ef'. .EXAMPLE Convert-MacAddress 0123.45ab.cdef Converts the MAC address '0123.45ab.cdef' to '01:23:45:ab:cd:ef'. .EXAMPLE Convert-MacAddress 01:23:45:ab:cd:ef -Delimiter . Converts the MAC address '01:23:45:ab:cd:ef' to '0123.45ab.cdef'. .EXAMPLE Convert-MacAddress 01:23:45:ab:cd:ef -Delimiter "" Converts the dotted MAC address '01:23:45:ab:cd:ef' to '012345abcdef'. .INPUTS Sysetm.String .OUTPUTS System.String .NOTES Name: Convert-MacAddress Author: Rich Kusak Created: 2011-08-28 LastEdit: 2011-08-29 10:02 Version: 1.0.0.0 .LINK http://en.wikipedia.org/wiki/MAC_address .LINK about_regular_expressions #> [CmdletBinding()] param ( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [ValidateScript({ $patterns = @( '^([0-9a-f]{2}:){5}([0-9a-f]{2})$' '^([0-9a-f]{2}-){5}([0-9a-f]{2})$' '^([0-9a-f]{4}.){2}([0-9a-f]{4})$' '^([0-9a-f]{12})$' ) if ($_ -match ($patterns -join '|')) {$true} else { throw "The argument '$_' does not match a valid MAC address format." } })] [string]$MacAddress, [Parameter(ValueFromPipelineByPropertyName=$true)] [ValidateSet(':', '-', '.', $null)] [string]$Delimiter = ':' ) process { $rawAddress = $MacAddress -replace '\\W' switch ($Delimiter) { {$_ -match ':|-'} { for ($i = 2 ; $i -le 14 ; $i += 3) { $result = $rawAddress = $rawAddress.Insert($i, $_) } break } '.' { for ($i = 4 ; $i -le 9 ; $i += 5) { $result = $rawAddress = $rawAddress.Insert($i, $_) } break } default { $result = $rawAddress } } # switch $result } # process } # function Convert-MacAddress
PowerShellCorpus/PoshCode/Audit iPhone_Palm Users.ps1
Audit iPhone_Palm Users.ps1
#Created by P. Sukus #Modified by D. Dill #Name: mobile users syncing through OWA audit #set the timeframe to audit in days $Daysold = 1 $Date = (get-date).adddays(-$daysold) $servers = "server1", "server2", "server3" foreach ($s in $servers) { Write-host -ForegroundColor Blue "Checking server $s for files from the last $daysold day(s)" $logfiles += gci -path \\\\$s\\c$\\inetpub\\logs\\LogFiles\\W3SVC1 | where {$_.LastWriteTime -gt $date} } Foreach ($l in $logfiles) { Write-host "Processing "$l.fullname Copy-item $l.fullname -Destination $pwd.path $palmusers += gc $l.name | where {$_ -match "DeviceType=Palm"} $iphoneusers += gc $l.name | where {$_ -match "DeviceType=iPhone"} Remove-Item $l.name } $iuser = @() $puser = @() foreach ($l in $iphoneusers | where {$_ -ne $null}) { $u = $l.split(" ")[7] if ($iuser -notcontains $u) { $iuser += "$u" } $u = $null } foreach ($l in $palmusers | where {$_ -ne $null}) { $u = $l.split(" ")[7] if ($puser -notcontains $u) { $puser += "$u" } $u = $null } $body = "<!DOCTYPE html PUBLIC `"-//W3C//DTD XHTML 1.0 Strict//EN`" `"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd`">" $body += "<html xmlns=`"http://www.w3.org/1999/xhtml`">" $body += "<head>" $body += "<title>iPhone Users</title>" $body += "</head><body>" $body += "<table border=1>" $body += "<colgroup>" $body += "<col/>" $body += "</colgroup>" $body += "<tr><td><b>iPhone Users</b></td></tr>" foreach ($y in $iuser) { $body += "<tr><td>$y</td></tr>" } $body += "<tr><td></td></tr>" $body += "<br>" $body += "<tr><td><b>Palm Users</b></td></tr>" foreach ($y in $puser) { $body += "<tr><td>$y</td></tr>" } $body += "</table>" $body += "<br>Audited servers: $servers <br>" $body += "Audited for: DeviceType=Palm and DeviceType=iPhone" $body += "</body></html>" $smtpServer = "yourmailserver" $mailer = new-object Net.Mail.SMTPclient($smtpserver) $From = "dontreplyiamascript@domain.com" $To = "youremail@yourdomain.com" $subject = "Mobile users syncing through OWA in the last $daysold day(s)" $msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body) $msg.IsBodyHTML = $true $mailer.send($msg) clear-variable logfiles clear-variable servers clear-variable daysold
PowerShellCorpus/PoshCode/Create-SCCMCollection.ps1
Create-SCCMCollection.ps1
function Create-SCCMCollection { param($Server = $Env:ComputerName, $Name, $Site, $ParentCollectionID = "COLLROOT") $ColClass = [WMIClass]"\\\\$Server\\Root\\SMS\\Site_$($Site):SMS_Collection" $Col = $ColClass.PSBase.CreateInstance() $Col.Name = $Name $Col.OwnedByThisSite = $True $Col.Comment = "Collection $Name" $Col.psbase $Col.psbase.Put() $NewCollectionID = (Get-WmiObject -computerName $Server -namespace Root\\SMS\\Site_$Site -class SMS_Collection | where {$_.Name -eq $Name}).CollectionID $RelClass = [WMIClass]"\\\\$Server\\Root\\SMS\\Site_$($Site):SMS_CollectToSubCollect" $Rel = $RelClass.PSBase.CreateInstance() $Rel.ParentCollectionID = $ParentCollectionID $Rel.SubCollectionID = $NewCollectionID $Rel.psbase $Rel.psbase.Put() }
PowerShellCorpus/PoshCode/VMWare Quick Migration_1.ps1
VMWare Quick Migration_1.ps1
######################################### #Name: VMWare Quick Migration Function #Author: Justin Grote <jgrote NOSPAMAT enpointe DOT com> #Credit: Inspired by Mike DiPetrillo's Quick Migration Script: http://www.mikedipetrillo.com/mikedvirtualization/2008/10/quick-migration-for-vmware-the-power-of-powershell.html #Source: http://poshcode.org/1246 #Version: 0.1 #Last Revised: 31 July 2009 # #Description: Performs the fucntional equivalent of a Hyper-V Quick Migration by suspending a VM, # moving it to a new host, and resuming it. This does not require vMotion licensing. # it works by providing required VM objects via the pipeline or the second argument, # and specifying the Destination host in the first argument. # The commeand accepts both text strings and VMHost objects for the VMHost Parameter # #Prerequisites: # Powershell v1 # VMWare PowerCLI 4.0 (May work with earlier version but not tested) # #Instructions to Install: Save this script and import into your session with, for example, . C:\\temp\\quickmigrate.ps1 # You can also include it in your PowerCLI profile to have it automatically included. #Command Usage: get-vm MyTestVM | Quick-MigrateVM "MyTestHost2" ######################################### function QuickMigrate-VM { PARAM( $NewVMHost = "" , [VMware.VimAutomation.Client20.VirtualMachineImpl]$VMsToMigrate = $null ) BEGIN { if (!$NewVMHost){ Write-Error "No Destination VMHost Specified. You must specify a host to migrate to. `n Example: Get-VM `"Test`" | QuickMigrate-VM `"Host1`"" break } elseif ($VMsToMigrate) { Write-Output $InputObject | &($MyInvocation.InvocationName) -NewVMHost $newVMHost } else { #If NewVMHost was provided as a String, convert it into a VMHost Object. if ($NewVMHost.GetType().Name -eq "String") { set-variable -name destinationVMHost -value (get-vmhost $NewVMHost) -scope 1 } #Make sure that we have a VMHost object to work with. if (! $destinationVMHost -or (! $destinationVMHost.GetType().Name -eq "VMHostImpl")) { write-error "Destination VM Host was not found or you provided the wrong object type. Please provide a VMHostImpl object or specify the fully qualified name of a VM Host" break } write-host -fore white "===Begin Quick Migration===" } } PROCESS { $step = 0 $skip = $false #In the Event of an error, output the error, and skip the rest of the current item. #This is a workaround for the fact that "continue" doesn't work in a function process loop. trap { write-host -fore yellow "`tSKIPPED: "$_.Exception.Message set-variable -name skip -value ($true) -scope 1 continue } $vmToMigrate = $_ ### Validation Checks if($_ -is [VMware.VimAutomation.Client20.VirtualMachineImpl]) { write-host -fore white "Quick Migrating $($vmToMigrate.Name) to $NewVMHost..." } else { throw "Object Passed was not a Virtual Machine object. Object must be of type VMware.VimAutomation.Client20.VirtualMachineImpl." } # Check for connected devices if (! $skip -and (get-cddrive $vmToMigrate).ConnectionState.Connected -ieq "TRUE") { throw "Connected CD Drive. Please disconnect and try again." } if (! $skip -and (get-floppydrive $vmToMigrate).ConnectionState.Connected -ieq "TRUE") { throw "Connected Floppy Drive. Please disconnect and try again." } # Make sure the current VM Host and the Destination Host are different. $sourceVMHost = get-vmhost -vm $vmToMigrate if (! $skip -and ($sourceVMHost.Name -eq $destinationVMHost.Name)) { throw "Source and Destination Hosts are the same." } ###Validation Complete, begin Migration if (! $skip) { $step++ write-host -fore cyan "`t$($step. Suspending" $vmToMigrate.Name"..." $suspend = Suspend-VM -VM $vmToMigrate -confirm:$false } if (! $skip) { $step++ write-host -fore cyan "`t($step). Moving" $vmToMigrate.Name "to" $destinationVMHost.Name"..." $migrate = Get-VM $vmToMigrate | Move-VM -Destination $destinationVMHost } if (! $skip) { $step++ write-host -fore cyan "`t($step). Resuming" $vmToMigrate.Name"..." $resume = Start-VM -VM $vmToMigrate } write-host -fore green "`tCOMPLETED" } END { write-host -fore white "===END Quick Migration===" } }
PowerShellCorpus/PoshCode/Select-GraphicalFiltered.ps1
Select-GraphicalFiltered.ps1
##############################################################################\n##\n## Select-GraphicalFilteredObject\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\nDisplay a Windows Form to help the user select a list of items piped in.\nAny selected items get passed along the pipeline.\n\n.EXAMPLE\n\ndir | Select-GraphicalFilteredObject\n\n Directory: C:\\\n\nMode LastWriteTime Length Name\n---- ------------- ------ ----\nd---- 10/7/2006 4:30 PM Documents and Settings\nd---- 3/18/2007 7:56 PM Windows\n\n#>\n\nSet-StrictMode -Version Latest\n\n$objectArray = @($input)\n\n## Ensure that they've piped information into the script\nif($objectArray.Count -eq 0)\n{\n Write-Error "This script requires pipeline input."\n return\n}\n\n## Load the Windows Forms assembly\nAdd-Type -Assembly System.Windows.Forms\n\n## Create the main form\n$form = New-Object Windows.Forms.Form\n$form.Size = New-Object Drawing.Size @(600,600)\n\n## Create the listbox to hold the items from the pipeline\n$listbox = New-Object Windows.Forms.CheckedListBox\n$listbox.CheckOnClick = $true\n$listbox.Dock = "Fill"\n$form.Text = "Select the list of objects you wish to pass down the pipeline"\n$listBox.Items.AddRange($objectArray)\n\n## Create the button panel to hold the OK and Cancel buttons\n$buttonPanel = New-Object Windows.Forms.Panel\n$buttonPanel.Size = New-Object Drawing.Size @(600,30)\n$buttonPanel.Dock = "Bottom"\n\n## Create the Cancel button, which will anchor to the bottom right\n$cancelButton = New-Object Windows.Forms.Button\n$cancelButton.Text = "Cancel"\n$cancelButton.DialogResult = "Cancel"\n$cancelButton.Top = $buttonPanel.Height - $cancelButton.Height - 5\n$cancelButton.Left = $buttonPanel.Width - $cancelButton.Width - 10\n$cancelButton.Anchor = "Right"\n\n## Create the OK button, which will anchor to the left of Cancel\n$okButton = New-Object Windows.Forms.Button\n$okButton.Text = "Ok"\n$okButton.DialogResult = "Ok"\n$okButton.Top = $cancelButton.Top\n$okButton.Left = $cancelButton.Left - $okButton.Width - 5\n$okButton.Anchor = "Right"\n\n## Add the buttons to the button panel\n$buttonPanel.Controls.Add($okButton)\n$buttonPanel.Controls.Add($cancelButton)\n\n## Add the button panel and list box to the form, and also set\n## the actions for the buttons\n$form.Controls.Add($listBox)\n$form.Controls.Add($buttonPanel)\n$form.AcceptButton = $okButton\n$form.CancelButton = $cancelButton\n$form.Add_Shown( { $form.Activate() } )\n\n## Show the form, and wait for the response\n$result = $form.ShowDialog()\n\n## If they pressed OK (or Enter,) go through all the\n## checked items and send the corresponding object down the pipeline\nif($result -eq "OK")\n{\n foreach($index in $listBox.CheckedIndices)\n {\n $objectArray[$index]\n }\n}
PowerShellCorpus/PoshCode/The Old Dogs ExcelCookBo.ps1
The Old Dogs ExcelCookBo.ps1
# # DATE : 6/21/2010 # COMMENT: This is an updated Version of my Cook Book from Augest of 2008 # # #=============================================================== # All errors and mistakes are my own. Thanks to all who have helped # along the way. # # One thing I would add is that if you are using anything but a US locale version of Excel some of # these scripts won't work, especially adding and saving workbooks. # # Here is a function that helps with this problem: # # From: http://blogs.msdn.com/powershell/archive/2006/04/25/583235.aspx # # ====================================================== Function Using-Culture ( [System.Globalization.CultureInfo]$culture, [ScriptBlock]$script) { $OldCulture = [System.Threading.Thread]::CurrentThread.CurrentCulture trap { [System.Threading.Thread]::CurrentThread.CurrentCulture = $OldCulture } [System.Threading.Thread]::CurrentThread.CurrentCulture = $culture $ExecutionContext.InvokeCommand.InvokeScript($script) [System.Threading.Thread]::CurrentThread.CurrentCulture = $OldCulture } # End Function Using-Culture en-us { $xl= New-Object -COM Excel.Application $xl.Visible = $true $xl.DisplayAlerts = $False $xl.Workbooks.Open("C:\\Scripts\\PowerShell\\test.xls") #$xl.Quit() #[System.Runtime.InteropServices.Marshal]::ReleaseComObject($xl) } # ====================================================== #_______________________________________________________________________ # How do I create an Excel object? $xl = new-object -comobject excel.application # ________________________________________________________________________ #How do I make Excel visible? $xl.Visible = $true # ________________________________________________________________________ # # How do I add a workbook? $wb = $xl.Workbooks.Add() # By default this adds three empty worksheets # ________________________________________________________________________ # # # How do I open an existing Workbook ? # $xl = New-Object -comobject Excel.Application $xl.Visible = $true $xl.DisplayAlerts = $False $wb = $xl.Workbooks.Open("C:\\Scripts\\powershell\\test.xls") # ________________________________________________________________________ # # #How do I add a worksheet to an existing workbook? $xl = new-object -comobject excel.application $xl.Visible = $true $xl.DisplayAlerts = $False $wb = $xl.Workbooks.Open("C:\\Scripts\\test.xls") $ws = $xl.Sheets.Add() # # ________________________________________________________________________ # # How do I activate a a worksheet? # Create Excel.Application object $xl = New-Object -comobject Excel.Application # Show Excel $xl.visible = $true $xl.DisplayAlerts = $False # Open a workbook $wb = $xl.workbooks.open("C:\\Scripts\\PowerShell\\test.xls") # Get sheets $ws1 = $wb.worksheets | where {$_.name -eq "sheet1"} #<------- Selects sheet 1 $ws2 = $wb.worksheets | where {$_.name -eq "sheet2"} #<------- Selects sheet 2 $ws3 = $wb.worksheets | where {$_.name -eq "sheet3"} #<------- Selects sheet 3 # Activate sheet 1 $ws1.activate() Start-Sleep 1 # Activate sheet 2 $ws2.activate() Start-Sleep 1 # Activate sheet 3 $ws3.activate() # _________________________________________________________________ # How do I change the value of a cell? $ws1.cells.Item(1,1).Value() = "x" # ________________________________________________________________________ # # How do I Find a specified cell? # $xlCellTypeLastCell = 11 $used = $ws.usedRange $lastCell = $used.SpecialCells($xlCellTypeLastCell) $row = $lastCell.row for ($i = 1; $i -le $row; $i++) { If ($ws1.cells.Item(1,2).Value() = "y") { # "do something" } } # And another way: # $mainRng.Select() $objSearch = $mainRng.Find("Grand Total") $objSearch.Select() # ________________________________________________________________________ # # How do I find and delete empty rows in Excel? # Function DeleteEmptyRows { $used = $ws.usedRange $lastCell = $used.SpecialCells($xlCellTypeLastCell) $row = $lastCell.row for ($i = 1; $i -le $row; $i++) { If ($ws.Cells.Item($i, 1).Value() -eq $Null) { $Range = $ws.Cells.Item($i, 1).EntireRow $Range.Delete() } } } $xlCellTypeLastCell = 11 $xl = New-Object -comobject excel.application $xl.Visible = $true $xl.DisplayAlerts = $False $wb = $xl.Workbooks.Open("C:\\Scripts\\Test.xls") # <-- Change as required! $ws = $wb.worksheets | where {$_.name -eq "Servers" } # <-- Or Sheet1 or Whatever DeleteEmptyRows # <—Call Function # ________________________________________________________________________ # # # How do I set a range with variables? $ws1.range("a${Sumrow}:b$Sumrow").font.bold = "true" # separate the : from the $ with {} on the left hand side # ________________________________________________________________________ # # How do I Set range to a value? $range4=$ws.range("3:3") $range4.cells="Row 3" # ________________________________________________________________________ # # How do I list the workbook's name? $wb.Name # ______________________________________________________________ # # How do I find the last used row number? $xlCellTypeLastCell = 11 $used = $ws.usedRange $lastCell = $used.SpecialCells($xlCellTypeLastCell) $lastrow = $lastCell.row # Or $mainRng = $ws1.UsedRange.Cells $RowCount = $mainRng.Rows.Count $R = $RowCount # ________________________________________________________________________ # # How do I find the last used column number? #This works for columns and rows $mainRng = $ws1.UsedRange.Cells $ColCount = $mainRng.Columns.Count $RowCount = $mainRng.Rows.Count $xRow = $RowCount $xCol = $ColCount # ________________________________________________________________________ # # How do I loop through a range of cells by row number? $xl = New-Object -comobject excel.application $xl.Visible = $true $xl.DisplayAlerts = $False $wb = $xl.Workbooks.Add() $ws = $wb.Worksheets.Item(1) for ($row = 1; $row -lt 11; $row++) { $ws.Cells.Item($row,1) = $row } # ________________________________________________________________________ # # How do I get today's date and format it as a string? $m = (get-date).month $d = (get-date).day $y = [string] (get-date).year $y = $y.substring($y.length - 2, 2) $f = "C:\\Scripts\\" + $m + "-" + $d + "-" + $y + ".xlsx" $wb.SaveAs($F) # C:\\Scripts\\6-18-10.xlsx # # ________________________________________________________________________ # # How do I write a list of files to Excel? $xl = new-object -comobject excel.application $xl.Visible = $true $xl.DisplayAlerts = $False $wb = $xl.Workbooks.Add() $ws = $wb.Worksheets.Item(1) $row = 1 $s = dir Z:\\MBSA_Report\\ScanData\\*.mbsa $s | foreach -process { $ws.Cells.Item($row,1) = $_; $row++ } # # this takes a long file name with spaces and splits it up, # It then picks out the 3rd element and writes it out. # The 3rd element is [2] because the first one is [0]. # sample file name: AD-Dom - 3IDCT001 (5-21-2010 4-28 PM).mbsa $xl = new-object -comobject excel.application $xl.Visible = $true $xl.DisplayAlerts = $False $wb = $xl.Workbooks.Add() $ws = $wb.Worksheets.Item(1) $row = 1 dir Z:\\MBSA_Report\\ScanData\\*.mbsa | ForEach-Object { $FileName = $_.name $N = $FileName.tostring() $E = $N.split() $F = $E[2] $ws.Cells.Item($row,1) = $F; $row++ } #Or for the whole file name $ws.Cells.Item($row,1) = $_; # ________________________________________________________________________ # # How do I write a list of processes to Excel? function Release-Ref ($ref) { #[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl) [System.Runtime.InteropServices.Marshal]::ReleaseComObject($ref) [System.GC]::Collect() [System.GC]::WaitForPendingFinalizers() } # ----------------------------------------------------- $xl = New-Object -comobject Excel.Application $xl.Visible = $true $xl.DisplayAlerts = $False $wb = $xl.Workbooks.Add() $ws = $wb.Worksheets.Item(1) $range = $ws.Cells.Item(1,1) $row = 1 $s = Get-Process | Select-Object name $s | foreach -process { $range = $ws.Cells.Item($row,1); $range.Value = $_.Name; $row++ } $wb.SaveAs("C:\\Scripts\\Get_Process.xls") Release-Ref $range Release-Ref $ws Release-Ref $wb $xl.Quit() Release-Ref $xl #***For a remote machine try $strComputer = (remote machine name) $P = gwmi win32_process -comp $strComputer # ________________________________________________________________________ # # How do I write the command history to Excel? function Release-Ref ($ref) { #[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl) [System.Runtime.InteropServices.Marshal]::ReleaseComObject($ref) [System.GC]::Collect() [System.GC]::WaitForPendingFinalizers() } $xl = New-Object -comobject Excel.Application $xl.Visible = $true $xl.DisplayAlerts = $False $wb = $excel.Workbooks.Add() $ws = $workbook.Worksheets.Item(1) $range = $worksheet.Cells.Item(1,1) $row = 1 $s = Get-History | Select-Object CommandLine $s | foreach -process { ` $range = $worksheet.Cells.Item($row,1); ` $range.Value = $_.CommandLine; ` $row++ } $xl.DisplayAlerts = $False $wb.SaveAs("C:\\Scripts\\Get_CommandLine.xls") Release-Ref $range Release-Ref $ws Release-Ref $wb $xl.Quit() Release-Ref $xl # ________________________________________________________________________ # # How Can I Convert a Tilde-Delimited File to Microsoft Excel Format? # Script name: ConvertTilde.ps1 # Created on: 2007-01-06 # Author: Kent Finkle # Purpose: How Can I Convert a Tilde-Delimited File to Microsoft Excel Format? $s = gc C:\\Scripts\\Test.txt $s = $s -replace("~","`t") $s | sc C:\\Scripts\\Test.txt $xl = new-object -comobject excel.application $xl.Visible = $true $xl.DisplayAlerts = $False $wb = $xl.Workbooks.Open("C:\\Scripts\\Test.txt") # ________________________________________________________________________ # # How can I add Validation to an Excel Worksheet? # # $comments = @' # Script name: Add-Validation.ps1 # Created on: Wednesday, September 19, 2007 # Author: Kent Finkle # Purpose: How can I use Windows Powershell to Add Validation to an # Excel Worksheet? # '@ #----------------------------------------------------- function Release-Ref ($ref) { ([System.Runtime.InteropServices.Marshal]::ReleaseComObject( [System.__ComObject]$ref) -gt 0) [System.GC]::Collect() [System.GC]::WaitForPendingFinalizers() } # End Function $xlValidateWholeNumber = 1 $xlValidAlertStop = 1 $xlBetween = 1 $xl = new-object -comobject excel.application $xl.Visible = $true $xl.DisplayAlerts = $False $wb = $xl.Workbooks.Add() $ws = $wb.Worksheets.Item(1) $r = $ws.Range("e5") $r.Validation.Add($xlValidateWholeNumber,$xlValidAlertStop, $xlBetween, "5", "10") $r.Validation.InputTitle = "Integers" $r.Validation.ErrorTitle = "Integers" $r.Validation.InputMessage = "Enter an integer from five to ten" $r.Validation.ErrorMessage = "You must enter a number from five to ten" $a = Release-Ref $r $a = Release-Ref $ws $a = Release-Ref $wb $a = Release-Ref $xl # ________________________________________________________________________ # # How do I add a Chart to an Excel Worksheet? $xrow = 1 $yrow = 8 $xl = New-Object -c excel.application $xl.visible = $true $xl.DisplayAlerts = $False $wb = $xl.workbooks.add() $ws = $wb.sheets.item(1) 1..8 | % { $ws.Cells.Item(1,$_) = $_ } 1..8 | % { $ws.Cells.Item(2,$_) = 9-$_ } $range = $ws.range("a${xrow}:h$yrow") $range.activate # create and assign the chart to a variable $ch = $xl.charts.add() # This will open a new sheet $ch = $ws.shapes.addChart().chart # This will put the Chart in the selected WorkSheet $ch.chartType = 58 $ch.setSourceData($range) $ch.export("C:\\test.jpg") $xl.quit() # excel has 48 chart styles, you can cycle through all 1..48 | % {$ch.chartStyle = $_; $xl.speech.speak("Style $_"); sleep 1} $ch.chartStyle = 27 # <-- use the one you like # And another Chart sample: Function XLcharts { $xlColumnClustered = 51 $xlColumns = 2 $xlLocationAsObject = 2 $xlCategory = 1 $xlPrimary = 1 $xlValue = 2 $xlRows = 1 $xlLocationAsNewSheet = 1 $xlRight = -4152 $xlBuiltIn =21 $xlCategory = 1 $xl = New-Object -comobject excel.application $xl.Visible = $true $xl.DisplayAlerts = $False $wb = $xl.Workbooks.Add() $ws = $wb.Worksheets.Item(1) $ws = $wb.Sheets.Add() $ws.Cells.Item(1, 2) = "Jan" $ws.Cells.Item(1, 3) = "Feb" $ws.Cells.Item(1, 4) = "Mar" $ws.Cells.Item(2, 1) = "John" $ws.Cells.Item(3, 1) = "Mae" $ws.Cells.Item(4, 1) = "Al" $ws.Cells.Item(2, 2) = 100 $ws.Cells.Item(2, 3) = 200 $ws.Cells.Item(2, 4) = 300 $ws.Cells.Item(3, 2) = 400 $ws.Cells.Item(3, 3) = 500 $ws.Cells.Item(3, 4) = 600 $ws.Cells.Item(4, 2) = 900 $ws.Cells.Item(4, 3) = 800 $ws.Cells.Item(4, 4) = 700 $Range = $ws.range("A1:D4") $ch = $xl.charts.add() $ch.chartType = 58 $ch.name ="Bar Chart" $ch.Tab.ColorIndex = 3 $ch.setSourceData($Range) [void]$ch.Location, $xlLocationAsObject, "Bar Chart" $ch.HasTitle = $False $ch.Axes($xlCategory, $xlPrimary).HasTitle = $False $ch.Axes($xlValue, $xlPrimary).HasTitle = $False $ch2 = $xl.Charts.Add() | Out-Null $ch2.HasTitle = $true $ch2.ChartTitle.Text = "Sales" $ch2.Axes($xlCategory).HasTitle = $true $ch2.Axes($xlCategory).AxisTitle.Text = "1st Quarter" $ch2.Axes($xlValue).HasTitle = $True $ch2.Axes($xlValue).AxisTitle.Text = "Dollars" [void]$ch2.Axes($xlValue).Select $ch2.name ="Columns with Depth" $ch2.Tab.ColorIndex = 5 [void]$ws.cells.entireColumn.Autofit() } # End Function # ________________________________________________________________________ # # How do I Move and resize a chart in an Excel Worksheet? $xl = New-Object -comobject Excel.Application # Opens Excel and 3 empty Worksheets # Show Excel $xl.visible = $true $xl.DisplayAlerts = $False # Open a workbook $wb = $xl.workbooks.add() #Create Worksheets $ws = $wb.Worksheets.Item(1) 1..8 | % { $ws.Cells.Item(1,$_) = $_ } # adds some data 1..8 | % { $ws.Cells.Item(2,$_) = 9-$_ } # adds some data # < ----- This is the good part -------------------------------------------------------> $range = $ws.range("a${xrow}:h$yrow") # sets the Data range we want to chart # create and assign the chart to a variable #$ch = $xl.charts.add() # This will open a new sheet $ch = $ws.shapes.addChart().chart # This will put the Chart in the selected WorkSheet $ch.chartType = 58 # Select Chart Type $ch.setSourceData($range) # Create the Chart $RngToCover = $ws.Range("D5:J19") # This is where we want the chart $ChtOb = $ch.Parent # This selects the curent Chart $ChtOb.Top = $RngToCover.Top # This moves it up to row 5 $ChtOb.Left = $RngToCover.Left # and to column D $ChtOb.Height = $RngToCover.Height # resize This sets the height of your chart to Rows 5 - 19 $ChtOb.Width = $RngToCover.Width # resize This sets the width to Columns D - J # ________________________________________________________________________ # # How do I sort a column in an Excel Worksheet? $xlSummaryAbove = 0 $xlSortValues = $xlPinYin = 1 $xlAscending = 1 $xlDescending = 2 $xlYes = 1 $xl = New-Object -comobject excel.application $xl.Visible = $true $xl.DisplayAlerts = $False $wb = $xl.Workbooks.Add() $ws = $wb.Worksheets.Item(1) # one-column sort $r = $ws.UsedRange $r2 = $ws.Range("B2") # Sorts on Column B and leaves Header alone $a = $r.sort($r2, $xlAscending) # two-column sort $r = $ws.UsedRange $r2 = $ws.Range("B2") $r3 = $ws.Range("E2") $a = $r.sort($r2, $xlAscending, $r3,$null, $xlAscending) # three-column sort $r = $ws1.UsedRange $r2 = $ws1.Range("B2") $r3 = $ws1.Range("E2") $r4 = $ws1.Range("C2") $a = $r.Sort($r2,$xlDescending,$r3,$null,$xlAscending, ` $r4,$xlAscending,$xlYes) #----------------------------------------------------- # How do I use xlConstants? $xlAutomatic=-4105 $xlBottom = -4107 $xlCenter = -4108 $xlContext = -5002 $xlContinuous=1 $xlDiagonalDown=5 $xlDiagonalUp=6 $xlEdgeBottom=9 $xlEdgeLeft=7 $xlEdgeRight=10 $xlEdgeTop=8 $xlInsideHorizontal=12 $xlInsideVertical=11 $xlNone=-4142 $xlThin=2 $xl = new-object -com excel.application $xl.visible=$true $wb = $xl.workbooks.open("d:\\book1.xls") $ws = $wb.worksheets | where {$_.name -eq "sheet1"} $selection = $ws.range("A1:D1") $selection.select() $selection.HorizontalAlignment = $xlCenter $selection.VerticalAlignment = $xlBottom $selection.WrapText = $false $selection.Orientation = 0 $selection.AddIndent = $false $selection.IndentLevel = 0 $selection.ShrinkToFit = $false $selection.ReadingOrder = $xlContext $selection.MergeCells = $false $selection.Borders.Item($xlInsideHorizontal).Weight = $xlThin ## You can also try this to center a column: [reflection.assembly]::loadWithPartialname("Microsoft.Office.Interop.Excel") | Out-Null $xlConstants = "microsoft.office.interop.excel.Constants" -as [type] $ws.columns.item("F").HorizontalAlignment = $xlConstants::xlCenter $ws.columns.item("K").HorizontalAlignment = $xlConstants::xlCenter # The next four lines of code create four enumeration types. # Enumeration types are used to tell Excel which values are allowed # for specific types of options. As an example, xlLineStyle enumeration # is used to determine the kind of line to draw: double, dashed, and so on. # These enumeration values are documented on MSDN. # To make the code easier to read, we create shortcut aliases for each # of the four enumeration types we will be using. # Essentially, we're casting a string that represents the name of the # enumeration to a [type]. This technique is actually a pretty cool trick: # http://technet.microsoft.com/en-us/magazine/2009.01.heyscriptingguy.aspx $lineStyle = "microsoft.office.interop.excel.xlLineStyle" -as [type] $colorIndex = "microsoft.office.interop.excel.xlColorIndex" -as [type] $borderWeight = "microsoft.office.interop.excel.xlBorderWeight" -as [type] $chartType = "microsoft.office.interop.excel.xlChartType" -as [type] For($b = 1 ; $b -le 2 ; $b++) { $ws.cells.item(1,$b).font.bold = $true $ws.cells.item(1,$b).borders.LineStyle = $lineStyle::xlDashDot $ws.cells.item(1,$b).borders.ColorIndex = $colorIndex::xlColorIndexAutomatic $ws.cells.item(1,$b).borders.weight = $borderWeight::xlMedium } $workbook.ActiveChart.chartType = $chartType::xl3DPieExploded $workbook.ActiveChart.SetSourceData($range) # ________________________________________________________________________ # # How do I use autofill in excel? $xlFillWeekdays = 6 $xl = New-Object -com excel.application $xl.visible=$true $wb = $xl.workbooks.add() $ws = $wb.worksheets | where {$_.name -eq "sheet1"} $range1= $ws.range("A1") $range1.value() = (get-date).toString("d") $range2 = $ws.range("A1:A25") $range1.AutoFill($range2,$xlFillWeekdays) $range1.entireColumn.Autofit() # Another example: $xlCellTypeLastCell = 11 $xl = new-object -com excel.application $xl.visible=$true $wb = $xl.workbooks.add() $ws = $wb.worksheets | where {$_.name -eq "sheet1"} $used = $ws.usedRange $lastCell = $used.SpecialCells($xlCellTypeLastCell) $lastrow = $lastCell.row $ws.Cells.Item(2,1).FormulaR1C1 = "=CONCATENATE(C[+1],C[+2],C[+3])" $range1= $ws.range("A2") $r = $ws.Range("A2:A$lastrow") $range1.AutoFill($r) | Out-Null [void]$range1.entireColumn.Autofit() $wb.close() $xl.quit() # ________________________________________________________________________ # # How to get a range and format it in excel? # get-excelrange.ps1 # opens an existing workbook in Excel 2007, using PowerShell # and turns a range bold # Thomas Lee - t...@psp.co.uk # Create base object $xl = new-object -comobject Excel.Application # make Excel visible $xl.visible = $true $xl.DisplayAlerts = $False # open a workbook $wb = $xl.workbooks.open("C:\\Scripts\\powershell\\test.xls") # Get sheet1 $ws = $wb.worksheets | where {$_.name -eq "sheet1"} # Make A1-B1 bold $range = $ws.range("A1:B1") $range.font.bold = "true" # Make A2-B2 italic $range2 = $ws.range("A2:B2") $range2.font.italic = "true" # Set range to a value $range4=$ws.range("3:3") $range4.cells="Row 3" # Set range to a Font size $range3=$ws.range("A2:B2") $Range3.font.size=24 # now format an entire row $range4=$ws.range("3:3") $range4.font.italic="$true" $range4.font.bold=$true $range4.font.size=10 $range4.font.name="Comic Sans MS" # now format a Range of cells $ws.Range("D1:F5").NumberFormat = "#,##0.00" # ______________________________________________________________________ # # How do I add a comment to a cell in Excel? $xl = New-Object -com Excel.Application $xl.visible = $true $xl.DisplayAlerts = $False $wb = $xl.Workbooks.Add() $ws = $wb.Worksheets.Item(1) $ws.Cells.Item(1,1) = “A value in cell A1.” [void]$ws.Range("A1").AddComment() [void]$ws.Range("A1").comment.Visible = $False [void]$ws.Range("A1").Comment.text("OldDog: `r this is a comment") [void]$ws.Range("A2").Select # The 'r adds a line feed after the comment's author. This is required! # ________________________________________________________________________ # # How do I copy and Paste in Excel (special)? $xl = New-Object -comobject Excel.Application # Show Excel $xl.visible = $true $xl.DisplayAlerts = $False $wb = $xl.Workbooks.Add() $ws = $wb.Worksheets.Item(1) $xlPasteValues = -4163 # Values only, not formulas $xlCellTypeLastCell = 11 # to find last used cell $used = $ws.usedRange $lastCell = $used.SpecialCells($xlCellTypeLastCell) $row = $lastCell.row $range = $ws.UsedRange [void]$ws.Range("A8:F$row").Copy() [void]$ws.Range("A8").PasteSpecial(-4163) # __________________________________________________________________________ # # How do I Add Worksheets, name them and save as today's date? #****************************************** # get today's date and format it as a string. $m = (get-date).month $d = (get-date).day $y = [string] (get-date).year $y = $y.substring($y.length - 2, 2) $f = "C:\\Scripts\\" + $m + "-" + $d + "-" + $y + ".xlsx" # Create Excel.Application object $xl = New-Object -comobject Excel.Application # Show Excel $xl.visible = $true $xl.DisplayAlerts = $False $wb = $xl.Workbooks.Add() $ws = $wb.Worksheets.Item(1) # this will add 9 sheets to the default 3 for a total of 12 sheets for ($i = 0; $i -le 8; $i++) { $ws = $wb.Sheets.Add() } # Now we name our new sheets $xl.Worksheets.item(1).name = "Jan" $xl.Worksheets.item(2).name = "Feb" $xl.Worksheets.item(3).name = "Mar" $xl.Worksheets.item(4).name = "Apr" $xl.Worksheets.item(5).name = "May" $xl.Worksheets.item(6).name = "June" $xl.Worksheets.item(7).name = "July" $xl.Worksheets.item(8).name = "Aug" $xl.Worksheets.item(9).name = "Sept" $xl.Worksheets.item(10).name = "Oct" $xl.Worksheets.item(11).name = "Nov" $xl.Worksheets.item(12).name = "Dec" # and here we save it $wb.SaveAs($F) #******************************************* # How do I find duplicate entries in Excel? # This Function creates a spreadsheet with some # duplicate names and then highlights the Dups in Blue Function XLFindDups { $xlExpression = 2 $xlPasteFormats = -4122 $xlNone = -4142 $xlToRight = -4161 $xlToLeft = -4159 $xlDown = -4121 $xlShiftToRight = -4161 $xlFillDefault = 0 $xlSummaryAbove = 0 $xlSortValues = $xlPinYin = 1 $xlAscending = 1 $xlDescending = 2 $xlYes = 1 $xlTopToBottom = 1 $xlPasteValues = -4163 # Values only, not formulas $xlCellTypeLastCell = 11 # to find last used cell $xl = new-object -comobject excel.application $xl.Visible = $true $xl.DisplayAlerts = $False $wb = $xl.Workbooks.Add() $ws = $wb.Worksheets.Item(1) $ws.name = "Concatenate" $ws.Tab.ColorIndex = 4 $ws.Cells.Item(1,1) = "FirstName" $ws.Cells.Item(1,2) = "MI" $ws.Cells.Item(1,3) = "LastName" $ws.Cells.Item(2,1) = "Jesse" $ws.Cells.Item(2,2) = "L" $ws.Cells.Item(2,3) = "Roberts" $ws.Cells.Item(3,1) = "Mary" $ws.Cells.Item(3,2) = "S" $ws.Cells.Item(3,3) = "Talbert" $ws.Cells.Item(4,1) = "Ben" $ws.Cells.Item(4,2) = "N" $ws.Cells.Item(4,3) = "Smith" $ws.Cells.Item(5,1) = "Ed" $ws.Cells.Item(5,2) = "S" $ws.Cells.Item(5,3) = "Turner" $ws.Cells.Item(6,1) = "Mary" $ws.Cells.Item(6,2) = "S" $ws.Cells.Item(6,3) = "Talbert" $ws.Cells.Item(7,1) = "Jesse" $ws.Cells.Item(7,2) = "L" $ws.Cells.Item(7,3) = "Roberts" $ws.Cells.Item(8,1) = "Joe" $ws.Cells.Item(8,2) = "L" $ws.Cells.Item(8,3) = "Smith" $ws.Cells.Item(9,1) = "Ben" $ws.Cells.Item(9,2) = "A" $ws.Cells.Item(9,3) = "Smith" $used = $ws.usedRange $lastCell = $used.SpecialCells($xlCellTypeLastCell) $lastrow = $lastCell.row $range4=$ws.range("2:2") $range4.Select() | Out-Null $xl.ActiveWindow.FreezePanes = $true $ws.cells.EntireColumn.AutoFit() | Out-Null $range1 = $ws.Range("A1").EntireColumn $range1.Insert($xlShiftToRight) | Out-Null $range1.Select() | Out-Null $ws.Cells.Item(1, 1) = "Concat" $r2 = $ws.Range("A2") $r2.Select() | Out-Null $ws.Cells.Item(2,1).FormulaR1C1 = "=CONCATENATE(C[+1],C[+2],C[+3])" $range1= $ws.range("A2") $r = $ws.Range("A2:A$lastrow") $range1.AutoFill($r) | Out-Null $range.EntireColumn.AutoFit() | Out-Null $select = $range1.SpecialCells(11).Select() | Out-Null $ws.Range("A2:A$lastrow").Copy()| Out-Null $ws1 = $wb.Sheets.Add() $ws1.name = "FindDups" $ws1 = $wb.worksheets | where {$_.name -eq "FindDups"} $ws1.Tab.ColorIndex = 5 $ws1.Select() | Out-Null [void]$ws1.Range("A2").PasteSpecial(-4163) $ws1.Range("A1").Select() | Out-Null $objRange = $xl.Range("B1").EntireColumn [void] $objRange.Insert($xlShiftToRight) $ws1.Cells.Item(1, 2) = "Dups" $range = $ws.range("B1:D$lastrow") $range.copy() | Out-Null [void]$ws1.Range("C1").PasteSpecial(-4163) $ws1.Cells.Item(2,2).FormulaR1C1 = "=COUNTIF(C[-1],RC[-1])>1" $range1= $ws1.range("B2") $range2 = $ws1.range("B2:B$lastrow") [void]$range1.AutoFill($range2,$xlFillDefault) # Thnaks to Wolfgang Kais for the following: $xl.Range("B2").Select() | Out-Null $xl.Selection.FormatConditions.Delete() $xl.Selection.FormatConditions.Add(2, 0, "=COUNTIF(A:A,A2)>1") | Out-Null $xl.Selection.FormatConditions.Item(1).Interior.ColorIndex = 8 $xl.Selection.Copy() | Out-Null $xl.Columns.Item("B:B").Select() | Out-Null $xl.Range("B2").Activate() | Out-Null $xl.Selection.PasteSpecial(-4122, -4142, $false, $false) | Out-Null $r = $ws1.UsedRange $r2 = $ws1.Range("B2") $r3 = $ws1.Range("E2") $r4 = $ws1.Range("C2") $a = $r.Sort($r2,$xlDescending,$r3,$null,$xlAscending, ` $r4,$xlAscending,$xlYes) $ws1.Application.ActiveWindow.FreezePanes=$true [void]$ws1.cells.entireColumn.Autofit() $s = $xl.Range("A1").EntireColumn $s.Hidden = $true $ws1.Range("B2").Select() | Out-Null } # ============================================================================================== # How do I show all 57 Colors in Excel? $xl = new-object -comobject excel.application $xl.Visible = $true $xl.DisplayAlerts = $False $wb = $xl.Workbooks.Add() $ws = $wb.Worksheets.Item(1) $row = 1 $i = 1 For($i = 1; $i -lt 57; $i++){ $ws.Cells.Item($row, 1) = "'$'ws.Cells.Item($row, 2).Font.ColorIndex = " + $row $ws.Cells.Item($row, 2).Font.ColorIndex = $row $ws.Cells.Item($row, 2) = "test " + $row $row++ } [void]$ws.cells.entireColumn.Autofit() # ============================================================================================== # How do I insert a Hyperlink into an Excel Spreadsheet? function Release-Ref ($info) { foreach ( $p in $args ) { ([System.Runtime.InteropServices.Marshal]::ReleaseComObject( [System.__ComObject]$p) -gt 0) [System.GC]::Collect() [System.GC]::WaitForPendingFinalizers() } } # End Function Function XLHyperlinks { $link = "http://www.microsoft.com/technet/scriptcenter" $xl = new-object -comobject excel.application $xl.Visible = $true $wb = $xl.Workbooks.Add() $ws = $wb.Worksheets.Item(1) $ws.Cells.Item(1, 1).Value() = "Script Center" $r = $ws.Range("A1") $objLink = $ws.Hyperlinks.Add($r, $link) $a = Release-Ref $r $ws $wb $xl } # End Function # ________________________________________________________________________ # # How do I sum a column in Excel? # Function xlSum { $range = $ws1.usedRange $row = $range.rows.count # Takes you to the last used row $Sumrow = $row + 1 $r = $ws1.Range("A2:A$row") # select the column to Add up $functions = $xl.WorkSheetfunction $ws.cells.item($Sumrow,1) = $functions.sum($r) # this uses the Excel sum function $rangeString = $r.address().tostring() -replace "\\$",'' # convert formula to Text $ws.cells.item($Sumrow,2) = "Sum $rangeString" # Print formula in Cell B & last row + 1 $ws1.cells.item($Sumrow,1).Select() $ws1.range("a${Sumrow}:b$Sumrow").font.bold = "true" # seperate the : from the $ with {} $ws1.range("a${Sumrow}:b$Sumrow").font.size=12 # Changes the font size to 12 points [void]$range.entireColumn.Autofit() } # End Function # ________________________________________________________________________ # # How do I SubTotal a column in an Excel Worksheet? # # # Sample Spreadsheet # mon tue wed # eggs 1 1 1 # ham 5 5 5 # spam 1 4 7 # spam 2 5 8 # spam 3 6 9 # # Code to sub total $xlSum = -4157 $range = $xl.range("A1:D6") $range.Subtotal(1,-4157,(2,3,4),$true,$False,$true) # Selection.Subtotal GroupBy:=1, Function:=xlSum, TotalList:=Array(4), _ # Replace:=True, PageBreaks:=False, SummaryBelowData:=True # ________________________________________________________________________ # # In this example Subtotals are sums grouped by each change in field 1 "Salesperson" # with Subtotals of field 2 "Amount". # Details of Subtotal function # SubTotal GroupBy =2, Function =XLSum, TotalList =Array(1), # Replace =False, PageBreaks =False, SummaryBelowData =$True Function XLSubtotals { $xlExpression = 2 $xlPasteFormats = -4122 $xlNone = -4142 $xlToRight = -4161 $xlToLeft = -4159 $xlDown = -4121 $xlShiftToRight = -4161 $xlFillDefault = 0 $xlSummaryAbove = 0 $xlSortValues = $xlPinYin = 1 $xlAscending = 1 $xlDescending = 2 $xlYes = 1 $xlTopToBottom = 1 $xlPasteValues = -4163 # Values only, not formulas $xlCellTypeLastCell = 11 # to find last used cell $xlSum = -4157 $xl = New-Object -comobject Excel.Application $xl.Visible = $true $xl.DisplayAlerts = $False $wb = $xl.Workbooks.Add() $ws = $wb.Worksheets.Item(1) $ws = $wb.Sheets.Add() $xl.Worksheets.item(1).name = "Detail" $xl.Worksheets.item(2).name = "ShowLevels1" $xl.Worksheets.item(3).name = "ShowLevels2" $xl.Worksheets.item(4).name = "ShowLevels3" $ws1 = $wb.worksheets | where {$_.name -eq "Detail"} $ws2 = $wb.worksheets | where {$_.name -eq "ShowLevels1"} #<------- Selects sheet 6 $ws3 = $wb.worksheets | where {$_.name -eq "ShowLevels2"} #<------- Selects sheet 5 $ws4 = $wb.worksheets | where {$_.name -eq "ShowLevels3"} #<------- Selects sheet 4 $ws1.Tab.ColorIndex = 8 $ws1.Tab.ColorIndex = 5 $ws2.Tab.ColorIndex = 6 $ws3.Tab.ColorIndex = 7 $ws1.Cells.Item(1,2) = "Amount" $ws1.Cells.Item(1,1) = "SalesPerson" $ws1.Cells.Item(2,2) = 7324 $ws1.Cells.Item(2,1) = "Jack" $ws1.Cells.Item(3,2) = 294 $ws1.Cells.Item(3,1) = "Elizabeth" $ws1.Cells.Item(4,2) = 41472 $ws1.Cells.Item(4,1) = "Renee" $ws1.Cells.Item(5,2) = 25406 $ws1.Cells.Item(5,1) = "Elizabeth" $ws1.Cells.Item(6,2) = 20480 $ws1.Cells.Item(6,1) = "Jack" $ws1.Cells.Item(7,2) = 11294 $ws1.Cells.Item(7,1)= "Renee" $ws1.Cells.Item(8,2) = 982040 $ws1.Cells.Item(8,1) = "Elizabeth" $ws1.Cells.Item(9,2) = 2622368 $ws1.Cells.Item(9,1) = "Jack" $ws1.Cells.Item(10,2) = 884144 $ws1.Cells.Item(10,1) = "Renee" $ws1.Range("B2").Select() | Out-Null $ws1.Application.ActiveWindow.FreezePanes=$true [void]$ws1.cells.entireColumn.Autofit() $ws1.Range("A1").Select() | Out-Null $r = $ws.Range("A2:A10") $r2 = $ws.Range("A2") # Sorts on Column B and leaves Header alone $a = $r.sort($r2, $xlAscending) $range1 = $ws1.Range("A1:B1").EntireColumn $Range1.Select() | Out-Null #$ws.Range.SpecialCells(11)).Select() $Range1.Copy() $ws1.Range("A1").Select() | Out-Null $ws2.Select() | Out-Null [void]$ws2.Range("A1").PasteSpecial(-4163) $ws3.Select() | Out-Null [void]$ws3.Range("A1").PasteSpecial(-4163) $ws4.Select() | Out-Null [void]$ws4.Range("A1").PasteSpecial(-4163) $ws2.Select() | Out-Null $range = $xl.range("A1:B10") $range.Subtotal(1,-4157,(2),$true,$False,$true) $ws2.Outline.ShowLevels(1) [void]$ws1.cells.entireColumn.Autofit() $ws2.Range("A1").Select() | Out-Null $ws3.Select() | Out-Null $range = $xl.range("A1:B10") $range.Subtotal(1,-4157,(2),$true,$False,$true) $ws3.Outline.ShowLevels(2) [void]$ws1.cells.entireColumn.Autofit() $ws3.Range("A1").Select() | Out-Null $ws4.Select() | Out-Null $range = $xl.range("A1:B10") $range.Subtotal(1,-4157,(2),$true,$False,$true) $ws4.Outline.ShowLevels(3) $ws1.Select() | Out-Null [void]$ws1.cells.entireColumn.Autofit() $ws1.Range("A1").Select() | Out-Null } # End Function #--------------------------------------------------- # #How do I set up Auto Filters in Excel? #This function sets up a spreadsheet and then sets Auto filters Function XLAutoFilter { $xlTop10Items = 3 $xlTop10Percent = 5 $xlBottom10Percent = 6 $xlBottom10Items = 4 $xlAnd = 1 $xlOr = 2 $xlNormal = -4143 $xlPasteValues = -4163 # Values only, not formulas $xlCellTypeLastCell = 11 # to find last used cell $xl = New-Object -comobject Excel.Application $xl.Visible = $true $xl.DisplayAlerts = $False $wb = $xl.Workbooks.Add() $ws = $wb.Worksheets.Item(1) $ws = $wb.Sheets.Add() $ws = $wb.Sheets.Add() $ws1 = $wb.worksheets | where {$_.name -eq "Sheet1"} #<------- Selects sheet 1 $ws2 = $wb.worksheets | where {$_.name -eq "Sheet2"} #<------- Selects sheet 2 $ws3 = $wb.worksheets | where {$_.name -eq "Sheet3"} #<------- Selects sheet 3 $ws4 = $wb.worksheets | where {$_.name -eq "Sheet4"} #<------- Selects sheet 4 $ws5 = $wb.worksheets | where {$_.name -eq "Sheet5"} #<------- Selects sheet 5 $ws1.Tab.ColorIndex = 8 $ws2.Tab.ColorIndex = 7 $ws3.Tab.ColorIndex = 6 $ws4.Tab.ColorIndex = 5 $ws5.Tab.ColorIndex = 4 $ws1.name = "Detail" $ws2.name = "JackOnly" $ws3.name = "Top2" $ws4.name = "LowestHighest" $ws5.name = "Top25Percent" $ws1.cells.Item(1,1) = "Amount" $ws1.cells.Item(1,2) = "SalesPerson" $ws1.cells.Item(2,1) = 1 $ws1.cells.Item(2,2) = "Jack" $ws1.cells.Item(3,1) = 2 $ws1.cells.Item(3,2) = "Elizabeth" $ws1.cells.Item(4,1) = 3 $ws1.cells.Item(4,2) = "Renee" $ws1.cells.Item(5,1) = 4 $ws1.cells.Item(5,2) = "Elizabeth" $ws1.cells.Item(6,1) = 5 $ws1.cells.Item(6,2) = "Jack" $ws1.cells.Item(7,1) = 6 $ws1.cells.Item(7,2) = "Renee" $ws1.cells.Item(8,1) = 7 $ws1.cells.Item(8,2) = "Elizabeth" $ws1.cells.Item(9,1) = 8 $ws1.cells.Item(9,2) = "Jack" $ws1.cells.Item(10,1) = 9 $ws1.cells.Item(10,2) = "Renee" $ws1.cells.Item(11,1) = 10 $ws1.cells.Item(11,2) = "Jack" $ws1.cells.Item(12,1) = 11 $ws1.cells.Item(12,2) = "Jack" $ws1.cells.Item(13,1) = 12 $ws1.cells.Item(13,2) = "Elizabeth" $ws1.cells.Item(14,1) = 13 $ws1.cells.Item(14,2) = "Renee" $ws1.cells.Item(15,1) = 14 $ws1.cells.Item(15,2) = "Elizabeth" $ws1.cells.Item(16,1) = 15 $ws1.cells.Item(16,2) = "Jack" $ws1.cells.Item(17,1) = 16 $ws1.cells.Item(17,2) = "Renee" $ws1.cells.Item(18,1) = 17 $ws1.cells.Item(18,2) = "Elizabeth" $ws1.cells.Item(19,1) = 18 $ws1.cells.Item(19,2) = "Jack" $ws1.cells.Item(20,1) = 19 $ws1.cells.Item(20,2) = "Renee" $ws1.cells.Item(21,1) = 20 $ws1.cells.Item(21,2) = "Renee" $used = $ws1.usedRange $lastCell = $used.SpecialCells($xlCellTypeLastCell) $lastrow = $lastCell.row $r = $ws1.Range("A1:B$lastrow") $ws1.Range("A1:B$lastrow").Copy() $ws2.Select() | Out-Null [void]$ws2.Range("A1").PasteSpecial(-4163) $ws3.Select() | Out-Null [void]$ws3.Range("A1").PasteSpecial(-4163) $ws4.Select() | Out-Null [void]$ws4.Range("A1").PasteSpecial(-4163) $ws5.Select() | Out-Null [void]$ws5.Range("A1").PasteSpecial(-4163) # $ws5.Range("A1").Select() # AutoFilter structure - Field, Criteria, Operator #$xl.Selection.AutoFilter 1, "10", $xlTop10Items #top 10 $xl.Range("A1").Select() | Out-Null $xl.Selection.AutoFilter(1, "2", $xlTop10Items) #top 2 #$xl.Selection.AutoFilter 1, "10", $xlTop10Percent #top 10 percent #$xl.Selection.AutoFilter 1, "25", $$xlTop10Percent #top 25 percent #$xl.Selection.AutoFilter 1, "5", $xlBottom10Items #Lowest 5 Items #$xl.Selection.AutoFilter 1, "10", $$xlBottom10Percent #Bottom 10 percent #$xl.Selection.AutoFilter 1, ">15" #size greater 15 #$xl.Selection.AutoFilter 1, ">19",XLOr , "<2" #Lowest and Highest #$xl.Selection.AutoFilter 2, "Jack" #Jack items only $ws5.cells.Item.EntireColumn.AutoFit $ws2.Select() $ws2.Range("A1").Select() # AutoFilter structure - Field, Criteria, Operator #$xl.Selection.AutoFilter 1, "10", $xlTop10Items #top 10 #$xl.Selection.AutoFilter 1, "2", $xlTop10Items #top 2 #$xl.Selection.AutoFilter 1, "10", $xlTop10Percent #top 10 percent #$xl.Selection.AutoFilter 1, "25", $xlTop10Percent #top 25 percent #$xl.Selection.AutoFilter 1, "5", $xlBottom10Items #Lowest 5 Items #$xl.Selection.AutoFilter 1, "10", $xlBottom10Percent #Bottom 10 percent #$xl.Selection.AutoFilter 1, ">15" #size greater 15 #$xl.Selection.AutoFilter 1, ">19",XLOr , "<2" #Lowest and Highest $xl.Selection.AutoFilter(2, "Jack") #Jack items only $ws2.cells.Item.EntireColumn.AutoFit $ws4.Select() $ws4.Range("A1").Select() # AutoFilter structure - Field, Criteria, Operator #$xl.Selection.AutoFilter 1, "10", $xlTop10Items #top 10 #$xl.Selection.AutoFilter 1, "2", $xlTop10Items #top 2 #$xl.Selection.AutoFilter 1, "10", $xlTop10Percent #top 10 percent #$xl.Selection.AutoFilter 1, "25", $xlTop10Percent #top 25 percent #$xl.Selection.AutoFilter 1, "5", $xlBottom10Items #Lowest 5 Items #$xl.Selection.AutoFilter 1, "10", $xlBottom10Percent #Bottom 10 percent #$xl.Selection.AutoFilter 1, ">15" #size greater 15 $xl.Selection.AutoFilter(1, ">19",$xlOr , "<2") #Lowest and Highest #$xl.Selection.AutoFilter 2, "Jack" #Jack items only $ws4.cells.Item.EntireColumn.AutoFit # "Top25Percent" $ws5.Select() $ws5.Range("A1").Select() # AutoFilter structure - Field, Criteria, Operator #$xl.Selection.AutoFilter 1, "10", $xlTop10Items #top 10 #$xl.Selection.AutoFilter 1, "2", $xlTop10Items #top 2 #$xl.Selection.AutoFilter 1, "10", $xlTop10Percent #top 10 percent $xl.Range("A1").Select() | Out-Null $xl.Selection.AutoFilter(1,"25",$xlTop10Percent) #top 25 percent #$xl.Selection.AutoFilter 1, "5", $xlBottom10Items #Lowest 5 Items #$xl.Selection.AutoFilter 1, "10", $xlBottom10Percent #Bottom 10 percent #$xl.Selection.AutoFilter 1, ">15" #size greater 15 #$xl.Selection.AutoFilter 1, ">19",XLOr , "<2" #Lowest and Highest #$xl.Selection.AutoFilter 2, "Jack" #Jack items only $ws5.cells.Item.EntireColumn.AutoFit } # End Function #--------------------------------------------------- # # # How do I set up a complex Formula in Excel? # Here is one that creates a Complex Formula and executes it Function XLFormula1 { $xl = New-Object -comobject excel.application $xl.Visible = $true $xl.DisplayAlerts = $False $wb = $xl.Workbooks.Add() $ws = $wb.Worksheets.Item(1) $ws.name = "ComplexFormula" $ws.Tab.ColorIndex = 9 $row = 2 $lastrow = $row $Col = 3 $Off = $Col - 1 $ws.Cells.Item(1, 1) = "FileName" $ws.Cells.Item(1, 2) = "Folder" $ws.Cells.Item(1, 3) = "FullPath" $ws.Cells.Item(2, 3) = "c:\\Folder1\\FunctionFolder1\\FunctionFolder2\\File1.txt" $ws.Cells.Item(3, 3) = "c:\\Folder1\\FunctionFolder1\\FunctionFolder2\\FunctionFolder3\\File2.txt" $ws.Cells.Item(4, 3) = "c:\\Folder1\\FunctionFolder1\\FunctionFolder2\\FunctionFolder3\\FunctionFolder4\\File3.txt" $lastrow = 4 #Filename $Range1 = $ws.Range("A2") $ws.Cells.Item(2,1).FormulaR1C1 = "=MID(C[2],FIND(CHAR(127),Substitute(C[2],""\\"",CHAR(127),LEN(C[2])-LEN(Substitute(C[2],""\\"",""""))))+1,254)" # Note I used 254 as a hardcoded length. No filename should ever reach this length. However…. # You could get the length programatically with the following # "=MID(C[2],FIND(CHAR(127),FunctionSubsTITUTE(C[2],""\\"",CHAR(127),LEN(C[2])-LEN(Substitute(C[2],""\\"",""""))))+1,LEN(C[2])-(FIND(CHAR(127),Substitute(C[2],""\\"",CHAR(127),LEN(C[2])-LEN(Substitute(C[2],""\\"",""""))))))" $range2 = $ws.Range("A2:A$lastrow") [void]$range1.AutoFill($range2,$xlFillDefault) #Folder $lastrow = 4 $ws.Range("B2").Select() | Out-Null $ws.Cells.Item(2,2).FormulaR1C1 = "=LEFT(C[1],FIND(CHAR(127),Substitute(C[1],""\\"",CHAR(127),LEN(C[1])-LEN(Substitute(C[1],""\\"",""""))))-1)" $R1 = $ws.Range("B2") $r2 = $ws.Range("B2:B$lastrow") [void]$R1.AutoFill($R2,$xlFillDefault) $ws.Cells.Item.EntireColumn.AutoFit $ws.Range("A2").Select() | Out-Null } # End Function #--------------------------------------------------- # # How do I set up a Pivot Table in Excel? # I was working with MBSA reports here. # Function Pivot { $xlPivotTableVersion12 = 3 $xlPivotTableVersion10 = 1 $xlCount = -4112 $xlDescending = 2 $xlDatabase = 1 $xlHidden = 0 $xlRowField = 1 $xlColumnField = 2 $xlPageField = 3 $xlDataField = 4 # R1C1 means Row 1 Column 1 or "A1" # R65536C5 means Row 65536 Column E or "E65536" $PivotTable = $wb.PivotCaches().Create($xlDatabase,"Report!R1C1:R65536C5",$xlPivotTableVersion10) $PivotTable.CreatePivotTable("Pivot!R1C1") | Out-Null [void]$ws3.Select() $ws3.Cells.Item(1,1).Select() $wb.ShowPivotTableFieldList = $true $PivotFields = $ws3.PivotTables("PivotTable1").PivotFields("Server") # Worksheet Name is Server $PivotFields.Orientation = $xlRowField $PivotFields.Position = 1 $PivotFields = $ws3.PivotTables("PivotTable1").PivotFields("KBID") # Column Header is KBID $PivotFields.Orientation = $xlColumnField $PivotFields.Position = 1 $PivotFields = $ws3.PivotTables("PivotTable1").PivotFields("KBID") # The data is in this column $PivotFields.Orientation=$xlDataField $mainRng = $ws3.UsedRange.Cells $RowCount = $mainRng.Rows.Count $R = $RowCount $R = $R - 1 $mainRng.Select() $objSearch = $mainRng.Find("Grand Total") $objSearch.Select() $C = $objSearch.Column Write-Host $C $R # this is just so I can see what's happining $xlSummaryAbove = 0 $xlSortValues = $xlPinYin = 1 $xlAscending = 1 $xlDescending = 2 $range1 = $ws3.UsedRange $range2 = $ws3.Cells.Item(3, $C) # one-column sort --> works [void]$range2.sort($range2, $xlDescending) # puts the highest numbers at the top } # End Function
PowerShellCorpus/PoshCode/Move-ISETAB.ps1
Move-ISETAB.ps1
function Move-ISETab { param( $offset = 1 ) $curFile = $psISE.CurrentFile if ($curFile.IsSaved) { $curTabFiles = $psISE.CurrentPowerShellTab.Files $tabs = $psISE.PowerShellTabs $Fileindex = $null foreach ($i in 0..($curTabFiles.count -1)) { if ($curTabFiles[$i].displayname -eq $curFile.DisplayName) { $Fileindex = $i break } } $file = $curFile.FullPath $Tabindex = $null foreach ($i in 0..($tabs.count -1)) { if ($tabs[$i].displayname -eq $psISE.CurrentPowerShellTab.DisplayName) { $Tabindex = $i break } } $newTabIndex = ($TabIndex + $offset) % $tabs.count $curTabFiles.removeAt($Fileindex) $newtab = $tabs[$newTabIndex] $psise.PowerShellTabs.SetSelectedPowerShellTab($newTab) $newObj = $tabs[$newTabIndex].files.add($file) } else { "You must save the file bevore moving it." } } $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("Move-ToNextPowerShellTab",{Move-ISETab}, "Ctrl+Alt+Shift+RIGHT") | out-null $psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("Move-ToLastPowerShellTab",{Move-ISETab -1}, "Ctrl+Alt+Shift+LEFT") | out-null
PowerShellCorpus/PoshCode/PinnedApplications.psm1.ps1
PinnedApplications.psm1.ps1
# ============================================================================================== # # # NAME: PinnedApplications.psm1 # # AUTHOR: Jan Egil Ring, Crayon # DATE : 26.02.2010 # # COMMENT: Module with the ability to pin and unpin programs from the taskbar and the Start-menu in Windows 7 and Windows Server 2008 R2 # # This module are based on the Add-PinnedApplication script created by Ragnar Harper and Kristian Svantorp: # http://blogs.technet.com/kristian/archive/2009/04/24/nytt-script-pin-to-taskbar.aspx # http://blog.crayon.no/blogs/ragnar/archive/2009/04/17/pin-applications-to-windows-7-taskbar.aspx # # For more information, see the following blog post: # http://blog.crayon.no/blogs/janegil/archive/2010/02/26/pin-and-unpin-applications-from-the-taskbar-and-start-menu-using-windows-powershell.aspx # # Locale supported: Norwegian, English # # # ============================================================================================== function Set-PinnedApplication { <# .SYNOPSIS This function are used to pin and unpin programs from the taskbar and Start-menu in Windows 7 and Windows Server 2008 R2 .DESCRIPTION The function have to parameteres which are mandatory: Action: PinToTaskbar, PinToStartMenu, UnPinFromTaskbar, UnPinFromStartMenu FilePath: The path to the program to perform the action on .EXAMPLE Set-PinnedApplication -Action PinToTaskbar -FilePath "C:\\WINDOWS\\system32\\notepad.exe" .EXAMPLE Set-PinnedApplication -Action UnPinFromTaskbar -FilePath "C:\\WINDOWS\\system32\\notepad.exe" .EXAMPLE Set-PinnedApplication -Action PinToStartMenu -FilePath "C:\\WINDOWS\\system32\\notepad.exe" .EXAMPLE Set-PinnedApplication -Action UnPinFromStartMenu -FilePath "C:\\WINDOWS\\system32\\notepad.exe" #> [CmdletBinding()] param( [Parameter(Mandatory=$true)][string]$Action, [string]$FilePath ) switch ($Action) { "PinToTaskbar" { $PinVerbTask = @{} $PinverbTask['En-US'] ="Pin to Taskbar" $PinverbTask['Nb-No'] ="Fest til oppgavelinjen" ##get culture $culture = $Host.CurrentUICulture.Name #Check to see if path actually exists if(-not (test-path $FilePath)) { write-warning "`nPath does not exist.`n $FilePath `nExiting... `n"; return } #this should only be done if a full path is given $path= split-path $FilePath #Create shell envir $shell=new-object -com "Shell.Application" $folder=$shell.Namespace($path) $item = $folder.Parsename((split-path $FilePath -leaf)) $verbs=$item.Verbs() foreach($v in $verbs){if($v.Name.Replace("&","") -match $PinVerbTask[$culture]){$v.DoIt()}} } "PinToStartMenu" { $PinVerbStart = @{} $PinverbStart['En-US'] ="Pin to Start Menu" $PinverbStart['Nb-No'] ="Fest til Start-menyen" ##get culture $culture = $Host.CurrentUICulture.Name #Check to see if path actually exists if(-not (test-path $FilePath)) { write-warning "`nPath does not exist.`n $FilePath `nExiting... `n"; return } #this should only be done if a full path is given $path= split-path $FilePath #Create shell envir $shell=new-object -com "Shell.Application" $folder=$shell.Namespace($path) $item = $folder.Parsename((split-path $FilePath -leaf)) $verbs=$item.Verbs() foreach($v in $verbs){if($v.Name.Replace("&","") -match $PinVerbStart[$culture]){$v.DoIt()}} } "UnPinFromTaskbar" { $UnPinVerbTask = @{} $UnPinverbTask['En-US'] ="Unpin from Taskbar" $UnPinverbTask['Nb-No'] ="Lĝsne programmet fra oppgavelinjen" ##get culture $culture = $Host.CurrentUICulture.Name #Check to see if path actually exists if(-not (test-path $FilePath)) { write-warning "`nPath does not exist.`n $FilePath `nExiting... `n"; return } #this should only be done if a full path is given $path= split-path $FilePath #Create shell envir $shell=new-object -com "Shell.Application" $folder=$shell.Namespace($path) $item = $folder.Parsename((split-path $FilePath -leaf)) $verbs=$item.Verbs() foreach($v in $verbs){if($v.Name.Replace("&","") -match $UnPinVerbTask[$culture]){$v.DoIt()}} } "UnPinFromStartMenu" { $UnPinVerbStart = @{} $UnPinverbStart['En-US'] ="Unpin from Start Menu" $UnPinverbStart['Nb-No'] ="Lĝsne fra Start-menyen" ##get culture $culture = $Host.CurrentUICulture.Name #Check to see if path actually exists if(-not (test-path $FilePath)) { write-warning "`nPath does not exist.`n $FilePath `nExiting... `n"; return } #this should only be done if a full path is given $path= split-path $FilePath #Create shell envir $shell=new-object -com "Shell.Application" $folder=$shell.Namespace($path) $item = $folder.Parsename((split-path $FilePath -leaf)) $verbs=$item.Verbs() foreach($v in $verbs){if($v.Name.Replace("&","") -match $UnPinVerbStart[$culture]){$v.DoIt()}} } default {Write-Warning "Invalid action specified. Valid actions are: PinToTaskbar, PinToStartMenu, UnPinFromTaskbar, UnPinFromStartMenu"} } }
PowerShellCorpus/PoshCode/WhoAmI_2.ps1
WhoAmI_2.ps1
function whoami { [System.Security.Principal.WindowsIdentity]::GetCurrent().Name }
PowerShellCorpus/PoshCode/Set-IPAddress.ps1
Set-IPAddress.ps1
function Set-IPAddress { param( [switch]$help, [string]$networkinterface =$(read-host "Enter the name of the NIC (ie Local Area Connection)"), [string]$ip = $(read-host "Enter an IP Address (ie 10.10.10.10)"), [string]$mask = $(read-host "Enter the subnet mask (ie 255.255.255.0)"), [string]$gateway = $(read-host "Enter the current name of the NIC you want to rename"), [string]$dns1 = $(read-host "Enter the first DNS Server (ie 10.2.0.28)"), [string]$dns2, [string]$registerDns = "TRUE" ) $usage = "A help message goes here with an example of how to use the function `n" $usage += "You can add more to the help message here, but be sure to use the backtick n at the end" if ($help) {Write-Host $usage} #Start writing code here $dns = $dns1 if($dns2){$dns ="$dns1,$dns2"} $index = (gwmi Win32_NetworkAdapter | where {$_.netconnectionid -eq $networkinterface}).InterfaceIndex $NetInterface = Get-WmiObject Win32_NetworkAdapterConfiguration | where {$_.InterfaceIndex -eq $index} $NetInterface.EnableStatic($ip, $subnetmask) $NetInterface.SetGateways($gateway) $NetInterface.SetDNSServerSearchOrder($dns) $NetInterface.SetDynamicDNSRegistration($registerDns) }
PowerShellCorpus/PoshCode/USB Script backup_1.ps1
USB Script backup_1.ps1
<# .SYNOPSIS Backup-ToUSB.ps1 (Version 2.0, 6 Jan 2012) The author may be contacted via www.SeaStarDevelopment.Bravehost.com .DESCRIPTION This script will backup recently changed *.ps1,*.psm1,*.psd1 files from any selected folder (default is $pwd) to any number of inserted USB devices, on which an archive folder 'PSarchive' will be created if it does not already exist. As a USB hard disk is a Type 3 device (similar to the system disk), use the -Unit D switch (drive letter 'D' for example) to distinguish such a unit and add it to the list of selected devices. .EXAMPLE .\\Backup-ToUsb -v This will just archive ps1 files and show the name of each file processed. .EXAMPLE function backup { Invoke-Expression ".\\Backup-ToUsb.ps1 -Unit D $args" } Add this function to $profile and it will add the USB Hard Disk 'D' as the standard backup device. .EXAMPLE .\\Backup-ToUSB.ps1 -type psm1 -v Select *.psm1 files to be archived. 'Verbose' will display the name of each file processed. Use '-type ps*' to archive all types in one operation. #> param ([String]$types = 'ps1', [String]$unit = $null, [String]$folder = $pwd, [Switch]$debug, [Switch]$verbose) if ($verbose) { $verbosePreference = 'Continue' } if ($debug) { $debugPreference = 'Continue' } $drive = '-<BLANK>-' if ($types -notmatch '^ps1|psd1|psm1|ps\\*$') { #Adjust to suit. Write-Warning "Invalid filetype ($types): ps1, psm1, psd1 only." exit 1 } if (!(Test-path $folder -pathType Container )) { [System.Media.SystemSounds]::Hand.Play() Write-Warning "$folder is not a directory - resubmit." exit 3 } $filter = 'DriveType = 2' if ($unit -match '^[d-z]$') { #Allow any single letter drive unit here. $filter = "DriveType = 2 OR (DriveType = 3 AND DeviceID = '" + "$unit" + ":')" } function copyFile ([string]$value) { Copy-Item -Path $value -Destination $newFolder -Force Write-Verbose "--> Archiving file: $value" $SCRIPT:files++ } Get-WMIObject Win32_LogicalDisk -filter $filter | Select-Object VolumeName, DriveType, FreeSpace, DeviceID | Where-Object {$_.VolumeName -ne $null} | foreach { $vol = $_.VolumeName $drive = $_.DeviceID + '\\' $type = $_.DriveType [int]$free = $_.FreeSpace / 1MB Write-Verbose "Scanning USB devices - Drive = [$drive] Name = $vol, Free = $free Mb" if (!(Test-Path $drive)) { Write-Warning "Error on drive $drive - restart." [System.Media.SystemSounds]::Hand.Play() exit 4 } [int]$SCRIPT:files = 0 #Reset counter for each new drive. $newFolder = $drive + "PSarchive" #Check if folder exists. if (!(Test-Path $newFolder)) { New-Item -path ($drive) -name PSarchive -type directory | Out-Null } (Get-ChildItem $folder -filter "*.$types") | foreach { $checkFile = $drive + 'PSArchive\\' + $_ if (Test-path $checkFile) { $lwtHdd = $_.LastWriteTime #HDD time last written. $lwtUsb = (Get-Item $checkFile).LastWriteTime #USB time. if ($lwtHdd -gt $lwtUsb) { Write-Debug "(HDD) $lwtHdd (USB) $LwtUsb $_" copyFile $_ } } else { #New file, so archive it anyway. copyFile $_ } } $print = "Backup to USB drive [{0}] (Volume = {2}) completed; {1} files copied." -f $drive, $files, $vol Write-Host "--> $print" } if ($drive -eq '-<BLANK>-') { [System.Media.SystemSounds]::Asterisk.Play() Write-Warning "No USB drive detected - Insert a device and resubmit." }
PowerShellCorpus/PoshCode/45f1a2cb-dfc8-4b9f-8b09-a17bceef8edc.ps1
45f1a2cb-dfc8-4b9f-8b09-a17bceef8edc.ps1
Function Get-ServiceDACL { [CmdletBinding()] param( [Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true)] [String]$Servicename, [Parameter(Mandatory=$false,Position=1)] [String]$Computername= ".") $sddl = Invoke-expression -Command "c:\\Windows\\System32\\sc.exe \\\\$Computername sdshow $Servicename" # $Servicename $sddl $parts = $sddl -split(":") #$parts.Length $i = 0 Write-Host "Getting Service DACL for $ServiceName on $Computername" While ($i -lt $parts.length) { $part = $parts[$i] Switch ($part) { "D" { $i++; Parse-DACL $parts[$i] } } $i++ } $sddl = "" } Function Parse-DACL { Param([String]$SDDLIN) [Array]$sddls = ($SDDLIN).split('(') Foreach ($SDDLI in $sddls) { #($SDDLI).replace(')';'') #$SDDLI $tokens = (($SDDLI).replace(')','')).split(";") If ($tokens[5]) { If ($tokens[5].length -gt 3) { [wmi]$obj = 'Win32_SID.SID="{0}"' -f $($tokens[5]) $encoded = [System.Convert]::ToBase64String($obj.BinaryRepresentation) $obj | Add-Member -MemberType NoteProperty -Name base64_sid -Value $encoded Write-Host "$($obj.ReferencedDomainName)\\$($obj.AccountName)" -ForegroundColor red } Else { Write-Host "$($Trustees.get_item($tokens[5]))" -ForegroundColor red } " " + $AceType.get_item($tokens[0]) [regex]::split($tokens[2], '(.{2})') | % {Write-host " $($PermissionType.get_item($_)) `n" -NoNewline} } } } $AceType = @{"A" = "ACCESS ALLOWED"; "D" = "ACCESS DENIED"; "OA" = "OBJECT ACCESS ALLOWED: ONLY APPLIES TO A SUBSET OF THE OBJECT(S)."; "OD" = "OBJECT ACCESS DENIED: ONLY APPLIES TO A SUBSET OF THE OBJECT(S)."; "AU" = "SYSTEM AUDIT"; "AL" = "SYSTEM ALARM"; "OU" = "OBJECT SYSTEM AUDIT"; "OL" = "OBJECT SYSTEM ALARM"; "ML" = "MANDATORY LABEL"} $AceFlags = @{ "CI" = "CONTAINER INHERIT: Child objects that are containers, such as directories, inherit the ACE as an explicit ACE."; "OI" = "OBJECT INHERIT: Child objects that are not containers inherit the ACE as an explicit ACE."; "NP" = "NO PROPAGATE: ONLY IMMEDIATE CHILDREN INHERIT THIS ACE."; "IO" = "INHERITANCE ONLY: ACE DOESN'T APPLY TO THIS OBJECT; BUT MAY AFFECT CHILDREN VIA INHERITANCE."; "ID" = "ACE IS INHERITED"; "SA" = "SUCCESSFUL ACCESS AUDIT"; "FA" = "FAILED ACCESS AUDIT" } $PermissionType = @{ "CC" = "Query Conf"; "DC" = "Change Conf"; "LC" = "QueryStat"; "SW" = "EnumDeps"; "RP" = "Start"; "WP" = "Stop"; "DT" = "Pause"; "LO" = "Interrogate"; "CR" = "UserDefined"; "GA" = "Generic All"; "GX" = "Generic Execute"; "GW" = "Generic Write"; "GR" = "Generic Read"; "SD" = "Standard Delete"; "RC" = "Read Control"; "WD" = "Write DAC"; "WO" = "Write Owner" } $Trustees = @{ "AO" = "Account operators"; "RU" = "Alias to allow previous Windows 2000"; "AN" = "Anonymous logon"; "AU" = "Authenticated users"; "BA" = "Built-in administrators"; "BG" = "Built-in guests"; "BO" = "Backup operators"; "BU" = "Built-in users"; "CA" = "Certificate server administrators"; "CG" = "Creator group"; "CO" = "Creator owner"; "DA" = "Domain administrators"; "DC" = "Domain computers"; "DD" = "Domain controllers"; "DG" = "Domain guests"; "DU" = "Domain users"; "EA" = "Enterprise administrators"; "ED" = "Enterprise domain controllers"; "WD" = "Everyone"; "PA" = "Group Policy administrators"; "IU" = "Interactively logged-on user"; "LA" = "Local administrator"; "LG" = "Local guest"; "LS" = "Local service account"; "SY" = "Local system"; "NU" = "Network logon user"; "NO" = "Network configuration operators"; "NS" = "Network service account"; "PO" = "Printer operators"; "PS" = "Personal self"; "PU" = "Power users"; "RS" = "RAS servers group"; "RD" = "Terminal server users"; "RE" = "Replicator"; "RC" = "Restricted code"; "SA" = "Schema administrators"; "SO" = "Server operators"; "SU" = "Service logon user" } #Example below queries the WinRM service on RemoteServer Get-ServiceDACL winrm RemoteServer
PowerShellCorpus/PoshCode/add-OLPublicFolder.ps1
add-OLPublicFolder.ps1
function add-OLPublicFolder { param ( [string]$PFName, #Name of the new Public Folder $PFType, #Type of the new Public Folder [string]$PFParent = "\\") #Parentfolder of the new Public Folder begin { #Outlook Constants to assign the needed values for the foldertypes [int]$olFolderInbox = 6 [int]$olFolderCalendar = 9 [int]$olFolderContacts = 10 [int]$olFolderJournal = 11 [int]$olFolderNotes = 12 [int]$olFolderTasks = 13 [int]$olPublicFoldersAllPublicFolders = 18 $outlook = new-object -ComObject Outlook.Application #init Outlook Com Object $namespace = $outlook.GetNamespace("MAPI") #get MAPI namespace # navigate to the folder "All Public Folders" $olObjAllPublicRootFolders = $namespace.GetDefaultFolder($olPublicFoldersAllPublicFolders) } process{ #inner function ######################################################################### function script:get-OLPublicFolderByPath { param ([string]$FolderPath = $(throw "Error 2: mandatory parameter '-FolderPath'")) $Folder = $null #init of empty OL folderobject $FoldersArray = @{} #force init of empty array #trim single or eading pairs of backslash If (($FolderPath).substring(0,2) -eq "\\\\") {$FolderPath = ($FolderPath.substring(2,$FolderPath.length - 2))} If (($FolderPath).substring(0,1) -eq "\\") {$FolderPath = ($FolderPath.substring(1,$FolderPath.length - 1))} #fill folderpath into array even if it is only one element if ($FolderPath.Contains("\\") -eq $true){$FoldersArray = $FolderPath.Split("\\")} else{$FoldersArray[0] = $FolderPath} $folders = $olObjAllPublicRootFolders.Folders #map root public folders for ($i = 0; $i -le ($FoldersArray.length - 1); $i++){ #for each element of the folderpath array $folders | %{ #push the folders into the pipeline if ($_.name -eq $FoldersArray[$i]) { #if the objectname equals the current element of the folderpath array $folders = $_.Folders #get the child items into $folders if ($i -eq ($FoldersArray.length - 1)) {return $_} #return the last element of the folderpath array } } } } ######################################################################### if ($_){ #if function is used in the pipeline you need to check the input if ($_.PFName -ne $null){ #name of the public folder $PFName = $_.PFName} #from first element of the object else{throw "Error 3: mandatory parameter '-PFName'"} #no name, no public folder! if ($_.PFType -ne $null){ #type of the public folder $PFType = $_.PFType #assign the correct values for foldertypes switch ($PFType) { #based on the provided string MAIL {$PFType = $olFolderInbox; break} CALENDAR {$PFType = $olFolderCalendar; break} CONTACT {$PFType = $olFolderContacts; break} JOURNAL {$PFType = $olFolderJournal; break} NOTE {$PFType = $olFolderNotes; break} TASK {$PFType = $olFolderTasks; break} default{ #and throw an error if you get garbage throw "Unknown public folder type in optional parameter '-PFType'` The supported public folder types are` Mail, Calendar, Contact, Task, Note and Journal` If no type is specified the default is Mail` The value was: $PFType"} } } else{$PFType = $olFolderInbox} #empty parameter $PFType if ($_.PFParent -ne $null){ #get desired position of the public folder $PFParent = $_.PFParent} #from input else{$PFParent = "\\"} #and make it root if nothing is provided } else{ if ($PFType -eq $null){$PFType = $olFolderInbox} #set default to mailfolder if param for $PFType was empty else{ switch ($PFType) { MAIL {$PFType = $olFolderInbox; break} CALENDAR {$PFType = $olFolderCalendar; break} CONTACT {$PFType = $olFolderContacts; break} JOURNAL {$PFType = $olFolderJournal; break} NOTE {$PFType = $olFolderNotes; break} TASK {$PFType = $olFolderTasks; break} default{ throw "Unknown public folder type in optional parameter '-PFType'` The supported public folder types are` Mail, Calendar, Contact, Task, Note and Journal` If no type is specified the default is Mail` The value was: $PFType" } } } } if ($PFParent -eq "\\"){ #root public folder or one somewhere down the tree? Anyway, map to the parentfolder of the new folder $ParentFolder = $olObjAllPublicRootFolders} #root public folder else{$ParentFolder = get-OLPublicFolderByPath -FolderPath $PFParent} #use the inline function to traverse the public folders $ParentFolder.Folders.Add($PFName, $PFType) #magic happens here ;-) Write-Host "Public folder $PFName created in path $PFParent." $ParentFolder = $null #reset parent folder to avoid wrong assignment for the next object } end{ #cleanup, cleanup, cleanup... $PFParent = $null $olObjAllPublicRootFolders = $null $namespace = $null $outlook = $null } }
PowerShellCorpus/PoshCode/Start-rdp_3.ps1
Start-rdp_3.ps1
\nFunction Global:Start-RDP {\n<#\n .Synopsis\n This Cmdlet starts a microsoft terminal session against the hostname provided.\n \n it is possible to collect credential information from a PSCredential file saved on the disk\n \n .Description \n This cmdlet starts a Microsoft terminal sesion against the hostname provided, by creating a rdp \n file and calling the mstsc with the rdp file as data. it will be possible to save credentials into \n the file in a semi secure way.\n \n Thsi script uses the pscredential type and the import-/export pscredential script from halr9000. These \n scripts makes i possible to save encrypted username/password data as a file. These data are only decryptable \n by the user encrypting it.\n \n When using the -LeaveRDPFile option is used then it is only a HASH of the password that is left in the file. \n ! This hash key can be decrypted by brute force attacks.\n \n .Parameter Hostname\n \n this is the hostname/ip of the server you want to connect to\n \n .Parameter Fullscreen\n \n Use this paramenter when wanting to connect rdp in fullscreen mode\n \n .Parameter Credentials\n \n Credentials can be both a path to a file \n a pscredential type object\n \n .Parameter Console\n \n use this parameter when wanting to connect to the admin/console session.\n \n .Parameter Path\n \n use this path as temp/permanent place to store the .rdp files.\n \n .Parameter LeaveRDPFile\n \n use this parameter when you want to leave the rdp files after connect. \n \n ! Remember this might be a security risk.\n \n .Example\n \n Start-Rdp -Hostname Server1.local.domain -credentials (get-credential) \n \n This will prompt for username and password and subsequent connect to the specified server\n \n .Example\n Export-pscredential\n start-rdp -hostname Server1.local.domain -credentials credentials.enc.xml \n This will prompt for username and password save the credentials to a file and subsequent connect \n to the specified server using the user/password data from the file\n \n .Example\n Export-pscredential\n Get-content serverlist.txt | start-rdp -credentials credentials.enc.xml \n This will prompt for username and password save the credentials to a file and subsequent connect \n to the servers listed in the serverlist.txt file, using the user/password data from the file\n .Requirements \n Import-pscredential cmdlet http://poshcode.org/473\n \n .Link\n http://doitsmarter.blogspot.com/\n http://www.poshcode.org\n \n .Notes\n ====================================================================\n Author(s): \n Allan Christiansen <christiansen.allan@Gmail.com>, http://doitsmarter.blogspot.com/\n \n Credits/Special thanks:\n Hal Rottenberg <hal@halr9000.com> for the Import/export-pscredential cmdlets. \n http://poshcode.org/501\n \n Date: 2013-03-13\n Revision: 1.0\n Output includes the following data\n None\n \n ====================================================================\n Disclaimer: This script is written as best effort and provides no \n warranty expressed or implied. Please contact the author(s) if you \n have questions about this script before running or modifying\n ==================================================================== \n#>\n Param(\n [Parameter(ValueFromPipeline=$true,Position=0,Mandatory=$True,HelpMessage="Enter the hostname to connect to")]\n $Hostname="",\n [Parameter(ValueFromPipeline=$false,Position=1,Mandatory=$false,HelpMessage="Select to start in fullscreen mode")]\n [Switch]$FullScreen,\n [Parameter(ValueFromPipeline=$false,Position=2,Mandatory=$false,HelpMessage="select to connect in admin mode")]\n [Switch]$Console,\n [Parameter(ValueFromPipeline=$false,Position=3,Mandatory=$false,HelpMessage="Enter path to Credential store .xml or input pscredential")]\n $Credentials,\n [Parameter(ValueFromPipeline=$false,Position=4,Mandatory=$false,HelpMessage="Path for directory to store rdp files")]\n $Path = "$Home\\Documents\\RDP",\n [Parameter(ValueFromPipeline=$false,Position=5,Mandatory=$false,HelpMessage="Remove .RDP file after start")]\n [Switch]$leaveRDPFile\n )\nBegin { \n If (!(test-path $Path -erroraction silentlycontinue)) {\n mkdir $Path | Out-Null\n }\n IF (($Credentials.gettype()).type -eq "PSCredential") {\n $cred = $Credentials\n } Else {\n If (test-path $Credentials -erroraction silentlycontinue) {\n $cred = Import-pscredential $Credentials\n } else {\n # Not Pscredential type object -\n # not a valid file path\n # lets ask the user\n $cred = get-credentials\n }\n $Encrypted = $cred.password | ConvertFrom-SecureString\n }\n \n #test screenmode and set to correct value\n $ScreenMode=1\n If ($Fullscreen) {\n $ScreenMode = 2\n }\n}\nProcess {\n #run through all hosts pased to script\n Foreach ($Hosts in $hostname) {\n IF ($Hosts -ne "") { \n $Filename = "$Path\\$Hosts.rdp"\n $RDPFileData = \n“screen mode id:i:$ScreenMode\ndesktopwidth:i:1024\ndesktopheight:i:768\nsession bpp:i:16\nwinposstr:s:0,1,0,0,800,600\nfull address:s:$Hosts\ncompression:i:1\nkeyboardhook:i:2\naudiomode:i:0\nredirectdrives:i:1\nredirectprinters:i:0\nredirectcomports:i:0\nredirectsmartcards:i:1\ndisplayconnectionbar:i:1\nautoreconnection enabled:i:1\nusername:s:$($cred.username)\nalternate shell:s:\nshell working directory:s:\ndisable wallpaper:i:1\ndisable full window drag:i:1\ndisable menu anims:i:1\ndisable themes:i:0\ndisable cursor setting:i:0\nbitmapcachepersistenable:i:1\npassword 51:b:$encrypted\n”\n If (!(test-path $Filename -erroraction silentlycontinue)) {\n Set-Content -path $Filename -Value $RDPFileData -Force -erroraction silentlycontinue\n } \n $param = ""\n If ($Console) {\n $Param += "/admin"\n } \n #\n IF ($Param -ne "") {\n Mstsc $Filename $Param\n } Else {\n Mstsc $Filename\n }\n \n #Remove the .rdp files if requested\n If (!$LeaveRDPFile) {\n Sleep 1\n Remove-item $filename -force\n }\n }\n }\n}\nEnd {\n # No cleanup needed\n}\n}\n New-Alias -name Global:RDP -Value Start-Rdp -Force\nIf ((get-command import-pscredential -erroraction silentlycontinue) -eq $False) {\n write-error "Import-/export-pscredential cmdlets from http://poshcode.org/473 are required for this cmdlet to have 100% functionality"\n Exit 1\n}
PowerShellCorpus/PoshCode/Set-ScreenResolution.ps1
Set-ScreenResolution.ps1
Function Set-ScreenResolution { <# .Synopsis Sets the Screen Resolution of the primary monitor .Description Uses Pinvoke and ChangeDisplaySettings Win32API to make the change .Example Set-ScreenResolution -Width 1024 -Height 768 #> param ( [Parameter(Mandatory=$true, Position = 0)] [int] $Width, [Parameter(Mandatory=$true, Position = 1)] [int] $Height ) $pinvokeCode = @" using System; using System.Runtime.InteropServices; namespace Resolution { [StructLayout(LayoutKind.Sequential)] public struct DEVMODE1 { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string dmDeviceName; public short dmSpecVersion; public short dmDriverVersion; public short dmSize; public short dmDriverExtra; public int dmFields; public short dmOrientation; public short dmPaperSize; public short dmPaperLength; public short dmPaperWidth; public short dmScale; public short dmCopies; public short dmDefaultSource; public short dmPrintQuality; public short dmColor; public short dmDuplex; public short dmYResolution; public short dmTTOption; public short dmCollate; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string dmFormName; public short dmLogPixels; public short dmBitsPerPel; public int dmPelsWidth; public int dmPelsHeight; public int dmDisplayFlags; public int dmDisplayFrequency; public int dmICMMethod; public int dmICMIntent; public int dmMediaType; public int dmDitherType; public int dmReserved1; public int dmReserved2; public int dmPanningWidth; public int dmPanningHeight; }; class User_32 { [DllImport("user32.dll")] public static extern int EnumDisplaySettings(string deviceName, int modeNum, ref DEVMODE1 devMode); [DllImport("user32.dll")] public static extern int ChangeDisplaySettings(ref DEVMODE1 devMode, int flags); public const int ENUM_CURRENT_SETTINGS = -1; public const int CDS_UPDATEREGISTRY = 0x01; public const int CDS_TEST = 0x02; public const int DISP_CHANGE_SUCCESSFUL = 0; public const int DISP_CHANGE_RESTART = 1; public const int DISP_CHANGE_FAILED = -1; } public class PrmaryScreenResolution { static public string ChangeResolution(int width, int height) { DEVMODE1 dm = GetDevMode1(); if (0 != User_32.EnumDisplaySettings(null, User_32.ENUM_CURRENT_SETTINGS, ref dm)) { dm.dmPelsWidth = width; dm.dmPelsHeight = height; int iRet = User_32.ChangeDisplaySettings(ref dm, User_32.CDS_TEST); if (iRet == User_32.DISP_CHANGE_FAILED) { return "Unable To Process Your Request. Sorry For This Inconvenience."; } else { iRet = User_32.ChangeDisplaySettings(ref dm, User_32.CDS_UPDATEREGISTRY); switch (iRet) { case User_32.DISP_CHANGE_SUCCESSFUL: { return "Success"; } case User_32.DISP_CHANGE_RESTART: { return "You Need To Reboot For The Change To Happen.\\n If You Feel Any Problem After Rebooting Your Machine\\nThen Try To Change Resolution In Safe Mode."; } default: { return "Failed To Change The Resolution"; } } } } else { return "Failed To Change The Resolution."; } } private static DEVMODE1 GetDevMode1() { DEVMODE1 dm = new DEVMODE1(); dm.dmDeviceName = new String(new char[32]); dm.dmFormName = new String(new char[32]); dm.dmSize = (short)Marshal.SizeOf(dm); return dm; } } } "@ Add-Type $pinvokeCode -ErrorAction SilentlyContinue [Resolution.PrmaryScreenResolution]::ChangeResolution($width,$height) }
PowerShellCorpus/PoshCode/Get-Comic.ps1
Get-Comic.ps1
#.Synopsis # Download comic strip images #.Description # Gets the latest comic from any of several different comic strips and downloads it to "My Pictures\\Comix" #.Parameter comic # The name of the comic to fetch: xkcd, dilbert, uf (user friendly) #.Notes # DEPEND-ON -Module HttpRest poshcode.org/787 # DEPEND-ON -Function Get-SpecialPath poshcode.org/858 # PARAM([string[]]$comic = "xkcd") BEGIN { ## CHANGE THESE TWO LINES: Import-Module HttpRest ## you can dot-source HttpRest instead, if you're on v1 ## If you don't have Get-SpecialPath, just hard-code this $ComixPath = Join-Path $(Get-SpecialPath MyPictures) "Comix" MkDir $ComixPath -Force | Push-Location function Test-ComicPath { Param($comic) $comicFile = Join-Path $ComixPath $("{0} {1}" -f $comic, $(Get-Date -f "yyyy-MM-dd")) $comicFile if( Test-Path "$comicFile.*" ) { $(ls "$comicFile.*") } else { $false } } } PROCESS { foreach($c in $comic) { $file,$exists = Test-ComicPath $c if($exists) { $exists; continue } $url = $null; switch($c) { "dilbert" { $doc = Invoke-Http GET "http`://dilbert.com/fast" -Wait ## Dilbert's Headers are broken (on purpose?) $doc.Headers["Content-Type"] = "text/html; charset=utf-8" $url = $doc | Receive-Http Text "//*[local-name()='img' and not(boolean(@alt))]/@src" if($url -notmatch "http`://dilbert.com/") { $url = "http`://dilbert.com/$url" } } "xkcd" { $url = Invoke-Http GET http`://xkcd.com/ | Receive-Http Text "//*[local-name()='img' and @title]/@src" } "uf" { $url = Invoke-Http GET http`://ars.userfriendly.org/cartoons/ @{id=$(Get-Date -f "yyyyMMdd")} | Receive-Http Text "//*[@alt='$(get-date -f 'S\\trip \\for MMM dd, yyyy')']/@src" } } if($url) { Invoke-Http GET $url | Receive-Http File "$file$([IO.Path]::GetExtension($url))" } else { Write-Warning "Couldn't get a url for $c" } } } END { Pop-Location }
PowerShellCorpus/PoshCode/SMS hierarchy in Visio.ps1
SMS hierarchy in Visio.ps1
# Name : smsDiagram.ps1 # Author : David "Makovec" Moravec # Web : http://www.powershell.cz # Email : powershell.cz@googlemail.com # Twitter: makovec # # Description: Draw SMS 2003 hierarchy in Visio # # Version: 1.0 # History: # v0.1 - (add) Alan's vDiagram functions # (add) WMI query # v0.2 - (add) -server parameter # (add) -textInfo parameter # (add) Primary/Secondary # v0.3 - (add) Visio drawing # (add) -debug parameter # v0.4 - (change) working with $x, $y to fine tune shapes # (add) save final Visio file # v1.0 - (changed) script renamed to smsDiagram # # Usage: smsDiagram.ps1 -server czsms01 # - Draw SMS hierarchy in Visio # smsDiagram.ps1 -server czsms01 -textInfo # - Print SMS hierarchy to console # ################################################################# param ( $server = $(throw "You must enter server name."), [switch]$debug, [switch]$textInfo ) # $debug set - enable messages if ($debug) { $DebugPreference = "Continue" Write-Debug "Debugging enabled." } ############################################################################### ########################################################## FUNCTIONS DEFINITION ############################################################################### # Function Add-VisioObject ############################################################################### function Add-VisioObject ($mastObj, $item) { Write-Debug "fnc(Add-VisioObject) $($item.SiteCode) - $($item.ServerName)" Write-Host "Adding $($item.SiteCode) - $($item.ServerName)" # Drop the selected stencil on the active page, with the coordinates x, y $shpObj = $pagObj.Drop($mastObj, $script:x, $script:y) # Enter text for the object $shpObj.Characters.Text = $item.SiteCode #Return the visioobject to be used return $shpObj } # function Add-VisioObject # Function Connect-VisioObject ############################################################################### function Connect-VisioObject ($firstObj, $secondObj) { $shpConn = $pagObj.Drop($pagObj.Application.ConnectorToolDataObject, 0, 0) # Connect its Begin to the 'From' shape: $connectBegin = $shpConn.CellsU("BeginX").GlueTo($firstObj.CellsU("PinX")) # Connect its End to the 'To' shape: $connectEnd = $shpConn.CellsU("EndX").GlueTo($secondObj.CellsU("PinX")) } # function Connect-VisioObject # Function Print-TextHierarchy ############################################################################### function Print-TextHierarchy { param ( $inputSrv, $level ) $downLevelSites = $servers |? {$_.ReportingSiteCode -eq $inputSrv.SiteCode} $level += 1 $space = " "*$level*2 if ($downLevelSites -ne $null) { foreach ($i in $downLevelSites) { Write-Host $space -NoNewLine if ($i.Type -eq 2) { $text = "$($i.SiteCode) (P)" } else { $text = "$($i.SiteCode)" } Write-Host $text Print-TextHierarchy $i $level } # foreach $downLevelSites } else { # empty block } # else } # function Print-TextHierarchy # Function Draw-VisioHierarchy ############################################################################### function Draw-VisioHierarchy { param ( $VSobjParent, $inputSrv ) # Type of server (primary/secondary) if ($inputSrv.Type -eq 2) { # Primary server $DrawObj = $PrimaryObj } else { # Secondary server $DrawObj = $SecondaryObj } $VSobjCurr = Add-VisioObject $DrawObj $inputSrv if ($VSobjParent -ne $null) { Connect-VisioObject $VSobjParent $VSobjCurr } $downLevelSites = $servers |? {$_.ReportingSiteCode -eq $inputSrv.SiteCode} if ($downLevelSites -ne $null) { $script:y -= 1.5 foreach ($i in $downLevelSites) { $script:x += 1 Draw-VisioHierarchy $VSobjCurr $i } # foreach $downLevelSites $script:x -= 1 } else { # Move secondary servers x-axis tam $script:x += 1 $script:y += 1.5 } # else $script:y -= 1.5 if ($inputSrv.Type -eq 2) { $script:x -= ($offset*$downLevelSites.Count)-1 } $script:x -= $offset } # function Draw-VisioHierarchy ############################################################################### ########################################################################## MAIN ############################################################################### # Load info from WMI ############################################################################### # Site code $siteCode = (Get-WmiObject -ComputerName $server -Namespace root/sms ` -Class SMS_ProviderLocation -Filter "ProviderForLocalSite='True'").SiteCode # SMS Namespace path $SMSWMINamespace = 'root/sms/site_'+$siteCode # List of children servers from SMS_Site class $servers = Get-WmiObject -ComputerName $server -Namespace $SMSWMINamespace -Class SMS_Site | ` Select ReportingSiteCode, SiteCode, ServerName, Type | ` Sort ReportingSiteCode, SiteCode # For testing at home use exported objects #$servers = Import-Clixml ./SMSsvr_t.xml | Sort ReportingSiteCode, SiteCode # Set central server as object $centralSMSServer = $servers[0] # Do you want text representation to the console ? if ($textInfo) { Write-Host "$($centralSMSServer.SiteCode) (P)" Print-TextHierarchy $centralSMSServer 0 return } # Prepare Visio objects ############################################################################### # Create an instance of Visio and create an empty document $AppVisio = New-Object -ComObject Visio.Application $docsObj = $AppVisio.Documents $DocObj = $docsObj.Add("Detailed Network Diagram.vst") # Set the active page $pagsObj = $AppVisio.ActiveDocument.Pages $pagObj = $pagsObj.Item(1) # Select stencils to drop $stnObj = $AppVisio.Documents.Item("SERVER_M.VSS") # Set server types shapes $PrimaryObj = $stnObj.Masters.Item("Database Server") $SecondaryObj = $stnObj.Masters.Item("Server") # Set coordinates for first object $script:x = 1 $script:y = 8 $offset = 1 Draw-VisioHierarchy $null $centralSMSServer # Resize to fit page $pagObj.ResizeToFitContents() $SaveFile = [system.Environment]::GetFolderPath('MyDocuments') + "\\My_smsDiagram.vsd" $DocObj.SaveAs($SaveFile) | Out-Null Write-Output "Document saved as $SaveFile"
PowerShellCorpus/PoshCode/Get-PipeLineObject.ps1
Get-PipeLineObject.ps1
# For TabExpansion.ps1 # this requires TabExpansion.ps1 function Get-PipeLineObject { $i = -2 do { $str = $line.Split("|")[$i] # 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, '[|;=]')[-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] } $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 = Get-Item . } 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)[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 } return; }
PowerShellCorpus/PoshCode/1456d523-444e-4f3c-bb7c-31c0cb1b218d.ps1
1456d523-444e-4f3c-bb7c-31c0cb1b218d.ps1
Param( [string]$CCNetListenerFile = $null, [string]$MyComputerName = [System.Environment]::MachineName, [string]$Config='Debug', [int]$CCNetLogQueueLength = 10 [switch]$NoBuild, [string]$SpecificVdir = $null ) # usage from ccnet will be something like this: #... #<powershell> #<scriptDirectory>iphi</scriptDirectory> #<script>deploy.ps1</script> #<executable>C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe</executable> #<dynamicValues> # <replacementValue property="buildArgs"> # <format>-CCNetListenerFile {0}</format> # <parameters> # <namedValue name="$CCNetListenerFile" value="Default" /> # </parameters> # </replacementValue> #</dynamicValues> #</powershell> #... [Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath # The CCNetListenerFile is an xml file used by ccnet to list what is going on during the build in details function CCNetListenerLog( $q ) { if($CCNetListenerFile -ne '' -and $CCNetListenerFile -ne $null) { $stream = [System.IO.StreamWriter] $CCNetListenerFile $stream.AutoFlush = $true; $stream.WriteLine("<data>") foreach( $item in $q ) { $stream.WriteLine($item) } $stream.WriteLine("</data>") $stream.Close() } } $q = New-Object System.Collections.Queue function LogBuildPoint( [string]$text ) { if( $q.Count -ge $CCNetLogQueueLength ) { # store in temp var so there is no output, can probably do this better ... $old = $q.Dequeue(); } $stamp = [System.DateTime]::Now.ToString("yyyy-MM-dd hh:mm:ss"); $item = "<Item Time='$stamp' Data='$text' />" $q.Enqueue( $item ); #use write-host because otherwise this becomes included in the function output, not necessarily written to the screen #also this write-host causes the message to be put in the build log when run from ccnet Write-Host $text if($CCNetListenerFile -ne '' -and $CCNetListenerFile -ne $null) { CCNetListenerLog $q } } #push directory (and update the environment variable so that relative paths work as expected without ".\\") function pd( [string]$location ) { Push-Location $location; [Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath; } #pop directory function ppd() { Pop-Location [Environment]::CurrentDirectory=(Get-Location -PSProvider FileSystem).ProviderPath; } function Build() { #you can log a repetative task and estimate when it will finish like this: $total = ($repetition_object | Measure-Object).Count $num = 0 $startTime = [System.DateTime]::Now $repetition_object | % { $_ | RepetitiveTask $num++ $curTime = [System.DateTime]::Now $percent = ($num / $total) $expected = ($startTime + (New-Object TimeSpan (($curTime - $startTime).Ticks / $percent))).ToShortTimeString() LogBuildPoint "Finished $num out of $total, expect to complete at: $expected" } } #useful if you want to call this from the CLI to declare the functions if(!$NoBuild) { Build }
PowerShellCorpus/PoshCode/7f47048d-3826-4d47-a13e-05e72014dacd.ps1
7f47048d-3826-4d47-a13e-05e72014dacd.ps1
#Find out how many accounts we should delete ( I'll make this interogate UPS at some point in future #for now this fudge will do Param ([int]$limit) if ($limit -eq 0) { $limit = 999999999 } $count = 1 write-host "------------- Started -------------" $output = Get-Date $output = "Started at " + $output.ToString() $output | Out-File -FilePath c:\\output.txt -append #Add SharePoint PowerShell SnapIn if not already added if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) { Add-PSSnapin "Microsoft.SharePoint.PowerShell" } #Add Quest AD PowerShell SnapIn if not already added if ((Get-PSSnapin "Quest.ActiveRoles.ADManagement" -ErrorAction SilentlyContinue) -eq $null) { Add-PSSnapin "Quest.ActiveRoles.ADManagement" } #Set my site host location. $site = new-object Microsoft.SharePoint.SPSite("http://mysites"); $ServiceContext = [Microsoft.SharePoint.SPServiceContext]::GetContext($site); #Get UserProfileManager and get all profiles $ProfileManager = new-object Microsoft.Office.Server.UserProfiles.UserProfileManager($ServiceContext) $AllProfiles = $ProfileManager.GetEnumerator() #iterate around the profiles foreach($profile in $AllProfiles) { #get the associated AD account $ADUser = $PROFILE.MultiloginAccounts | Get-QADUser #check if the account is diasabled in AD if ($ADUser.AccountIsDisabled) { #delete the profile $ProfileManager.RemoveUserProfile($ADUser.NTAccountName) $output = $count.ToString() + ": " + $ADUser.NTAccountName $output | Out-File -FilePath c:\\output.txt -append write-host $output $count++ if ($count -gt $limit) { break } } } write-host "------------- Finished -------------" write-host ($count -1) accounts removed $output = Get-Date $output = "Finished at " + $output.ToString() $output | Out-File -FilePath c:\\output.txt -append $site.Dispose()
PowerShellCorpus/PoshCode/Get-DhcpClient.ps1
Get-DhcpClient.ps1
<# .Description A C# P/Invoke wrapper for DhcpEnumSubnetClients from the DHCP API .Parameter Server A DHCP server to query .Parameter Scope The IP address representing the scope to query #> [CmdLetBinding()] Param( [Parameter(Mandatory = $True)] [Net.IPAddress]$Server, [Parameter(Mandatory = $True)] [Net.IPAddress]$Scope ) # # Add the namespace # Try { [Void][Dhcp.DhcpClient] } Catch { } If (!$?) { Add-Type @" using System; using System.Collections; using System.Net; using System.Runtime.InteropServices; using Dhcp; namespace Dhcp { public class ConvertTo { public static IPAddress IP(UInt32 Value) { Byte[] IPArray = new Byte[4]; for (int i = 3; i > -1; i--) { Double Remainder = Value % Math.Pow(256, i); IPArray[3 - i] = (Byte)((Value - Remainder) / Math.Pow(256, i)); Value = (UInt32)Remainder; } return IPAddress.Parse(String.Format("{0}.{1}.{2}.{3}", IPArray[0], IPArray[1], IPArray[2], IPArray[3])); } public static UInt32 UInt32(IPAddress IP) { UInt32 Value = 0; Byte[] Bytes = IP.GetAddressBytes(); for (int i = 0; i < 4; i++) { Value = Value | (UInt32)(Bytes[i] << (8 * (3 - i))); } return Value; } } public class Functions { [DllImport("dhcpsapi.dll")] public static extern UInt32 DhcpEnumSubnetClients( [MarshalAs(UnmanagedType.LPWStr)] String ServerIpAddress, uint SubnetAddress, ref uint ResumeHandle, uint PreferredMaximum, out IntPtr ClientInfo, out uint ClientsRead, out uint ClientsTotal ); } public class Structures { [StructLayout(LayoutKind.Sequential)] public struct DATE_TIME { public UInt32 dwLowDateTime; public UInt32 dwHighDateTime; public DateTime ToDateTime() { if (dwHighDateTime == 0 && dwLowDateTime == 0) { return DateTime.MinValue; } if (dwHighDateTime == int.MaxValue && dwLowDateTime == UInt32.MaxValue) { return DateTime.MaxValue; } return DateTime.FromFileTime((((long)dwHighDateTime) << 32) | dwLowDateTime); } } [StructLayout(LayoutKind.Sequential)] public struct DHCP_BINARY_DATA { public uint DataLength; public IntPtr Data; public override String ToString() { return String.Format("{0:X2}:{1:X2}:{2:X2}:{3:X2}:{4:X2}:{5:X2}", Marshal.ReadByte(this.Data), Marshal.ReadByte(this.Data, 1), Marshal.ReadByte(this.Data, 2), Marshal.ReadByte(this.Data, 3), Marshal.ReadByte(this.Data, 4), Marshal.ReadByte(this.Data, 5)); } }; [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct DHCP_CLIENT_INFO_ARRAY { public uint NumElements; public IntPtr Clients; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct DHCP_CLIENT_INFO { public uint ClientIpAddress; public uint SubnetMask; public DHCP_BINARY_DATA ClientHardwareAddress; [MarshalAs(UnmanagedType.LPWStr)] public string ClientName; [MarshalAs(UnmanagedType.LPWStr)] public string ClientComment; public DATE_TIME ClientLeaseExpires; public DHCP_HOST_INFO OwnerHost; } [StructLayout(LayoutKind.Sequential)] public struct DHCP_HOST_INFO { uint IpAddress; [MarshalAs(UnmanagedType.LPWStr)] String NetBiosName; [MarshalAs(UnmanagedType.LPWStr)] String HostName; } } public class DhcpClient { public String Name; public String MACAddress; public IPAddress IpAddress; public IPAddress SubnetMask; public String Description; public DateTime LeaseExpires; internal DhcpClient(Structures.DHCP_CLIENT_INFO RawReservation) { this.IpAddress = ConvertTo.IP(RawReservation.ClientIpAddress); this.SubnetMask = ConvertTo.IP(RawReservation.SubnetMask); this.MACAddress = RawReservation.ClientHardwareAddress.ToString(); this.Name = RawReservation.ClientName; this.Description = RawReservation.ClientComment; this.LeaseExpires = RawReservation.ClientLeaseExpires.ToDateTime(); } public static DhcpClient[] Get(IPAddress ServerIP, IPAddress ScopeIP) { ArrayList Clients = new ArrayList(); uint resumeHandle = 0; IntPtr info_array_ptr; uint numClientsRead = 0; uint totalClients = 0; String Server = ServerIP.ToString(); UInt32 Scope = ConvertTo.UInt32(ScopeIP); UInt32 ReturnCode = Functions.DhcpEnumSubnetClients( Server, Scope, ref resumeHandle, 65536, out info_array_ptr, out numClientsRead, out totalClients ); Structures.DHCP_CLIENT_INFO_ARRAY rawClients = (Structures.DHCP_CLIENT_INFO_ARRAY)Marshal.PtrToStructure(info_array_ptr, typeof(Structures.DHCP_CLIENT_INFO_ARRAY)); IntPtr current = rawClients.Clients; for (int i = 0; i < (int)rawClients.NumElements; i++) { Structures.DHCP_CLIENT_INFO rawMachine = (Structures.DHCP_CLIENT_INFO)Marshal.PtrToStructure(Marshal.ReadIntPtr(current), typeof(Structures.DHCP_CLIENT_INFO)); Clients.Add(new DhcpClient(rawMachine)); current = (IntPtr)((int)current + (int)Marshal.SizeOf(typeof(IntPtr))); } return (DhcpClient[])Clients.ToArray(typeof(DhcpClient)); } } } "@ } # # Execute Get() # [Dhcp.DhcpClient]::Get($Server, $Scope)
PowerShellCorpus/PoshCode/Import-ExcelToSQL.ps1
Import-ExcelToSQL.ps1
#Change these settings as needed $filepath = 'C:\\Users\\u00\\Documents\\backupset.xlsx' #Comment/Uncomment connection string based on version #Connection String for Excel 2007: $connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=`"$filepath`";Extended Properties=`"Excel 12.0 Xml;HDR=YES`";" #Connection String for Excel 2003: #$connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=`"$filepath`";Extended Properties=`"Excel 8.0;HDR=Yes;IMEX=1`";" $qry = 'select * from [backupset$]' $sqlserver = 'Z002\\SQLEXPRESS' $dbname = 'SQLPSX' #Create a table in destination database with the with referenced columns and table name. $tblname = 'ExcelData_fill' ####################### function Get-ExcelData { param($connString, $qry='select * from [sheet1$]') $conn = new-object System.Data.OleDb.OleDbConnection($connString) $conn.open() $cmd = new-object System.Data.OleDb.OleDbCommand($qry,$conn) $da = new-object System.Data.OleDb.OleDbDataAdapter($cmd) $dt = new-object System.Data.dataTable [void]$da.fill($dt) $conn.close() $dt } #Get-ExcelData ####################### function Write-DataTableToDatabase { param($dt,$destServer,$destDb,$destTbl) $connectionString = "Data Source=$destServer;Integrated Security=true;Initial Catalog=$destdb;" $bulkCopy = new-object ("Data.SqlClient.SqlBulkCopy") $connectionString $bulkCopy.DestinationTableName = "$destTbl" $bulkCopy.WriteToServer($dt) }# Write-DataTableToDatabase ####################### $dt = Get-ExcelData $connString $qry Write-DataTableToDatabase $dt $sqlserver $dbname $tblnam
PowerShellCorpus/PoshCode/Oracle NetApp CommVault .ps1
Oracle NetApp CommVault .ps1
#Path Below must be set to reflect ORACLE_HOME [Reflection.Assembly]::LoadFile("C:\\app\\oracle\\product\\11.2.0\\client_1\\ODP.NET\\bin\\2.x\\Oracle.DataAccess.dll") Import-Module DataOntap #Populate credentials below function nas2snapadd {param ($volname) Connect-NaController -Name nau-nas2.naucom.com | out-null Write-Output $volname New-NaSnapshot -Name $volname -SnapName "backup_agent" | Out-Null } function nas1snapadd {param ($volname) Connect-NaController -Name nau-nas1.naucom.com | out-null Write-Output $volname New-NaSnapshot -Name $volname -SnapName "backup_agent" | Out-Null } function nas2snaprem {param ($volname) Connect-NaController -Name nau-nas2.naucom.com | Out-Null $snapstodel = Get-NaSnapshot -Name $volname -snapname backup_agent if ($snapstodel -ne $null){ foreach($sn in $snapstodel){ Write-Output $volname $sn.Name Remove-NaSnapshot -Volume $volname -SnapName $sn.Name -Confirm:$false } } } function nas1snaprem {param ($volname) Connect-NaController -Name nau-nas1.naucom.com | out-null $snapstodel = Get-NaSnapshot -Name $volname -snapname backup_agent if ($snapstodel -ne $null){ foreach($sn in $snapstodel){ Write-Output $volname $sn.Name Remove-NaSnapshot -Volume $volname -SnapName $sn.Name -Confirm:$false } } } $nas1vols = @("ncpp_data01", "ncpp_data03", "ncpp_redo01", "ncpp_redo03") $nas2vols = @("ncpp_data02", "ncpp_data04", "ncpp_data05", "ncpp_redo02", "ncpp_redo04") foreach($vol in $nas1vols){ nas1snaprem $vol } foreach($vol in $nas2vols){ nas2snaprem $vol } $constr = "User Id=backup_agent;Password=password;Data Source=ncrp" $sql="ALTER DATABASE BEGIN BACKUP" $sql2="ALTER DATABASE END BACKUP" $conn = New-Object Oracle.DataAccess.Client.OracleConnection($constr) $conn.Open() $command = New-Object Oracle.DataAccess.Client.OracleCommand( $sql,$conn) $reader=$command.ExecuteReader() $reader.Dispose() $command.Dispose() foreach($vol in $nas1vols){ nas1snapadd $vol } foreach($vol in $nas2vols){ nas2snapadd $vol } $command = New-Object Oracle.DataAccess.Client.OracleCommand( $sql2,$conn) $reader=$command.ExecuteReader() $reader.Dispose() $command.Dispose() $conn.Close() #Start CommVault Tape Job $psi = new-object System.Diagnostics.ProcessStartInfo $psi.Verb = "runas" $psi.FileName = "N:\\scripts\\ncpp_nas1.bat" [System.Diagnostics.Process]::Start($psi) | out-null $psi.FileName = "N:\\scripts\\ncpp_nas2.bat" [System.Diagnostics.Process]::Start($psi) | out-null
PowerShellCorpus/PoshCode/Export ASP Events 2 evtx.ps1
Export ASP Events 2 evtx.ps1
# Be sure to include the tailing backslash "\\" $DstFolder = "D:\\somefolder\\" $EvtSession = New-Object System.Diagnostics.Eventing.Reader.EventLogSession($env:computername) [string[]] $ProviderList = $EvtSession.GetProviderNames() | Select-String asp for($i=0;$i -lt $ProviderList.Length;$i++){ $EvtQuery = "*[System/Provider/@Name=`""+$ProviderList[$i]+"`"]" $Dst = $DstFolder+$env:computername+"_"+($ProviderList[$i]).replace(" ","_")+".evtx" if(Test-Path -Path $Dst){Remove-Item -Path $Dst -Force} $EvtSession.ExportLogAndMessages('Application','LogName',$EvtQuery,$Dst) }
PowerShellCorpus/PoshCode/Test-Port_8.ps1
Test-Port_8.ps1
Param([string]$srv,$port=135,$timeout=3000,[switch]$verbose) # Test-Port.ps1 # Does a TCP connection on specified port (135 by default) $ErrorActionPreference = "SilentlyContinue" # Create TCP Client $tcpclient = new-Object system.Net.Sockets.TcpClient # Tell TCP Client to connect to machine on Port $iar = $tcpclient.BeginConnect($srv,$port,$null,$null) # Set the wait time $wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false) # Check to see if the connection is done if(!$wait) { # Close the connection and report timeout $tcpclient.Close() if($verbose){Write-Host "Connection Timeout"} Return $false } else { # Close the connection and report the error if there is one $error.Clear() $tcpclient.EndConnect($iar) | out-Null if(!$?){if($verbose){write-host $error[0]};$failed = $true} $tcpclient.Close() } # Return $true if connection Establish else $False if($failed){return $false}else{return $true}
PowerShellCorpus/PoshCode/fc2365e4-98a7-4ee6-89b0-65c32dfbe01a.ps1
fc2365e4-98a7-4ee6-89b0-65c32dfbe01a.ps1
#You'll need admin perms on all the servers to run this... Write-Host "ComputerName in White, then Local Groups in Green, Local Groups' Members in White" #This feeds the script a list of server names (ServerList.txt, placed in the same directory) #for which I want the Local Groups and all those groups' Members. $x = Get-Content ServerList.txt # this feeds each servername, one by one, into the process... foreach ($j in $x) { #The server name becomes variable $strComputer $strComputer = "$j" #The Server name then becomes the variable $strComputer, and its name #is printed out in all CAPS $computer = [ADSI]("WinNT://" + $strComputer + ",computer") $g = $computer.name.ToString() $g.ToUpper(); " " #The local security groups on the Server is then found, #and fed to the array $a $group = $computer.psbase.children | where{$_.psbase.schemaclassname -eq "group"} $a = @() foreach ($member in $group.psbase.syncroot) {$a += $member.name } #Each Local Group Member is then printed (in white,and with a space) underneath its Group's name #(Group name printed in green) foreach ($i in $a) { $group =[ADSI]"WinNT://$j/$i" Write-Host "$i" -fore green $members = @($group.psbase.Invoke("Members")) $members | foreach { Write-Host " ",$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)} } Write-host " " Write-host " " Write-host " " }
PowerShellCorpus/PoshCode/ConvertFrom-CliXml_2.ps1
ConvertFrom-CliXml_2.ps1
function ConvertFrom-CliXml { param( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)] [ValidateNotNullOrEmpty()] [String[]]$InputObject ) begin { $OFS = "`n" [String]$xmlString = "" } process { $xmlString += $InputObject } end { $type = [PSObject].Assembly.GetType('System.Management.Automation.Deserializer') $ctor = $type.GetConstructor('instance,nonpublic', $null, @([xml.xmlreader]), $null) $sr = New-Object System.IO.StringReader $xmlString $xr = New-Object System.Xml.XmlTextReader $sr $deserializer = $ctor.Invoke($xr) $method = @($type.GetMethods('nonpublic,instance') | Where-Object {$_.Name -like "Deserialize"})[1] $done = $type.GetMethod('Done', [System.Reflection.BindingFlags]'nonpublic,instance') while (!$done.Invoke($deserializer, @())) { try { $method.Invoke($deserializer, "") } catch { Write-Warning "Could not deserialize ${string}: $_" } } $xr.Close() $sr.Dispose() } }
PowerShellCorpus/PoshCode/ConvertTo-RelativeTime.ps1
ConvertTo-RelativeTime.ps1
function ConvertTo-RelativeTimeString { #.Synopsis # Calculates a relative text version of a duration #.Description # Generates a string approximation of a timespan, like "x minutes" or "x days." Note this method does not add "about" to the front, nor "ago" to the end unless you pass them in. #.Parameter Span # A TimeSpan to convert to a string #.Parameter Before # A DateTime representing the start of a timespan. #.Parameter After # A DateTime representing the end of a timespan. #.Parameter Prefix # The prefix string, pass "about" to render: "about 4 minutes" #.Parameter Postfix # The postfix string, like "ago" to render: "about 4 minutes ago" [CmdletBinding(DefaultParameterSetName="TwoDates")] PARAM( [Parameter(ParameterSetName="TimeSpan",Mandatory=$true)] [TimeSpan]$span , [Parameter(ParameterSetName="TwoDates",Mandatory=$true,ValueFromPipeline=$true)] [Alias("DateCreated")] [DateTime]$before , [Parameter(ParameterSetName="TwoDates", Mandatory=$true, Position=0)] [DateTime]$after , [Parameter(Position=1)] [String]$prefix = "" , [Parameter(Position=2)] [String]$postfix = "" ) PROCESS { if($PSCmdlet.ParameterSetName -eq "TwoDates") { $span = $after - $before } "$( switch($span.TotalSeconds) { {$_ -le 1} { "$prefix a second $postfix "; break } {$_ -le 60} { "$prefix $($span.Seconds) seconds $postfix "; break } {$_ -le 120} { "$prefix a minute $postfix "; break } {$_ -le 2700} { "$prefix $($span.Minutes) minutes $postfix "; break } # 45 minutes or less {$_ -le 5400} { "$prefix an hour $postfix "; break } # 45 minutes to 1.5 hours {$_ -le 86400} { "$prefix $($span.Hours) hours $postfix "; break } # less than a day {$_ -le 172800} { "$prefix 1 day $postfix "; break } # less than two days default { "$prefix $($span.Days) days $postfix "; break } } )".Trim() } }
PowerShellCorpus/PoshCode/Invoke-SSH Wrapper.ps1
Invoke-SSH Wrapper.ps1
function Invoke-SSH { param ( [string]$Server = "$(throw 'Server is a mandatory parameter.')", $Credential = "$(throw 'Credential is a mandatory parameter.')", [switch]$Echo = $true, [string]$Command = "$(throw 'Command is a mandatory parameter.')" ) # Since function name is same as cmdlet, we have to fully-qualify cmdlet name using format Snapin\\Cmdlet $ShellObject = Netcmdlets\\Invoke-SSH -Server $Server -Credential $Credential -Force -Command $Command # Foreach loop creates a string array from the output, one line per array item $Output = $ShellObject | ForEach-Object { ($_.Text).split("`n") } # By default will simulate a bash-like prompt with username and server. Good for pasting in emails. if ( $Echo ) { $UserName = $Credential.UserName -replace "\\\\" Write-Host -foregroundcolor Yellow "$UserName@$Server # $Command" } Write-Output $Output }
PowerShellCorpus/PoshCode/Get-DetailedSystemInform.ps1
Get-DetailedSystemInform.ps1
##############################################################################\n##\n## Get-DetailedSystemInformation\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 detailed information about a system.\n\n.EXAMPLE\n\nGet-DetailedSystemInformation LEE-DESK > output.txt\nGets detailed information about LEE-DESK and stores the output into output.txt\n\n#>\n\nparam(\n ## The computer to analyze\n $Computer = "."\n)\n\nSet-StrictMode -Version Latest\n\n"#"*80\n"System Information Summary"\n"Generated $(Get-Date)"\n"#"*80\n""\n""\n\n"#"*80\n"Computer System Information"\n"#"*80\nGet-WmiObject Win32_ComputerSystem -Computer $computer | Format-List *\n\n"#"*80\n"Operating System Information"\n"#"*80\nGet-WmiObject Win32_OperatingSystem -Computer $computer | Format-List *\n\n"#"*80\n"BIOS Information"\n"#"*80\nGet-WmiObject Win32_Bios -Computer $computer | Format-List *\n\n"#"*80\n"Memory Information"\n"#"*80\nGet-WmiObject Win32_PhysicalMemory -Computer $computer | Format-List *\n\n"#"*80\n"Physical Disk Information"\n"#"*80\nGet-WmiObject Win32_DiskDrive -Computer $computer | Format-List *\n\n"#"*80\n"Logical Disk Information"\n"#"*80\nGet-WmiObject Win32_LogicalDisk -Computer $computer | Format-List *
PowerShellCorpus/PoshCode/Get-Dependency_1.ps1
Get-Dependency_1.ps1
############################################################################## #.AUTHOR # Josh Einstein # Einstein Technologies, LLC ############################################################################## $BuiltInAliases = @{} $BuiltInCmdlets = @{} $BuiltInFunctions = @{} $BuiltInVariables = @{} ############################################################################## #.SYNOPSIS # Gets a list of tokenized strings from the specified PowerShell code sample # which can be used for dependency analysis or other unique purposes. # #.DESCRIPTION # This command will use the currently active PowerShell ISE editor tab if the # current shell is PowerShell ISE and a block of code was not provided to # the command. # #.PARAMETER Type # If specified, returns only PSTokens of the specified type(s). # #.PARAMETER Token # If specified, returns only PSTokens that contain the specified text. # #.PARAMETER Text # The block of text to tokenize. If this parameter is not specified, and the # current shell is PowerShell ISE, the current editor tab's text will be used # otherwise, no output is returned. # #.PARAMETER Path # Specifies the path to an item. Wildcards are permitted. # #.PARAMETER LiteralPath # Specifies the path to an item. Unlike Path, the value of LiteralPath is # used exactly as it is typed. No characters are interpreted as wildcards. # If the path includes escape characters, enclose it in single quotation marks. # Single quotation marks tell Windows PowerShell not to interpret any # characters as escape sequences. # #.PARAMETER Lines # If specified, returns only the tokens that are on one of the line numbers # specified. This is useful for doing a two-pass check as in the first example # which aims to list function declarations which consist of two related tokens, # the keyword containing the word "function" and the command argument containing # the function name. It is assumed they will both be on the same line. # #.EXAMPLE # $FunctionLines = Get-PSToken -Type Keyword -Token function | %{ $_.StartLine } # $FunctionNames = Get-PSToken -Type CommandArgument | ?{ $FunctionLines -contains $_.StartLine } # #.LINK # Get-Dependency # #.RETURNVALUE # A collection of PSTokens parsed from the source code. ############################################################################## function Get-PSToken { [CmdletBinding(DefaultParameterSetName='Selection')] param( [Parameter(Position=1)] [String[]]$Type, [Parameter(Position=2)] [String[]]$Token, [Parameter(ParameterSetName='Path', Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [String[]]$Path, [Alias("PSPath")] [Parameter(ParameterSetName='LiteralPath', Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [String[]]$LiteralPath, [Parameter()] [Int32[]]$Lines ) process { if ($PSCmdlet.ParameterSetName -eq 'Selection') { if (-not $PSISE) { throw 'The Selection parameter set is not valid outside of the PowerShell ISE.' } if (-not $PSISE.CurrentOpenedFile) { throw 'There is no file currently opened.' } if (-not $PSISE.CurrentOpenedFile.IsSaved) { throw 'Please save the currently active document first.' } if ($PSISE.CurrentOpenedFile.IsUntitled) { throw 'Please save the currently active document first.' } $ResolvedPaths = @(Resolve-Path -LiteralPath $PSISE.CurrentOpenedFile.FullPath) } elseif ($PSCmdlet.ParameterSetName -match '^(Literal)?Path$') { switch ($PSCmdlet.ParameterSetName) { Path { $ResolvedPaths = @(Resolve-Path -Path $Path) } LiteralPath { $ResolvePathArgs = @(Resolve-Path -LiteralPath $LiteralPath) } } } # Delegate path expansion to Resolve-Path foreach ($ResolvedPath in $ResolvedPaths) { $ScriptContent = Get-Content $ResolvedPath # Call the PSParser to tokenize! $ParserErrors = [System.Management.Automation.PSParseError[]]@() $ParserTokens = [System.Management.Automation.PSParser]::Tokenize($ScriptContent, [Ref]$ParserErrors) # If there were any errors, write them out as warnings for ($i=0; $i -lt $ParserErrors.Length; $i++) { $ParserError = $ParserErrors[$i] if (-not $ParserError.Token) { Write-Warning $ParserError.Message } else { Write-Warning "($($ParserError.Token.StartLine), $($ParserError.Token.StartColumn)) $($ParserError.Message)" } } if (-not $ParserTokens.Count) { return } # Filter the output if ($Type.Length) { $ParserTokens = @($ParserTokens | ?{ $Type -contains $_.Type }) } # Filter By Type if ($Token.Length) { $ParserTokens = @($ParserTokens | ?{ $Token -contains $_.Content }) } # Filter By Content if ($Lines.Length) { $ParserTokens = @($ParserTokens | ?{ $Lines -contains $_.StartLine }) } # Filter By Line if (-not $ParserTokens.Count) { return } # Return the tokens, adding a Path property to each one # that points back to the script or editor file # note that text blocks will have a null path $ParserTokens | Add-Member -PassThru NoteProperty Script (Split-Path -Leaf $ResolvedPath) } } # process } ############################################################################## #.SYNOPSIS # Calculates the dependencies of a script file, block of PowerShell code, or # an open PowerShell ISE document. # #.DESCRIPTION # Before deploying a script or module, it is important to ensure that any # external dependencies are resolved otherwise code that runs fine on your # machine will bomb on someone else's. This function will scan a single # level of dependencies from the specified script and by default returns # any dependency that is 1) not a part of the built-in PowerShell command # and variable configuration and 2) not defined in the script being analyzed. # You can override this behavior and include these dependencies with the # Force parameter. # #.PARAMETER Path # Specifies the path to an item. Wildcards are permitted. # #.PARAMETER LiteralPath # Specifies the path to an item. Unlike Path, the value of LiteralPath is # used exactly as it is typed. No characters are interpreted as wildcards. # If the path includes escape characters, enclose it in single quotation marks. # Single quotation marks tell Windows PowerShell not to interpret any # characters as escape sequences. # #.PARAMETER Text # The block of text to tokenize. If this parameter is not specified, and the # current shell is PowerShell ISE, the current editor tab's text will be used # otherwise, no output is returned. # #.PARAMETER Unresolved # When specified, only unresolved dependencies are returned. # #.PARAMETER Force # When specified, all dependencies are included, even if they are known to # be defined locally or in the default PowerShell configuration. # #.EXAMPLE # Get-Dependency | Out-GridView # #.LINK # Get-PSToken # #.RETURNVALUE # An array of PSObjects containing information about the external dependencies. ############################################################################## function Get-Dependency { [CmdletBinding(DefaultParameterSetName='Selection')] param( [Parameter(ParameterSetName='Path', Position=1, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [String[]]$Path, [Alias("PSPath")] [Parameter(ParameterSetName='LiteralPath', Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [String[]]$LiteralPath, [Parameter()] [Switch]$Unresolved, [Parameter()] [Switch]$Force ) begin { $Dependencies = New-Object System.Collections.ArrayList $LocalFunctions = @{} $ImportedAliases = @{} $ImportedCmdlets = @{} $ImportedFunctions = @{} ############################################################################## #.SYNOPSIS # Strips off the scope modifier of an identifier so its name can be checked. ############################################################################## filter Normalize-Identifier([String]$Name) { if ($_ -is [System.Management.Automation.PSToken]) { $Name = $_.Content } if ($_ -is [String]) { $Name = $_ } $Name -replace '^$?(Script|Global|Local):','' } ############################################################################## #.SYNOPSIS # Wraps calls to Get-PSToken, making sure to use the appropriate parameter set. ############################################################################## function Get-PSTokenProxy([String[]]$Type,[String[]]$Token,[Int32[]]$Lines) { $GetPSTokenArgs = @{} if ($Type.Length) { $GetPSTokenArgs['Type'] = $Type } if ($Token.Length) { $GetPSTokenArgs['Token'] = $Token } if ($Lines.Length) { $GetPSTokenArgs['Lines'] = $Lines } $ResolvedPaths | Get-PSToken @GetPSTokenArgs } ############################################################################## #.SYNOPSIS # Rebuilds the cache of built-in command, alias, function, and variable names # that are present in an unconfigured PowerShell session so that they can # be skipped from dependency checking. ############################################################################## function Discover-BuiltInCommands { if ($BuiltInCmdlets.Count -eq 0) { $BuiltInAliases.Clear() $BuiltInCmdlets.Clear() $BuiltInFunctions.Clear() $BuiltInVariables.Clear() $Posh = [PowerShell]::Create() try { [Void]$Posh.AddScript('Get-Command -CommandType Cmdlet,Function,Alias') foreach($CommandInfo in $Posh.Invoke()) { switch($CommandInfo.CommandType) { Alias { $BuiltInAliases[$CommandInfo.Name] = $true } Cmdlet { $BuiltInCmdlets[$CommandInfo.Name] = $true } Function { $BuiltInFunctions[$CommandInfo.Name] = $true } } } [Void]$Posh.AddScript('Get-Variable') foreach($VariableInfo in $Posh.Invoke()) { $BuiltInVariables[$VariableInfo.Name] = $true } # Note: PSISE won't appear as a built-in variable this way # I decided I actually prefer it that way. I want to know if # I accidentially couple a script to the ISE $BuiltInVariables['this'] = $true } finally { $Posh.Dispose() } } # if count 0 } ############################################################################## #.SYNOPSIS # Scans the source code for Import-Module statements and gathers up the # module export information into hashtables. ############################################################################## function Discover-ModuleImports { $ImportedAliases.Clear() $ImportedCmdlets.Clear() $ImportedFunctions.Clear() $TokenLines = @(Get-PSTokenProxy Command Import-Module | %{$_.StartLine}) if (-not $TokenLines.Length) { return } # nothing to do $TokenNames = @(Get-PSTokenProxy CommandArgument -Lines $TokenLines | Normalize-Identifier) if (-not $TokenNames.Length) { return } # nothing to do # Find out which referenced modules are not imported $MissingModules = @() foreach ($TokenName in $TokenNames) { if (-not (Get-Module $TokenName)) { $MissingModules += $TokenName } } if ($MissingModules.Length) { $MenuItem1 = New-Object System.Management.Automation.Host.ChoiceDescription "&No - Do Not Import Modules" $MenuItem2 = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes - Import These Modules" [System.Management.Automation.Host.ChoiceDescription[]]$MenuItems = @($MenuItem1,$MenuItem2) $MenuCaption = "Imported Modules Not Loaded" $MenuMessage = "One or more modules imported by the script are not currently loaded.`r`n" + "This can lead to unresolved external references and missing`r`n" + "information in the dependency report.`r`n" + "`r`n" + "You can attempt to temporarily import the following modules into the`r`n" + "session by selection the option below.`r`n" + "`r`n" foreach ($MissingModule in $MissingModules) { $MenuMessage += " Import-Module $MissingModule`r`n" } # Show the menu # If the user picks choice Y then import the modules # Because you can't import modules into the global scope from a lower scope, # the imported module will not be visible from outside of the current scope. $Response = $Host.UI.PromptForChoice($MenuCaption, $MenuMessage, $MenuItems, 0) if ($Response = 1) { foreach ($MissingModule in $MissingModules) { # Using Invoke-Expression so this Import-Module command # doesn't cause a screw-up when checking dependencies of # Dependency.psm1. Gay huh... Invoke-Expression ".{Import-Module $MissingModule -ErrorAction Continue}" } } } $ImportedModules = @(Get-Module $TokenNames -ListAvailable) + @(Get-Module $TokenNames) foreach ($ImportedModule in $ImportedModules) { $ImportedModule.ExportedAliases.Values | %{ $ImportedAliases[$_.Name] = $_ } $ImportedModule.ExportedCmdlets.Values | %{ $ImportedCmdlets[$_.Name] = $_ } $ImportedModule.ExportedFunctions.Values | %{ $ImportedFunctions[$_.Name] = $_ } } } ############################################################################## #.SYNOPSIS # Scans the source code for function and filter keywords that define local # functions that should not be treated as external dependencies. ############################################################################## function Discover-LocalFunctions { $LocalFunctions.Clear() # Gather information about defined functions $TokenLines = @(Get-PSTokenProxy Keyword function,filter | %{$_.StartLine}) if (-not $TokenLines.Length) { return } # nothing to do $TokenNames = @(Get-PSTokenProxy CommandArgument -Lines $TokenLines | Normalize-Identifier) if (-not $TokenNames.Length) { return } # nothing to do # No CommandInfo for these so we'll just store a bool foreach ($TokenName in $TokenNames) { $LocalFunctions[$TokenName] = $true } } ############################################################################## #.SYNOPSIS # Removes references to built-in Cmdlets, functions, variables, etc from # the input stream. ############################################################################## filter Exclude-BuiltInReferences { if ($Force) { return $_ } $Token = $_ $TokenName = Normalize-Identifier $Token.Content # Is it built in? # If so, skip it. if ($Token.Type -eq 'Command') { if ($BuiltInAliases[$TokenName]) { return } if ($BuiltInCmdlets[$TokenName]) { return } if ($BuiltInFunctions[$TokenName]) { return } } elseif ($Token.Type -eq 'Variable') { if ($BuiltInVariables[$TokenName]) { return } } $Token } ############################################################################## #.SYNOPSIS # Removes references to locally defined functions from the input stream. ############################################################################## filter Exclude-LocalReferences { if ($Force) { return $_ } $Token = $_ $TokenName = Normalize-Identifier $Token.Content # Is it built in? # If so, skip it. if ($Token.Type -eq 'Command') { if ($LocalFunctions[$TokenName]) { return } } $Token } ############################################################################## #.SYNOPSIS # Gets a single command with the specified name, taking into account that the # command name may need to have conflicting wildcard characters escaped and # avoiding the error when a command does not exist. ############################################################################## function Get-SafeCommand([String]$Name) { $SafeName = [System.Management.Automation.WildcardPattern]::Escape($Name) $CommandInfo = Get-Command -Name $SafeName -ErrorAction SilentlyContinue | Select -First 1 if (-not $CommandInfo) { $CommandInfo = $ImportedAliases[$Name] } if (-not $CommandInfo) { $CommandInfo = $ImportedFunctions[$Name] } if (-not $CommandInfo) { $CommandInfo = $ImportedCmdlets[$Name] } $CommandInfo } ############################################################################## #.SYNOPSIS # Gets a single variable with the specified name, taking into account that the # variable name may need to have conflicting wildcard characters escaped and # avoiding the error when a variable does not exist. ############################################################################## function Get-SafeVariable([String]$Name) { $SafeName = [System.Management.Automation.WildcardPattern]::Escape($Name) $VariableInfo = Get-Variable -Name $SafeName -Scope Global -ErrorAction SilentlyContinue | Select -First 1 $VariableInfo } ############################################################################## #.SYNOPSIS # Selects the first instance of each distinct combination of token type and # content (function/variable name etc) and includes the line number of the # first occurrence. # #.DESCRIPTION # This is a basically just a ugly way of doing: # SELECT Type,Content,Min(StartLine) FROM ... GROUP BY Type,Content # Which PowerShell cannot easily represent as far as I know ############################################################################## function Select-UniqueTokens { $Input | Group-Object Type,Content | Select-Object @( @{N='Type'; E={ $_.Group[0].Type } }, @{N='Content'; E={ $_.Group[0].Content } }, @{N='Script'; E={ $_.Group[0].Script } } @{N='StartLine'; E={ $_.Group[0].StartLine } } ) } ############################################################################## #.SYNOPSIS # Creates a new PSObject for holding information about the external dependency ############################################################################## function New-Dependency($Token) { # Create a PSObject to hold the values # we will output from this function New-Object PSObject | Add-Member -PassThru NoteProperty Script ($Token.Script) | Add-Member -PassThru NoteProperty Module ($null) | Add-Member -PassThru NoteProperty Type ($Token.Type) | Add-Member -PassThru NoteProperty Name (Normalize-Identifier $Token.Content) | Add-Member -PassThru NoteProperty Target ($null) | Add-Member -PassThru NoteProperty Resolved ($false) | Add-Member -PassThru NoteProperty File ($null) } } # begin process { if ($PSCmdlet.ParameterSetName -eq 'Selection') { if (-not $PSISE) { throw 'The Selection parameter set is not valid outside of the PowerShell ISE.' } if (-not $PSISE.CurrentOpenedFile) { throw 'There is no file currently opened.' } if (-not $PSISE.CurrentOpenedFile.IsSaved) { throw 'Please save the currently active document first.' } if ($PSISE.CurrentOpenedFile.IsUntitled) { throw 'Please save the currently active document first.' } $ResolvedPaths = @(Resolve-Path -LiteralPath $PSISE.CurrentOpenedFile.FullPath) } elseif ($PSCmdlet.ParameterSetName -match '^(Literal)?Path$') { switch ($PSCmdlet.ParameterSetName) { Path { $ResolvedPaths = @(Resolve-Path -Path $Path) } LiteralPath { $ResolvedPaths = @(Resolve-Path -LiteralPath $LiteralPath) } } } # Discover imported modules and function definitions Discover-BuiltInCommands Discover-ModuleImports Discover-LocalFunctions # Parse the source code # Gives back command and variable references $Tokens = @( Get-PSTokenProxy Command,Variable | Exclude-BuiltInReferences | Exclude-LocalReferences | Select-UniqueTokens ) foreach ($Token in $Tokens) { $Dependency = New-Dependency $Token # HANDLE VARIABLE REFERENCES if ($Token.Type -eq 'Variable') { if ($VariableInfo = Get-SafeVariable $Dependency.Name) { $Dependency.Module = $VariableInfo.ModuleName $Dependency.Resolved = $true } else { # Skip this dependency # Could not find this variable in global state # So we can only assume that the variable is # localized somewhere and cannot really be # resolved as an external dependency # TODO: maybe look for a setter or arg name # to determine if it's really external or not continue } } # Token Type = Variable # HANDLE COMMAND REFERENCES if ($Token.Type -eq 'Command') { if ($CommandInfo = Get-SafeCommand $Dependency.Name) { $Dependency.Type= $CommandInfo.CommandType $Dependency.Resolved = $true # Is it an alias? # If so, we want to resolve the target if ($CommandInfo.CommandType -eq 'Alias') { # Is the alias resolved? if ($CommandInfo.ResolvedCommandName) { # Is alias the same name as the target? # If so, this is generally a disambiguating alias and can be ignored. if ($CommandInfo.Name -eq $CommandInfo.ResolvedCommandName) { if ($BuiltInAliases[$CommandInfo.ResolvedCommandName]) { continue } if ($BuiltInCmdlets[$CommandInfo.ResolvedCommandName]) { continue } if ($BuiltInFunctions[$CommandInfo.ResolvedCommandName]) { continue } } $Dependency.Target = $CommandInfo.ResolvedCommandName $CommandInfo = $CommandInfo.ResolvedCommand } else { # The alias points to an unresolved command $Dependency.Resolved = $false } } # Command Type = Alias # Command Source Info # Note that in the case of resolved aliases, CommandInfo is now # pointing to the resolved command and modules/paths/etc will reflect that if ($CommandInfo.ModuleName) { $Dependency.Module = $CommandInfo.ModuleName } if ($CommandInfo.ScriptBlock.File) { $Dependency.File = $CommandInfo.ScriptBlock.File } if ($CommandInfo.Path) { $Dependency.File = $CommandInfo.Path } if ($CommandInfo.DLL) { $Dependency.File = $CommandInfo.DLL } } # Is Command Is Resolved } # Token Type = Command if ($Unresolved -and $Dependency.Resolved) { continue } [Void]$Dependencies.Add($Dependency) } # foreach Token } # process end { # returns all output at the end $Dependencies | Sort Script,Module,Type,Name } # end }
PowerShellCorpus/PoshCode/hex2dec_2.ps1
hex2dec_2.ps1
@echo off ::unequal symbols for %%i in ("!", "x") do if "%1" equ "%%~i" goto:error ::display help information args for %%i in ("-h", "/h", "-help", "/help") do ( if "%1" equ "%%~i" if not defined run goto:help ) if "%1" equ "-?" if not defined run goto:help if "%1" equ "/?" if not defined run goto:help ::interactive mode if "%1" equ "" ( if not defined run goto:interactive goto:error ) ::parsing input data setlocal enabledelayedexpansion ::verify arguments length set "args=0" for %%i in (%*) do set /a "args+=1" if "%args%" neq "1" if not defined run goto:help if "%args%" neq "1" if defined run goto:error ::checking is arg hex or dec 2>nul set /a "res=%1" if "%1" equ "%res%" goto:dec2hex ::patterns echo "%1" | findstr /r \\x > nul set e1=%errorlevel% echo "%1" | findstr /r [0-9a-f] > nul set e2=%errorlevel% echo "%1" | findstr /r [g-wyz] > nul set e3=%errorlevel% ::debugging info section rem # echo %e1% %e2% %e3% ::parsing error codes if %e1% equ 0 if %e2% equ 0 if %e3% equ 1 set "k=%1" & goto:hex2dec if %e1% equ 1 if %e2% equ 0 if %e3% equ 1 set "k=0x%1" & goto:hex2dec goto:error :dec2hex 2>nul set /a "num=%1" set "map=0123456789ABCDEF" for /l %%i in (1, 1, 8) do ( set /a "res=num & 15, num >>=4" for %%j in (!res!) do set "hex=!map:~%%j,1!!hex!" ) for /f "tokens=* delims=0" %%i in ("!hex!") do set "hex=0x%%i" echo %1 = !hex! & goto:eof :hex2dec set "num=%k%" if "%num:~0,1%" equ "x" goto:error 2>nul set /a "res=%k%" for /f "tokens=2,3" %%i in ('findstr "# " "%~dpnx0"') do set "num=!num:%%i=%%j!" if "%res%" neq "" (echo !num! = !res!) else goto:error endlocal exit /b :error if defined run echo =^>err & goto:eof echo Invalid data. exit /b 1 :help ::Hex2dec v1.11 - converts hex to decimal and vice versa ::Copyright (C) 2012 Greg Zakharov :: ::Usage: hex2dec [decimal | hexadecimal] :: ::Example 1: :: C:\\>hex2dec 0x017a :: 0x017A = 378 :: ::Example 2: :: C:\\>hex2dec 13550 :: 13550 = 0x34EE :: ::Example 3: :: C:\\>hex2dec 23f :: 0x23F = 575 :: ::Note: hex2dec starts with interactive mode if there is ::no argument. for /f "tokens=* delims=:" %%i in ('findstr "^::" "%~dpnx0"') do echo.%%i exit /b 0 rem :: Upper case chart :: # a A # b B # c C # d D # e E # f F rem :: End of chart :: :interactive ::interactive mode on echo Hex2dec v1.11 - converts hex to decimal and vice versa echo. echo Enter decimal or hexademical number and press Enter to echo take result. Use "exit" or "clear" commands to quit or echo to make host clear. echo. setlocal ::already launched marker set "run=true" :begin set /p "ask=>>> " cmd /c "%~dpnx0" %ask% if "%ask%" equ "clear" cls if "%ask%" equ "exit" cls & goto:eof echo. goto:begin endlocal exit /b
PowerShellCorpus/PoshCode/scriptable telnet client.ps1
scriptable telnet client.ps1
function read-stream ([Parameter(Posistion=0,Mandatory=$true)][validatenotnull()] [System.Net.Sockets.NetworkStream]$stream, [String]$expect = "") { $buffer = new-object system.byte[] 1024 $enc = new-object system.text.asciiEncoding ## Read all the data available from the stream, writing it to the ## screen when done. ## Allow data to buffer start-sleep -m 100 $output = "" while($stream.DataAvailable -or $output -notmatch $expect) { $read = $stream.Read($buffer, 0, 1024) $output = "$output$($enc.GetString($buffer, 0, $read))" ## Allow data to buffer for a bit start-sleep -m 100 } $output.split("`n") } function send-command ([parameter(position=0,Mandatory=$true)][validatenotnull()] [String]$hostname, [parameter(position=1,Mandatory=$true)][validatenotnull()] [String]$User, [parameter(position=2,Mandatory=$true)][validatenotnull()] [String]$Password, [parameter(position=3,Mandatory=$true,valuefrompipeline=$true)][validatenotnull()] [String]$InputObject, [string]$Expect = "") { begin { $sock = new-object system.net.sockets.tcpclient($hostname,23) $str = $sock.GetStream() $wrt = new-object system.io.streamwriter($str) read-stream($str) $wrt.writeline($user) $wrt.flush() read-stream($str) $wrt.writeline($password) $wrt.flush() read-stream($str, $expect) } process { $wrt.writeline($InputObject) $wrt.flush() read-stream($str, $expect) } end { $wrt.writeline("exit") $wrt.flush() read-stream($str) ## Close the streams $wrt.Close() $str.Close() $sock.close() } }
PowerShellCorpus/PoshCode/Findup_4.ps1
Findup_4.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 ConsoleApplication1 { 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 Program { 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 (fs[i].FI.FullName == fs[c].FI.FullName) // 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/GPRS Online log_3.ps1
GPRS Online log_3.ps1
<# .SYNOPSIS Get-GprsTime (V3.0 Update for Windows 7) Check the total connect time of any GPRS devices from a specified date. Use Get-Help .\\Get-GprsTime -full to view Help for this file. .DESCRIPTION Display all the GPRS modem Event Log entries. While applications issued by the mobile phone manufacturers will invariably monitor only their own usage, this will show any logged GPRS activity, be it via PCMCIA, USB, mobile phone, etc. Use the -Verbose switch for some extra information if desired. A default value can be set with the -Monthly switch but can be temporarily overridden with any -Start value and deleted by entering an invalid date. Now uses .NET Parse to use any culture date input. Switches -M and -S cannot be used together. A Balloon prompt will be issued in the Notification area for the 5 days before the nominal month end. NOTE: this can effectively be suppressed by using a value higher than the SIM card term, ie something like -Account 90 for a 30 day card which will override the default setting. Use -Today to check only today's usage. Define a function in $profile to set any permanent switches, for example to set the account value permanently to 30 days. function GPRS { Invoke-Expression "Get-GprsTime -Account 30 $args" } .EXAMPLE .\\Get-GprsTime.ps1 -Monthly 4/8/2011 This will set the default search date to start from 4/8/2011 and is used to reset the start date each month for the average 30/31 day SIM card. .EXAMPLE .\\Get-GprsTime.ps1 -Start 12/07/2009 -Account 100 -Verbose Search from 12/07/2011 and also show (Verbose) details for each session. The Account switch will override any balloon prompt near the SIM expiry date. .EXAMPLE .\\Get-GprsTime.ps1 5/9/2011 -v Search one day only and show session details. .EXAMPLE .\\Get-GprsTime.ps1 -Today Show all sessions for today. This always defaults to verbose output. .EXAMPLE .\\Get-GprsTime.ps1 -Debug Shows the first available Event Log record and confirms switch settings. .NOTES A shorter total time than that actually used will result if the Event Log does not contain earlier dates; just increase the log size in such a case. The author can be contacted at www.SeaStarDevelopment.Bravehost.com and a (binary compiled) Module version of this procedure is included in the file Gprs3038.zip download there; the execution time of the module being about 10 times faster than this script. For the Event Log to record connect & disconnect events, the modem software should be set to RAS rather than NDIS. #> Param ([String] $start, [String] $monthly, [Int] $account = 0, #Start warning prompt 5 days before month end. [Switch] $today, [Switch] $verbose, [Switch] $debug) Trap [System.Management.Automation.MethodInvocationException] { [Int]$line = $error[0].InvocationInfo.ScriptLineNumber [System.Media.SystemSounds]::Hand.Play() if ($line -eq 196) { Write-Warning "[$name] Current GPRS variable has been deleted." $monthly = "" [Environment]::SetEnvironmentVariable("GPRS",$monthly,"User") } else { Write-Warning "[$name] Date is missing or invalid $SCRIPT:form" } exit 1 } #Establish the Operating System...We only need to confirm XP or later. function Get-OSVersion($computer,[ref]$osv) { $os = Get-WmiObject -class Win32_OperatingSystem -computerName $computer Switch ($os.Version) { "5.1.2600" { $osv.value = "xp" } default { "Version not listed" } } } $osv = $null $version = Get-OSVersion "localhost" ([ref]$osv) if ($osv -eq 'xp') { $logname = 'System' $connEvent = 20158 $discEvent = 20159 $source = 'RemoteAccess' } else { #Treat As Vista or Windows 7. $logname = 'Application' $connEvent = 20225 $discEvent = 20226 $source = 'RasClient' } $entryType = 'Information' $logEntry = $null $oldest = Get-eventlog -LogName $logname | #Get the earliest Log record. Where-Object {$_.Source -eq $source} | Where-Object {$_.EntryType -eq $entryType } | Sort-Object TimeGenerated | Select-Object -first 1 if ($oldest.TimeGenerated) { $logEntry = "System Event records available from - $($oldest.TimeGenerated.ToLongDateString())" } $name = $myInvocation.MyCommand $newLine = "[$name] The switches -Start and -Monthly can only be used separately." if ($debug) { $DebugPreference = 'Continue' } if ($start -and $monthly) { [System.Media.SystemSounds]::Hand.Play() Write-Warning "$newLine" exit 1 } $SCRIPT:form = "" #In certain cases Culture & UICulture can be different and have been known to # return conflicting results regarding '-is [DateTime]' queries, etc. if ($Host.CurrentCulture -eq $Host.CurrentUICulture) { $SCRIPT:form = '-Use format mm/dd/year' [Int]$culture = "{0:%d}" -f [DateTime] "6/5/2009" #Returns local day. If ($culture -eq 6) { $SCRIPT:form = '-Use format dd/mm/year' } } $ErrorActionPreference = 'SilentlyContinue' $VerbosePreference = 'SilentlyContinue' $WarningPreference = 'Continue' $conn = $disc = $default = $print = $null $timeNow = [DateTime]::Now $total = $timeNow - $timeNow #Set initial value to 00:00:00. $insert = "since" if ($verbose) { $VerbosePreference = 'Continue' } function CreditMsg ($value, $value2) { $value = [Math]::Abs($value) $prefix = "CURRENT" [DateTime] $creditDT = $value2 $creditDT = $creditDT.AddDays($value) #Add the -Account days. $thisDay = "{0:M/d/yyyy}" -f [DateTime]::Now #Force US format. #If we use '$number = $creditDT - (Get-Date)' instead of the line below we #can sometimes get a value of 1 returned instead 2, hence the above lines. $number = $creditDT - [DateTime] $thisDay [String] $credit = $creditDT $credit = $credit.Replace('00:00:00','') #Remove any trailing time. $credit = "{0:d}" -f [DateTime]$credit Switch($number.Days) { 1 {$prefix = "($value days) will expire tomorrow"; break} 0 {$prefix = "($value days) will expire today"; break} -1 {$prefix = "($value days) expired yesterday"; break} {($_ -lt 0)} {$prefix = "($value days) expired on $credit"; break} {($_ -le 5)} {$prefix = "($value days) will expire on $credit"} Default {$prefix = "CURRENT"} #Only come here if over 5 days. } return $prefix } function Interval ([String] $value) { Switch -regex ($value) { '^00:00:\\d+(.*)$' {$suffix = "seconds"; break} '^00:\\d+:\\d+(.*)$' {$suffix = "minutes"; break} '^\\d+:\\d+:\\d+(.*)$' {$suffix = " hours"; break} '^(\\d+)\\D(\\d+)(.*)$' {$suffix = " hours" $pDays = $matches[1] $pHours = $matches[2] [string]$pMinSec = $matches[3] [string]$tHours = (([int]$pDays) * 24)+[int]$pHours $value = $tHours + $pminSec; break} default {$suffix = " hours"} #Should never come here! } return "$value $suffix" } function CheckSetting ($value) { if ($value) { #Correct for local culture. $print = $default.ToShortDateString() } else { $print = "(Value not set)" } return $print } #The Script effectively starts here............................................. $getGprs = [Environment]::GetEnvironmentVariable("GPRS","User") #First check for GPRS variable and change from US date format to current locale. if ([DateTime]::TryParse($getGprs, [Ref]$timeNow)) { #No error as date is valid. $default = "{0:d}" -f [datetime]$getGprs $default = [DateTime]::Parse($default) $checkParts = "{0:yyyy},{0:%M}" -f $default $times = $checkParts.Split(',') $dayCount = [DateTime]::DaysInMonth($times[0],$times[1]) #Range 28-31. if($account -eq 0) { $account = $dayCount $summary = "$($dayCount.ToString()) days" } else { $summary = "$($account.Tostring()) days" } $text = CreditMsg $account $getGprs #Check if within 5 days of expiry date. if ($text -ne "CURRENT") { [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") $objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon $objNotifyIcon.Icon = [System.Drawing.SystemIcons]::Exclamation $objNotifyIcon.BalloonTipIcon = "Info" $objNotifyIcon.BalloonTipTitle = "GPRS online account" $objNotifyIcon.BalloonTipText = "Credit $text" $objNotifyIcon.Visible = $True $objNotifyIcon.ShowBalloonTip(10000) } } else { $summary = "(Days not set)" if ((!$today) -and (!$monthly) -and (!$start)) { [System.Media.SystemSounds]::Hand.Play() Write-Warning("Monthly date is either invalid or not set.") exit 1 } } if ($start) { $start = [DateTime]::Parse($start) #Trigger TRAP if invalid! [DateTime]$limit = $start $convert = "{0:D}" -f $limit $print = CheckSetting $default } if ($monthly) { $start = [DateTime]::Parse($monthly) #Trigger TRAP if invalid! Write-Output "Setting GPRS (monthly) environment variable to: $monthly" $gprs = [String]$start.Replace('00:00:00','') [Environment]::SetEnvironmentVariable("GPRS",$gprs,"User") [DateTime] $limit = $start #Change to required US date format. $convert = "{0:D}" -f $limit $print = $limit.ToShortDateString() $summary = "(Days undetermined)" #Will show next time around. } if ($today) { $verBosePreference = 'Continue' #Show VERBOSE by default. [DateTime] $limit = (Get-Date) $convert = "{0:D}" -f $limit $limit = $limit.Date #Override any start date if using -Today input. $insert = "for today" $print = CheckSetting $default } if ((!$today) -and (!$monthly) -and (!$start)) { if ($default) { $monthly = $default [DateTime] $limit = $monthly $convert = "{0:D}" -f $limit $print = CheckSetting $default } } Write-Verbose "All records $($insert.Replace('for ','')) - $convert" Write-Verbose "Script activation - User [$($env:UserName)] Computer [$($env:ComputerName)]" Write-Output "" Write-Output "Calculating total connect time of all GPRS modem devices..." #We cannot proceed beyond here without a valid $limit value. Write-Debug "Using - [Search date] $($limit.ToShortDateString()) [Account] $summary [GPRS Monthly] $print" if ($logEntry) { Write-Debug "$logEntry" } $lines = Get-EventLog $logname | Where-Object {($_.TimeGenerated -ge $limit) -and ` ($_.EventID -eq $discEvent -or $_.EventID -eq $connEvent)} if ($lines) { Write-Verbose "A total of $([Math]::Truncate($lines.Count/2)) online sessions extracted from the System Event Log." } else { Write-Output "(There are no events indicated in the System Event Log)" } $lines | ForEach-Object { $source = $_.Source if ($_.EventID -eq $discEvent) { #Event 20159 is Disconnect. $disc = $_.TimeGenerated } else { #Event 20158 is Connect. $conn = $_.TimeGenerated } #We are only interested in matching pairs of DISC/CONN... if ($disc -ne $null -and $conn -ne $null -and $disc -gt $conn) { $diff = $disc - $conn $total += $diff $convDisc = "{0:G}" -f $disc $convConn = "{0:G}" -f $conn $period = Interval $diff Write-Verbose "Disconnect at $convDisc. Online - $period" Write-Verbose " Connect at $convConn." } } #End ForEach if (!$source) { $source = '(Undetermined)' } Write-Verbose "Using local event source - System Event Log [$source]" $period = Interval $total Write-Output "Total online usage $insert $convert is $($period.Replace(' ',' '))." Write-Output ""
PowerShellCorpus/PoshCode/Start-TimeoutDialog.ps1
Start-TimeoutDialog.ps1
<# \n .Synopsis\n Displays a message box that will timeout after a set number of seconds.\n This script was written because WSHShell.Popup has a bug.\n \n Platform: Windows 7 32bit, Windows 2008 R2 64bit\n Author: Grant Carthew.\n Date: Apr 2011\n Updated: \n\n .Description\n When calling this script it creates a message box with custom settings\n and displays the message. There is a countdown timer displayed on the\n message box to inform the user when the message will timeout.\n \n If the user presses Button1 then the text on Button1 is returned.\n If the user presses Button2 then the text on Button2 is returned.\n If the message box times out then the string TIMEOUT is returned.\n \n .Parameter Title\n The title of the message box.\n Default = "Timeout"\n \n .Parameter Message\n The message to display on the message box.\n Default = "Timeout Message"\n \n .Parameter Button1Text\n The text to display on the left hand button.\n This text is returned if the user clicks the button.\n Button1 is the default accept button so ENTER will press Button1\n Default = "OK"\n \n .Parameter Button2Text\n The text to display on the right hand button.\n This text is returned if the user clicks the button.\n Button2 is the default cancel button so ESC will press Button2\n Default = "Cancel"\n \n .Parameter Seconds\n The timeout value for the message box.\n If the message box is displayed for this amount of time then\n it will close and the string TIMEOUT will be returned.\n Default = 30\n \n .Example\n Start-TimeoutDialog -Title "Shutdown" -Message "This system will shutdown in 50 minutes." -Seconds 3000\n#> \n\nparam\n(\n [parameter(Mandatory=$false)]\n [String]\n $Title = "Timeout",\n \n [parameter(Mandatory=$false)]\n [String]\n $Message = "Timeout Message",\n \n [parameter(Mandatory=$false)]\n [String]\n $Button1Text = "OK",\n \n [parameter(Mandatory=$false)]\n [String]\n $Button2Text = "Cancel",\n \n [parameter(Mandatory=$false)]\n [Int]\n $Seconds = 30\n)\n\nBEGIN\n{\n Write-Verbose -Message ("Begin: " + $MyInvocation.MyCommand.Path)\n [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null\n $F = $null\n $B1 = $null\n $B2 = $null\n $L = $null\n $TB = $null\n $Timer = $null\n $Result = $null\n $TimeLeft = New-TimeSpan -Seconds $Seconds\n $ONESEC = New-TimeSpan -Seconds 1\n}\n\nPROCESS\n{\n # Form\n $F = New-Object -TypeName System.Windows.Forms.Form \n $F.Text = $Title\n $F.Size = New-Object -TypeName System.Drawing.Size(300,150) \n $F.StartPosition = "CenterScreen"\n $F.Topmost = $true\n $F.KeyPreview = $true\n $F.ShowInTaskbar = $false\n $F.ShowIcon = $false\n $F.FormBorderStyle = "FixedDialog"\n $F.MaximizeBox = $false\n $F.MinimizeBox = $false\n\n # Button One\n $B1 = New-Object -TypeName System.Windows.Forms.Button\n $B1.Size = New-Object -TypeName System.Drawing.Size(75,23)\n $B1.Location = New-Object -TypeName System.Drawing.Size(125,90)\n $B1.Text = $Button1Text\n $B1.Add_Click({$Result=$Button1Text;$F.Close()})\n $F.Controls.Add($B1)\n $F.AcceptButton = $B1\n\n # Button Two\n $B2 = New-Object -TypeName System.Windows.Forms.Button\n $B2.Size = New-Object -TypeName System.Drawing.Size(75,23)\n $B2.Location = New-Object -TypeName System.Drawing.Size(210,90)\n $B2.Text = $Button2Text\n $B2.Add_Click({$Result=$Button2Text;$F.Close()})\n $F.Controls.Add($B2)\n $F.CancelButton = $B2\n\n # Label\n $L = New-Object -TypeName System.Windows.Forms.Label\n $L.Size = New-Object -TypeName System.Drawing.Size(280,65) \n $L.Location = New-Object -TypeName System.Drawing.Size(10,15) \n $L.Text = $Message\n $F.Controls.Add($L) \n\n # Textbox\n $TB = New-Object -TypeName System.Windows.Forms.TextBox \n $TB.Size = New-Object -TypeName System.Drawing.Size(100,20) \n $TB.Location = New-Object -TypeName System.Drawing.Size(10,91)\n $TB.TextAlign = "Center"\n $TB.ReadOnly = $true\n $TB.Text = [String]$TimeLeft.Hours + " : " + $TimeLeft.Minutes + " : " + $TimeLeft.Seconds\n $F.Controls.Add($TB)\n \n # Windows Timer\n $Timer = New-Object -TypeName System.Windows.Forms.Timer\n $Timer.Interval = 1000\n $Timer.Add_Tick({$TimeLeft = $TimeLeft - $ONESEC;$TB.Text = [String]$TimeLeft.Hours + " : " + $TimeLeft.Minutes + " : " + $TimeLeft.Seconds;if ($TimeLeft.TotalSeconds -lt 1) { $Result = "TIMEOUT"; $F.Close() } })\n $Timer.Start()\n\n # Show\n $F.Add_Shown({$F.Activate()})\n $F.ShowDialog() | Out-Null\n $Result\n}\n\nEND\n{\n Write-Verbose -Message ("End: " + $MyInvocation.MyCommand.Name)\n}
PowerShellCorpus/PoshCode/New-Script 1.1.ps1
New-Script 1.1.ps1
## New-Script function ## Creates a new script from the most recent commands in history ################################################################################################## ## Example Usage: ## New-Script ScriptName 4 ## creates a script from the most recent four commands ## New-Script ScriptName -id 10,11,12,14 ## creates a script from the specified commands in history ## New-Script Clipboard 2 ## sends the most recent two commands to the clipboard ################################################################################################## ## As a tip, I use a prompt function something like this to get the ID into the prompt: ## ## function prompt { ## return "`[{0}]: " -f ((get-history -count 1).Id + 1) ## } ################################################################################################## ## Revision History ## 1.0 - initial release ## 1.1 - fix bug with specifying multiple IDs ################################################################################################## #function New-Script { param( [string]$script=(Read-Host "A name for your script"), [int]$count=1, [int[]]$id=@((Get-History -count 1| Select Id).Id) ) $commands = &{if($id.Count -gt 1){ Get-History -id $id } else { Get-History -count $count }} | &{process{ $_.CommandLine }} if($script -eq "clipboard") { if( @(Get-PSSnapin -Name "pscx").Count ) { $commands | out-clipboard }elseif(@(gcm clip.exe).Count) { $commands | clip } } else { # default to putting it in my "Windows PowerShell\\scripts" folder which I have in my path... $folder = Split-Path $script if(!$folder) { $folder = Join-Path (Split-Path $Profile) "Scripts" } if(!(Test-Path $folder)) { Throw (new-object System.IO.DirectoryNotFoundException "Cannot find path '$folder' because it does not exist.") } # add the ps1 extension if it's not already there ... $file = Join-Path $folder (Split-Path $script -leaf) if(!(([IO.FileInfo]$file).Extension)) { $file = "$file.ps1" } $commands | set-content $file } #}
PowerShellCorpus/PoshCode/HttpRest 1.2.ps1
HttpRest 1.2.ps1
#requires -version 2.0 ## HttpRest module version 1.2 #################################################################################################### ## Still only the initial stages of converting to a full v2 module ## Based on the REST api from MindTouch's Dream SDK ## ## INSTALL: ## You need mindtouch.dream.dll (mindtouch.core.dll, SgmlReaderDll.dll, log4net.dll) from the SDK ## Get MindTouch_Dream_1.6.0.zip or greater from http`://sourceforge.net/projects/dekiwiki/files/ ## Unpack it, and you can find these dlls in the "dist" folder. ## Make sure to put them in the folder with this script module. ## ## For documentation of Dream: http`://wiki.developer.mindtouch.com/Dream #################################################################################################### ## Version History ## 1.0 First Release ## 1.0.1 Added Get-WebPageContent ## 1.0.2 Bug fix for Invoke-Http credential issues ## 1.1.0 First release of a PowerShell 2.0 (CTP3/Windows7) version.... ## 1.1.1 Added Get-WebPageText and Get-Webfile ... cleaned up options ## 1.2 Added Hashtable parsing on Get-DreamMessage ## Fixed parsing on Get-DreamPlug so we don't get errors on PowerShell 2 ## Added ParameterSet on Invoke-Http to pass in a plug directly (easier to debug) #################################################################################################### ## Usage: ## function Get-Google { ## Invoke-Http GET http`://www.google.com/search @{q=$args} | ## Receive-Http Xml "//h3[@class='r']/a" | Select href, InnerText ## } ## ######################################################################### ## function Get-WebFile($url,$cred) { ## Invoke-Http GET $url -auth $cred | Receive-Http File ## } ## ######################################################################### ## function Send-Paste { ## PARAM($PastebinURI="http`://posh.jaykul.com/p/",[IO.FileInfo]$file) ## PROCESS { ## if($_){[IO.FileInfo]$file=$_} ## ## if($file.Exists) { ## $ofs="`n" ## $result = Invoke-Http POST $PastebinURI @{ ## format="posh" # PowerShell ## expiry="d" # (d)ay or (m)onth or (f)orever ## poster=$([Security.Principal.WindowsIdentity]::GetCurrent().Name.Split("\\")[-1]) ## code2="$((gc $file) -replace "http`://","http``://")" # To get past the spam filter. ## paste="Send" ## } -Type FORM_URLENCODED -Wait ## $xml = $result.AsDocument().ToXml() ## write-output $xml.SelectSingleNode("//*[@class='highlight']/*").href ## } else { throw "File Not Found" } ## }} ## #################################################################################################### if(!$PSScriptRoot){ Write-Debug $($MyInvocation.MyCommand | out-string) $PSScriptRoot=(Split-Path $MyInvocation.MyCommand.Path -Parent) } # Write-Debug "Invocation: $($MyInvocation.MyCommand.Path)" # Write-Debug "Invocation: $($MyInvocation.MyCommand)" # Write-Debug "Invocation: $($MyInvocation)" Write-Debug "PSScriptRoot: '$PSScriptRoot'" # This Module depends on MindTouch.Dream $null = [Reflection.Assembly]::LoadFrom( "$PSScriptRoot\\mindtouch.dream.dll" ) # MindTouch.Dream requires: mindtouch.dream.dll, mindtouch.core.dll, SgmlReaderDll.dll, and log4net.dll) # This Module also depends on utility functions from System.Web $null = [Reflection.Assembly]::LoadWithPartialName("System.Web") ## Some utility functions are defined at the bottom [uri]$global:url = "" [System.Management.Automation.PSCredential]$global:HttpRestCredential = $null function Get-DreamMessage($Content,$Type) { #Write-Verbose "Content: $(if($Content){$Content.GetType()}else{"null"}) $($Content.Length) and Type: $(if($Type){$Type.GetType()}else{"null"})" if(!$Content) { Write-Verbose "No Content" return [MindTouch.Dream.DreamMessage]::Ok() } if( $Content -is [System.Xml.XmlDocument]) { Write-Verbose "Xml Content" return [MindTouch.Dream.DreamMessage]::Ok( $Content ) } if($Content -is [Hashtable]) { $kvp = $Content.GetEnumerator() | %{ new-object "System.Collections.Generic.KeyValuePair[[String],[String]]" $_.Key, $_.Value } Write-Verbose "Hashtable content: $($kvp | ft -auto | out-string -stream | %{ " $_ ".TrimEnd()} )" return [MindTouch.Dream.DreamMessage]::Ok( $kvp ) } if(Test-Path $Content -EA "SilentlyContinue") { Write-Verbose "File Content" return [MindTouch.Dream.DreamMessage]::FromFile((Convert-Path (Resolve-Path $Content))); } if($Type -is [String]) { Write-Verbose "Specific Content: $([MindTouch.Dream.MimeType]::$Type)" $Type = [MindTouch.Dream.MimeType]::$Type } if($Type -is [MindTouch.Dream.DreamMessage]) { Write-Verbose "Specific Content: $([MindTouch.Dream.MimeType]::$Type)" return [MindTouch.Dream.DreamMessage]::Ok( $Type, $Content ) } else { Write-Verbose "Unspecified string content" return [MindTouch.Dream.DreamMessage]::Ok( $([MindTouch.Dream.MimeType]::TEXT), $Content ) } } function Get-DreamPlug { [CmdletBinding()] PARAM ( $Url, [hashtable]$With, [hashtable]$Headers ) if($Url -is [array]) { Write-Verbose "URL is an array of parts" if($Url[0] -is [hashtable]) { Write-Verbose "URL is an array of hashtable parts" $plug = [MindTouch.Dream.Plug]::New($global:url) foreach($param in $url.GetEnumerator()) { if($param.Value) { $plug = $plug.At($param.Key,"=$(Encode-Twice $param.Value)") } else { $plug = $plug.At($param.Key) } } } else { [URI]$uri = Join-Url $global:url $url $plug = [MindTouch.Dream.Plug]::New($uri) } } elseif($url -is [string]) { Write-Verbose "String URL" trap { continue } [URI]$uri = $url if(!$uri.IsAbsoluteUri) { $uri = Join-Url $global:url $url Write-Verbose "Relative URL, appending to $($global:url) to get: $uri" } $plug = [MindTouch.Dream.Plug]::New($uri) } else { Write-Verbose "No URL, using default $($global:url)" $plug = [MindTouch.Dream.Plug]::New($global:url) } if($with) { foreach($w in $with.GetEnumerator()) { if($w.Value) { $plug = $plug.With($w.Key,$w.Value) } } Write-Verbose "Added 'with' params: $plug" } if($headers) { foreach($header in $Headers.GetEnumerator()) { if($header.Value) { $plug = $plug.WithHeader($header.Key,$header.Value) } } Write-Verbose "Added 'with' params: $plug" } return $plug } #CMDLET Receive-Http { Function Receive-Http { PARAM( # [Parameter(Position=1, Mandatory=$false)] # [ValidateSet("Xml", "File", "Text","Bytes")] # [Alias("As")] $Output = "Xml" , # [Parameter(Position=2, Mandatory=$false)] [string]$Path , # [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Result")] # [Alias("IO")] # [MindTouch.Dream.Result``1[[MindTouch.Dream.DreamMessage]]] $InputObject #, # [Parameter(Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Response")] # [MindTouch.Dream.DreamMessage] # $response ) BEGIN { if($InputObject) { Write-Output $inputObject | Receive-Http $Output $Path } # else they'd better pass it in on the pipeline ... } PROCESS { $response = $null if($_ -is [MindTouch.Dream.Result``1[[MindTouch.Dream.DreamMessage]]]) { $response = $_.Wait() } elseif($_ -is [MindTouch.Dream.DreamMessage]) { $response = $_ } elseif($_) { throw "We can only pipeline [MindTouch.Dream.DreamMessage] objects, or [MindTouch.Dream.Result`1[DreamMessage]] objects" } if($response) { Write-Debug $($response | Out-String) if(!$response.IsSuccessful) { Write-Error $($response | Out-String) Write-Verbose $response.AsText() throw "ERROR: '$($response.Status)' Response Status." } else { switch($Output) { "File" { ## Joel's magic filename guesser ... if(!$Path) { [string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $response.Headers["Content-Disposition"] ).Groups[1].Value $Path = $fileName.trim("\\/""'") if(!$Path){ if($response.ResponseUri) { $fileName = $response.ResponseUri.Segments[-1] $Path = $fileName.trim("\\/") if(!([IO.FileInfo]$Path).Extension) { $Path = $Path + "." + $response.ContentType.Split(";")[0].Split("/")[1] } } } } if($Path) { $File = Get-FileName $Path } else { $File = Get-FileName } $null = [StreamUtil]::CopyToFile( $response.AsStream(), $response.ContentLength, $File ) Get-ChildItem $File } "XDoc" { if($Path) { $response.AsDocument()[$Path] } else { $response.AsDocument()#.ToXml() } } "Xml" { if($Path) { $response.AsDocument().ToXml().SelectNodes($Path) } else { $response.AsDocument().ToXml() } } "Text" { if($Path) { $response.AsDocument()[$Path] | % { $_.AsInnerText } } else { $response.AsText() } } "Bytes" { $response.AsBytes() } } } } } } ## http`://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html ## Nobody actually uses HEAD or OPTIONS, right? ## And nobody's even heard of TRACE or CONNECT ;) # CMDLET Invoke-Http { Function Invoke-Http { [CmdletBinding(DefaultParameterSetName="ByPath")] PARAM( [Parameter(Position=0, Mandatory=$false)] [ValidateSet("POST", "GET", "PUT", "DELETE", "HEAD", "OPTIONS")] ## There are other verbs, but we need a list to make sure you don't screw up [string]$Verb = "GET" , [Parameter(Position=1, Mandatory=$true, ValueFromPipeline=$false, ParameterSetName="WithPlug")] [MindTouch.Dream.Plug] $Plug , [Parameter(Position=1, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="ByPath")] [string] $Path , [Parameter(Position=2, Mandatory=$false, ParameterSetName="ByPath")] [hashtable]$With , [Parameter(Position=3, Mandatory=$false, ParameterSetName="ByPath")] [hashtable]$Headers , [Parameter(Mandatory=$false)] $Content , [Parameter(Mandatory=$false)] $Cookies , [Parameter(Mandatory=$false)] $Type # Of Content , [Parameter(Mandatory=$false)] [switch]$authenticate , [Parameter(Mandatory=$false)] $credentials , [Parameter(Mandatory=$false)] [switch]$Persistent ## Note this ALSO causes WaitForResponse , [switch]$waitForResponse ) PROCESS { if(!$Plug){ #$PSCmdlet.ParameterSetName -eq $ByPath) { $Plug = Get-DreamPlug $Path $With $Headers } ## Special Handling for FORM_URLENCODED if($Type -like "Form*" -and !$Content) { $dream = [MindTouch.Dream.DreamMessage]::Ok( $Plug.Uri ) $Plug = [MindTouch.Dream.Plug]::New( $Plug.Uri.SchemeHostPortPath ) Write-Verbose "RECREATED Plug: $($Plug.Uri.SchemeHostPortPath)" } else { $dream = Get-DreamMessage $Content $Type Write-Verbose "Created Dream with Content: $($dream.AsText() |out-String)" } if(!$plug -or !$dream) { throw "Can't come up with a request!" } if($Persistent -and $global:HttpRestCookies) { $dream.Cookies.Add( $global:HttpRestCookies ) } if($Cookies) { $dream.Cookies.Add( $Cookies ) } if($authenticate -or $credentials){ if($credentials -is [System.Management.Automation.PSCredential]) { Write-Verbose "AUTHENTICATING AS $($credentials.GetNetworkCredential().UserName)" $plug = $plug.WithCredentials($credentials.GetNetworkCredential()) } elseif($credentials -is [System.Net.ICredentials]) { Write-Verbose "AUTHENTICATING AS $($credentials.GetNetworkCredential().UserName)" $plug = $plug.WithCredentials($credentials.GetNetworkCredential()) } else { if($credentials) { Write-Error "Credential must be a PSCredential or a System.Net.ICredentials" } $null = Get-HttpCredential # Make sure they have global credentials Write-Verbose "AUTHENTICATING AS $($global:HttpRestCredential.UserName)" $plug = $plug.WithCredentials($global:HttpRestCredential.GetNetworkCredential()) } } Write-Verbose $plug.Uri ## DEBUG: Write-Debug "URI: $($Plug.Uri)" Write-Debug "Verb: $($Verb.ToUpper())" Write-Debug $($dream | gm | Out-String) $result = $plug.InvokeAsync( $Verb.ToUpper(), $dream ) Write-Debug $($result | Out-String) # if($DebugPreference -eq "Continue") { # Write-Debug $($result.Wait() | Out-String) # } if($waitForResponse -or $Persistent) { $result = $result.Wait() $global:HttpRestCookies = $result.Cookies } write-output $result trap [MindTouch.Dream.DreamResponseException] { Write-Error @" TRAPPED DreamResponseException $($_.Exception.Response | Out-String) $($_.Exception.Response.Headers | Out-String) "@ break; } } } function Get-WebPageContent { [CmdletBinding()] param( [Parameter(Position=0,Mandatory=$true)] [string]$url , [Parameter(Position=1,Mandatory=$false)] [string]$xpath="" , [Parameter(Position=2,Mandatory=$false)] [hashtable]$with=@{} , [Parameter(Mandatory=$false)] [switch]$Persist , [Parameter(Mandatory=$false)] [switch]$Authenticate ) BEGIN { $out = "Text"; if($Xml) { $out="Xml" } } PROCESS { invoke-http get $url $with -Authenticate:$Authenticate -Persist:$Persist | receive-http xml $xpath } } function Get-WebPageText { [CmdletBinding()] param( [Parameter(Position=0,Mandatory=$true)] [string]$url , [Parameter(Position=1,Mandatory=$false)] [string]$xpath="" , [Parameter(Position=2,Mandatory=$false)] [hashtable]$with=@{} , [Parameter(Mandatory=$false)] [switch]$Persist , [Parameter(Mandatory=$false)] [switch]$Authenticate ) BEGIN { $out = "Text"; if($Xml) { $out="Xml" } } PROCESS { invoke-http get $url $with -Authenticate:$Authenticate -Persist:$Persist | receive-http text $xpath } } function Get-WebFile { [CmdletBinding()] param( [Parameter(Position=0,Mandatory=$true)] [string]$url , [Parameter(Position=1,Mandatory=$false)] [string]$path="" , [Parameter(Position=2,Mandatory=$false)] [hashtable]$with=@{} , [Parameter(Mandatory=$false)] [switch]$Persist , [Parameter(Mandatory=$false)] [switch]$Authenticate ) PROCESS { Invoke-Http GET $url $with -Authenticate:$Authenticate -Persist:$Persist | Receive-Http File $path } } new-alias gwpc Get-WebPageContent -EA "SilentlyContinue" new-alias http Invoke-Http -EA "SilentlyContinue" new-alias rcv Receive-Http -EA "SilentlyContinue" # function Get-Http { return Invoke-Http "GET" @args } # function New-Http { return Invoke-Http "PUT" @args } # function Update-Http { return Invoke-Http "POST" @args } # function Remove-Http { return Invoke-Http "DELETE" @args } # new-alias Set-Http Update-Http # new-alias Put-Http New-Http # new-alias Post-Http Update-Http # new-alias Delete-Http Remove-Http function Set-HttpDefaultUrl { PARAM ([uri]$baseUri=$(Read-Host "Please enter the base Uri for your RESTful web-service")) $global:url = $baseUri } function Set-HttpCredential { param($Credential=$(Get-CredentialBetter -Title "Http Authentication Request - $($global:url.Host)" ` -Message "Your login for $($global:url.Host)" ` -Domain $($global:url.Host)) ) if($Credential -is [System.Management.Automation.PSCredential]) { $global:HttpRestCredential = $Credential } elseif($Credential -is [System.Net.NetworkCredential]) { $global:HttpRestCredential = new-object System.Management.Automation.PSCredential $Credential.UserName, $(ConvertTo-SecureString $credential.Password) } } function Get-HttpCredential { if(!$global:url) { Set-HttpDefaultUrl } if(!$global:HttpRestCredential) { Set-HttpCredential } if(!$Secure) { return $global:HttpRestCredential.GetNetworkCredential(); } else { return $global:HttpRestCredential } } # function Authenticate-Http { # PARAM($URL=@("users","authenticate"), $Credential = $(Get-HttpCredential)) # $plug = [MindTouch.Dream.Plug]::New( $global:url ) # $null = $plug.At("users", "authenticate").WithCredentials( $auth.UserName, $auth.Password ).Get() # } function ConvertTo-UrlDoubleEncode { param([string]$text) return [System.Web.HttpUtility]::UrlEncode( [System.Web.HttpUtility]::UrlEncode( $text ) ) } New-Alias Encode-Twice ConvertTo-UrlDoubleEncode function Join-Url ( [uri]$baseUri=$global:url ) { $ofs="/";$BaseUrl = "" if($BaseUri -and $baseUri.AbsoluteUri) { $BaseUrl = "$($baseUri.AbsoluteUri.Trim('/'))/" } return [URI]"$BaseUrl$([string]::join("/",@($args)).TrimStart('/'))" } function ConvertTo-SecureString { Param([string]$input) $result = new-object System.Security.SecureString foreach($c in $input.ToCharArray()) { $result.AppendChar($c) } $result.MakeReadOnly() return $result } ## Unit-Test Get-FileName ## Should return TRUE ## (Get-FileName C:\\Windows\\System32\\Notepad.exe) -eq "C:\\Windows\\System32\\Notepad.exe" -and ## (Get-FileName C:\\Windows\\Notepad.exe C:\\Windows\\System32\\) -eq "C:\\Windows\\System32\\Notepad.exe" -and ## (Get-FileName WaitFor.exe C:\\Windows\\System32\\WaitForIt.exe) -eq "C:\\Windows\\System32\\WaitForIt.exe" -and ## (Get-FileName -Path C:\\Windows\\System32\\WaitForIt.exe) -eq "C:\\Windows\\System32\\WaitForIt.exe" function Get-FileName { param($fileName=$([IO.Path]::GetRandomFileName()), $path) $fileName = $fileName.trim("\\/""'") ## if the $Path has a file name, and it's folder exists: if($Path -and !(Test-Path $Path -Type Container) -and (Test-Path (Split-Path $path) -Type Container)) { $path ## if the $Path is just a folder (and it exists) } elseif($Path -and (Test-Path $path -Type Container)) { $fileName = Split-Path $fileName -leaf Join-Path $path $fileName ## If there's no valid $Path, and the $FileName has a folder... } elseif((Split-Path $fileName) -and (Test-Path (Split-Path $fileName))) { $fileName } else { Join-Path (Get-Location -PSProvider "FileSystem") (Split-Path $fileName -Leaf) } } function Get-UtcTime { Param($Format="yyyyMMddhhmmss") [DateTime]::Now.ToUniversalTime().ToString($Format) } ## Get-CredentialBetter ## An improvement over the default cmdlet which has no options ... ################################################################################################### ## History ## v 1.2 Refactor ShellIds key out to a variable, and wrap lines a bit ## v 1.1 Add -Console switch and set registry values accordingly (ouch) ## v 1.0 Add Title, Message, Domain, and UserName options to the Get-Credential cmdlet ################################################################################################### function Get-CredentialBetter{ PARAM([string]$UserName, [string]$Title, [string]$Message, [string]$Domain, [switch]$Console) $ShellIdKey = "HKLM:\\SOFTWARE\\Microsoft\\PowerShell\\1\\ShellIds" ## Carefully EA=SilentlyContinue because by default it's MISSING, not $False $cp = (Get-ItemProperty $ShellIdKey ConsolePrompting -ea "SilentlyContinue") ## Compare to $True, because by default it's $null ... $cp = $cp.ConsolePrompting -eq $True if($Console -and !$cp) { Set-ItemProperty $ShellIdKey ConsolePrompting $True } elseif(!$Console -and $Console.IsPresent -and $cp) { Set-ItemProperty $ShellIdKey ConsolePrompting $False } ## Now call the Host.UI method ... if they don't have one, we'll die, yay. $Host.UI.PromptForCredential($Title,$Message,$UserName,$Domain,"Generic","Default") ## BoyScouts: Leave everything better than you found it (I'm tempted to leave it = True) Set-ItemProperty $ShellIdKey ConsolePrompting $cp -ea "SilentlyContinue" } Export-ModuleMember -Function * -Alias * # Export-ModuleMember Invoke-Http, Receive-Http, Set-HttpCredential, Set-HttpDefaultUrl # SIG # Begin signature block # MIILCQYJKoZIhvcNAQcCoIIK+jCCCvYCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR # AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUaAKbQvIL86hvpi4AVRDIFI7Z # cKagggbgMIIG3DCCBMSgAwIBAgIJALPpqDj9wp7xMA0GCSqGSIb3DQEBBQUAMIHj # MQswCQYDVQQGEwJVUzERMA8GA1UECBMITmV3IFlvcmsxEjAQBgNVBAcTCVJvY2hl # c3RlcjEhMB8GA1UEChMYaHR0cDovL0h1ZGRsZWRNYXNzZXMub3JnMSgwJgYDVQQL # Ex9TY3JpcHRpbmcgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MTcwNQYDVQQDEy5odHRw # Oi8vSHVkZGxlZE1hc3Nlcy5vcmcgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MScwJQYJ # KoZIhvcNAQkBFhhKYXlrdWxASHVkZGxlZE1hc3Nlcy5vcmcwHhcNMDkwMzE1MTkx # OTE5WhcNMTAwMzE1MTkxOTE5WjCBqzELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5l # dyBZb3JrMRIwEAYDVQQHEwlSb2NoZXN0ZXIxITAfBgNVBAoTGGh0dHA6Ly9IdWRk # bGVkTWFzc2VzLm9yZzESMBAGA1UECxMJU2NyaXB0aW5nMRUwEwYDVQQDEwxKb2Vs # IEJlbm5ldHQxJzAlBgkqhkiG9w0BCQEWGEpheWt1bEBIdWRkbGVkTWFzc2VzLm9y # ZzCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAPfqxOG9TQN+qZjZ6KfM # +zBK0YpjeyPL/cFgiGBhiIdYWTBtkbZydFr3IiERKRsUJ0/SKFbhf0C3Bvd/neTJ # qiZjH4D6xkrfdLlWMmmSXXqjSt48jZp+zfCAIaF8K84e9//7lMicdVFE6VcgoATZ # /eMKQky4JvphJpzDHYPLxLJQrKd0pjDDwspjdX5RedWkzeZBG7VfBnebLWUzgnMX # IxRQKfFCMryQDP8weceOnJjfJEf2FYmdpsEg5EKKKbuHsQCMVTxfteKdPvh1oh05 # 1GWyPsvEPh4auJUT8pAVvrdxq+/O9KW/UV01UxjRYM1vdklNw8g7mkJTrrHjSjl7 # tuugCnJjt5kN6v/OaUtRRMR68O85bSTVGOxJGCHUKlyuuTx9tnfIgy4siFYX1Ve8 # xwaAdN3haTon3UkWzncHOq3reCIVF0luwRZu7u+TnOAnz2BRlt+rcT0O73GN20Fx # gyN2f5VGBbw1KuS7T8XZ0TFCspUdgwAcmTGuEVJKGhVcGAvNlLx+KPc5dba4qEfs # VZ0MssC2rALC1z61qWuucb5psHYhuD2tw1SrztywuxihIirZD+1+yKE4LsjkM1zG # fQwDO/DQJwkdByjfB2I64p6mk36OlZAFxVfRBpXSCzdzbgKpuPsbtjkb5lGvKjE1 # JFVls1SHLJ9q80jHz6yW7juBAgMBAAGjgcgwgcUwHQYDVR0OBBYEFO0wLZyg+qGH # Z4WO8ucEGNIdU1T9MB8GA1UdIwQYMBaAFN2N42ZweJLF1mz0j70TMxePMcUHMAkG # A1UdEwQCMAAwEQYJYIZIAYb4QgEBBAQDAgTwMCoGA1UdJQEB/wQgMB4GCCsGAQUF # BwMBBggrBgEFBQcDAgYIKwYBBQUHAwMwCwYDVR0PBAQDAgTwMCwGCWCGSAGG+EIB # DQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTANBgkqhkiG9w0BAQUF # AAOCAgEAmKihxd6KYamLG0YLvs/unUTVJ+NW3jZP16R28PpmidY/kaBFOPhYyMl2 # bBGQABe7LA5rpHFAs0F56gYETNoFk0qREVvaoz9u18VfLb0Uwqtnq0P68L4c7p2q # V3nKmWjeI6H7BAyFuogxmMH5TGDfiqrrVSuh1LtPbkV2Wtto0SAxP0Ndyts2J8Ha # vu/2rt0Ic5AkyD+RblFPtzkCC/MLVwSNAiDSKGRPRrLaiGxntEzR59GRyf2vwhGg # oAXUqcJ/CVeHCP6qdSTM39Ut3RmMZHXz5qY8bvLgNYL6MtcJAx+EeUhW497alzm1 # jInXdbikIh0d/peTSDyLbjS8CPFFtS6Z56TDGMf+ouTpEA16otcWIPA8Zfjq+7n7 # iBHjeuy7ONoJ2VDNgqn9B+ft8UWRwnJbyB85T83OAGf4vyhCPz3Kg8kWxY30Bhnp # Fayc6zQKCpn5o5T0/a0BBHwAyMfr7Lhav+61GpzzG1KfAw58N2GV8KCPKNEd3Zdz # y07aJadroVkW5R+35mSafKRJp5pz20GDRwZQllqGH1Y/UJFEiI0Bme9ecbl2vzNp # JjHyl/jLVzNVrBI5Zwb0lCLsykApgNY0yrwEqaiqwcxq5nkXFDhDPQvbdulihSo0 # u33fJreCm2fFyGbTuvR61goSksAvLQhvijLAzcKqWKG+laOtYpAxggOTMIIDjwIB # ATCB8TCB4zELMAkGA1UEBhMCVVMxETAPBgNVBAgTCE5ldyBZb3JrMRIwEAYDVQQH # EwlSb2NoZXN0ZXIxITAfBgNVBAoTGGh0dHA6Ly9IdWRkbGVkTWFzc2VzLm9yZzEo # MCYGA1UECxMfU2NyaXB0aW5nIENlcnRpZmljYXRlIEF1dGhvcml0eTE3MDUGA1UE # AxMuaHR0cDovL0h1ZGRsZWRNYXNzZXMub3JnIENlcnRpZmljYXRlIEF1dGhvcml0 # eTEnMCUGCSqGSIb3DQEJARYYSmF5a3VsQEh1ZGRsZWRNYXNzZXMub3JnAgkAs+mo # OP3CnvEwCQYFKw4DAhoFAKB4MBgGCisGAQQBgjcCAQwxCjAIoAKAAKECgAAwGQYJ # KoZIhvcNAQkDMQwGCisGAQQBgjcCAQQwHAYKKwYBBAGCNwIBCzEOMAwGCisGAQQB # gjcCARUwIwYJKoZIhvcNAQkEMRYEFIkZIwG8zpBkI/XtpIHDMXpbi0kcMA0GCSqG # SIb3DQEBAQUABIICAMZvVmo7gkXm4VzZsE0mPzEWV27Z5f116glbefnNS/23HK+t # S5am6TjriqlJ+ge5c6WcjcwSdsljoZGkkr2iSj7m03Xir0Y57/v6JWYAk1uX+0ec # wv8L4ww0bTGK5xbTkkmcH11JEh6aXlDmMIh0e7fj/pjjU+rxNiajxsZ6iVqp0i2J # tbjU+dj8wcyolt8qhQBLRGreZ8O3z8+UYPvTrcg5mTOtlZlhpgjPuVmlvZDOaNSx # zBv8oBZWHplknQfz6ZoSG79wilRWT1Yh7k/jSK8jFrEuziSZ3F1fgWAbOrho+0LK # 6dB6u2P38Ybx2P2b8zStVP4dBU8q3zEiRHTMqPUCcsAgCj0Xxzw4Ai3MJn3qYTzU # xsK66xmhWEPh3x94Tzoa6YHY6Su22JdfGYbBzZKY4iHHA16UJ1S3DUXbjK98wGmM # /QWZFkgme0A6Q9Ish7tkj3Xykr+JFMmLF87EIZuiQK8TseOr+N8hpDsIKe2dv/9M # YSyGP5kb4WipBLUhyA6j8j/LWAZIUDYeQTrVCwWv2uFdFCLY2MvdMWx0CXE7FSLg # H/ZC8Vr2fWjpYW7qQCbAnsj06NfhWQtnGwyItcOAlI31hDWYykfhgk3PYEybdEX3 # Xg1a9rQt6r/P3h6fx7U3kP3hnbSfLLpE9FEnWlX61ovKC3tqxqqAGW2C3AaC # SIG # End signature block
PowerShellCorpus/PoshCode/Hash Checker On One Line.ps1
Hash Checker On One Line.ps1
# to make it readable, I've wrapped the lines, but you can remove all the line breaks: &{ PARAM($FileName,$HashFileName) ((Get-Content $HashFileName) -match $FileName)[0].split(" ")[0] -eq [string]::Join("", ( [Security.Cryptography.HashAlgorithm]::Create( ([IO.Path]::GetExtension($HashFileName).Substring(1).ToUpper()) ).ComputeHash( [IO.File]::ReadAllBytes( (Convert-Path $FileName) ) ) | ForEach { "{0:x2}" -f $_ })) @@# Note that the last line here includes the PARAMETERS: FileName and HashFileName } npp.5.3.1.Installer.exe npp.5.3.1.release.md5
PowerShellCorpus/PoshCode/List AddRemovePrograms.ps1
List AddRemovePrograms.ps1
if(!(gwmi -list Win32_AddRemovePrograms)) { set-content $pwd\\RegProgs.mof @' #pragma namespace("\\\\\\\\.\\\\root\\\\cimv2") instance of __Win32Provider as $Instprov { Name ="RegProv" ; ClsID = "{fe9af5c0-d3b6-11ce-a5b6-00aa00680c3f}" ; }; instance of __InstanceProviderRegistration { Provider =$InstProv; SupportsPut =TRUE; SupportsGet =TRUE; SupportsDelete =FALSE; SupportsEnumeration = TRUE; }; [dynamic, provider("RegProv"), ProviderClsid("{fe9af5c0-d3b6-11ce-a5b6-00aa00680c3f}"), ClassContext("local|HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall")] class Win32_AddRemovePrograms { [key] string ProdID; [PropertyContext("DisplayName")] string DisplayName; [PropertyContext("Publisher")] string Publisher; [PropertyContext("DisplayVersion")] string Version; [PropertyContext("UninstallString")] string UninstallString; [PropertyContext("EstimatedSize")] string EstimatedSizeKb; [PropertyContext("InstallDate")] string InstallDate; }; '@ #if((gwmi Win32_OperatingSystem -Property OSArchitecture).OSArchitecture -eq '64-bit') { #if([intptr]::size -eq 8) { if( test-path HKLM:\\SOFTWARE\\Wow6432Node ) { add-content $pwd\\RegProgs.mof @' [dynamic, provider("RegProv"), ProviderClsid("{fe9af5c0-d3b6-11ce-a5b6-00aa00680c3f}"), ClassContext("local|HKEY_LOCAL_MACHINE\\\\SOFTWARE\\\\Wow6432Node\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Uninstall")] class Win32_AddRemovePrograms32 { [key] string ProdID; [PropertyContext("DisplayName")] string DisplayName; [PropertyContext("Publisher")] string Publisher; [PropertyContext("DisplayVersion")] string Version; [PropertyContext("UninstallString")] string UninstallString; [PropertyContext("EstimatedSize")] string EstimatedSizeKb; [PropertyContext("InstallDate")] string InstallDate; }; '@ } Write-Warning "MOF compiler will be RunAs Administrator ..." if( (new-object Security.Principal.WindowsPrincipal ([Security.Principal.WindowsIdentity]::GetCurrent()) ).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) ) { mofcomp.exe $pwd\\RegProgs.mof } else { (start-process mofcomp.exe -verb runas -Args "$pwd\\RegProgs.mof" -Passthru).WaitForExit() # -class:forceupdate } } ## EXAMPLE: ## List installed 64 bit applications with ".NET" in the name (or 32bit on Windows 32bit) Get-WmiObject Win32_AddRemovePrograms -filter "DisplayName like '%.NET%'" | Sort-Object DisplayName | Format-Table DisplayName, Version if( test-path HKLM:\\SOFTWARE\\Wow6432Node ) { ## List installed 32 bit applications with ".NET" in the name (or nothing on Windows 32bit) Get-WmiObject Win32_AddRemovePrograms32 -filter "DisplayName like '%.NET%'" | Sort-Object DisplayName | Format-Table DisplayName, Version } ## NOTE: the alternative is a registry query which is much longer and more typing ... Get-ItemProperty HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* DisplayName,Publisher,DisplayVersion,UninstallString,EstimatedSize,InstallDate -ea 0 | Where-Object { $_.DisplayName -like "*.Net*" } | Sort-Object DisplayName | Format-Table DisplayName, DisplayVersion, EstimatedSize -AutoSize ## And which performs miserably, by comparison: # Duration Command # -------- ------- # 0.23302s Get-WmiObject Win32_AddRemovePrograms32 -filter ... # 1.04610s Get-ItemProperty HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* ...
PowerShellCorpus/PoshCode/Find-String.ps1
Find-String.ps1
## Find-String.ps1\n########################################################################################################################\n## Find-String is basically a PowerShell 1.0 wrapper around { select-string } which will append the "Matches" to it\n## Highlight-Matches takes a collections of MatchInfo objects and prints them out, highlighting the actual match.\n## \n## Based on:\n## http://weblogs.asp.net/whaggard/archive/2007/03/23/powershell-script-to-find-strings-and-highlight-them-in-the-output.aspx\n##\n## It should be noted that this DOES NOT return objects on the pipeline unless you specify -passthru\n## If you do specify passthru, it will Add the "Matches" property to the MatchInfo objects, \n## making them more like ## the 2.0 MatchInfo object.\n########################################################################################################################\nfunction Find-String {\nPARAM( [regex] $pattern = $(Read-Host "Regular expression search pattern")\n , [string] $filter = "*.*"\n , [switch] $recurse\n , [switch] $caseSensitive\n , [switch] $summary\n)\n\n$v2 = [bool](new-object Microsoft.PowerShell.Commands.MatchInfo | gm "Matches")\n\nif ($pattern.ToString() -eq "") { throw "Nothing to search for! Please provide a search pattern!" }\n\nif( (-not $caseSensitive) -and (-not $pattern.Options -match "IgnoreCase") ) {\n $pattern = New-Object regex $pattern.ToString(),@($pattern.Options,"IgnoreCase")\n}\n\nif($summary) {\n [string[]] $summaryText = ""\n $summaryText += "Matches Lines FileName"\n $summaryText += "------- ----- --------"\n\n $totalCount = 0; $totalLines = 0;\n}\n# Do the actual find in the files\nGet-ChildItem -recurse:$recurse -filter:$filter |\n foreach { \n if($summary) {\n $fileCount = 0; $lineCount = 0;\n }\n if($v2) {\n $select = "Select-String -input `$_ -caseSensitive:`$caseSensitive -pattern:`$pattern -AllMatches"\n } else {\n $select = "Select-String -input `$_ -caseSensitive:`$caseSensitive -pattern:`$pattern"\n } \n \n iex $select | foreach {\n if(!$v2) {\n Add-Member -Input $_ -MemberType NoteProperty -Name "Matches" -Value $pattern.Matches($_.Line) -ErrorAction SilentlyContinue\n }\n\n Write-Output $_\n \n if($summary) {\n $lineCount++\n $fileCount += $_.Matches.Count\n }\n }\n if($summary) {\n $totalCount += $fileCount;\n $totalLines += $lineCount;\n if( $fileCount -gt 0) {\n $summaryText += "{0,7} {1,5} {2}" -f $fileCount, $lineCount, $_\n }\n }\n }\nif($summary) {\n $summaryText += "------- ----- -----"\n $summaryText += "{0,7} {1,5} TOTALS" -f $totalCount, $totalLines\n $summaryText += ""\n $summaryText | Out-Host\n}\n\n}\n\n# Write the line with the pattern highlighted in red\nfunction Highlight-Matches\n{\n PARAM ([Microsoft.PowerShell.Commands.MatchInfo[]]$match, [Switch]$Passthru)\n BEGIN {\n if($match) { \n $match | Write-Host-HighlightMatches\n }\n }\n PROCESS { \n if($_ -and ($_ -isnot [Microsoft.PowerShell.Commands.MatchInfo])) {\n throw "Expected Microsoft.PowerShell.Commands.MatchInfo objects on the pipeline"\n } elseif($_) {\n Write-Host ("{0} {1,5} {2,3}: " -f $_.FileName, "($($_.LineNumber))", $_.matches.Count) -nonewline\n $index = 0;\n foreach($match in $_.Matches) {\n Write-Host $_.line.SubString($index, $match.Index - $index) -nonewline\n Write-Host $match.Value -ForegroundColor Red -nonewline\n $index = $match.Index + $match.Length\n }\n if($index -lt $_.line.Length) {\n Write-Host $_.line.SubString($index) -nonewline\n }\n Write-Host\n \n if($Passthru) { $_ }\n }\n }\n}\n
PowerShellCorpus/PoshCode/Connect-AccessDB.ps1
Connect-AccessDB.ps1
# Functions for connecting to and working with Access databases # Matt Wilson # May 2009 function Connect-AccessDB ($global:dbFilePath) { # Test to ensure valid path to database file was supplied if (-not (Test-Path $dbFilePath)) { Write-Error "Invalid Access database path specified. Please supply full absolute path to database file!" } # TO-DO: Add check to ensure file is either MDB or ACCDB # Create a new ADO DB connection COM object, which will give us useful methods & properties such as "Execute"! $global:AccessConnection = New-Object -ComObject ADODB.Connection # Actually open the database so we can start working with its contents # Access 00-03 (MDB) format has a different connection string than 2007 if ((Split-Path $dbFilePath -Leaf) -match [regex]"\\.mdb$") { Write-Host "Access 2000-2003 format (MDB) detected! Using Microsoft.Jet.OLEDB.4.0." $AccessConnection.Open("Provider = Microsoft.Jet.OLEDB.4.0; Data Source= $dbFilePath") } # Here's the check for if 2007 connection is necessary if ((Split-Path $dbFilePath -Leaf) -match [regex]"\\.accdb$") { Write-Host "Access 2007 format (ACCDB) detected! Using Microsoft.Ace.OLEDB.12.0." $AccessConnection.Open("Provider = Microsoft.Ace.OLEDB.12.0; Persist Security Info = False; Data Source= $dbFilePath") } } function Open-AccessRecordSet ($global:SqlQuery) { # Ensure SQL query isn't null if ($SqlQuery.length -lt 1) { Throw "Please supply a SQL query for the recordset selection!" } # Variables used for the connection itself. Leave alone unless you know what you're doing. $adOpenStatic = 3 $adLockOptimistic = 3 # Create the recordset object using the ADO DB COM object $global:AccessRecordSet = New-Object -ComObject ADODB.Recordset # Finally, go and get some records from the DB! $AccessRecordSet.Open($SqlQuery, $AccessConnection, $adOpenStatic, $adLockOptimistic) } function Get-AccessRecordSetStructure { # TO-DO: Should probably test to ensure valid $accessRecordSet exists & has records # Cycle through the fields in the recordset, but only pull out the properties we care about Write-Output $AccessRecordSet.Fields | Select-Object Name,Attributes,DefinedSize,type } function Convert-AccessRecordSetToPSObject { # TO-DO: Should probably test to ensure valid $accessRecordSet exists & has records # Get an array of field names which we will later use to create custom PoSh object names $fields = Get-AccessRecordSetStructure # Move to the very first record in the RecordSet before cycling through each one $AccessRecordSet.MoveFirst() # Cycle through each RECORD in the set and create that record to an object do { # Create a SINGLE blank object we can use in a minute to add properties/values to $record = New-Object System.Object # For every FIELD in the DB, lookup the CURRENT value of that field and add a new PoSh object property with that name and value foreach ($field in $fields) { $fieldName = $field.Name # This makes working with the name a LOT easier in Write-Host, etc. #Write-Host "Working with field: $fieldName" #Write-Host "Preparing to set value to: $($AccessRecordset.Fields.Item($fieldName).Value)" $record | Add-Member -type NoteProperty -name $fieldName -value $AccessRecordSet.Fields.Item($fieldName).Value } # Output the custom object we just created Write-Output $record # Tell the recordset to advance forward one before doing this again with another object $AccessRecordset.MoveNext() } until ($AccessRecordset.EOF -eq $True) } function Execute-AccessSQLStatement ($query) { $AccessConnection.Execute($query) } function Convert-AccessTypeCode ([string]$typeCode) { # Build some lookup tables for our Access type codes so we can convert values pretty easily $labelLookupHash = @{"AutoNumber"="3"; "Text"="202"; "Memo"="203"; "Date/Time"="7"; "Currency"="6"; "Yes/No"="11"; "OLE Object"="205"; "Byte"="17"; "Integer"="2"; "Long Integer"="3"; "Single"="4"; "Double"="5"} $codeLookupHash = @{"3"="AutoNumber"; "202"="Text"; "203"="Memo"; "7"="Date/Time"; "6"="Currency"; "11"="Yes/No"; "205"="OLE Object"; "17"="Byte"; "2"="Integer"; "3"="Long Integer"; "4"="Single"; "5"="Double"} # Convert a value depending on what type of data was supplied if ($typeCode -match [regex]"^\\d{1,3}$") { $valueFound = $codeLookupHash.$typeCode if ($valueFound) { Write-Output $valueFound } else { Write-Output "Unknown" } } else { $valueFound = $labelLookupHash.$typeCode if ($valueFound) { Write-Output $valueFound } else { Write-Output "Unknown" } } } function Close-AccessRecordSet { $AccessRecordSet.Close() } function Disconnect-AccessDB { $AccessConnection.Close() } # Connect-AccessDB "C:\\fso\\ConfigurationMaintenance.accdb" # Open-AccessRecordSet "SELECT * FROM printers" # $printersDB = Convert-AccessRecordSetToPSObject | Select-Object caption,driverName | Format-Table -AutoSize; $printersDB # Close-AccessRecordSet # Disconnect-AccessDB
PowerShellCorpus/PoshCode/1bcb760e-1da1-47f8-9433-4a6a544b6c98.ps1
1bcb760e-1da1-47f8-9433-4a6a544b6c98.ps1
/* * Schreiben sie ein Programm,dass ihnen für eine bestimmte Stelle, * die zugehörige Fibonacci Zahl ausgibt. */ package fibonacci; /* * @author Tobias Günther */ public class Fibonacci { public static void main(String[] args) { int fragestelle = 9; //Gefragte Stelle int result = fibo(fragestelle); //Übergeben der Variable System.out.println(result); //Ergebnisausgabe } public static int fibo(int fragestelle) { int result; //Definiton der Variable für das Ergebnis if (fragestelle == 2) { //Sonderfall: 2=1 return 1; } else if (fragestelle == 1) { //Sonderfall: 1=1 return 1; } else { result = fibo(fragestelle - 1) + fibo(fragestelle - 2); // fib(n)=(fib(n-1)+(fibn-2) [2vorherigen StellenAddieren] } return result; } }
PowerShellCorpus/PoshCode/Search-Help.ps1
Search-Help.ps1
##############################################################################\n##\n## Search-Help\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\nSearch the PowerShell help documentation for a given keyword or regular\nexpression.\n\n.EXAMPLE\n\nSearch-Help hashtable\nSearches help for the term 'hashtable'\n\n.EXAMPLE\n\nSearch-Help "(datetime|ticks)"\nSearches help for the term datetime or ticks, using the regular expression\nsyntax.\n\n#>\n\nparam(\n ## The pattern to search for\n [Parameter(Mandatory = $true)]\n $Pattern\n)\n\nSet-StrictMode -Version Latest\n\n$helpNames = $(Get-Help * | Where-Object { $_.Category -ne "Alias" })\n\n## Go through all of the help topics\nforeach($helpTopic in $helpNames)\n{\n ## Get their text content, and\n $content = Get-Help -Full $helpTopic.Name | Out-String\n if($content -match "(.{0,30}$pattern.{0,30})")\n {\n $helpTopic | Add-Member NoteProperty Match $matches[0].Trim()\n $helpTopic | Select-Object Name,Match\n }\n}
PowerShellCorpus/PoshCode/Get-SQLSaturdaySessions.ps1
Get-SQLSaturdaySessions.ps1
function Get-SQLSaturdaySessionList { param( [string] $Number = "111", $GetUnscheduled ) $baseUrl = "http://sqlsaturday.com/" + $Number $url = $baseUrl + "/schedule.aspx" $page = $null try { Write-Verbose "Initiating WebClient" $webclient = New-Object system.net.webclient Write-Verbose "Attempting to download from $url" $page = $webclient.DownloadString($url) } catch [Exception] { Write-Error ("Could not download {0}. The following error was logged:`r`n{1}" -f $url, $error[0]) } # We only want to continue if something was downloaded if ($page) { Write-Verbose "Page downloaded" if(!$GetUnscheduled){ Write-Verbose "Getting Scheduled" #<td><a href="/viewsession.aspx?sat=94&amp;sessionid=5471">Randy Knight<br><br>But it worked great in Dev! Performance for Devs<br><br>Level: Beginner</a></td> #<td><a href="/viewsession.aspx?sat=89&sessionid=4942">Adam Jorgensen<br /><br />Zero to Cube<br/ ><br />Level: Intermediate</a></td> $regex = [regex]'href="(?<url>/viewsession.aspx\\?sat=\\d+\\&(?:amp;)?sessionid=\\d+)">\\s*(?<speaker>[^<]+)<br\\s*/?\\s*><br\\s*/?\\s*>(?<title>[^<]+)<br\\s*/?\\s*><br\\s*/?\\s*>Level:\\s*(?<level>[^<]+)</a>' } else{ Write-Verbose "Getting Unscheduled" $regex = [regex]'href="(?<url>/viewsession.aspx\\?sat=\\d+\\&(?:amp;)?sessionid=\\d+)">\\s*(?<title>[^<]+)</a></td><td>(?<speaker>[^<]+)</td><td>(?<level>[^<]+)</td>' } $matches = $regex.Matches($page) Write-Verbose "Match Count: $($matches.count)" $table = New-Object system.Data.DataTable "MyTable" $col = New-Object system.Data.DataColumn Title,([string]) $table.columns.add($col) $col = New-Object system.Data.DataColumn Speaker,([string]) $table.columns.add($col) $col = New-Object system.Data.DataColumn Level,([string]) $table.columns.add($col) $col = New-Object system.Data.DataColumn URL,([string]) $table.columns.add($col) $matches | % {$row = $table.NewRow(); $row.URL = $baseUrl + $_.Groups['url']; $row.Title = $_.Groups['title']; $row.Speaker = $_.Groups['speaker'] -replace '[\\s\\.,]+',' '; $row.Level = $_.Groups['level']; $table.Rows.Add($row) } $table } } $num = $args[0] if($num){ if($args.length -eq 1){ Get-SQLSaturdaySessionList -Number $num | Group-Object -Property Speaker } else{ Get-SQLSaturdaySessionList -Number $num -GetUnscheduled "Whee Unscheduled!" | Group-Object -Property Speaker } } else{ Write-Host "Please include an event number: $($MyInvocation.InvocationName) 89" } #Get-SQLSaturdaySessionList -Number 111 -GetUnscheduled "YesPlease" | Sort-Object -Property Speaker | Group-Object -Property Speaker #Get-SQLSaturdaySessionList -Number 111 -GetUnscheduled "YesPlease" | Sort-Object -Property Speaker | Group-Object -Property Level #Get-SQLSaturdaySessionList -Number 111 | Sort-Object -Property Speaker | Group-Object -Property Speaker; #Get-SQLSaturdaySessionList -Number 111 | Sort-Object -Property Speaker | Group-Object -Property Speaker | measure
PowerShellCorpus/PoshCode/PowerShell Talk Xen1.ps1
PowerShell Talk Xen1.ps1
#The PowerShell Talk #Demo 1 - Hypervisors #Xen! #Connect to XenServer Get-Credential | connect-Xenserver -Url http://XenServer_URL/sdk #Create Our Network Create-XenServer:Network -NameLabel "Test Network" #Change it's description Get-XenServer:Network -NameFilter "Test Network" | Set-XenServer:Network.NameDescription "This is the test network for the XenServer Demo" #Destroy it Get-XenServer:Network -NameFilter "Test Network" | Destroy-XenServer:Network
PowerShellCorpus/PoshCode/g.ps1
g.ps1
function Get-User($user) { $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/Test-Server.ps1
Test-Server.ps1
Function Test-Server{ [cmdletBinding()] param( [parameter(Mandatory=$true,ValueFromPipeline=$true)] [string[]]$ComputerName, [parameter(Mandatory=$false)] [switch]$CredSSP, [Management.Automation.PSCredential] $Credential) begin{ $total = Get-Date $results = @() if($credssp){if(!($credential)){Write-Host "must supply Credentials with CredSSP test";break}} } process{ foreach($name in $computername) { $dt = $cdt= Get-Date Write-verbose "Testing: $Name" $failed = 0 try{ $DNSEntity = [Net.Dns]::GetHostEntry($name) $domain = ($DNSEntity.hostname).replace("$name.","") $ips = $DNSEntity.AddressList | %{$_.IPAddressToString} } catch { $rst = "" | select Name,IP,Domain,Ping,WSMAN,CredSSP,RemoteReg,RPC,RDP $rst.name = $name $results += $rst $failed = 1 } Write-verbose "DNS: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)" if($failed -eq 0){ foreach($ip in $ips) { $rst = "" | select Name,IP,Domain,Ping,WSMAN,CredSSP,RemoteReg,RPC,RDP $rst.name = $name $rst.ip = $ip $rst.domain = $domain ####RDP Check (firewall may block rest so do before ping try{ $socket = New-Object Net.Sockets.TcpClient($name, 3389) if($socket -eq $null) { $rst.RDP = $false } else { $rst.RDP = $true $socket.close() } } catch { $rst.RDP = $false } Write-verbose "RDP: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)" #########ping if(test-connection $ip -count 1 -Quiet) { Write-verbose "PING: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)" $rst.ping = $true try{############wsman Test-WSMan $ip | Out-Null $rst.WSMAN = $true } catch {$rst.WSMAN = $false} Write-verbose "WSMAN: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)" if($rst.WSMAN -and $credssp) ########### credssp { try{ Test-WSMan $ip -Authentication Credssp -Credential $cred $rst.CredSSP = $true } catch {$rst.CredSSP = $false} Write-verbose "CredSSP: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)" } try ########remote reg { [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, $ip) | Out-Null $rst.remotereg = $true } catch {$rst.remotereg = $false} Write-verbose "remote reg: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)" try ######### wmi { $w = [wmi] '' $w.psbase.options.timeout = 15000000 $w.path = "\\\\$Name\\root\\cimv2:Win32_ComputerSystem.Name='$Name'" $w | select none | Out-Null $rst.RPC = $true } catch {$rst.rpc = $false} Write-verbose "WMI: $((New-TimeSpan $dt ($dt = get-date)).totalseconds)" } else { $rst.ping = $false $rst.wsman = $false $rst.credssp = $false $rst.remotereg = $false $rst.rpc = $false } $results += $rst }} Write-Verbose "Time for $($Name): $((New-TimeSpan $cdt ($dt)).totalseconds)" Write-Verbose "----------------------------" } } end{ Write-Verbose "Time for all: $((New-TimeSpan $total ($dt)).totalseconds)" Write-Verbose "----------------------------" return $results } }
PowerShellCorpus/PoshCode/SqlProxy_3.psm1.ps1
SqlProxy_3.psm1.ps1
# --------------------------------------------------------------------------- ### <Author> ### Chad Miller ### </Author> ### <Description> ### Based on functions in SQLPSX. SqlProxy.psm1 module is used for administering ### SQL Server logins, users, and roles. Designed to be used with PS Remoting. ### All actions audited to a custom Eventlog. ### See Write-SqlProxyLog for log setup details ### </Description> # --------------------------------------------------------------------------- try {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop} catch {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo"} try {add-type -AssemblyName "Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop; $smoVersion = 10} catch {add-type -AssemblyName "Microsoft.SqlServer.Smo"; $smoVersion = 9} try {add-type -AssemblyName "Microsoft.SqlServer.SqlEnum, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop; $smoVersion = 10} catch {add-type -AssemblyName "Microsoft.SqlServer.SqlEnum"; $smoVersion = 9} try { try {add-type -AssemblyName "Microsoft.SqlServer.SMOExtended, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop} catch {add-type -AssemblyName "Microsoft.SqlServer.SMOExtended" -EA Stop} } catch {Write-Warning "SMOExtended not available"} $EventID = @{ "Add-SqlDatabaseRoleMember"=0 "Add-SqlLogin"=1 "Add-SqlServerRoleMember"=2 "Add-SqlUser"=3 "Remove-SqlDatabaseRoleMember"=4 "Remove-SqlLogin"=5 "Remove-SqlServerRoleMember"=6 "Remove-SqlUser"=7 "Rename-SqlLogin"=8 "Set-SqlLogin"=9 "Set-SqlLoginDefaultDatabase"=10 } ####################### <# .SYNOPSIS Gets a ServerConnection. .DESCRIPTION The Get-SqlConnection function gets a ServerConnection to the specified SQL Server. .INPUTS None You cannot pipe objects to Get-SqlConnection .OUTPUTS Microsoft.SqlServer.Management.Common.ServerConnection Get-SqlConnection returns a Microsoft.SqlServer.Management.Common.ServerConnection object. .EXAMPLE Get-SqlConnection "Z002\\sql2K8" This command gets a ServerConnection to SQL Server Z002\\SQL2K8. .EXAMPLE Get-SqlConnection "Z002\\sql2K8" "sa" "Passw0rd" This command gets a ServerConnection to SQL Server Z002\\SQL2K8 using SQL authentication. .LINK Get-SqlConnection #> function Get-SqlConnection { param( [Parameter(Position=0, Mandatory=$true)] [string]$sqlserver, [Parameter(Position=1, Mandatory=$false)] [string]$username, [Parameter(Position=2, Mandatory=$false)] [string]$password ) Write-Verbose "Get-SqlConnection $sqlserver" try { if($Username -and $Password) { $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $sqlserver,$username,$password } else { $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $sqlserver } $con.Connect() Write-Output $con } catch { $message = $_.Exception.GetBaseException().Message write-error $message } } #Get-ServerConnection ####################### <# .SYNOPSIS Gets an SMO Server object. .DESCRIPTION The Get-SqlServer function gets a SMO Server object for the specified SQL Server. .INPUTS None You cannot pipe objects to Get-SqlServer .OUTPUTS Microsoft.SqlServer.Management.Smo.Server Get-SqlServer returns a Microsoft.SqlServer.Management.Smo.Server object. .EXAMPLE Get-SqlServer "Z002\\sql2K8" This command gets an SMO Server object for SQL Server Z002\\SQL2K8. .EXAMPLE Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd" This command gets a SMO Server object for SQL Server Z002\\SQL2K8 using SQL authentication. .LINK Get-SqlServer #> function Get-SqlServer { param( [Parameter(Position=0, Mandatory=$true)] [string]$sqlserver, [Parameter(Position=1, Mandatory=$false)] [string]$username, [Parameter(Position=2, Mandatory=$false)] [string]$password, [Parameter(Position=3, Mandatory=$false)] [string]$StatementTimeout=0 ) #When $sqlserver passed in from the SMO Name property, brackets #are automatically inserted which then need to be removed $sqlserver = $sqlserver -replace "\\[|\\]" Write-Verbose "Get-SqlServer $sqlserver" $con = Get-SqlConnection $sqlserver $Username $Password $server = new-object ("Microsoft.SqlServer.Management.Smo.Server") $con #Some operations might take longer than the default timeout of 600 seconnds (10 minutes). Set new default to unlimited $server.ConnectionContext.StatementTimeout = $StatementTimeout $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.StoredProcedure], "IsSystemObject") $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.Table], "IsSystemObject") $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.View], "IsSystemObject") $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.UserDefinedFunction], "IsSystemObject") #trap { "Check $SqlServer Name"; continue} $server.ConnectionContext.Connect() Write-Output $server } #Get-SqlServer ####################### <# .SYNOPSIS Gets an SMO Database object. .DESCRIPTION The Get-SqlDatabase function gets an SMO Database object for the specified SQL Database or collection of Database objects. .INPUTS None You cannot pipe objects to Get-SqlDatabase .OUTPUTS Microsoft.SqlServer.Management.Smo.Database Get-SqlDatabase returns a Microsoft.SqlServer.Management.Smo.Database object. .EXAMPLE Get-SqlDatabase "Z002\\sql2K8" This command gets a collection of SMO Database objects for SQL Server Z002\\SQL2K8. .EXAMPLE Get-SqlDatabase $(Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd") "pubs" This command gets a SMO Database object for SQL database pubs on the SQL Server Z002\\SQL2K8 using SQL authentication. .LINK Get-SqlDatabase #> function Get-SqlDatabase { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$false)] [string]$dbname, [Parameter(Position=2, Mandatory=$false)] [switch]$force ) switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Get-SqlDatabase:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Get-SqlDatabase $($server.Name) $dbname" if ($dbname) { if ($server.Databases.Contains("$dbname") -and $server.Databases[$dbname].IsAccessible) {$server.Databases[$dbname]} else {throw "Database $dname does not exist or is not accessible."} } elseif ($force) { $server.Databases | where {$_.IsAccessible -eq $true} } #Skip systems databases else { $server.Databases | where {$_.IsSystemObject -eq $false -and $_.IsAccessible -eq $true} } } # Get-SqlDatabase ####################### <# .SYNOPSIS Executes a query and returns an array of System.Data.DataRow. .DESCRIPTION The Get-SqlData function executes a query and returns an array of System.Data.DataRow. .INPUTS None You cannot pipe objects to Get-SqlData .OUTPUTS System.Data.DataRow Get-SqlData returns an array of System.Data.DataRow. .EXAMPLE Get-SqlData "Z002\\sql2K8" "pubs" "select * from authors" This command executes the specified SQL query using Windows authentication. .EXAMPLE $server = Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd" Get-SqlData $server "pubs" "select * from authors" This command executes the specified SQL query using SQL authentication. .LINK Get-SqlData #> function Get-SqlData { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$qry ) switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Get-SqlData:Param '`$dbname' must be a String or Database object." } } #Write-Verbose "Get-SqlData $($database.Parent.Name) $($database.Name) $qry" Write-Verbose "Get-SqlData $($database.Parent.Name) $($database.Name)" $ds = $database.ExecuteWithResults("$qry") $ds.Tables | foreach { $_.Rows} }# Get-SqlData ####################### <# .SYNOPSIS Executes a query that does not return a result set. .DESCRIPTION The Set-SqlData function executes a query that does not return a result set. .INPUTS None You cannot pipe objects to Set-SqlData .OUTPUTS None Set-SqlData does not produce any output. .EXAMPLE Set-SqlData "Z002\\sql2K8" "pubs" "Update authors set au_lname = 'Brown' WHERE au_lname = 'White'" This command executes the specified SQL query using Windows authentication. .EXAMPLE $server = Set-SqlServer "Z002\\sql2K8" "sa" "Passw0rd" Set-SqlData $server "pubs" "Update authors set au_lname = 'Brown' WHERE au_lname = 'White'" This command executes the specified SQL query using SQL authentication. .LINK Set-SqlData #> function Set-SqlData { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$dbname, [Parameter(Position=2, Mandatory=$true)] [string]$qry ) switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Set-SqlData:Param '`$dbname' must be a String or Database object." } } #Write-Verbose "Set-SqlData $($database.Parent.Name) $($database.Name) $qry" Write-Verbose "Set-SqlData $($database.Parent.Name) $($database.Name)" $database.ExecuteNonQuery("$qry") }# Set-SqlData ####################### <# .SYNOPSIS Gets an SMO Login object. .DESCRIPTION The Get-SqlLogin function gets a collection of SMO Login objects for the specified SQL Server. .INPUTS None You cannot pipe objects to Get-SqlLogin .OUTPUTS Microsoft.SqlServer.Management.Smo.Login Get-SqlLogin returns a Microsoft.SqlServer.Management.Smo.Login object. .EXAMPLE Get-SqlLogin "Z002\\sql2K8" This command gets a collection of SMO Login objects for SQL Server Z002\\SQL2K8. .LINK Get-SqlLogin #> function Get-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver ) switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Get-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Get-SqlLogin $($server.Name)" foreach ($login in $server.Logins | where {$_.LoginType.ToString() -ne 'Certificate'}) { #Return Login Object $login } } # Get-SqlLogin ####################### <# .SYNOPSIS Adds a login to a SQL Server. .DESCRIPTION The Add-SqlLogin function adds a new login to the specified SQL server. .INPUTS None You cannot pipe objects to Add-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlLogin "Z002\\sql2k8" "TestPSUnit" "SQLPSXTesting" 'SqlLogin' This command adds the TestPSUnit login to the Z002\\sql2k8 server. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Add-SqlLogin $server "TestPSUnit" "SQLPSXTesting" 'SqlLogin' This command adds the TestPSUnit login to the Z002\\sql2k8 server. .LINK Add-SqlLogin #> function Add-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$false)] [System.Security.SecureString]$password, [Parameter(Position=3, Mandatory=$false)] [Microsoft.SqlServer.Management.Smo.LoginType]$logintype='WindowsUser', [Parameter(Position=4, Mandatory=$false)] [string]$DefaultDatabase='master', [Parameter(Position=5, Mandatory=$false)] [switch]$PasswordExpirationEnabled, [Parameter(Position=6, Mandatory=$false)] [switch]$PasswordPolicyEnforced, [Parameter(Position=7, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=8, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Add-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Add-SqlLogin $($server.Name) $name" $login = new-object ('Microsoft.SqlServer.Management.Smo.Login') $server, $name $login.DefaultDatabase = $defaultDatabase if ($logintype -eq 'SqlLogin') { $login.LoginType = $logintype if ($server.Information.Version.Major -ne '8') { $login.PasswordExpirationEnabled = $($PasswordExpirationEnabled.IsPresent) $login.PasswordPolicyEnforced = $($PasswordPolicyEnforced.IsPresent) } try { $login.Create($password) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } elseif ($logintype -eq 'WindowsUser' -or $logintype -eq 'WindowsGroup') { $login.LoginType = $logintype try { $login.Create() $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | % {"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } } #Add-SqlLogin ####################### <# .SYNOPSIS Removes a login from a SQL Server. .DESCRIPTION The Remove-SqlLogin function removes a login from the specified SQL server. .INPUTS None You cannot pipe objects to Remove-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlLogin "Z002\\sql2k8" "TestPSUnit" This command removes the TestPSUnit login from the Z002\\sql2k8 server. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Remove-SqlLogin $server "TestPSUnit" This command removes the TestPSUnit login from the Z002\\sql2k8 server. .LINK Remove-SqlLogin #> function Remove-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=3, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Remove-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Remove-SqlLogin $($server.Name) $name" $login = Get-SqlLogin $server | where {$_.name -eq $name} try { if ($login) { $login.Drop() $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "Login $name does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Remove-SqlLogin ####################### <# .SYNOPSIS Removes a login from a SQL Server. .DESCRIPTION The Set-SqlLogin function changes a SQL Login Password. .INPUTS None You cannot pipe objects to Set-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE $pwd_secure_string = read-host "Enter a Password:" -assecurestring Set-SqlLogin "Z002\\sql2k8" "TestPSUnit" $pwd_secure_string This command sets the password for TestPSUnit login. .LINK Set-SqlLogin #> function Set-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$true)] [System.Security.SecureString]$password, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Set-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Set-SqlLogin $($server.Name) $name" $login = Get-SqlLogin $server | where {$_.name -eq $name} try { if ($login) { $login.ChangePassword($password,$true,$false) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "Login $name does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Set-SqlLogin ####################### <# .SYNOPSIS Removes a login from a SQL Server. .DESCRIPTION The Set-SqlLoginDefaultDatabase function changes a SQL Login default database. .INPUTS None You cannot pipe objects to Set-SqlLoginDefaultDatabase .OUTPUTS None This function does not generate any output. .EXAMPLE Set-SqlLoginDefaultDatabase "Z002\\sql2k8" "TestPSUnit" 'master' This command sets the default database for TestPSUnit login. .LINK Set-SqlLoginDefaultDatabase #> function Set-SqlLoginDefaultDatabase { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$true)] [string]$DefaultDatabase, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Set-SqlLoginDefaultDatabase:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Set-SqlLoginDefaultDatabase $($server.Name) $name" $login = Get-SqlLogin $server | where {$_.name -eq $name} try { if ($login) { $login.DefaultDatabase = $DefaultDatabase $login.Alter() $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "Login $name does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Set-SqlLoginDefaultDatabase ####################### <# .SYNOPSIS Removes a login from a SQL Server. .DESCRIPTION The Rename-SqlLogin function renames a SQL Login. .INPUTS None You cannot pipe objects to Rename-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE Rename-SqlLogin "Z002\\sql2k8" "TestPSUnit" "CheckPSUnit" This command renames the login TestPSUnit. .LINK Rename-SqlLogin #> function Rename-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$true)] [string]$newname, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Rename-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Rename-SqlLogin $($server.Name) $name $newname" $login = Get-SqlLogin $server | where {$_.name -eq $name} try { if ($login) { $login.Rename("$newName") $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "Login $name does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Rename-SqlLogin ####################### <# .SYNOPSIS Adds a new user to a database. .DESCRIPTION The Add-SqlUser function adds a new user to the specified database. .INPUTS None You cannot pipe objects to Add-SqlUser .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlUser "Z002\\sql2k8" "pubs" "TestPSUnit" This command adds the TestPSUnit login to the pubs database. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Add-SqlUser -dbname $database "TestPSUnit" This command adds the TestPSUnit login to the pubs database. .LINK Add-SqlUser #> function Add-SqlUser { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$false)] [string]$login=$name, [Parameter(Position=4, Mandatory=$false)] [string]$defaultSchema='dbo', [Parameter(Position=5, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=6, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Add-SqlUser:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Add-SqlUser $($database.Name) $name" $user = new-object ('Microsoft.SqlServer.Management.Smo.User') $database, $name $user.Login = $login if ($database.parent.Information.Version.Major -ne '8') { $user.DefaultSchema = $defaultschema } try { $user.Create() $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Add-SqlUser ####################### <# .SYNOPSIS Removes a user from a database. .DESCRIPTION The Remove-SqlUser function removes a user from the specified database. .INPUTS None You cannot pipe objects to Remove-SqlUser .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlUser "Z002\\sql2k8" "pubs" "TestPSUnit" This command Removes the TestPSUnit user from the pubs database. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Remove-SqlUser -dbname $database "TestPSUnit" This command Removes the TestPSUnit user from the pubs database. .LINK Remove-SqlUser #> function Remove-SqlUser { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Remove-SqlUser:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Remove-SqlUser $($database.Name) $name" $user = $database.Users[$name] try { if ($user) { $user.Drop() $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "User $name does not exist in database $($database.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Remove-SqlUser ####################### <# .SYNOPSIS Gets an SMO ServerRole object. .DESCRIPTION The Get-SqlServerRole function gets a collection of SMO ServerRole objects for the specified SQL Server. .INPUTS None You cannot pipe objects to Get-SqlServerRole .OUTPUTS Microsoft.SqlServer.Management.Smo.ServerRole Get-SqlServerRole returns a Microsoft.SqlServer.Management.Smo.ServerRole object. .EXAMPLE Get-SqlServerRole "Z002\\sql2K8" This command gets a collection of SMO ServerRole objects for SQL Server Z002\\SQL2K8. .LINK Get-SqlServerRole #> function Get-SqlServerRole { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver ) switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Get-SqlServerRole:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Get-SqlServerRole $($server.Name)" foreach ($svrole in $server.Roles) { #Return ServerRole Object $svrole } } #Get-SqlServerRole ####################### <# .SYNOPSIS Adds a login to a server role. .DESCRIPTION The Add-SqlServerRoleMember function adds a login to the specified server role. .INPUTS None You cannot pipe objects to Add-SqlServerRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlServerRoleMember "Z002\\sql2k8" "TestPSUnit" "bulkadmin" This command adds the TestPSUnit login to the bulkadmin server role. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Add-SqlServerRoleMember $server "TestPSUnit" "bulkadmin" This command adds the TestPSUnit login to the bulkadmin server role. .LINK Add-SqlServerRoleMember #> function Add-SqlServerRoleMember { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$loginame, [Parameter(Position=2, Mandatory=$true)] [string]$rolename, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Add-SqlServerRoleMember:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Add-SqlServerRoleMember $($server.Name) $name" if($server.Logins | where {$_.name -eq $loginame}) { $svrole = Get-SqlServerRole $server | where {$_.name -eq $rolename} try { if ($svrole) { $svrole.AddMember($loginame) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "ServerRole $rolename does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } else { throw "Login $loginame does not exist on server $($server.Name)." } } #Add-SqlServerRoleMember ####################### <# .SYNOPSIS Removes a login from a server role. .DESCRIPTION The Remove-SqlServerRoleMember function removes a login from the specified server role. .INPUTS None You cannot pipe objects to Remove-SqlServerRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlServerRoleMember "Z002\\sql2k8" "TestPSUnit" "bulkadmin" This command Removes the TestPSUnit login from the bulkadmin server role. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Remove-SqlServerRoleMember $server "TestPSUnit" "bulkadmin" This command Removes the TestPSUnit login from the bulkadmin server role. .LINK Remove-SqlServerRoleMember #> function Remove-SqlServerRoleMember { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$loginame, [Parameter(Position=2, Mandatory=$true)] [string]$rolename, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Remove-SqlServerRoleMember:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Remove-SqlServerRoleMember $($server.Name) $name" if($server.Logins | where {$_.name -eq $loginame}) { $svrole = Get-SqlServerRole $server | where {$_.name -eq $rolename} try { if ($svrole) { $svrole.DropMember($loginame) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "ServerRole $rolename does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } else { throw "Login $loginame does not exist on server $($server.Name)." } } #Remove-SqlServerRoleMember ####################### <# .SYNOPSIS Returns a SMO DatabaseRole object with additional properties. .DESCRIPTION The Get-SqlDatabaseRole function gets a collection of SMO DatabaseRole objects for the specified SQL Database. .INPUTS Microsoft.SqlServer.Management.Smo.Database You can pipe database objects to Get-SqlDatabaseRole .OUTPUTS Microsoft.SqlServer.Management.Smo.DatabaseRole Get-SqlDatabaseRole returns a Microsoft.SqlServer.Management.Smo.DatabaseRole object. .EXAMPLE Get-SqlDatabaseRole $(Get-SqlDatabase "Z002\\sql2K8" pubs) This command gets a collection of SMO DatabaseRole objects for SQL Server Z002\\SQL2K8, pubs database. .EXAMPLE Get-SqlDatabase "Z002\\sql2K8" | Get-SqlDatabaseRole This command gets a collection SMO DatabaseRole objects for all SQL databases on the SQL Server Z002\\SQL2K8. .LINK Get-SqlDatabaseRole #> function Get-SqlDatabaseRole { param( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline = $true)] [Microsoft.SqlServer.Management.Smo.Database]$database ) process { foreach ($role in $database.Roles) { #Return DatabaseRole Object $role } } } #Get-SqlDatabaseRole ####################### <# .SYNOPSIS Adds a user or role to a database role. .DESCRIPTION The Add-SqlDatabaseRoleMember function adds a user or role to the specified database role. .INPUTS None You cannot pipe objects to Add-SqlDatabaseRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlDatabaseRoleMember "Z002\\sql2k8" "pubs" "TestPSUnit" "TestPSUnitDBRole" This command adds the TestUnit user to the TestPSUnitDBRole database role. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Add-SqlDatabaseRoleMember -dbname $database -name "TestPSUnit" -rolename "TestPSUnitDBRole" This command adds the TestUnit user to the TestPSUnitDBRole database role. .LINK Add-SqlDatabaseRoleMember #> function Add-SqlDatabaseRoleMember { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$true)] [string]$rolename, [Parameter(Position=4, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=5, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Add-SqlDatabaseRoleMember:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Add-SqlDatabaseRoleMember $($database.Name) $name $rolename" if(($database.Users | where {$_.name -eq $name}) -or ($database.Roles | where {$_.name -eq $name})) { $role = Get-SqlDatabaseRole $database | where {$_.name -eq $rolename} try { if ($role) { $role.AddMember($name) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "DatabaseRole $rolename does not exist in database $($database.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } else { throw "Role or User $name does not exist in database $($database.Name)." } } #Add-SqlDatabaseRoleMember ####################### <# .SYNOPSIS Removes a user or role from a database role. .DESCRIPTION The Remove-SqlDatabaseRoleMember function removes a user or role from the specified database role. .INPUTS None You cannot pipe objects to Remove-SqlDatabaseRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlDatabaseRoleMember "Z002\\sql2k8" "pubs" "TestPSUnit" "TestPSUnitDBRole" This command removes the TestUnit user to the TestPSUnitDBRole database role. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Remove-SqlDatabaseRoleMember -dbname $database -name "TestPSUnit" -rolename "TestPSUnitDBRole" This command removes the TestUnit user to the TestPSUnitDBRole database role. .LINK Remove-SqlDatabaseRoleMember #> function Remove-SqlDatabaseRoleMember { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$true)] [string]$rolename, [Parameter(Position=4, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=5, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Remove-SqlDatabaseRoleMember:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Remove-SqlDatabaseRoleMember $($database.Name) $name $rolename" if(($database.Users | where {$_.name -eq $name}) -or ($database.Roles | where {$_.name -eq $name})) { $role = Get-SqlDatabaseRole $database | where {$_.name -eq $rolename} try { if ($role) { $role.DropMember($name) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "DatabaseRole $rolename does not exist in database $($database.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } else { throw "Role or User $name does not exist in database $($database.Name)." } } #Remove-SqlDatabaseRoleMember ####################### <# .SYNOPSIS Writes an entry to SqlProxy Log File. .DESCRIPTION The Write-SqlProxyLog function writes an entry to the SqlProxy Log File. .INPUTS None You cannot pipe objects to Write-SqlProxyLog .OUTPUTS None This function does not generate any output. .EXAMPLE $message = "PSUserName=$PSUserName`n" + $($psBoundParameters.GetEnumerator() | %{"$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message This command writes a message to the SQLProxy Log .NOTES This must be run as administrator to create the new EventLog and EventLog Source!!! New-EventLog -LogName SqlProxy -Source SqlProxy .LINK Write-SqlProxyLog #> function Write-SqlProxyLog { param( [Parameter(Position=0, Mandatory=$true)] $EventID, [Parameter(Position=1, Mandatory=$true)] $Message, [Parameter(Position=2, Mandatory=$false)] $EntryType='SuccessAudit' ) write-eventlog -logname SqlProxy -source SqlProxy -eventID $eventID -message $message -EntryType $EntryType } #Write-SqlProxyLog
PowerShellCorpus/PoshCode/SharpSsh Functions.ps1
SharpSsh Functions.ps1
## USING the binaries from: ## http://downloads.sourceforge.net/sharpssh/SharpSSH-1.1.1.13.bin.zip [void][reflection.assembly]::LoadFrom( (Resolve-Path "~\\Documents\\WindowsPowerShell\\Libraries\\Tamir.SharpSSH.dll") ) ## NOTE: These are bare minimum functions, and only cover ssh, not scp or sftp ## also, if you "expect" something that doesn't get output, you'll be completely stuck. ## ## As a suggestion, the best way to handle the output is to "expect" your prompt, and then do ## select-string matching on the output that was captured before the prompt. function New-SshSession { Param( [string]$UserName , [string]$HostName , [string]$RSAKeyFile , [switch]$Passthru ) if($RSAKeyFile -and (Test-Path $RSAKeyFile)){ $global:LastSshSession = new-object Tamir.SharpSsh.SshShell ` $cred.GetNetworkCredential().Domain, $cred.GetNetworkCredential().UserName $global:LastSshSession.AddIdentityFile( (Resolve-Path $RSAKeyFile) ) } else { $cred = $host.UI.PromptForCredential("SSH Login Credentials", "Please specify credentials in user@host format", "$UserName@$HostName","") $global:LastSshSession = new-object Tamir.SharpSsh.SshShell ` $cred.GetNetworkCredential().Domain, $cred.GetNetworkCredential().UserName, $cred.GetNetworkCredential().Password } $global:LastSshSession.Connect() $global:LastSshSession.RemoveTerminalEmulationCharacters = $true if($Passthru) { return $global:LastSshSession } } function Remove-SshSession { Param([Tamir.SharpSsh.SshShell]$SshShell=$global:LastSshSession) $SshShell.WriteLine( "exit" ) sleep -milli 500 if($SshShell.ShellOpened) { Write-Warning "Shell didn't exit cleanly, closing anyway." } $SshShell.Close() $SshShell = $null } function Invoke-Ssh { Param( [string]$command , [regex]$expect ## there ought to be a non-regex parameter set... , [Tamir.SharpSsh.SshShell]$SshShell=$global:LastSshSession ) if($SshShell.ShellOpened) { $SshShell.WriteLine( $command ) if($expect) { $SshShell.Expect( $expect ).Split("`n") } else { sleep -milli 500 $SshShell.Expect().Split("`n") } } else { throw "The ssh shell isn't open!" } } function Send-Ssh { Param( [string]$command , [Tamir.SharpSsh.SshShell]$SshShell=$global:LastSshSession ) if($SshShell.ShellOpened) { $SshShell.WriteLine( $command ) } else { throw "The ssh shell isn't open!" } } function Receive-Ssh { Param( [RegEx]$expect ## there ought to be a non-regex parameter set... , [Tamir.SharpSsh.SshShell]$SshShell=$global:LastSshSession ) if($SshShell.ShellOpened) { if($expect) { $SshShell.Expect( $expect ).Split("`n") } else { sleep -milli 500 $SshShell.Expect().Split("`n") } } else { throw "The ssh shell isn't open!" } }
PowerShellCorpus/PoshCode/8e2c5f39-6676-4cb0-bdac-6f8819060c49.ps1
8e2c5f39-6676-4cb0-bdac-6f8819060c49.ps1
#------------------------------------------------------------------------------ # # get the 'connect' entries from the logs of all the Exchange CAS servers # only keep the last 30 days # # runs at 2AM #------------------------------------------------------------------------------ Function Get-ClientVersionConnectLogs () { Param( $LogDate=$Null ) If ($LogDate) { # this is the default location for these logs during install $Script:CAS | %{gc ( '\\\\' + $_.Name + '\\c$\\Program Files\\Microsoft\\Exchange Server\\V14\\Logging\\RPC Client Access\\RCA_'+$T+'-*.LOG') |?{$_-match"OUTLOOK.EXE"-and$_-match",Connect,"}} } } # Starting with today, work back checking to see that a file for # that days exists, if it does not then create it # # the directory where you keep these "connect logs" - change to fit your needs $Script:CasLogUNCDir ='\\\\<server>\\<drv>\\Data\\CASConnectLogs' # get all the CAS servers -- only get 2010 servers ( I have 2007 servers too) $Script:CAS = Get-ExchangeServer | ?{ $_.IsClientAccessServer -eq $true -and $_.AdminDisplayVersion -match "^Version 14" } # loop thru the last 14 days and collect the logs 1..14 | % { $T=Get-Date ((Get-Date).adddays(($_) * -1)) -Format 'yyyyMMdd' $Script:CASLogFile = $('OLConnect-' + $T + '.txt') $FileName = Join-Path -Path $Script:CasLogUNCDir -ChildPath $Script:CASLogFile if(-not (Test-Path $FileName)) { Write-output "Working: " $T Get-ClientVersionConnectLogs $T | Out-File $FileName } } # Now check to see if any files are old than 30 days and kill them gci $Script:CasLogUNCDir | ? {$_.LastWritetime -lt ((get-date).adddays(-30))} | Remove-Item | Out-Null
PowerShellCorpus/PoshCode/34acf364-c8a0-4ea5-8002-1b134280c15b.ps1
34acf364-c8a0-4ea5-8002-1b134280c15b.ps1
# # simple example using a hash to parse CAS Connect Logs # # after using the get-CASConnectLogEntries.ps1 to collect the log information # this script runs thru those files and counts Cached vs Classic # # # the directory where you keep these "cas connect logs" - change to fit your needs $Script:CasLogUNCDir ='\\\\<server>\\<drv>\\Web\\Data\\CASConnectLogs' # Hast Table to hold results : LegacyExchangeDN-Clientversion, Mode $Clients = @{} foreach ($Line in (gci $Script:CasLogUNCDir | gc) ) { #legacyExchangeDN $LEDN = $Line.Split(",")[3] #Outlook version $OLVER = $Line.Split(",")[6] #ClientMode $Mode = $Line.Split(",")[7] if(-not ($Clients.ContainsKey($LEDN+'-'+$OLVer))) { $Clients.Add($($LEDN+'-'+$OLVer),$MODE) } } "Total Clients [ {0} ]; Cached [ {1} ]; Classic [ {2} ]"-f ($Clients.Count),(($Clients.getenumerator() | ?{$_.value-match'Cached'}).Count),(($Clients.getenumerator() | ?{$_.value-notmatch'Cached'}).Count)
PowerShellCorpus/PoshCode/finddupe_11.ps1
finddupe_11.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." -f red; exit} for ($i=0;$i -ne $files.count; $i++) # Cycle thru all files { if ($files[$i] -eq $null) {continue} $md5 = $null $filecheck = $files[$i] $files[$i] = $null for ($c=0;$c -ne $files.count; $c++) { if ($files[$c] -eq $null) {continue} # write-host "Comparing $filecheck and $($files[$c]) `r" -nonewline if ($filecheck.length -eq $files[$c].length) { #write-host "Comparing MD5 of $($filecheck.fullname) and $($files[$c].fullname) `r" -nonewline if ($md5 -eq $null) {$md5 = (get-md5 $filecheck)} if ($md5 -eq (get-md5 $files[$c])) { write-host "Size and MD5 match: " -fore red -nonewline "{0} and {1}" -f $filecheck.fullname, $files[$c].fullname $matches++ if ($del -eq $true) { if ($noprompt -eq $true) { del $files[$c].fullname write-host "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 "Number of bytes recovered: $bytesrec." write-host ""
PowerShellCorpus/PoshCode/Invoke-Generic_1.ps1
Invoke-Generic_1.ps1
function Invoke-Generic { #.Synopsis # Invoke Generic method definitions via reflection: [CmdletBinding()] param( [Parameter(Position=0,Mandatory=$true,ValueFromPipelineByPropertyName=$true)] [Alias('On')] $InputObject , [Parameter(Position=1,ValueFromPipelineByPropertyName=$true)] [Alias('Named')] [string]$MethodName , [Parameter(Position=2)] [Alias("Types")] [Type[]]$ParameterTypes , [Parameter(Position=4, ValueFromRemainingArguments=$true, ValueFromPipelineByPropertyName=$true)] [Object[]]$WithArgs , [Switch]$Static ) begin { if($Static) { $BindingFlags = [System.Reflection.BindingFlags]"IgnoreCase,Public,Static" } else { $BindingFlags = [System.Reflection.BindingFlags]"IgnoreCase,Public,Instance" } } process { $Type = $InputObject -as [Type] if(!$Type) { $Type = $InputObject.GetType() } if($WithArgs -and -not $ParameterTypes) { $ParameterTypes = $withArgs | % { $_.GetType() } } elseif(!$ParameterTypes) { $ParameterTypes = [Type]::EmptyTypes } trap { continue } $MemberInfo = $Type.GetMethod($MethodName, $BindingFlags) if(!$MemberInfo) { $MemberInfo = $Type.GetMethod($MethodName, $BindingFlags, $null, $NonGenericArgumentTypes, $null) } if(!$MemberInfo) { $MemberInfo = $Type.GetMethods($BindingFlags) | Where-Object { $MI = $_ [bool]$Accept = $MI.Name -eq $MethodName if($Accept){ Write-Verbose "$Accept = $($MI.Name) -eq $($MethodName)" [Array]$GenericTypes = @($MI.GetGenericArguments() | Select -Expand Name) [Array]$Parameters = @($MI.GetParameters() | Add-Member ScriptProperty -Name IsGeneric -Value { $GenericTypes -Contains $this.ParameterType } -Passthru) $Accept = $ParameterTypes.Count -eq $Parameters.Count Write-Verbose " $Accept = $($Parameters.Count) Arguments" if($Accept) { for($i=0;$i -lt $Parameters.Count;$i++) { $Accept = $Accept -and ( $Parameters[$i].IsGeneric -or ($ParameterTypes[$i] -eq $Parameters[$i].ParameterType)) Write-Verbose " $Accept =$(if($Parameters[$i].IsGeneric){' GENERIC or'}) $($ParameterTypes[$i]) -eq $($Parameters[$i].ParameterType)" } } } return $Accept } | Sort { @($_.GetGenericArguments()).Count } | Select -First 1 } Write-Verbose "Time to make generic methods." Write-Verbose $MemberInfo [Type[]]$GenericParameters = @() [Array]$ConcreteTypes = @($MemberInfo.GetParameters() | Select -Expand ParameterType) for($i=0;$i -lt $ParameterTypes.Count;$i++){ Write-Verbose "$($ParameterTypes[$i]) ? $($ConcreteTypes[$i] -eq $ParameterTypes[$i])" if($ConcreteTypes[$i] -ne $ParameterTypes[$i]) { $GenericParameters += $ParameterTypes[$i] } $ParameterTypes[$i] = Add-Member -in $ParameterTypes[$i] -Type NoteProperty -Name IsGeneric -Value $($ConcreteTypes[$i] -ne $ParameterTypes[$i]) -Passthru } $ParameterTypes | Where-Object { $_.IsGeneric } Write-Verbose "$($GenericParameters -join ', ') generic parameters" $MemberInfo = $MemberInfo.MakeGenericMethod( $GenericParameters ) Write-Verbose $MemberInfo if($WithArgs) { [Object[]]$Arguments = $withArgs | %{ $_.PSObject.BaseObject } Write-Verbose "Arguments: $(($Arguments | %{ $_.GetType().Name }) -Join ', ')" $MemberInfo.Invoke( $InputObject, $Arguments ) } else { $MemberInfo.Invoke( $InputObject ) } } }
PowerShellCorpus/PoshCode/Download File (with %).ps1
Download File (with %).ps1
<# .SYNOPSIS Downloads a file showing the progress of the download .DESCRIPTION This Script will download a file locally while showing the progress of the download .EXAMPLE .\\Download-File.ps1 'http:\\\\someurl.com\\somefile.zip' .EXAMPLE .\\Download-File.ps1 'http:\\\\someurl.com\\somefile.zip' 'C:\\Temp\\somefile.zip' .PARAMETER url url to be downloaded .PARAMETER localFile the local filename where the download should be placed .NOTES FileName : Download-File.ps1 Author : CrazyDave LastModified : 18 Jan 2011 9:39 AM PST #Requires -Version 2.0 #> param( [Parameter(Mandatory=$true)] [String] $url, [Parameter(Mandatory=$false)] [String] $localFile = (Join-Path $pwd.Path $url.SubString($url.LastIndexOf('/'))) ) begin { $client = New-Object System.Net.WebClient $Global:downloadComplete = $false $eventDataComplete = Register-ObjectEvent $client DownloadFileCompleted ` -SourceIdentifier WebClient.DownloadFileComplete ` -Action {$Global:downloadComplete = $true} $eventDataProgress = Register-ObjectEvent $client DownloadProgressChanged ` -SourceIdentifier WebClient.DownloadProgressChanged ` -Action { $Global:DPCEventArgs = $EventArgs } } process { Write-Progress -Activity 'Downloading file' -Status $url $client.DownloadFileAsync($url, $localFile) while (!($Global:downloadComplete)) { $pc = $Global:DPCEventArgs.ProgressPercentage if ($pc -ne $null) { Write-Progress -Activity 'Downloading file' -Status $url -PercentComplete $pc } } Write-Progress -Activity 'Downloading file' -Status $url -Complete } end { Unregister-Event -SourceIdentifier WebClient.DownloadProgressChanged Unregister-Event -SourceIdentifier WebClient.DownloadFileComplete $client.Dispose() $Global:downloadComplete = $null $Global:DPCEventArgs = $null Remove-Variable client Remove-Variable eventDataComplete Remove-Variable eventDataProgress [GC]::Collect() }
PowerShellCorpus/PoshCode/Get-SqlWmi.ps1
Get-SqlWmi.ps1
try {add-type -AssemblyName "Microsoft.SqlServer.SqlWmiManagement, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop} catch {add-type -AssemblyName "Microsoft.SqlServer.SqlWmiManagement"} ####################### <# .SYNOPSIS Gets SQL Server WMI information. .DESCRIPTION The Get-SqlWmi function gets port, instance and service account wmi information for all SQL instances on a computer. .EXAMPLE Get-SqlWmi "Z002" This command gets information for computername Z002. .NOTES Version History v1.0 - Chad Miller - Initial release #> function Get-SqlWmi { [CmdletBinding()] param( [Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [ValidateNotNullorEmpty()] [string[]]$ComputerName ) #Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer only works on SQL 2005 and higher. If we fail to gather info at least output #null values and computername for 2000 servers in catch block BEGIN {} PROCESS { foreach ($computer in $computername) { try { $wmi = new-object "Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer" $Computer -ErrorAction 'Stop' $ht = @{} $wmi.Services| where {$_.Type -eq 'SqlServer'} | foreach {$instance = $_.PathName -replace '".+"\\s{1}-s',""; $ht.Add($instance,$_.ServiceAccount)} $wmi.ServerInstances | foreach { new-object psobject -property @{ ComputerName=$Computer; Port=$_.ServerProtocols["Tcp"].IPAddresses["IPAll"].IPAddressProperties["TcpPort"].Value; AccountName=$ht[$_.Name]; Instance=$_.Name } } } catch { #SQL Server 2000 Does not support the WMI.ManagedComputer class. Try and use SQL-DMO try { $dmoServer = New-Object -comobject "SQLDMO.SQLServer" $dmoServer.loginsecure = $true $instances = $dmoServer.ListInstalledInstances($computer) | foreach {($_) } $dmoServer = $null #Clustered server will list server1\\instance1 and server2\\instance2 #Filter so just server1 is listed $instances | where { $_ -like "$computer*"} | foreach { $dmoServer = New-Object -comobject "SQLDMO.SQLServer" $dmoServer.loginsecure = $true $dmoServer.connect($_) new-object psobject -property @{ ComputerName=$Computer; Port=$dmoServer.registry.tcpport; AccountName=$dmoServer.StartupAccount; Instance = $dmoServer.ServiceName -replace 'MSSQL\\$','' } $dmoServer.close() $dmoServer = $null } } catch { new-object psobject -property @{ComputerName=$Computer;Port=$null;AccountName=$null;Instance=$null} } } } } END {} } #Get-SqlWmi
PowerShellCorpus/PoshCode/SqlProxy_4.psm1.ps1
SqlProxy_4.psm1.ps1
# --------------------------------------------------------------------------- ### <Author> ### Chad Miller ### </Author> ### <Description> ### Based on functions in SQLPSX. SqlProxy.psm1 module is used for administering ### SQL Server logins, users, and roles. Designed to be used with PS Remoting. ### All actions audited to a custom Eventlog. ### See Write-SqlProxyLog for log setup details ### </Description> # --------------------------------------------------------------------------- try {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop} catch {add-type -AssemblyName "Microsoft.SqlServer.ConnectionInfo"} try {add-type -AssemblyName "Microsoft.SqlServer.Smo, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop; $smoVersion = 10} catch {add-type -AssemblyName "Microsoft.SqlServer.Smo"; $smoVersion = 9} try {add-type -AssemblyName "Microsoft.SqlServer.SqlEnum, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop; $smoVersion = 10} catch {add-type -AssemblyName "Microsoft.SqlServer.SqlEnum"; $smoVersion = 9} try { try {add-type -AssemblyName "Microsoft.SqlServer.SMOExtended, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" -EA Stop} catch {add-type -AssemblyName "Microsoft.SqlServer.SMOExtended" -EA Stop} } catch {Write-Warning "SMOExtended not available"} $EventID = @{ "Add-SqlDatabaseRoleMember"=0 "Add-SqlLogin"=1 "Add-SqlServerRoleMember"=2 "Add-SqlUser"=3 "Remove-SqlDatabaseRoleMember"=4 "Remove-SqlLogin"=5 "Remove-SqlServerRoleMember"=6 "Remove-SqlUser"=7 "Rename-SqlLogin"=8 "Set-SqlLogin"=9 "Set-SqlLoginDefaultDatabase"=10 } ####################### <# .SYNOPSIS Gets a ServerConnection. .DESCRIPTION The Get-SqlConnection function gets a ServerConnection to the specified SQL Server. .INPUTS None You cannot pipe objects to Get-SqlConnection .OUTPUTS Microsoft.SqlServer.Management.Common.ServerConnection Get-SqlConnection returns a Microsoft.SqlServer.Management.Common.ServerConnection object. .EXAMPLE Get-SqlConnection "Z002\\sql2K8" This command gets a ServerConnection to SQL Server Z002\\SQL2K8. .EXAMPLE Get-SqlConnection "Z002\\sql2K8" "sa" "Passw0rd" This command gets a ServerConnection to SQL Server Z002\\SQL2K8 using SQL authentication. .LINK Get-SqlConnection #> function Get-SqlConnection { param( [Parameter(Position=0, Mandatory=$true)] [string]$sqlserver, [Parameter(Position=1, Mandatory=$false)] [string]$username, [Parameter(Position=2, Mandatory=$false)] [string]$password ) Write-Verbose "Get-SqlConnection $sqlserver" try { if($Username -and $Password) { $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $sqlserver,$username,$password } else { $con = new-object ("Microsoft.SqlServer.Management.Common.ServerConnection") $sqlserver } $con.Connect() Write-Output $con } catch { $message = $_.Exception.GetBaseException().Message write-error $message } } #Get-ServerConnection ####################### <# .SYNOPSIS Gets an SMO Server object. .DESCRIPTION The Get-SqlServer function gets a SMO Server object for the specified SQL Server. .INPUTS None You cannot pipe objects to Get-SqlServer .OUTPUTS Microsoft.SqlServer.Management.Smo.Server Get-SqlServer returns a Microsoft.SqlServer.Management.Smo.Server object. .EXAMPLE Get-SqlServer "Z002\\sql2K8" This command gets an SMO Server object for SQL Server Z002\\SQL2K8. .EXAMPLE Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd" This command gets a SMO Server object for SQL Server Z002\\SQL2K8 using SQL authentication. .LINK Get-SqlServer #> function Get-SqlServer { param( [Parameter(Position=0, Mandatory=$true)] [string]$sqlserver, [Parameter(Position=1, Mandatory=$false)] [string]$username, [Parameter(Position=2, Mandatory=$false)] [string]$password, [Parameter(Position=3, Mandatory=$false)] [string]$StatementTimeout=0 ) #When $sqlserver passed in from the SMO Name property, brackets #are automatically inserted which then need to be removed $sqlserver = $sqlserver -replace "\\[|\\]" Write-Verbose "Get-SqlServer $sqlserver" $con = Get-SqlConnection $sqlserver $Username $Password $server = new-object ("Microsoft.SqlServer.Management.Smo.Server") $con #Some operations might take longer than the default timeout of 600 seconnds (10 minutes). Set new default to unlimited $server.ConnectionContext.StatementTimeout = $StatementTimeout $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.StoredProcedure], "IsSystemObject") $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.Table], "IsSystemObject") $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.View], "IsSystemObject") $server.SetDefaultInitFields([Microsoft.SqlServer.Management.SMO.UserDefinedFunction], "IsSystemObject") #trap { "Check $SqlServer Name"; continue} $server.ConnectionContext.Connect() Write-Output $server } #Get-SqlServer ####################### <# .SYNOPSIS Gets an SMO Database object. .DESCRIPTION The Get-SqlDatabase function gets an SMO Database object for the specified SQL Database or collection of Database objects. .INPUTS None You cannot pipe objects to Get-SqlDatabase .OUTPUTS Microsoft.SqlServer.Management.Smo.Database Get-SqlDatabase returns a Microsoft.SqlServer.Management.Smo.Database object. .EXAMPLE Get-SqlDatabase "Z002\\sql2K8" This command gets a collection of SMO Database objects for SQL Server Z002\\SQL2K8. .EXAMPLE Get-SqlDatabase $(Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd") "pubs" This command gets a SMO Database object for SQL database pubs on the SQL Server Z002\\SQL2K8 using SQL authentication. .LINK Get-SqlDatabase #> function Get-SqlDatabase { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$false)] [string]$dbname ) switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Get-SqlDatabase:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Get-SqlDatabase $($server.Name) $dbname" if ($dbname) { if ($server.Databases.Contains("$dbname") -and $server.Databases[$dbname].IsAccessible) {$server.Databases[$dbname]} else {throw "Database $dname does not exist or is not accessible."} } else { $server.Databases | where {$_.IsAccessible -eq $true} } } # Get-SqlDatabase ####################### <# .SYNOPSIS Executes a query and returns an array of System.Data.DataRow. .DESCRIPTION The Get-SqlData function executes a query and returns an array of System.Data.DataRow. .INPUTS None You cannot pipe objects to Get-SqlData .OUTPUTS System.Data.DataRow Get-SqlData returns an array of System.Data.DataRow. .EXAMPLE Get-SqlData "Z002\\sql2K8" "pubs" "select * from authors" This command executes the specified SQL query using Windows authentication. .EXAMPLE $server = Get-SqlServer "Z002\\sql2K8" "sa" "Passw0rd" Get-SqlData $server "pubs" "select * from authors" This command executes the specified SQL query using SQL authentication. .LINK Get-SqlData #> function Get-SqlData { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$qry ) switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Get-SqlData:Param '`$dbname' must be a String or Database object." } } #Write-Verbose "Get-SqlData $($database.Parent.Name) $($database.Name) $qry" Write-Verbose "Get-SqlData $($database.Parent.Name) $($database.Name)" $ds = $database.ExecuteWithResults("$qry") $ds.Tables | foreach { $_.Rows} }# Get-SqlData ####################### <# .SYNOPSIS Executes a query that does not return a result set. .DESCRIPTION The Set-SqlData function executes a query that does not return a result set. .INPUTS None You cannot pipe objects to Set-SqlData .OUTPUTS None Set-SqlData does not produce any output. .EXAMPLE Set-SqlData "Z002\\sql2K8" "pubs" "Update authors set au_lname = 'Brown' WHERE au_lname = 'White'" This command executes the specified SQL query using Windows authentication. .EXAMPLE $server = Set-SqlServer "Z002\\sql2K8" "sa" "Passw0rd" Set-SqlData $server "pubs" "Update authors set au_lname = 'Brown' WHERE au_lname = 'White'" This command executes the specified SQL query using SQL authentication. .LINK Set-SqlData #> function Set-SqlData { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$dbname, [Parameter(Position=2, Mandatory=$true)] [string]$qry ) switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Set-SqlData:Param '`$dbname' must be a String or Database object." } } #Write-Verbose "Set-SqlData $($database.Parent.Name) $($database.Name) $qry" Write-Verbose "Set-SqlData $($database.Parent.Name) $($database.Name)" $database.ExecuteNonQuery("$qry") }# Set-SqlData ####################### <# .SYNOPSIS Adds a login to a SQL Server. .DESCRIPTION The Add-SqlLogin function adds a new login to the specified SQL server. .INPUTS None You cannot pipe objects to Add-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlLogin "Z002\\sql2k8" "TestPSUnit" "SQLPSXTesting" 'SqlLogin' This command adds the TestPSUnit login to the Z002\\sql2k8 server. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Add-SqlLogin $server "TestPSUnit" "SQLPSXTesting" 'SqlLogin' This command adds the TestPSUnit login to the Z002\\sql2k8 server. .LINK Add-SqlLogin #> function Add-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$false)] [System.Security.SecureString]$password, [Parameter(Position=3, Mandatory=$false)] [Microsoft.SqlServer.Management.Smo.LoginType]$logintype='WindowsUser', [Parameter(Position=4, Mandatory=$false)] [string]$DefaultDatabase='master', [Parameter(Position=5, Mandatory=$false)] [switch]$PasswordExpirationEnabled, [Parameter(Position=6, Mandatory=$false)] [switch]$PasswordPolicyEnforced, [Parameter(Position=7, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=8, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Add-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Add-SqlLogin $($server.Name) $name" try { $login = new-object ('Microsoft.SqlServer.Management.Smo.Login') $server, $name $login.DefaultDatabase = $defaultDatabase $login.LoginType = $logintype if ($logintype -eq 'SqlLogin') { if ($server.Information.Version.Major -ne '8') { $login.PasswordExpirationEnabled = $($PasswordExpirationEnabled.IsPresent) $login.PasswordPolicyEnforced = $($PasswordPolicyEnforced.IsPresent) } $login.Create($password) } else { $login.Create() } $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Add-SqlLogin ####################### <# .SYNOPSIS Removes a login from a SQL Server. .DESCRIPTION The Remove-SqlLogin function removes a login from the specified SQL server. .INPUTS None You cannot pipe objects to Remove-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlLogin "Z002\\sql2k8" "TestPSUnit" This command removes the TestPSUnit login from the Z002\\sql2k8 server. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Remove-SqlLogin $server "TestPSUnit" This command removes the TestPSUnit login from the Z002\\sql2k8 server. .LINK Remove-SqlLogin #> function Remove-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=3, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Remove-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Remove-SqlLogin $($server.Name) $name" try { $login = $server.Logins["$name"] if ($login) { $login.Drop() $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "Login $name does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Remove-SqlLogin ####################### <# .SYNOPSIS Removes a login from a SQL Server. .DESCRIPTION The Set-SqlLogin function changes a SQL Login Password. .INPUTS None You cannot pipe objects to Set-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE $pwd_secure_string = read-host "Enter a Password:" -assecurestring Set-SqlLogin "Z002\\sql2k8" "TestPSUnit" $pwd_secure_string This command sets the password for TestPSUnit login. .LINK Set-SqlLogin #> function Set-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$true)] [string]$password, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Set-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Set-SqlLogin $($server.Name) $name" try { $login = $server.Logins["$name"] if ($login) { $login.ChangePassword($password,$true,$false) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "Login $name does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Set-SqlLogin ####################### <# .SYNOPSIS Removes a login from a SQL Server. .DESCRIPTION The Set-SqlLoginDefaultDatabase function changes a SQL Login default database. .INPUTS None You cannot pipe objects to Set-SqlLoginDefaultDatabase .OUTPUTS None This function does not generate any output. .EXAMPLE Set-SqlLoginDefaultDatabase "Z002\\sql2k8" "TestPSUnit" 'master' This command sets the default database for TestPSUnit login. .LINK Set-SqlLoginDefaultDatabase #> function Set-SqlLoginDefaultDatabase { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$true)] [string]$DefaultDatabase, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Set-SqlLoginDefaultDatabase:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Set-SqlLoginDefaultDatabase $($server.Name) $name" try { $login = $server.Logins["$name"] if ($login) { $login.DefaultDatabase = $DefaultDatabase $login.Alter() $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "Login $name does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Set-SqlLoginDefaultDatabase ####################### <# .SYNOPSIS Removes a login from a SQL Server. .DESCRIPTION The Rename-SqlLogin function renames a SQL Login. .INPUTS None You cannot pipe objects to Rename-SqlLogin .OUTPUTS None This function does not generate any output. .EXAMPLE Rename-SqlLogin "Z002\\sql2k8" "TestPSUnit" "CheckPSUnit" This command renames the login TestPSUnit. .LINK Rename-SqlLogin #> function Rename-SqlLogin { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$name, [Parameter(Position=2, Mandatory=$true)] [string]$newname, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Rename-SqlLogin:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Rename-SqlLogin $($server.Name) $name $newname" try { $login = $server.Logins["$name"] if ($login) { $login.Rename("$newName") $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "Login $name does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Rename-SqlLogin ####################### <# .SYNOPSIS Adds a new user to a database. .DESCRIPTION The Add-SqlUser function adds a new user to the specified database. .INPUTS None You cannot pipe objects to Add-SqlUser .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlUser "Z002\\sql2k8" "pubs" "TestPSUnit" This command adds the TestPSUnit login to the pubs database. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Add-SqlUser -dbname $database "TestPSUnit" This command adds the TestPSUnit login to the pubs database. .LINK Add-SqlUser #> function Add-SqlUser { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$false)] [string]$login=$name, [Parameter(Position=4, Mandatory=$false)] [string]$defaultSchema='dbo', [Parameter(Position=5, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=6, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Add-SqlUser:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Add-SqlUser $($database.Name) $name" try { $user = new-object ('Microsoft.SqlServer.Management.Smo.User') $database, $name $user.Login = $login if ($database.parent.Information.Version.Major -ne '8') { $user.DefaultSchema = $defaultschema } $user.Create() $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Add-SqlUser ####################### <# .SYNOPSIS Removes a user from a database. .DESCRIPTION The Remove-SqlUser function removes a user from the specified database. .INPUTS None You cannot pipe objects to Remove-SqlUser .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlUser "Z002\\sql2k8" "pubs" "TestPSUnit" This command Removes the TestPSUnit user from the pubs database. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Remove-SqlUser -dbname $database "TestPSUnit" This command Removes the TestPSUnit user from the pubs database. .LINK Remove-SqlUser #> function Remove-SqlUser { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Remove-SqlUser:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Remove-SqlUser $($database.Name) $name" try { $user = $database.Users[$name] if ($user) { $user.Drop() $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "User $name does not exist in database $($database.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } #Remove-SqlUser ####################### <# .SYNOPSIS Adds a login to a server role. .DESCRIPTION The Add-SqlServerRoleMember function adds a login to the specified server role. .INPUTS None You cannot pipe objects to Add-SqlServerRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlServerRoleMember "Z002\\sql2k8" "TestPSUnit" "bulkadmin" This command adds the TestPSUnit login to the bulkadmin server role. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Add-SqlServerRoleMember $server "TestPSUnit" "bulkadmin" This command adds the TestPSUnit login to the bulkadmin server role. .LINK Add-SqlServerRoleMember #> function Add-SqlServerRoleMember { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$loginame, [Parameter(Position=2, Mandatory=$true)] [string]$rolename, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Add-SqlServerRoleMember:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Add-SqlServerRoleMember $($server.Name) $name" if($server.Logins["$loginame"]) { try { $svrole = $server.Roles["$rolename"] if ($svrole) { $svrole.AddMember($loginame) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "ServerRole $rolename does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } else { throw "Login $loginame does not exist on server $($server.Name)." } } #Add-SqlServerRoleMember ####################### <# .SYNOPSIS Removes a login from a server role. .DESCRIPTION The Remove-SqlServerRoleMember function removes a login from the specified server role. .INPUTS None You cannot pipe objects to Remove-SqlServerRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlServerRoleMember "Z002\\sql2k8" "TestPSUnit" "bulkadmin" This command Removes the TestPSUnit login from the bulkadmin server role. .EXAMPLE $server = Get-SqlServer "Z002\\sql2k8" Remove-SqlServerRoleMember $server "TestPSUnit" "bulkadmin" This command Removes the TestPSUnit login from the bulkadmin server role. .LINK Remove-SqlServerRoleMember #> function Remove-SqlServerRoleMember { param( [Parameter(Position=0, Mandatory=$true)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] [string]$loginame, [Parameter(Position=2, Mandatory=$true)] [string]$rolename, [Parameter(Position=3, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=4, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($sqlserver.GetType().Name) { 'String' { $server = Get-SqlServer $sqlserver } 'Server' { $server = $sqlserver } default { throw 'Remove-SqlServerRoleMember:Param `$sqlserver must be a String or Server object.' } } Write-Verbose "Remove-SqlServerRoleMember $($server.Name) $name" if($server.Logins["$loginame"]) { try { $svrole = $server.Roles["$rolename"] if ($svrole) { $svrole.DropMember($loginame) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "ServerRole $rolename does not exist on server $($server.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } else { throw "Login $loginame does not exist on server $($server.Name)." } } #Remove-SqlServerRoleMember ####################### <# .SYNOPSIS Adds a user or role to a database role. .DESCRIPTION The Add-SqlDatabaseRoleMember function adds a user or role to the specified database role. .INPUTS None You cannot pipe objects to Add-SqlDatabaseRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Add-SqlDatabaseRoleMember "Z002\\sql2k8" "pubs" "TestPSUnit" "TestPSUnitDBRole" This command adds the TestUnit user to the TestPSUnitDBRole database role. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Add-SqlDatabaseRoleMember -dbname $database -name "TestPSUnit" -rolename "TestPSUnitDBRole" This command adds the TestUnit user to the TestPSUnitDBRole database role. .LINK Add-SqlDatabaseRoleMember #> function Add-SqlDatabaseRoleMember { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$true)] [string]$rolename, [Parameter(Position=4, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=5, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Add-SqlDatabaseRoleMember:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Add-SqlDatabaseRoleMember $($database.Name) $name $rolename" if ($database.Users["$name"]) { try { $role = $database.Roles["$rolename"] if ($role) { $role.AddMember($name) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "DatabaseRole $rolename does not exist in database $($database.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } else { throw "User $name does not exist in database $($database.Name)." } } #Add-SqlDatabaseRoleMember ####################### <# .SYNOPSIS Removes a user or role from a database role. .DESCRIPTION The Remove-SqlDatabaseRoleMember function removes a user or role from the specified database role. .INPUTS None You cannot pipe objects to Remove-SqlDatabaseRoleMember .OUTPUTS None This function does not generate any output. .EXAMPLE Remove-SqlDatabaseRoleMember "Z002\\sql2k8" "pubs" "TestPSUnit" "TestPSUnitDBRole" This command removes the TestUnit user to the TestPSUnitDBRole database role. .EXAMPLE $database = Get-SqlDatabase "Z002\\sql2k8" "pubs" Remove-SqlDatabaseRoleMember -dbname $database -name "TestPSUnit" -rolename "TestPSUnitDBRole" This command removes the TestUnit user to the TestPSUnitDBRole database role. .LINK Remove-SqlDatabaseRoleMember #> function Remove-SqlDatabaseRoleMember { param( [Parameter(Position=0, Mandatory=$false)] $sqlserver, [Parameter(Position=1, Mandatory=$true)] $dbname, [Parameter(Position=2, Mandatory=$true)] [string]$name, [Parameter(Position=3, Mandatory=$true)] [string]$rolename, [Parameter(Position=4, Mandatory=$true)] [string]$ChangeOrder, [Parameter(Position=5, Mandatory=$false)] [string]$Description ) $ErrorActionPreference = "Stop" $PSUserName = $PSSenderInfo.UserInfo.Identity.Name switch ($dbname.GetType().Name) { 'String' { $database = Get-SqlDatabase $sqlserver $dbname } 'Database' { $database = $dbname } default { throw "Remove-SqlDatabaseRoleMember:Param '`$dbname' must be a String or Database object." } } Write-Verbose "Remove-SqlDatabaseRoleMember $($database.Name) $name $rolename" if ($database.Users["$name"]) { try { $role = $database.Roles["$rolename"] if ($role) { $role.DropMember($name) $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage } else { throw "DatabaseRole $rolename does not exist in database $($database.Name)." } } catch { $message = $_.Exception.GetBaseException().Message $logmessage = "PSUserName=$PSUserName" + $($psBoundParameters.GetEnumerator() | %{"`n$($_.Key)=$($_.Value)"}) + "`n$message" write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $logmessage -EntryType 'Error' Write-Error $message } } else { throw "User $name does not exist in database $($database.Name)." } } #Remove-SqlDatabaseRoleMember ####################### <# .SYNOPSIS Writes an entry to SqlProxy Log File. .DESCRIPTION The Write-SqlProxyLog function writes an entry to the SqlProxy Log File. .INPUTS None You cannot pipe objects to Write-SqlProxyLog .OUTPUTS None This function does not generate any output. .EXAMPLE $message = "PSUserName=$PSUserName`n" + $($psBoundParameters.GetEnumerator() | %{"$($_.Key)=$($_.Value)"}) write-sqlproxylog -eventID $eventID."$($myinvocation.mycommand.name)" -message $message This command writes a message to the SQLProxy Log .NOTES This must be run as administrator to create the new EventLog and EventLog Source!!! New-EventLog -LogName SqlProxy -Source SqlProxy .LINK Write-SqlProxyLog #> function Write-SqlProxyLog { param( [Parameter(Position=0, Mandatory=$true)] $EventID, [Parameter(Position=1, Mandatory=$true)] $Message, [Parameter(Position=2, Mandatory=$false)] $EntryType='SuccessAudit' ) write-eventlog -logname SqlProxy -source SqlProxy -eventID $eventID -message $message -EntryType $EntryType } #Write-SqlProxyLog
PowerShellCorpus/PoshCode/Move-Mailbox _2.ps1
Move-Mailbox _2.ps1
param( #distribution group holding usermailbox(es) [string] $DistGroup = "XC2010Move", #move requests per batch/script run [int] $BatchCount = 5 ) #remove user(s) without mailbox Get-DistributionGroupMember $DistGroup | get-user -Filter {Recipienttype -eq "User"} -EA SilentlyContinue | Remove-DistributionGroupMember -Identity $DistGroup -Confirm:$False #set quotas on moved mailbox(es) and then remove from group Get-DistributionGroupMember $DistGroup | Get-Mailbox -RecipientTypeDetails "UserMailbox" -EA SilentlyContinue | Where {($_.MailboxMoveStatus -eq ‘Completed’)} | Set-Mailbox -IssueWarningQuota "1920MB" -ProhibitSendQuota "1984MB" -ProhibitSendReceiveQuota "2048MB" Get-DistributionGroupMember $DistGroup | Get-Mailbox -EA SilentlyContinue -RecipientTypeDetails "UserMailbox" | Remove-DistributionGroupMember -Identity $DistGroup -Confirm:$False #remove move request(s) upon completion Get-MoveRequest -MoveStatus Completed | Remove-MoveRequest -Confirm:$False #get pre-2010 mailbox(es) not yet moved $MB2Move = Get-DistributionGroupMember $DistGroup | Get-Mailbox -EA SilentlyContinue | Where {($_.RecipientTypeDetails -eq "LegacyMailbox") -and ($_.MailboxMoveStatus -eq ‘None’) -and ($_.ExchangeUserAccountControl -ne "AccountDisabled")} | Get-Random -Count $BatchCount #create batch label as reference $batch = "$($env:computername)_MoveMB_{0:ddMMM_yyyy}" -f (Get-Date) #move pre-2010 mailbox(es) ForEach ($SingleMailbox in $MB2Move) {New-MoveRequest –Identity $SingleMailbox -BadItemLimit 100 -AcceptLargeDataLoss -Batchname $batch}
PowerShellCorpus/PoshCode/Make a phone call_1.ps1
Make a phone call_1.ps1
<# .NOTES AUTHOR: Sunny Chakraborty(sunnyc7@gmail.com) WEBSITE: http://tekout.wordpress.com VERSION: 0.1 CREATED: 17th April, 2012 LASTEDIT: 17th April, 2012 Requires: PowerShell v2 or better .CHANGELOG 4/17/2012 Try passing powershell objects to PROTO API and pass the variables to .JS file Pass other system variables and check if text to speech can translate double or a double-to-char conversion is required. .SYNOPSIS Make a phone call from Powershell. .DESCRIPTION The script demonstrates how you can collect state-data in powershell and pass it as an argument to a REST API call and alert a System Admin. For this example, TROPO REST API's were used. (www.tropo.com) The phone-number will receive a Call with the following text To speech Please check the server $this. The percent Free Space on C Drive is $inDecimals. This is a proof of concept. V 0.1 There are numerous areas of improvement. .IMPORTANT Please create a new account and setup your application in tropo. Its free for dev use. http://www.tropo.com Copy and replace the TOKEN in your application with the TOKEN below to initiate a call. .OTHER JAVASCRIPT (Hosted on Tropo) TropoTest.js call('+' + numToCall , { timeout:30, callerID:'19172688401', onAnswer: function() { say("Houston ! We have a problem "); say("Please check the server" + sourceServer ); say("The percent Free Space on C Drive is" + freeCDisk ); say("Goodbye."); log("Call logged Successfully"); }, onTimeout: function() { log("Call timed out"); }, onCallFailure: function() { log("Call could not be completed as dialed"); } }); #> # Proto API section. Please replace protoToken with your own Application Token, # I am posting my API token here so that someone can download and run the script by editing just the cell # field. $baseUrl = "https://api.tropo.com/1.0/sessions?action=create&" # Modify these variables. $protoToken = "10b0026696a79f448eb21d8dbc69d78acf12e2f1f62f291feecec8f2b8d1eac76da63d91dd317061a5a9eeb0" #US 10 Digit only for now. For Example 17327911234,19177911234 $myCell = '11234567890' # Functions Function get-FreeDiskPercentForC { $disk = Get-DiskUsage $free = $disk[0].FreeSpace / $disk[0].TotalSize $freeDiskCPercent = [System.Math]::Round($free, 2) $freeDiskCPercent } # Get some more parameters here. $sourceServer =hostname $cDisk = get-FreeDiskPercentForC # Concatenate and form the Proto API string. I am sure someone can figure out a better way to do this than just adding. $callThis = $baseUrl+ 'token=' + $protoToken + '&numToCall=' + $myCell + '&sourceServer=' + $sourceServer + '&freeCDisk=' + $cDisk # Call the Proto API # I could have tested this with Invoke-RestMethod, but I didn't see the point. I am not receiving any data from the URL. $newClient = new-object System.Net.WebClient $newClient.DownloadString($callThis)
PowerShellCorpus/PoshCode/58fc59d6-61a1-47e9-8c5f-1b9b9d17a727.ps1
58fc59d6-61a1-47e9-8c5f-1b9b9d17a727.ps1
#PrinterChecking Script By Henrik Pedersen Ċmark and Daniel Lundgren #This script is designed to check what printers that is still in use. #It's assumed the printer is classed as inactive if it hasnt been used in X months #The script is reading the Systemlog on a printserver of your choice, the one you type in the hostname for, #sorting the log on eventID 10 (successful print) and searching for entries the latest 6 months. #When its done it gets printer ports and ques from the same server and then compare them to the messageline from the eventlog. #And then checking if the mportname of is in the message. #If it is, it will write the name to a file and if not it will write the name to another file. #You will need admin rights to use the script. $date = Get-Date -UFormat %Y%m%d #Finding out what host to check logs from Write-Host "What server do you want to get the eventlog from?" $hostname = Read-Host Write-Host "Getting eventlog from remote server "$hostname". Please wait..." Write-Host "Please wait... (this might take a few minutes)" #Get Eventlog from a remote host $events = gwmi -ComputerName $hostname -query "select * from win32_ntlogevent where logfile='system' and eventcode='10' and sourcename='print'" | Select-Object EventCode, Timegenerated, Message | sort Timegenerated #Making a variable for the printerports $printerports = Get-WmiObject -computername $hostname Win32_Printer | Select-Object Portname, DeviceID, __server, name #Converting newest logtimes to DateTime $newest = [System.Management.ManagementDateTimeConverter]::ToDateTime($events[0].TimeGenerated) Write-Host "Oldest logentry is from:" $newest Write-Host "How many months back do you want to check?" $months = Read-Host #Checks is the path where the files gonna be added exists, it it dont, it creates it if ((Test-Path -path $hostname) -ne $True) { New-Item -type directory -path $hostname } $counter = 0 while ($counter -ne ($printerports.count-1)) { $foundprinted = 0 #Looping through each line and checking for how old the events are and if they match the current printerquename foreach ($line in $events) { #Converting Timegenerated to DateTime $current = ([System.Management.ManagementDateTimeConverter]::ToDateTime($line.TimeGenerated)) #Checking each line for beeing less then X months and has quename in the message if ($current -gt $(Get-Date).AddMonths(-$months) -and ($line.message -match $printerports[$counter].name )) { $foundprinted = 1 } } if ($foundprinted) { write-host -ForegroundColor Green $printerports[$counter].name"is in use!" #Writing to a file add-content -path $hostname\\Validprinters_$date.txt -Value $printerports[$counter].name } else { #Writing to another file write-host -ForegroundColor red $printerports[$counter].name "is not in use!" add-content -path $hostname\\Invalidprinters_$date.txt -Value $printerports[$counter].name } #Adds 1 to the counter so the loop ends after all quenames are checked $counter=$counter+1 }
PowerShellCorpus/PoshCode/chkhash_1.ps1
chkhash_1.ps1
# calculate SHA512 of file. function Get-SHA512([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]')) { $stream = $null; $cryptoServiceProvider = [System.Security.Cryptography.SHA512CryptoServiceProvider]; $hashAlgorithm = new-object $cryptoServiceProvider $stream = $file.OpenRead(); $hashByteArray = $hashAlgorithm.ComputeHash($stream); $stream.Close(); ## We have to be sure that we close the file stream if any exceptions are thrown. trap { if ($stream -ne $null) { $stream.Close(); } break; } foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }} return [string]$result; } function noequal ( $first, $second) { foreach($s in $second) { if ($first -eq $s) {return $false} } return $true } # chkhash.ps1 [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #3] [-u] [-h [path of .xml database]] # -u updates the XML file database and exits # otherwise, all files are checked against the XML file database. # -h specifies location of xml hash database $hashespath=".\\hashes.xml" del variable:\\args3 -ea 0 del variable:\\args2 -ea 0 del variable:\\xfiles -ea 0 del variable:\\files -ea 0 del variable:\\exclude -ea 0 $args3=@() $args2=$args $nu = 0 $errs = 0 $fc = 0 $upd = $false $create = $false for($i=0;$i -lt $args2.count; $i++) { if ($args2[$i] -like "-h*") # -help specified? { "Usage: .\\chkhash.ps1 [-h] [-u] [-c] [-x <file path of hashes .xml database>] [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #n] [-e <Dirs>]" "Options: -h - Help display." " -c - Create hash database. If .xml hash database does not exist, -c will be assumed." " -u - Update changed files and add new files to existing database." " -x - specifies .xml database file path to use. Default is .\\hashes.xml" " -e - exclude dirs. Put this after the files/dirs you want to check with SHA512 and needs to be fullpath (e.g. c:\\users\\bob not ..\\bob)." "" "Examples: PS>.\\chkhash.ps1 c:\\ d:\\ -c -x c:\\users\\bob\\hashes\\hashes.xml" " PS>.\\chkhash.ps1 c:\\users\\alice\\pictures\\sunset.jpg -a -x c:\\users\\alice\\hashes\\pictureshashes.xml" " PS>.\\chkhash.ps1 c:\\users\\eve\\documents d:\\media\\movies -x c:\\users\\eve\\hashes\\private.xml" " PS>.\\chkhash.ps1 c:\\users\\eve -x c:\\users\\eve\\hashes\\private.xml -e c:\\users\\eve\\hashes" "" "Note: files in subdirectories of any specified directory are automatically processed." exit } if ($args2[$i] -like "-u*") {$upd=$true;continue} # Update and Add new files to database? if ($args2[$i] -like "-c*") {$create=$true;continue} # Create database specified? if ($args2[$i] -like "-x*") {$i++;$hashespath=$args2[$i];continue} # Get hashes xml database path if ($args2[$i] -like "-e*") # Exclude files, dirs { do { $i++ $exclude+=@($args2[$i]) } while ($args2[$i] -notlike "-*" -and $i -lt $args2.count-1) continue } $args3+=@($args2[$i]) # Add files/dirs } "ChkHash.ps1 - .\\chkhash.ps1 -h for usage." "" if ($args3.count -eq 0) {exit} # Get list of files and SHA512 hash them. "Enumerating files from specified locations..." $files=@(dir -literalpath $args3 -recurse -ea 0 | ?{$_.mode -notmatch "d"} | ?{noequal $_.directoryname $exclude}) # Get list of files if ($files.count -eq 0) {"No files found. Exiting."; exit} if ($create -eq $true -or !(test-path $hashespath)) # Create database? { # Create SHA512 hashes of files and write to new database $files = $files | %{write-host "Hashing $($_.fullname) ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru} $files |export-clixml $hashespath "Created $hashespath" "$($files.count) file hashes saved. Exiting." exit } $xfiles=@(import-clixml $hashespath) "Loaded $($xfiles.count) file hash(es) from $hashespath" $hash=@{} for($x=0;$x -lt $xfiles.count; $x++) { if ($hash.contains($xfiles[$x].fullname)) {continue} $hash.Add($xfiles[$x].fullname,$x) } foreach($f in $files) { $n=($hash.($f.fullname)) if ($n -eq $null) { $nu++ # increment needs/needed updating count if ($upd -eq $false) {"Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue "Hashing $($f.fullname) ..." # Create SHA512 hash of file $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru} $xfiles+=@($f) # then add file + hash to list continue } $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru} # Update and continue is specified. $fc++ # increment files checked. if ($xfiles[$n].SHA512 -eq $f.SHA512) # Check SHA512 for mixmatch. { continue } $errs++ # increment mixmatches if ($upd -eq $true) { $xfiles[$n]=$f; "Updated `"$($f.fullname)`"";continue} "Bad SHA-512 found: `"$($f.fullname)`"" } if ($upd -eq $true) # if database updated { $xfiles|export-clixml $hashespath # write xml database "Updated $hashespath" "$nu file hash(es) added to database." "$errs file hash(es) updated in database." exit } "$errs SHA-512 mixmatch(es) found." "$fc file(s) SHA512 matched." if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
PowerShellCorpus/PoshCode/Send-Growl _3.0.ps1
Send-Growl _3.0.ps1
## This is the first version of a Growl module (just dot-source to use in PowerShell 1.0) ## v 1.0 supports a very simple notice, and no callbacks ## v 2.0 supports registering multiple message types ## supports callbacks ## v 2.1 redesigned to be a module used from apps, rather than it's own "PowerGrowler" app ## ## TODO: ## * Test sending notices to other PCs directly ## 2011/04/13 fix for Growl for Windows v2.0.6 Set-StrictMode -Version 2 ## this is just a default now, you'll have opportunities to override it... $script:appName = "PowerGrowler" [Reflection.Assembly]::LoadFrom("$(Split-Path (gp HKCU:\\Software\\Growl).'(default)')\\Growl.Connector.dll") | Out-Null if(!(Test-Path Variable:Global:PowerGrowlerNotices)) { $global:PowerGrowlerNotices = @{} } ## We can safely recreate this, it doesn't store much $script:PowerGrowler = New-Object "Growl.Connector.GrowlConnector" function Register-GrowlType { #.Synopsis # Register a new Type name for growl notices from PowerGrowl #.Description # Creates a new type name that can be used for sending growl notices #.Parameter AppName # The name of the application you want to register as #.Parameter Name # The type name to be used sending growls #.Parameter DisplayName # The test to use for display (defaults to use the same value as the type name) #.Parameter Icon # Overrides the default icon of the message (accepts .ico, .png, .bmp, .jpg, .gif etc) #.Parameter MachineName # The name of a remote machine to register remotely instead of locally. #.Parameter Priority # Overrides the default priority of the message (use sparingly) #.Example # Register-GrowlType "PoshTwitter" "Command Completed" # # Registers the type "Command Completed," using the default icon, for sending notifications to the local PC # PARAM( [Parameter(Mandatory=$true,Position=0)] [String]$AppName , [Parameter(Mandatory=$true,Position=1)] [ValidateScript( {!$global:PowerGrowlerNotices.Contains($AppName) -OR !$global:PowerGrowlerNotices.$AppName.Notices.ContainsKey($_)} )] [String]$Name , [Parameter(Mandatory=$false,Position=5)] [String]$Icon = "$PSScriptRoot\\default.ico" , [Parameter(Mandatory=$false,Position=6)] [String]$DisplayName = $Name , [Parameter(Mandatory=$false,Position=7)] [String]$MachineName , [Parameter(Mandatory=$false)] [String]$AppIcon ) [Growl.Connector.NotificationType]$Notice = $Name $Notice.DisplayName = $DisplayName $Notice.Icon = Convert-Path (Resolve-Path $Icon) if($MachineName) { $Notice.MachineName = $MachineName } if(!$global:PowerGrowlerNotices.Contains($AppName)) { $global:PowerGrowlerNotices.Add( $AppName, ([Growl.Connector.Application]$AppName) ) $global:PowerGrowlerNotices.$AppName = Add-Member -input $global:PowerGrowlerNotices.$AppName -Name Notices -Type NoteProperty -Value (New-Object hashtable) -Passthru $global:PowerGrowlerNotices.$AppName.Icon = Convert-Path (Resolve-Path $AppIcon) } $global:PowerGrowlerNotices.$AppName.Notices.Add( $Name, $Notice ) $script:PowerGrowler.Register( $global:PowerGrowlerNotices.$AppName , [Growl.Connector.NotificationType[]]@($global:PowerGrowlerNotices.$AppName.Notices.Values) ) } function Set-GrowlPassword { #.Synopsis # Set the Growl password #.Description # Set the password and optionally, the encryption algorithm, for communicating with Growl #.Parameter Password # The password for Growl #.Parameter Encryption # The algorithm to be used for encryption (defaults to AES) #.Parameter KeyHash # The algorithm to be used for key hashing (defaults to SHA1) PARAM( [Parameter(Mandatory=$true,Position=0)] [String]$Password , [Parameter(Mandatory=$false,Position=1)] [ValidateSet( "AES", "DES", "RC2", "TripleDES", "PlainText" )] [String]$Encryption = "AES" , [Parameter(Mandatory=$false,Position=2)] [ValidateSet( "MD5", "SHA1", "SHA256", "SHA384", "SHA512" )] [String]$KeyHash = "SHA1" ) $script:PowerGrowler.EncryptionAlgorithm = [Growl.Connector.Cryptography+SymmetricAlgorithmType]::"$Encryption" $script:PowerGrowler.KeyHashAlgorithm = [Growl.Connector.Cryptography+SymmetricAlgorithmType]::"$KeyHash" $script:PowerGrowler.Password = $Password } ## Register the "PowerGrowler" "Default" notice so everything works out of the box Register-GrowlType $script:AppName "Default" -appIcon "$PsScriptRoot\\default.ico" function Register-GrowlCallback { #.Synopsis # Register a script to be called when each notice is finished. #.Description # Registers a scriptblock as a handler for the NotificationCallback event. You should accept two parameters, a Growl.Connector.Response and a Growl.Connector.CallbackData object. # # The NotificationCallback only happens when a callback is requested, which in this Growl library only happens if you pass both CallbackData and CallbackType to the Send-Growl function. #.Example # Register-GrowlCallback { PARAM( $response, $context ) # Write-Host "Response $($response|out-string)" -fore Cyan # Write-Host "Context $($context|fl|out-string)" -fore Green # Write-Host $("Response Type: {0}`nNotification ID: {1}`nCallback Data: {2}`nCallback Data Type: {3}`n" -f $context.Result, $context.NotificationID, $context.Data, $context.Type) -fore Yellow # } # # Registers an informational debugging-style handler. # PARAM( [Parameter(Mandatory=$true)] [Scriptblock]$Handler ) Register-ObjectEvent $script:PowerGrowler NotificationCallback -Action $Handler } function Send-Growl { [CmdletBinding(DefaultParameterSetName="DataCallback")] #.Synopsis # Send a growl notice #.Description # Send a growl notice with the scpecified values #.Parameter Caption # The short caption to display #.Parameter Message # The message to send (most displays will resize to accomodate) #.Parameter NoticeType # The type of notice to send. This MUST be the name of one of the registered types, and senders should bear in mind that each registered type has user-specified settings, so you should not abuse the types, but create your own for messages that will recur. # For example, the user settings allow certain messages to be disabled, set to a different "Display", or to have their Duration and Stickyness changed, as well as have them be Forwarded to another device, have Sounds play, and set different priorities. #.Parameter Icon # Overrides the default icon of the message (accepts .ico, .png, .bmp, .jpg, .gif etc) #.Parameter Priority # Overrides the default priority of the message (use sparingly) #.Example # Send-Growl "Greetings" "Hello World!" # # The Hello World of Growl. #.Example # Send-Growl "You've got Mail!" "Message for you sir!" -icon ~\\Icons\\mail.png # # Displays a message with a couple of movie quotes and a mail icon. # PARAM ( [Parameter(Mandatory=$true, Position=0)] [ValidateScript( {$global:PowerGrowlerNotices.Contains($AppName)} )] [string]$AppName , [Parameter(Mandatory=$true, Position=1)][Alias("Type")] [ValidateScript( {$global:PowerGrowlerNotices.$AppName.Notices.ContainsKey($_)} )] [string]$NoticeType , [Parameter(Mandatory=$true, Position=2)] [string]$Caption , [Parameter(Mandatory=$true, Position=3)] [string]$Message , [Parameter(Mandatory=$false, Position=4, ParameterSetName="UrlCallback")] [Uri]$Url , [Parameter(Mandatory=$false, Position=4, ParameterSetName="DataCallback")] [string]$CallbackData , [Parameter(Mandatory=$false, Position=5, ParameterSetName="DataCallback")] [string]$CallbackType , [string]$Icon , [Growl.Connector.Priority]$Priority = "Normal" ) $notice = New-Object Growl.Connector.Notification $appName, $NoticeType, (Get-Date).Ticks.ToString(), $caption, $Message if($Icon) { $notice.Icon = Convert-Path (Resolve-Path $Icon) } if($Priority) { $notice.Priority = $Priority } if($DebugPreference -gt "SilentlyContinue") { Write-Output $notice } if( Test-Path Variable:Local:Url ) { $context = new-object Growl.Connector.CallbackContext $(if(Test-Path Variable:Local:CallbackData){$CallbackData}else{$Url.ToString()}) Write-Host $Url -Fore Cyan $script:PowerGrowler.Notify($notice, $context) } elseif( (Test-Path Variable:Local:CallbackData) -and (Test-Path Variable:Local:CallbackType) ) { $context = new-object Growl.Connector.CallbackContext $CallbackData,$CallbackType Write-Host $context.CallbackUrl -Fore Magenta $script:PowerGrowler.Notify($notice, $context) } else { $script:PowerGrowler.Notify($notice) } } Export-ModuleMember -Function Send-Growl, Set-GrowlPassword, Register-GrowlCallback, Register-GrowlType
PowerShellCorpus/PoshCode/Compare 2 foldertrees_1.ps1
Compare 2 foldertrees_1.ps1
function Compare-Foldertrees { param( $path1, $path2 ) $len1 = $path1.length $len2 = $path2.length . Require-function Get-MD5 Write-Host "====== First path only =======`n" gci $path1 -rec | ? {! $_.PSISContainer} | % { $fileName1 = $_.fullName $fileName = $fileName1.substring($len1) $filename2 = $path2 + $fileName #$filename1 #$filename2 if (! (Test-Path $filename2)) { "$filename" } } Write-Host "`n====== Second path only =======`n" gci $path2 -rec | ? {! $_.PSISContainer} | % { $fileName2 = $_.fullName $fileName = $fileName2.substring($len2) $filename1 = $path2 + $fileName #$filename1 #$filename2 if (! (Test-Path $filename1)) { "$filename" } } Write-Host "`n====== Different =======`n" gci $path1 -rec | ? {! $_.PSISContainer} | % { $fileName1 = $_.fullName $fileName = $fileName1.substring($len1) $filename2 = $path2 + $fileName #$filename1 #$filename2 if ( (Test-Path $filename2)) { $md1 = Get-MD5($filename1) $md2 = Get-MD5($filename2) if ($md1 -ne $md2) { "$filename" & 'C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\diffmerge.exe' $fileName1 $filename2 } } } }
PowerShellCorpus/PoshCode/Write-Indented.ps1
Write-Indented.ps1
function Write-Host { #.Synopsis # Wraps Write-Host with support for indenting based on stack depth. #.Description # This Write-Host cmdlet customizes output. You can indent the text using PadIndent, or indent based on stack depth using AutoIndent or by setting the global variable $WriteHostAutoIndent = $true. # # You can specify the color of text by using the ForegroundColor parameter, and you can specify the background color by using the BackgroundColor parameter. The Separator parameter lets you specify a string to use to separate displayed objects. The particular result depends on the program that is hosting Windows PowerShell. #.Example # write-host "no newline test >" -nonewline # no newline test >C:\\PS> # # This command displays the input to the console, but because of the NoNewline parameter, the output is followed directly by the prompt. #.Example # C:\\PS> write-host (2,4,6,8,10,12) -Separator ", -> " -foregroundcolor DarkGreen -backgroundcolor white # 2, -> 4, -> 6, -> 8, -> 10, -> 12 # # This command displays the even numbers from 2 through 12. The Separator parameter is used to add the string , -> (comma, space, -, >, space). #.Example # write-host "Red on white text." -ForegroundColor red -BackgroundColor white # Red on white text. # # This command displays the string "Red on white text." The text is red, as defined by the ForegroundColor parameter. The background is white, as defined by the BackgroundColor parameter. #.Example # $WriteHostAutoIndent = $true # C:\\PS>&{ # >> Write-Host "Level 1" # >> &{ Write-Host "Level 2" # >> &{ Write-Host "Level 3" } # >> Write-Host "Level 2" # >> } } # Level 1 # Level 2 # Level 3 # Level 2 # # This command displays how you can set WriteHostAutoIndent to control the output of a series of nested functions that use Write-Host for logging... #.Inputs # System.Object # You can pipe objects to be written to the host #.Outputs # None # Write-Host sends objects to the host. It does not return any objects. However, the host might display the objects that Write-Host sends to it. [CmdletBinding(HelpUri='http://go.microsoft.com/fwlink/?LinkID=113426', RemotingCapability='None')] param( # Objects to display in the console. [Parameter(Position=0, ValueFromPipeline=$true, ValueFromRemainingArguments=$true)] [System.Object[]] ${Object}, # Specifies that the content displayed in the console does not end with a newline character. [switch] ${NoNewline}, # String to the output between objects displayed on the console. [System.Object] ${Separator}, # Specifies the text color. There is no default. [System.ConsoleColor] ${ForegroundColor}, # Specifies the background color. There is no default [System.ConsoleColor] ${BackgroundColor}, # If set, Write-Host will indent based on the stack depth. Defaults to the global preference variable $WriteHostAutoIndent (False). [Switch] $AutoIndent = $(if($Global:WriteHostAutoIndent){$Global:WriteHostAutoIndent}else{$False}), # Amount to indent (before auto indent). Defaults to the global preference variable $WriteHostPadIndent (0). [Int] $PadIndent = $(if($Global:WriteHostPadIndent){$Global:WriteHostPadIndent}else{0}), # Number of spaces in each indent. Defaults to the global preference variable WriteHostIndentSize (2). [Int] $IndentSize = $(if($Global:WriteHostIndentSize){$Global:WriteHostIndentSize}else{2}) ) begin { function Get-ScopeDepth { $depth = 0 trap { continue } # trap outside the do-while scope do { $null = Get-Variable PID -Scope (++$depth) } while($?) return $depth - 3 } if($PSBoundParameters.ContainsKey("AutoIndent")) { $null = $PSBoundParameters.Remove("AutoIndent") } if($PSBoundParameters.ContainsKey("PadIndent")) { $null = $PSBoundParameters.Remove("PadIndent") } if($PSBoundParameters.ContainsKey("IndentSize")) { $null = $PSBoundParameters.Remove("IndentSize") } $Indent = $PadIndent if($AutoIndent) { $Indent += (Get-ScopeDepth) * $IndentSize } $Width = $Host.Ui.RawUI.BufferSize.Width - $Indent if($PSBoundParameters.ContainsKey("Object")) { $OFS = $Separator $PSBoundParameters["Object"] = $( foreach($line in $Object) { $line = "$line".Trim("`n").Trim("`r") for($start = 0; $start -lt $line.Length; $start += $Width -1) { $Count = if($Width -gt ($Line.Length - $start)) { $Line.Length - $start} else { $Width - 1} (" " * $Indent) + $line.SubString($start,$Count).Trim() } } ) -join ${Separator} } try { $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Host', [System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = {& $wrappedCmd @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $OFS = $Separator $_ = $( foreach($line in $_) { $line = "$line".Trim("`n").Trim("`r") for($start = 0; $start -lt $line.Length; $start += $Width -1) { $Count = if($Width -gt ($Line.Length - $start)) { $Line.Length - $start} else { $Width - 1} (" " * $Indent) + $line.SubString($start,$Count).Trim() } } ) -join ${Separator} $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } } function Write-Verbose { #.Synopsis # Wraps Write-Verbose with support for indenting based on stack depth. Writes text to the verbose message stream. #.Description # This Write-Verbose customizes output. You can indent the text using PadIndent, or indent based on stack depth using AutoIndent or by setting the global variable $WriteHostAutoIndent = $true. #.Example # $VerbosePreference = "Continue" # C:\\PS>write-verbose "Testing Verbose" # VERBOSE: Testing Verbose # # Setting the VerbosePreference causes Write-Verbose output to be displayed in the console #.Example # C:\\PS> write-Verbose (2,4,6,8,10,12) -Separator ", -> " # VERBOSE: 2, -> 4, -> 6, -> 8, -> 10, -> 12 # # This command displays the even numbers from 2 through 12. The Separator parameter is used to add the string , -> (comma, space, -, >, space). #.Example # $WriteVerboseAutoIndent = $true # C:\\PS>&{ # >> Write-Verbose "Level 1" # >> &{ Write-Verbose "Level 2" # >> &{ Write-Verbose "Level 3" } # >> Write-Verbose "Level 2" # >> } } # VERBOSE: Level 1 # VERBOSE: Level 2 # VERBOSE: Level 3 # VERBOSE: Level 2 # # This command displays how you can set WriteHostAutoIndent to control the output of a series of nested functions that use Write-Verbose for logging... #.Inputs # System.Object # You can pipe objects to be written to the verbose message stream. #.Outputs # None # Write-Verbose sends objects to the verbose message stream. It does not return any objects. However, the host might display the objects if the $VerbosePreference [CmdletBinding(HelpUri='http://go.microsoft.com/fwlink/?LinkID=113429', RemotingCapability='None')] param( # Objects to display in the console. [Parameter(Position=0, ValueFromPipeline=$true, ValueFromRemainingArguments=$true)] [System.Object[]] ${Message}, # String to the output between objects displayed on the console. [System.Object] ${Separator}, # If set, Write-Verbose will indent based on the stack depth. Defaults to the global preference variable $WriteVerboseAutoIndent (False). [Switch] $AutoIndent = $(if($Global:WriteVerboseAutoIndent){$Global:WriteVerboseAutoIndent}else{$False}), # Amount to indent (before auto indent). Defaults to the global preference variable $WriteVerbosePadIndent (0). [Int] $PadIndent = $(if($Global:WriteVerbosePadIndent){$Global:WriteVerbosePadIndent}else{0}), # Number of spaces in each indent. Defaults to the global preference variable WriteVerboseIndentSize (2). [Int] $IndentSize = $(if($Global:WriteVerboseIndentSize){$Global:WriteVerboseIndentSize}else{2}) ) begin { function Get-ScopeDepth { $depth = 0 trap { continue } # trap outside the do-while scope do { $null = Get-Variable PID -Scope (++$depth) } while($?) return $depth - 3 } if($PSBoundParameters.ContainsKey("AutoIndent")) { $null = $PSBoundParameters.Remove("AutoIndent") } if($PSBoundParameters.ContainsKey("PadIndent")) { $null = $PSBoundParameters.Remove("PadIndent") } if($PSBoundParameters.ContainsKey("IndentSize")) { $null = $PSBoundParameters.Remove("IndentSize") } if($PSBoundParameters.ContainsKey("Separator")) { $null = $PSBoundParameters.Remove("Separator") } $Indent = $PadIndent if($AutoIndent) { $Indent += (Get-ScopeDepth) * $IndentSize } $Prefix = "VERBOSE: ".Length $Width = $Host.Ui.RawUI.BufferSize.Width - $Indent - $Prefix if($PSBoundParameters.ContainsKey("Message")) { $OFS = $Separator $PSBoundParameters["Message"] = $( foreach($line in $Message) { $line = "$line".Trim("`n").Trim("`r") for($start = 0; $start -lt $line.Length; $start += $Width - 1) { $Count = if($Width -gt ($Line.Length - $start)) { $Line.Length - $start} else { $Width - 1} if($start) { (" " * ($Indent + $Prefix)) + $line.SubString($start,$Count).Trim() } else { (" " * $Indent) + $line.SubString($start,$Count).Trim() } } } ) -join "`n" } try { $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) { $PSBoundParameters['OutBuffer'] = 1 } $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Verbose', [System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = {& $wrappedCmd @PSBoundParameters } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } catch { throw } } process { try { $OFS = $Separator $_ = $( foreach($line in $_) { $line = "$line".Trim("`n").Trim("`r") for($start = 0; $start -lt $line.Length; $start += $Width - 1) { $Count = if($Width -gt ($Line.Length - $start)) { $Line.Length - $start} else { $Width - 1} if($start) { (" " * ($Indent + $Prefix)) + $line.SubString($start,$Count).Trim() } else { (" " * $Indent) + $line.SubString($start,$Count).Trim() } } } ) -join "`n" $steppablePipeline.Process($_) } catch { throw } } end { try { $steppablePipeline.End() } catch { throw } } }
PowerShellCorpus/PoshCode/Get-OnlineHelp.ps1
Get-OnlineHelp.ps1
## This is a VERY EARLY prototype of a function that could retrieve cmdlet help from TechNet ... ## and hypothetically, other online help sites which used the same format (none) # REQUIRES the HttpRest module, to convert XHTML to XML (Uses Get-WebPageContent below) # Otherwise I'm getting 503 errors when trying to resolve the DTD (need to look into that param( [Parameter(Mandatory=$true,Position=0)] [String]$Name , [Parameter(Mandatory=$false,Position=1)] [String[]]$Sections= @("Name", "Synopsis", "Syntax", "Description") ) # http://poshcode.org/1718 function Select-Expand { <# .Synopsis Like Select-Object -Expand, but with recursive iteration of a select chain .Description Takes a dot-separated series of properties to expand, and recursively iterates the output of each property ... .Parameter Property A collection of property names to expand. Each property can be a dot-separated series of properties, and each one is expanded, iterated, and then evaluated against the next .Parameter InputObject The input to be selected from .Parameter Unique If set, this becomes a pipeline hold-up, and the total output is checked to ensure uniqueness .Parameter EmptyToo If set, Select-Expand will include empty/null values in it's output .Example Get-Help Get-Command | Select-Expand relatedLinks.navigationLink.uri -Unique This will return the online-help link for Get-Command. It's the equivalent of running the following command: C:\\PS> Get-Help Get-Command | Select-Object -Expand relatedLinks | Select-Object -Expand navigationLink | Select-Object -Expand uri | Where-Object {$_} | Select-Object -Unique #> param( [Parameter(ValueFromPipeline=$false,Position=0)] [string[]]$Property , [Parameter(ValueFromPipeline=$true)] [Alias("IO")] [PSObject[]]$InputObject , [Switch]$Unique , [Switch]$EmptyToo ) begin { if($unique) { $output = @() } } process { foreach($io in $InputObject) { foreach($prop in $Property -split "\\.") { if($io -ne $null) { $io = $io | Select-Object -Expand $prop Write-Verbose $($io | out-string) } } if(!$EmptyToo -and ($io -ne $null)) { $io = $io | Where-Object {$_} } if($unique) { $output += @($io) } else { Write-Output $io } } } end { if($unique) { Write-Output $output | Select-Object -Unique } } } # New-Alias slep Select-Expand function Get-OnlineHelpContent { param( [Parameter(Mandatory=$true,Position=0)] [String]$Name , [Parameter(Mandatory=$false,Position=1)] [String[]]$Sections= @("Name", "Synopsis", "Syntax", "Description") ) process { $uri = Get-Help $Name | Select-Expand relatedLinks.navigationLink.uri -Unique if(!$uri) { throw "Couldn't find online help URL for $Name" } $req = [System.Net.HttpWebRequest]::Create($uri) $req.Method = "HEAD" $response = $req.GetResponse() $uri = $response.ResponseUri.AbsoluteUri + "(pull)" $response.Close() # clean up like a good boy write-verbose "Fetching: $uri" # LEST THERE BE ANY DOUBT: THIS uses HttpRest to convert XHTML to XML $global:OnlineHelpContent = Get-WebPageContent $uri "//*[local-name()='div' and @class='ContentArea']" # Name, Synopsis, Syntax, Description, $NameNode = $global:OnlineHelpContent.SelectSingleNode("//*[local-name()='div' and @class='topic']/*[local-name()='div' and @class='title']") $NameNode.SetAttribute("header","NAME") $global:OnlineHelpContent = $global:OnlineHelpContent.SelectSingleNode("//*[local-name()='div' and @id='mainBody']") $Synopsis = $global:OnlineHelpContent.SelectSingleNode("*[local-name()='p']") $Synopsis.SetAttribute("header","SYNOPSIS") $headers = $OnlineHelpContent.h2 | ForEach-Object { $_.InnerText().Trim() } $content = $OnlineHelpContent.div | ForEach-Object { $_ } $global:help = @{Name=$NameNode; Synopsis=$Synopsis} if($headers.Count -ne $content.Count) { Write-Warning "Unmatched content" foreach($header in $headers) { $help.$header = $OnlineHelpContent.SelectNodes( "//*[preceding-sibling::*[1][local-name()='h2' and normalize-space()='$header']]" ) $help.$header.SetAttribute("header",$header.ToUpper()) } } else { for($h=0;$h -lt $headers.Count; $h++){ $help.($headers[$h]) = $content[$h] $help.($headers[$h]).SetAttribute("header",$headers[$h].ToUpper()) } } $help $content[$Sections] | ForEach-Object { Write-Output Write-Output $_.Header Write-Output Write-Output ($_.InnerText() -replace '^[\\n\\s]*\\n|\\n\\s+$') } } } Get-OnlineHelpContent $Name | out-null $help[$Sections] | ForEach-Object { Write-Host Write-Host $_.Header -Fore Cyan Write-Host Write-Host ($_.InnerText() -replace '^[\\n\\s]*\\n|\\n\\s+$') }
PowerShellCorpus/PoshCode/Install-Solarized.ps1
Install-Solarized.ps1
param($Path = "~\\AppData\\Roaming\\Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar\\Windows PowerShell.lnk" ) # SOLARIZED HEX 16/8 TERMCOL XTERM/HEX L*A*B RGB HSB # --------- ------- ---- ------- ----------- ---------- ----------- ----------- # base03 #002b36 8/4 brblack 234 #1c1c1c 15 -12 -12 0 43 54 193 100 21 # base02 #073642 0/4 black 235 #262626 20 -12 -12 7 54 66 192 90 26 # base01 #586e75 10/7 brgreen 240 #585858 45 -07 -07 88 110 117 194 25 46 # base00 #657b83 11/7 bryellow 241 #626262 50 -07 -07 101 123 131 195 23 51 # base0 #839496 12/6 brblue 244 #808080 60 -06 -03 131 148 150 186 13 59 # base1 #93a1a1 14/4 brcyan 245 #8a8a8a 65 -05 -02 147 161 161 180 9 63 # base2 #eee8d5 7/7 white 254 #e4e4e4 92 -00 10 238 232 213 44 11 93 # base3 #fdf6e3 15/7 brwhite 230 #ffffd7 97 00 10 253 246 227 44 10 99 # yellow #b58900 3/3 yellow 136 #af8700 60 10 65 181 137 0 45 100 71 # orange #cb4b16 9/3 brred 166 #d75f00 50 50 55 203 75 22 18 89 80 # red #dc322f 1/1 red 160 #d70000 50 65 45 220 50 47 1 79 86 # magenta #d33682 5/5 magenta 125 #af005f 50 65 -05 211 54 130 331 74 83 # violet #6c71c4 13/5 brmagenta 61 #5f5faf 50 15 -45 108 113 196 237 45 77 # blue #268bd2 4/4 blue 33 #0087ff 55 -10 -45 38 139 210 205 82 82 # cyan #2aa198 6/6 cyan 37 #00afaf 60 -35 -05 42 161 152 175 74 63 # green #859900 2/2 green 64 #5f8700 60 -20 65 133 153 0 68 100 60 ## On Windows, we don't have "Magenta" and "BrightMagenta" -- We have "Magenta" and "DarkMagenta" ## Consequently, the Solarized order is confusing, we'll use the .Net ConsoleColor order instead $Black = 0 $DarkBlue = 1 $DarkGreen = 2 $DarkCyan = 3 $DarkRed = 4 $DarkMagenta = 5 $DarkYellow = 6 ## Yes, these really are switched, numerically speaking ... ## They're really DarkWhite (Gray) and LightBlack (DarkGray) $Gray = 7 $DarkGray = 8 $Blue = 9 $Green = 10 $Cyan = 11 $Red = 12 $Magenta = 13 $Yellow = 14 $White = 15 # Requires the "Get-Link script":http://poshcode.org/2493 $lnk = Get-Link $Path $lnk.ConsoleColors[$Black] = "#002b36" # Base03 $lnk.ConsoleColors[$DarkBlue] = "#073642" # Base02 $lnk.ConsoleColors[$DarkGreen] = "#586e75" # Base01 $lnk.ConsoleColors[$DarkCyan] = "#657b83" # Base00 $lnk.ConsoleColors[$DarkRed] = "#839496" # Base0 $lnk.ConsoleColors[$DarkMagenta] = "#6c71c4" # Violet $lnk.ConsoleColors[$DarkYellow] = "#cb4b16" # Orange $lnk.ConsoleColors[$Gray] = "#eee8d5" # Base2 $lnk.ConsoleColors[$DarkGray] = "#93a1a1" # Base1 $lnk.ConsoleColors[$Blue] = "#268bd2" # Blue $lnk.ConsoleColors[$Green] = "#859900" # Green $lnk.ConsoleColors[$Cyan] = "#2aa198" # Cyan $lnk.ConsoleColors[$Red] = "#dc322f" # Red $lnk.ConsoleColors[$Magenta] = "#d33682" # Magenta $lnk.ConsoleColors[$Yellow] = "#b58900" # Yellow $lnk.ConsoleColors[$White] = "#fdf6e3" # Base3 $lnk.Save() ## You need to put these at the top of your profile now ... ## BEGIN SOLARIZING ---------------------------------------------- ## Based on whether we're elevated or not, switch between DARK and LIGHT versions of Solarized: if( ([System.Environment]::OSVersion.Version.Major -gt 5) -and ( # Vista and ... new-object Security.Principal.WindowsPrincipal ( # current user is an administrator (Note: ROLE, not GROUP) [Security.Principal.WindowsIdentity]::GetCurrent()) ).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) ) { # Set the WindowTitlePrefix for my prompt function, so it won't need to test for IsInRole Administrator again. $Host.UI.RawUI.WindowTitle = $global:WindowTitlePrefix = "PoSh ${Env:UserName}@${Env:UserDomain} (ADMIN)" $Host.UI.RawUI.BackgroundColor = "White" $Host.UI.RawUI.ForegroundColor = "DarkCyan" } else { $Host.UI.RawUI.WindowTitle = $global:WindowTitlePrefix = "PoSh ${Env:UserName}@${Env:UserDomain}" $Host.UI.RawUI.BackgroundColor = "Black" $Host.UI.RawUI.ForegroundColor = "DarkRed" } Clear-Host $Host.PrivateData.ErrorForegroundColor = "Magenta" $Host.PrivateData.ErrorBackgroundColor = $Host.UI.RawUI.BackgroundColor $Host.PrivateData.WarningForegroundColor = "DarkYellow" $Host.PrivateData.WarningBackgroundColor = $Host.UI.RawUI.BackgroundColor $Host.PrivateData.DebugForegroundColor = "Yellow" $Host.PrivateData.DebugBackgroundColor = $Host.UI.RawUI.BackgroundColor $Host.PrivateData.VerboseForegroundColor = "Blue" $Host.PrivateData.VerboseBackgroundColor = $Host.UI.RawUI.BackgroundColor $Host.PrivateData.ProgressForegroundColor = "Green" $Host.PrivateData.ProgressBackgroundColor = $Host.UI.RawUI.BackgroundColor ## END SOLARIZING ----------------------------------------------
PowerShellCorpus/PoshCode/New-Activity.ps1
New-Activity.ps1
# # By Adam Driscoll # This is very much a test function to see if this was possible. There was no polishing done. Please visit # http://csharpening.net/?p=867 for more information. # function global:Test-IsCommonParameter { param ( $Parameter ) 'WhatIf','Confirm','UseTransaction','Verbose','Debug','OutBuffer','OutVariable','WarningVariable','ErrorVariable','ErrorAction','WarningAction' -contains $Parameter.Name } function global:New-Activity { param( [string] $CommandName, [String] $OutputAssembly ) $Command = Get-Command -Name $CommandName $ParameterString = "" foreach($parameter in $Command.Parameters.Values ) { if (Test-IsCommonParameter -Parameter $Parameter) { continue } $ParameterType = $parameter.ParameterType if ($ParameterType -match "switch") { $ParameterType = "SwitchParameter" } if ($ParameterType -match "scriptblock") { $ParameterType = "ScriptBlock" } $ParameterString += " [ParameterSpecificCategory] public InArgument<$ParameterType> $($Parameter.Name) {get;set;} " } $MethodString = "" foreach($parameter in $command.Parameters.Values) { if (Test-IsCommonParameter -Parameter $Parameter) { continue } $ParameterName = $parameter.Name $MethodString += " if (this.$ParameterName.Expression != null) { shell2.AddParameter(`"$ParameterName`", this.$ParameterName.Get(context)); } " } $ClassName = $Command.Name.Replace("-", "") $FullName = $command.ModuleName + "\\" + $command.Name Add-Type -OutputType Library -OutputAssembly $OutputAssembly -ReferencedAssemblies "System.Activities","C:\\windows\\assembly\\GAC_MSIL\\Microsoft.PowerShell.Workflow.ServiceCore\\3.0.0.0__31bf3856ad364e35\\Microsoft.PowerShell.Workflow.ServiceCore.dll" -TypeDefinition " using System.Activities; using System.Management.Automation; using Microsoft.PowerShell.Activities; using System; namespace CustomActitivies { public sealed class $ClassName : PSRemotingActivity { public $ClassName() { base.DisplayName = `"$ClassName`"; } $ParameterString protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context) { PowerShell shell = PowerShell.Create(); PowerShell shell2 = shell.AddCommand(this.PSCommandName); $MethodString ActivityImplementationContext context2 = new ActivityImplementationContext(); context2.PowerShellInstance = shell; return context2; } public override string PSCommandName { get { return @`"$FullName`"; } } } } " }
PowerShellCorpus/PoshCode/fc04d684-2f9d-418f-9f82-eaef4aa9cfcd.ps1
fc04d684-2f9d-418f-9f82-eaef4aa9cfcd.ps1
Function Get-DrsGroup { <# .SYNOPSIS Retrieves DRS groups from a cluster. .DESCRIPTION Retrieves DRS groups from a cluster. .PARAMETER Cluster Specify the cluster for which you want to retrieve the DRS groups .PARAMETER Name Specify the name of the DRS group you want to retrieve. .EXAMPLE Get-DrsGroup -Cluster $Cluster -Name "VMs DRS Group" Retrieves the DRS group "Vms DRS Group" from cluster $Cluster. .EXAMPLE Get-Cluster | Get-DrsGroup Retrieves all the DRS groups for all clusters. .INPUTS ClusterImpl .OUTPUTS ClusterVmGroup ClusterHostGroup .COMPONENT VMware vSphere PowerCLI #> param([parameter(Mandatory=$true, ValueFromPipeline=$true)]$Cluster, [string] $Name="*") process { $Cluster = Get-Cluster -Name $Cluster if($Cluster) { $Cluster.ExtensionData.ConfigurationEx.Group | ` Where-Object {$_.Name -like $Name} } } } Function Add-VMToDrsGroup { <# .SYNOPSIS Adds a virtual machine to a cluster VM DRS group. .DESCRIPTION Adds a virtual machine to a cluster VM DRS group. .PARAMETER Cluster Specify the cluster for which you want to retrieve the DRS groups .PARAMETER DrsGroup Specify the DRS group you want to retrieve. .PARAMETER VM Specify the virtual machine you want to add to the DRS Group. .EXAMPLE Add-VMToDrsGroup -Cluster $Cluster -DrsGroup "VM DRS Group" -VM $VM Adds virtual machine $VM to the DRS group "VM DRS Group" of cluster $Cluster. .EXAMPLE Get-Cluster MyCluster | Get-VM "A*" | Add-VMToDrsGroup -Cluster MyCluster -DrsGroup $DrsGroup Adds all virtual machines with a name starting with "A" in cluster MyCluster to the DRS group $DrsGroup of cluster MyCluster. .INPUTS VirtualMachineImpl .OUTPUTS Task .COMPONENT VMware vSphere PowerCLI #> param([parameter(Mandatory=$true)] $Cluster, [parameter(Mandatory=$true)] $DrsGroup, [parameter(Mandatory=$true, ValueFromPipeline=$true)] $VM) begin { $Cluster = Get-Cluster -Name $Cluster } process { if ($Cluster) { if ($DrsGroup.GetType().Name -eq "string") { $DrsGroupName = $DrsGroup $DrsGroup = Get-DrsGroup -Cluster $Cluster -Name $DrsGroup } if (-not $DrsGroup) { Write-Error "The DrsGroup $DrsGroupName was not found on cluster $($Cluster.name)." } else { if ($DrsGroup.GetType().Name -ne "ClusterVmGroup") { Write-Error "The DrsGroup $DrsGroupName on cluster $($Cluster.Name) doesn't have the required type ClusterVmGroup." } else { $VM = $Cluster | Get-VM -Name $VM If ($VM) { $spec = New-Object VMware.Vim.ClusterConfigSpecEx $spec.groupSpec = New-Object VMware.Vim.ClusterGroupSpec[] (1) $spec.groupSpec[0] = New-Object VMware.Vim.ClusterGroupSpec $spec.groupSpec[0].operation = "edit" $spec.groupSpec[0].info = $DrsGroup $spec.groupSpec[0].info.vm += $VM.ExtensionData.MoRef $Cluster.ExtensionData.ReconfigureComputeResource_Task($spec, $true) } } } } } }
PowerShellCorpus/PoshCode/Get-Parameter_12.ps1
Get-Parameter_12.ps1
param ( $Cmdlet, [switch]$ShowCommon, [switch]$Full ) $command = Get-Command $Cmdlet -ea silentlycontinue # resolve aliases (an alias can point to another alias) while ($command.CommandType -eq "Alias") { $command = Get-Command ($command.definition) } if (-not $command) { return } foreach ($paramset in $command.ParameterSets){ $Output = @() foreach ($param in $paramset.Parameters) { if ( ! $ShowCommon ) { if ($param.aliases -match "vb|db|ea|wa|ev|wv|ov|ob|wi|cf") { continue } } $process = "" | Select-Object Name, Type, ParameterSet, Aliases, Position, IsMandatory, Pipeline, PipelineByPropertyName $process.Name = $param.Name if ( $param.ParameterType.Name -eq "SwitchParameter" ) { $process.Type = "Boolean" } else { switch -regex ( $param.ParameterType ) { "Nullable``1\\[(.+)\\]" { $process.Type = $matches[1].Split('.')[-1] + " (nullable)" ; break } default { $process.Type = $param.ParameterType.Name } } } if ( $paramset.name -eq "__AllParameterSets" ) { $process.ParameterSet = "Default" } else { $process.ParameterSet = $paramset.Name } $process.Aliases = $param.aliases if ( $param.Position -lt 0 ) { $process.Position = $null } else { $process.Position = $param.Position } $process.IsMandatory = $param.IsMandatory $process.Pipeline = $param.ValueFromPipeline $process.PipelineByPropertyName = $param.ValueFromPipelineByPropertyName $output += $process } if ( ! $Full ) { $Output | Select-Object Name, Type, ParameterSet, IsMandatory, Pipeline } else { Write-Output $Output } }
PowerShellCorpus/PoshCode/convert-vim2css.ps1
convert-vim2css.ps1
param( [string] $vimfile ) # some instructions we don't care for $ignorable = ( 'link', 'clear' ) $nrx = 'hi (?<n>\\w+)' $fgrx = 'guifg=(?<n>#\\w+)' $bgrx = 'guibg=(?<n>#\\w+)' $frx = 'gui=(?<n>\\S+)' (gc $vimfile) | ?{ ($_ -match $nrx) -and ($ignorable -notcontains $matches.n) } | %{ if ( $matches.n -eq 'Normal' ) { write '.codebg {' write ' border-left: solid 1em #303030;' write ' font-size: 1.1em;' write ' padding: 0.8em 0.5em;' } else { write ".$($matches.n) {" } if ( $_ -match $fgrx ) { write " color: $($matches.n);" } if ( $_ -match $bgrx ) { write " background: $($matches.n);" } # element could any combination of these if ( $_ -match $frx ) { switch ( $matches.n.split(',') ) { "italic" { write " font-style: $_;" } "bold" { write " font-weight: $_;" } "underline" { write " text-decoration: $_;" } } } write '}' } # other boilerplate code write 'code {' write ' font-family: Consolas, "DejaVu Sans Mono", "Lucida Console", monospace; ' write '}'
PowerShellCorpus/PoshCode/86.88.239.115.ps1
86.88.239.115.ps1
function Set-IPAddress { param( [string]$networkinterface =$(read-host "Enter the name of the NIC (ie Local Area Connection)"), [string]$ip = $(read-host "Enter an IP Address (ie 10.10.10.10)"), [string]$mask = $(read-host "Enter the subnet mask (ie 255.255.255.0)"), [string]$gateway = $(read-host "Enter the current name of the NIC you want to rename"), [string]$dns1 = $(read-host "Enter the first DNS Server (ie 10.2.0.28)"), [string]$dns2, [string]$registerDns = "TRUE" ) $dns = $dns1 if($dns2){$dns ="$dns1","$dns2"} $index = (gwmi Win32_NetworkAdapter | where {$_.netconnectionid -eq $networkinterface}).InterfaceIndex $NetInterface = Get-WmiObject Win32_NetworkAdapterConfiguration | where {$_.InterfaceIndex -eq $index} $NetInterface.EnableStatic($ip, $subnetmask) $NetInterface.SetGateways($gateway) $NetInterface.SetDNSServerSearchOrder($dns) $NetInterface.SetDynamicDNSRegistration($registerDns) }
PowerShellCorpus/PoshCode/Enable-MailboxJunkEmail..ps1
Enable-MailboxJunkEmail..ps1
@@# Author: Jon Webster @@# Name: Enable-MailboxJunkEmail @@# Created: 1/27/2009 # # Version: 1.0 # History: 1.0 01/27/2009 Initial version param( $Identity, [string]$CasURL, [string]$User, [string]$Password, $DomainController, [switch]$help ) BEGIN { Function Usage { Write-Host @' Enable Server Side Junk E-mail filtering through Outlook Web Access `n Usage: Enable-MailboxJunkEmail -Identity <string> -CasURL <string> -User <string> -Password <string> -DomainController <string> `n Parameters: Identity: The Identity of mailbox who's server side Junk E-mail you want to enable. CasURL: The (OWA) Client Access Server Address of the exchange server you want to use. User: The fullaccess user's 'username' connecting to the mailbox that you want to change. Password: The fullaccess user's 'password' connecting to the mailbox that you want to change. DomainController: The fully qualified domain name (FQDN) of the domain controller that you want to use. `n Example: Enable-MailboxJunkEmail -Identity "john.doe@consoto.com" -CasURL "mail.consoto.com" -User "CONSOTO\\Administrator" -Password "AdminPassword!" '@ } if($help -or $args -contains "-?") { Usage return } Function ValidateParams { # These required parameters are not passed via pipeline # $Identity $ErrorMessage = "" if(!$CasURL) { $ErrorMessage += "Missing parameter: The -CasURL parameter is required. Please pass a valid Client Access Server Url`n" } if(!$User) { $ErrorMessage += "Missing parameter: The -User parameter is required. Please pass a valid Username for OWA mailbox authentication`n" } if(!$Password) { $ErrorMessage += "Missing parameter: The -Password parameter is required. Please pass a valid password for OWA mailbox authentication`n" } if($ErrorMessage) { throw $ErrorMessage break } } Function ValidatePipeline { if($_) { $ErrorMessage = "" if(!$_.Identity) { $ErrorMessage += "Missing Pipeline property: The Identity property is required." } else { Set-Variable -Name Identity -Scope 1 -Value $_.Identity } if($ErrorMessage) { throw $ErrorMessage break } } } Function UpdateJunk { param ([string]$mbMailbox) $xmlstr = "<params><fEnbl>1</fEnbl></params>" $req.Open("POST", "https://" + $CasURL + "/owa/" + $mbMailbox + "/ev.owa?oeh=1&ns=JunkEmail&ev=Enable", $False) $req.setRequestHeader("Content-Type", "text/xml; charset=""UTF-8""") $req.setRequestHeader("Content-Length", $xmlstr.Length) $req.Send($xmlstr) Write-Debug $req.status Write-Debug $req.GetAllResponseHeaders() if($req.status -ne 200) { Write-Error $req.responsetext return } if($req.responsetext -match "name=lngFrm") { Write-Host "Mailbox has not been logged onto before via OWA" $pattern = "<option selected value=""(.*?)"">" $matches = [regex]::Matches($req.responsetext,$pattern) if($matches.count -eq 2) { $lcidarry = $matches[0].Groups[1].Value Write-Debug $lcidarry $tzidarry = $matches[1].Groups[1].Value Write-Debug $tzidarry $pstring = "lcid=" + $lcidarry + "&tzid=" + $tzidarry $req.Open("POST", "https://" + $CasURL + "/owa/" + $mbMailbox + "/lang.owa", $False) $req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded") $req.setRequestHeader("Content-Length", $pstring.Length) # not required? #$req.setRequestHeader("cookie", $reqCadata) # Error here $req.send($pstring) if($req.responsetext -match "errMsg") { # Permission Error Write-Error "Authentication Error" } else { Write-Debug $req.status if($req.status -eq 200 -and $req.responsetext -notmatch "errMsg") { Write-Host "Trying to update the Junk E-mail setting again." UpdateJunk($mbMailbox) Write-Host "Removing OWA Language and Timezone settings..." &{ # We'll get a warning if no properties were modified. # That warning means replication hasn't occurred yet. $warningPreference = "Stop" $script:count = 0 $loop = $true while($loop) { $loop = $false Set-Mailbox $mbMailbox -Languages $null -DomainController $DomainController trap { if($script:count -lt 5) { # Try for up to 20 seconds Write-Debug "Unable to Reset Languages trying again in 5 seconds." Sleep 5 Set-Variable -Name loop -Scope 1 -Value $true $script:count++ } else { Write-Debug "Failed." } continue } } $warningPreference = "Continue" } } else { Write-Warning "Failed to set Default OWA settings" } } } else { Write-Warning "Script failed to retrieve default values" } Write-Host "Junk E-Mail setting Changed Successfully" } } ValidateParams } PROCESS { ValidatePipeline $mbx = Get-Mailbox -Identity $Identity -DomainController $DomainController -ErrorAction SilentlyContinue if(!$mbx) {throw "Invalid Mailbox specified: $Identity"} $szXml = "destination=https://" + $CasURL + "/owa/&flags=0&username=" + $User $szXml = $szXml + "&password=" + $Password + "&SubmitCreds=Log On&forcedownlevel=0&trusted=0" $req = New-Object -COMObject "MSXML2.ServerXMLHTTP.6.0" $req.Open("POST", "https://" + $CasURL + "/owa/auth/owaauth.dll", $False) $req.SetOption(2, 13056) $req.Send($szXml) Write-Debug $req.GetAllResponseHeaders() if($req.responsetext -match "wrng") { Write-Error "The user name or password that you entered is not valid. Try entering it again." return; } UpdateJunk($mbx.PrimarySMTPAddress) }
PowerShellCorpus/PoshCode/VMware Daily Report.ps1
VMware Daily Report.ps1
# vCheck - Daily Error Report # # Changes: # Version 1.10 - Added How many days old the snapshots are # Version 1.9 - Added ability to change user account which makes the WMI calls # Version 1.8 - Added Real name resolution via AD and sorted disk space by PerfFree # Version 1.7 - Added Event Logs for VMware warnings and errors for past day # Version 1.6 - Add details to service state to see if it is expected or not # Version 1.5 - Check for objects to see if they exist before sending the email + add VMs with No VMTools # Using mail script by Jakob Bindslet (jakob@bindslet.dk), 20. december 2007 param( [string] $VISRV) # You can change the following defaults by altering the below settings: # # Set the SMTP Server address $SMTPSRV = "myexchangeserver.mydomain.comk" # Set the Email address to recieve from $EmailFrom = "reports@mydomain.com" # Set the Email address to send the email to $EmailTo = "myemail@mydomain.com" #### Detail Settings #### # Set the username of the account with permissions to access the VI Server # for event logs and service details - you will be asked for the same username and password # only the first time this runs after setting the below username. # If it is left blank it will use the credentials of the user who runs the script $SetUsername = "" # Set the location to store the credentials in a secure manner $CredFile = ".\\mycred.crd" # Set the warning threshold for Datastore % Free Space $DatastoreSpace = "5" # Set the warning threshold for snapshots in days old $SnapshotAge = 14 # Set the number of days to show VMs created & removed for $VMsNewRemovedAge = 5 # Set the number of days of VC Events to check for errors $VCEventAge = 1 # Set tge bumber of days of VC Event Logs to check for warnings and errors $VCEvntlgAge = 1 ####################################### # Start of script if ($VISRV -eq ""){ Write-Host Write-Host "Please specify a VI Server name eg...." Write-Host " powershell.exe DailyReport.ps1 MYVISERVER" Write-Host Write-Host exit } function Send-SMTPmail() { ## Setting defaults $to = $null; $from = $null; $from = $null; $subject = $null; $body = $null; $attachment = $null; $html = $null; $cc = $null; $bcc = $null; $port = $null $alert = $null; $timeout = $null $LastArg = $args.length -1 for ($i = 0; $i -le $LastArg; $i += 2) { if ($args[$i].substring(0,1) -eq "-") { switch ($args[$i]) { -smtpserver {$smtpserver = $args[$i+1]} -to {$to = $args[$i+1]} -from {$from = $args[$i+1]} -subject {$subject = $args[$i+1]} -body {$body = $args[$i+1]} -attachment {$attachment = $args[$i+1]} -html {$html = "yes"} -cc {$cc = $args[$i+1]} -bcc {$bcc = $args[$i+1]} -port {$port = $args[$i+1]} -alert {$alert = "yes"} -timeout {$timeout = $args[$i+1]} } } } $mailer = new-object Net.Mail.SMTPclient($smtpserver) if ($port -ne $null) {$mailer.port = $port} if ($timeout -ne $null) {$mailer.timeout = $timeout} $msg = new-object Net.Mail.MailMessage($from,$to,$subject,$body) if ($html -eq "yes") {$msg.IsBodyHTML = $true} if ($cc -ne $null) {$msg.cc.add($cc)} if ($bcc -ne $null) {$msg.bcc.add($bcc)} if ($alert -eq "yes") {$msg.Headers.Add("message-id", "<3bd50098e401463aa228377848493927-1>")} if ($attachment -ne $null) { $attachment = new-object Net.Mail.Attachment($attachment) $msg.attachments.add($attachment) } $mailer.send($msg) } Function Get-CustomHTML ($Header){ $Report = @" <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"> <html><head><title>$($Header)</title> <META http-equiv=Content-Type content='text/html; charset=windows-1252'> <meta name="save" content="history"> <style type="text/css"> DIV .expando {DISPLAY: block; FONT-WEIGHT: normal; FONT-SIZE: 10pt; RIGHT: 8px; COLOR: #ffffff; FONT-FAMILY: Tahoma; POSITION: absolute; TEXT-DECORATION: underline} TABLE {TABLE-LAYOUT: fixed; FONT-SIZE: 100%; WIDTH: 100%} *{margin:0} .dspcont { BORDER-RIGHT: #bbbbbb 1px solid; BORDER-TOP: #bbbbbb 1px solid; PADDING-LEFT: 16px; FONT-SIZE: 8pt;MARGIN-BOTTOM: -1px; PADDING-BOTTOM: 5px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; WIDTH: 95%; COLOR: #000000; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; BACKGROUND-COLOR: #f9f9f9} .filler {BORDER-RIGHT: medium none; BORDER-TOP: medium none; DISPLAY: block; BACKGROUND: none transparent scroll repeat 0% 0%; MARGIN-BOTTOM: -1px; FONT: 100%/8px Tahoma; MARGIN-LEFT: 43px; BORDER-LEFT: medium none; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: medium none; POSITION: relative} .save{behavior:url(#default#savehistory);} .dspcont1{ display:none} a.dsphead0 {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 5px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; CURSOR: hand; COLOR: #FFFFFF; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; WIDTH: 95%; BACKGROUND-COLOR: #cc0000} a.dsphead1 {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 5px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; CURSOR: hand; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; WIDTH: 95%; BACKGROUND-COLOR: #7BA7C7} a.dsphead2 {BORDER-RIGHT: #bbbbbb 1px solid; PADDING-RIGHT: 5em; BORDER-TOP: #bbbbbb 1px solid; DISPLAY: block; PADDING-LEFT: 5px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; MARGIN-BOTTOM: -1px; MARGIN-LEFT: 0px; BORDER-LEFT: #bbbbbb 1px solid; CURSOR: hand; COLOR: #ffffff; MARGIN-RIGHT: 0px; PADDING-TOP: 4px; BORDER-BOTTOM: #bbbbbb 1px solid; FONT-FAMILY: Tahoma; POSITION: relative; HEIGHT: 2.25em; WIDTH: 95%; BACKGROUND-COLOR: #A5A5A5} a.dsphead1 span.dspchar{font-family:monospace;font-weight:normal;} td {VERTICAL-ALIGN: TOP; FONT-FAMILY: Tahoma} th {VERTICAL-ALIGN: TOP; COLOR: #cc0000; TEXT-ALIGN: left} BODY {margin-left: 4pt} BODY {margin-right: 4pt} BODY {margin-top: 6pt} </style> </head> <body> <b><font face="Arial" size="5">$($Header)</font></b><hr size="8" color="#cc0000"> <font face="Arial" size="1"><b>Generated on $($ENV:Computername)</b></font><br> <font face="Arial" size="1">Report created on $(Get-Date)</font> <div class="filler"></div> <div class="filler"></div> <div class="filler"></div> <div class="save"> "@ Return $Report } Function Get-CustomHeader0 ($Title){ $Report = @" <h1><a class="dsphead0">$($Title)</a></h1> <div class="filler"></div> "@ Return $Report } Function Get-CustomHeader ($Num, $Title){ $Report = @" <h2><a class="dsphead$($Num)"> $($Title)</a></h2> <div class="dspcont"> "@ Return $Report } Function Get-CustomHeaderClose{ $Report = @" </DIV> <div class="filler"></div> "@ Return $Report } Function Get-CustomHeader0Close{ $Report = @" </DIV> "@ Return $Report } Function Get-CustomHTMLClose{ $Report = @" </div> </body> </html> "@ Return $Report } Function Get-HTMLTable { param([array]$Content) $HTMLTable = $Content | ConvertTo-Html $HTMLTable = $HTMLTable -replace '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">', "" $HTMLTable = $HTMLTable -replace '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">', "" $HTMLTable = $HTMLTable -replace '<html xmlns="http://www.w3.org/1999/xhtml">', "" $HTMLTable = $HTMLTable -replace '<html>', "" $HTMLTable = $HTMLTable -replace '<head>', "" $HTMLTable = $HTMLTable -replace '<title>HTML TABLE</title>', "" $HTMLTable = $HTMLTable -replace '</head><body>', "" $HTMLTable = $HTMLTable -replace '</body></html>', "" Return $HTMLTable } Function Get-HTMLDetail ($Heading, $Detail){ $Report = @" <TABLE> <tr> <th width='25%'><b>$Heading</b></font></th> <td width='75%'>$($Detail)</td> </tr> </TABLE> "@ Return $Report } function Find-Username ($username){ if ($username -ne $null) { $root = [ADSI]"" $filter = ("(&(objectCategory=user)(samAccountName=$Username))") $ds = new-object system.DirectoryServices.DirectorySearcher($root,$filter) $ds.PageSize = 1000 $ds.FindOne() } } function Get-VIServices { If ($SetUsername -ne ""){ $Services = get-wmiobject win32_service -Credential $creds -ComputerName $VISRV | Where {$_.DisplayName -like "VMware*" } } Else { $Services = get-wmiobject win32_service -ComputerName $VISRV | Where {$_.DisplayName -like "VMware*" } } $myCol = @() Foreach ($service in $Services){ $MyDetails = "" | select-Object Name, State, StartMode, Health If ($service.StartMode -eq "Auto") { if ($service.State -eq "Stopped") { $MyDetails.Name = $service.Displayname $MyDetails.State = $service.State $MyDetails.StartMode = $service.StartMode $MyDetails.Health = "Unexpected State" } } If ($service.StartMode -eq "Auto") { if ($service.State -eq "Running") { $MyDetails.Name = $service.Displayname $MyDetails.State = $service.State $MyDetails.StartMode = $service.StartMode $MyDetails.Health = "OK" } } If ($service.StartMode -eq "Disabled") { If ($service.State -eq "Running") { $MyDetails.Name = $service.Displayname $MyDetails.State = $service.State $MyDetails.StartMode = $service.StartMode $MyDetails.Health = "Unexpected State" } } If ($service.StartMode -eq "Disabled") { if ($service.State -eq "Stopped") { $MyDetails.Name = $service.Displayname $MyDetails.State = $service.State $MyDetails.StartMode = $service.StartMode $MyDetails.Health = "OK" } } $myCol += $MyDetails } Write-Output $myCol } function Get-DatastoreSummary { param( $InputObject = $null ) begin { } process { if ($InputObject -and $_) { throw 'The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.' return } $processObject = $(if ($InputObject) {$InputObject} else {$_}) if ($processObject) { $myCol = @() foreach ($ds in $_) { $MyDetails = "" | select-Object Name, Type, CapacityMB, FreeSpaceMB, PercFreeSpace $MyDetails.Name = $ds.Name $MyDetails.Type = $ds.Type $MyDetails.CapacityMB = $ds.CapacityMB $MyDetails.FreeSpaceMB = $ds.FreeSpaceMB $MyDetails.PercFreeSpace = [math]::Round(((100 * ($ds.FreeSpaceMB)) / ($ds.CapacityMB)),0) $myCol += $MyDetails } $myCol | Where { $_.PercFreeSpace -lt $DatastoreSpace } } } end { } } function Get-SnapshotSummary { param( $InputObject = $null ) BEGIN { } PROCESS { if ($InputObject -and $_) { throw 'ParameterBinderStrings\\AmbiguousParameterSet' break } elseif ($InputObject) { $InputObject } elseif ($_) { $mySnaps = @() foreach ($snap in $_){ $SnapshotInfo = Get-SnapshotExtra $snap $mySnaps += $SnapshotInfo } $mySnaps | Select VM, Name, @{N="DaysOld";E={((Get-Date) - $_.Created).Days}}, @{N="Creator";E={(Find-Username (($_.Creator.split("\\"))[1])).Properties.displayname}}, Created, Description | Sort DaysOld } else { throw 'ParameterBinderStrings\\InputObjectNotBound' } } END { } } function Get-SnapshotTree{ param($tree, $target) $found = $null foreach($elem in $tree){ if($elem.Snapshot.Value -eq $target.Value){ $found = $elem continue } } if($found -eq $null -and $elem.ChildSnapshotList -ne $null){ $found = Get-SnapshotTree $elem.ChildSnapshotList $target } return $found } function Get-SnapshotExtra ($snap){ $guestName = $snap.VM # The name of the guest $tasknumber = 999 # Windowsize of the Task collector $taskMgr = Get-View TaskManager # Create hash table. Each entry is a create snapshot task $report = @{} $filter = New-Object VMware.Vim.TaskFilterSpec $filter.Time = New-Object VMware.Vim.TaskFilterSpecByTime $filter.Time.beginTime = (($snap.Created).AddDays(-5)) $filter.Time.timeType = "startedTime" $collectionImpl = Get-View ($taskMgr.CreateCollectorForTasks($filter)) $dummy = $collectionImpl.RewindCollector $collection = $collectionImpl.ReadNextTasks($tasknumber) while($collection -ne $null){ $collection | where {$_.DescriptionId -eq "VirtualMachine.createSnapshot" -and $_.State -eq "success" -and $_.EntityName -eq $guestName} | %{ $row = New-Object PsObject $row | Add-Member -MemberType NoteProperty -Name User -Value $_.Reason.UserName $vm = Get-View $_.Entity if($vm -ne $null){ $snapshot = Get-SnapshotTree $vm.Snapshot.RootSnapshotList $_.Result if($snapshot -ne $null){ $key = $_.EntityName + "&" + ($snapshot.CreateTime.ToString()) $report[$key] = $row } } } $collection = $collectionImpl.ReadNextTasks($tasknumber) } $collectionImpl.DestroyCollector() # Get the guest's snapshots and add the user $snapshotsExtra = $snap | % { $key = $_.vm.Name + "&" + ($_.Created.ToString()) if($report.ContainsKey($key)){ $_ | Add-Member -MemberType NoteProperty -Name Creator -Value $report[$key].User } $_ } $snapshotsExtra } Function Set-Cred ($File) { $Credential = Get-Credential $credential.Password | ConvertFrom-SecureString | Set-Content $File } Function Get-Cred ($User,$File) { $password = Get-Content $File | ConvertTo-SecureString $credential = New-Object System.Management.Automation.PsCredential($user,$password) $credential } If ($SetUsername -ne ""){ if ((Test-Path -Path $CredFile) -eq $false) { Set-Cred $CredFile } $creds = Get-Cred $SetUsername $CredFile } $VIServer = Connect-VIServer $VISRV If ($VIServer.IsConnected -ne $true){ # Fix for scheduled tasks not running. $USER = $env:username $APPPATH = "C:\\Documents and Settings\\" + $USER + "\\Application Data" #SET THE APPDATA ENVIRONMENT WHEN NEEDED if ($env:appdata -eq $null -or $env:appdata -eq 0) { $env:appdata = $APPPATH } $VIServer = Connect-VIServer $VISRV If ($VIServer.IsConnected -ne $true){ send-SMTPmail -to $EmailTo -from $EmailFrom -subject "ERROR: $VISRV Daily Report" -smtpserver $SMTPSRV -body "The Connect-VISERVER Cmdlet did not work, please check you VI Server." exit } } $VM = Get-VM $VMH = Get-VMHost $Clusters = Get-Cluster $Datastores = Get-Datastore $FullVM = Get-View -ViewType VirtualMachine $MyReport = Get-CustomHTML "$VIServer Daily Report" $MyReport += Get-CustomHeader0 ($VIServer.Name) # ---- General Summary Info ---- $MyReport += Get-CustomHeader "1" "General Details" $MyReport += Get-HTMLDetail "Number of Hosts:" (($VMH).Count) $MyReport += Get-HTMLDetail "Number of VMs:" (($VM).Count) $MyReport += Get-HTMLDetail "Number of Clusters:" (($Clusters).Count) $MyReport += Get-HTMLDetail "Number of Datastores:" (($Datastores).Count) $MyReport += Get-CustomHeaderClose # ---- Snapshot Information ---- $Snapshots = $VM | Get-Snapshot | Where {$_.Created -lt ((Get-Date).AddDays(-$SnapshotAge))} | Get-SnapshotSummary If (($Snapshots | Measure-Object).count -gt 0) { $MyReport += Get-CustomHeader "1" "Snapshots (Over $SnapshotAge Days Old)" $MyReport += Get-HTMLTable $Snapshots $MyReport += Get-CustomHeaderClose } # ---- Datastore Information ---- $OutputDatastores = $Datastores | Get-DatastoreSummary | Sort PercFreeSpace If (($OutputDatastores | Measure-Object).count -gt 0) { $MyReport += Get-CustomHeader "1" "Datastores (Less than $DatastoreSpace% Free)" $MyReport += Get-HTMLTable $OutputDatastores $MyReport += Get-CustomHeaderClose } # ---- VMs created or Cloned ---- $VIEvent = Get-VIEvent -maxsamples 10000 -Start (Get-Date).AddDays(-$VMsNewRemovedAge) $OutputCreatedVMs = $VIEvent | where {$_.Gettype().Name -eq "VmCreatedEvent" -or $_.Gettype().Name -eq "VmBeingClonedEvent" -or $_.Gettype().Name -eq "VmBeingDeployedEvent"} | Select createdTime, @{N="User";E={(Find-Username (($_.userName.split("\\"))[1])).Properties.displayname}}, fullFormattedMessage If (($OutputCreatedVMs | Measure-Object).count -gt 0) { $MyReport += Get-CustomHeader "1" "VMs Created or Cloned (Last $VMsNewRemovedAge Day(s))" $MyReport += Get-HTMLTable $OutputCreatedVMs $MyReport += Get-CustomHeaderClose } # ---- VMs Removed ---- $OutputRemovedVMs = $VIEvent | where {$_.Gettype().Name -eq "VmRemovedEvent"}| Select createdTime, @{N="User";E={(Find-Username (($_.userName.split("\\"))[1])).Properties.displayname}}, fullFormattedMessage If (($OutputRemovedVMs | Measure-Object).count -gt 0) { $MyReport += Get-CustomHeader "1" "VMs Removed (Last $VMsNewRemovedAge Day(s))" $MyReport += Get-HTMLTable $OutputRemovedVMs $MyReport += Get-CustomHeaderClose } # ---- VC Errors ---- $OutputErrors = Get-VIEvent -maxsamples 10000 -Start (Get-Date).AddDays(-$VCEventAge ) -Type Error | Select createdTime, @{N="User";E={(Find-Username (($_.userName.split("\\"))[1])).Properties.displayname}}, fullFormattedMessage If (($OutputErrors | Measure-Object).count -gt 0) { $MyReport += Get-CustomHeader "1" "Error Events (Last $VCEventAge Day(s))" $MyReport += Get-HTMLTable $OutputErrors $MyReport += Get-CustomHeaderClose } # ---- No VM Tools ---- $NoTools = $FullVM | Where { $_.Runtime.PowerState -eq "poweredOn" } | Select Name, @{N="ToolsVersion"; E={$_.Config.tools.toolsVersion}} | Where { $_.ToolsVersion -eq 0} | Select Name If (($NoTools | Measure-Object).count -gt 0) { $MyReport += Get-CustomHeader "1" "No VMTools" $MyReport += Get-HTMLTable $NoTools $MyReport += Get-CustomHeaderClose } # ---- CD-Roms Connected ---- $CDConn = $VM | Where { $_ | Get-CDDrive | Where { $_.ConnectionState.Connected -eq "true" } } | Select Name, Host If (($CDConn | Measure-Object).count -gt 0) { $MyReport += Get-CustomHeader "1" "VM: CD-ROM Connected - VMotion Violation" $MyReport += Get-HTMLTable $CDConn $MyReport += Get-CustomHeaderClose } # ---- Floppys Connected ---- $Floppy = $VM | Where { $_ | Get-FloppyDrive | Where { $_.ConnectionState.Connected -eq "true" } } | Select Name, Host If (($Floppy | Measure-Object).count -gt 0) { $MyReport += Get-CustomHeader "1" "VM:Floppy Drive Connected - VMotion Violation" $MyReport += Get-HTMLTable $Floppy $MyReport += Get-CustomHeaderClose } # ---- Virtual Center Details ---- $MyReport += Get-CustomHeader "1" "$VIServer Service Details" $MyReport += Get-HTMLTable (Get-VIServices) $MyReport += Get-CustomHeaderClose # ---- Virtual Center Event Logs - Error ---- $ConvDate = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime([DateTime]::Now.AddDays(-$VCEvntlgAge)) If ($SetUsername -ne ""){ $ErrLogs = Get-WmiObject -Credential $creds -computer $VIServer -query ("Select * from Win32_NTLogEvent Where Type='Error' and TimeWritten >='" + $ConvDate + "'") | Where {$_.Message -like "*VMware*"} | Select @{N="TimeGenerated";E={$_.ConvertToDateTime($_.TimeGenerated)}}, Message } Else { $ErrLogs = Get-WmiObject -computer $VIServer -query ("Select * from Win32_NTLogEvent Where Type='Error' and TimeWritten >='" + $ConvDate + "'") | Where {$_.Message -like "*VMware*"} | Select @{N="TimeGenerated";E={$_.ConvertToDateTime($_.TimeGenerated)}}, Message } If (($ErrLogs | Measure-Object).count -gt 0) { $MyReport += Get-CustomHeader "1" "$VIServer Event Logs: Error" $MyReport += Get-HTMLTable ($ErrLogs) $MyReport += Get-CustomHeaderClose } # ---- Virtual Center Event Logs - Warning ---- $ConvDate = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime([DateTime]::Now.AddDays(-1)) If ($SetUsername -ne ""){ $WarnLogs = Get-WmiObject -Credential $creds -computer $VIServer -query ("Select * from Win32_NTLogEvent Where Type='Warning' and TimeWritten >='" + $ConvDate + "'") | Where {$_.Message -like "*VMware*"} | Select @{N="TimeGenerated";E={$_.ConvertToDateTime($_.TimeGenerated)}}, Message } Else { $WarnLogs = Get-WmiObject -computer $VIServer -query ("Select * from Win32_NTLogEvent Where Type='Warning' and TimeWritten >='" + $ConvDate + "'") | Where {$_.Message -like "*VMware*"} | Select @{N="TimeGenerated";E={$_.ConvertToDateTime($_.TimeGenerated)}}, Message } If (($WarnLogs | Measure-Object).count -gt 0) { $MyReport += Get-CustomHeader "1" "$VIServer Event Logs: Warning" $MyReport += Get-HTMLTable ($WarnLogs) $MyReport += Get-CustomHeaderClose } $MyReport += Get-CustomHeader0Close $MyReport += Get-CustomHTMLClose #Uncomment the following lines to save the htm file in a central location #$Date = Get-Date #$Filename = "C:\\Temp\\" + $VIServer + "DailyReport" + "_" + $Date.Day + "-" + $Date.Month + "-" + $Date.Year + ".htm" #$MyReport | out-file -encoding ASCII -filepath $Filename #Invoke-Item $Filename send-SMTPmail -to $EmailTo -from $EmailFrom -subject "$VISRV Daily Report" -smtpserver $SMTPSRV -body $MyReport -html "yes" $VIServer | Disconnect-VIServer -Confirm:$false
PowerShellCorpus/PoshCode/Test-Host.ps1
Test-Host.ps1
function Test-Host { <# .Synopsis Test a host for connectivity using either WMI ping or TCP port .Description Allows you to test a host for connectivity before further processing .Parameter Server Name of the Server to Process. .Parameter TCPPort TCP Port to connect to. (default 135) .Parameter Timeout Timeout for the TCP connection (default 1 sec) .Parameter Property Name of the Property that contains the value to test. .Example # To test a list of hosts. cat ServerFile.txt | Test-Host | Invoke-DoSomething .Example # To test a list of hosts against port 80. cat ServerFile.txt | Test-Host -tcp 80 | Invoke-DoSomething .Example # To test the output of Get-ADComputer using the dnshostname property Get-ADComputer | Test-Host -property dnsHostname | Invoke-DoSomething .OUTPUTS Object .INPUTS object .Link N/A NAME: Test-Host AUTHOR: YetiCentral\\bshell Website: www.bsonposh.com LASTEDIT: 02/04/2009 18:25:15 #Requires -Version 2.0 #> [CmdletBinding()] Param( [Parameter(ValueFromPipeline=$true,Mandatory=$True)] [string]$Server, [Parameter()] [int]$TCPPort, [Parameter()] [int]$timeout=1000, [Parameter()] [string]$property ) Begin { function TestPort { Param($srv,$tport,$tmOut) Write-Verbose " [TestPort] :: Start" Write-Verbose " [TestPort] :: Setting Error state = 0" $ErrorActionPreference = "SilentlyContinue" Write-Verbose " [TestPort] :: Creating [system.Net.Sockets.TcpClient] instance" $tcpclient = New-Object system.Net.Sockets.TcpClient Write-Verbose " [TestPort] :: Calling BeginConnect($srv,$tport,$null,$null)" $iar = $tcpclient.BeginConnect($srv,$tport,$null,$null) Write-Verbose " [TestPort] :: Waiting for timeout [$timeout]" $wait = $iar.AsyncWaitHandle.WaitOne($tmOut,$false) # Traps trap { Write-Verbose " [TestPort] :: General Exception" Write-Verbose " [TestPort] :: End" return $false } trap [System.Net.Sockets.SocketException] { Write-Verbose " [TestPort] :: Exception: $($_.exception.message)" Write-Verbose " [TestPort] :: End" return $false } if(!$wait) { $tcpclient.Close() Write-Verbose " [TestPort] :: Connection Timeout" Write-Verbose " [TestPort] :: End" return $false } else { Write-Verbose " [TestPort] :: Closing TCP Sockett" $tcpclient.EndConnect($iar) | out-Null $tcpclient.Close() } if($?){Write-Verbose " [TestPort] :: End";return $true} } function PingServer { Param($MyHost) Write-Verbose " [PingServer] :: Pinging $MyHost" $pingresult = Get-WmiObject win32_pingstatus -f "address='$MyHost'" Write-Verbose " [PingServer] :: Ping returned $($pingresult.statuscode)" if($pingresult.statuscode -eq 0) {$true} else {$false} } } Process { Write-Verbose "" Write-Verbose " Server : $Server" if($TCPPort) { Write-Verbose " Timeout : $timeout" Write-Verbose " Port : $TCPPort" if($property) { Write-Verbose " Property : $Property" if(TestPort $Server.$property -tport $TCPPort -tmOut $timeout){$Server} } else { if(TestPort $Server -tport $TCPPort -tmOut $timeout){$Server} } } else { if($property) { Write-Verbose " Property : $Property" if(PingServer $Server.$property){$Server} } else { Write-Verbose " Simple Ping" if(PingServer $Server){$Server} } } Write-Verbose "" } }
PowerShellCorpus/PoshCode/chkhash.ps1
chkhash.ps1
# calculate SHA512 of file. function Get-SHA512([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]')) { $stream = $null; $cryptoServiceProvider = [System.Security.Cryptography.SHA512CryptoServiceProvider]; $hashAlgorithm = new-object $cryptoServiceProvider $stream = $file.OpenRead(); $hashByteArray = $hashAlgorithm.ComputeHash($stream); $stream.Close(); ## We have to be sure that we close the file stream if any exceptions are thrown. trap { if ($stream -ne $null) { $stream.Close(); } break; } foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }} return [string]$result; } # chkhash.ps1 [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #3] [-u] [-h [path of .xml database]] # -u updates the XML file database and exits # otherwise, all files are checked against the XML file database. # -h specifies location of xml hash database $hashespath=".\\hashes.xml" del variable:\\args3 -ea 0 del variable:\\args2 -ea 0 del variable:\\xfiles -ea 0 del variable:\\files -ea 0 $args3=@() $args2=$args $nu = 0 $errs = 0 $fc = 0 $upd = $false $create = $false for($i=0;$i -lt $args2.count; $i++) { if ($args2[$i] -like "-h*") # -help specified? { "Usage: .\\chkhash.ps1 [-h] [-u] [-c] [-x <file path of hashes .xml database>] [file(s)/dir #1] [file(s)/dir #2] ... [file(s)/dir #n]" "Options: -h - Help display." " -c - Create hash database. If .xml hash database does not exist, -c will be assumed." " -u - Update changed files and add new files to existing database." " -x - specifies .xml database file path to use. Default is .\\hashes.xml" "" "Examples: PS>.\\chkhash.ps1 c:\\ d:\\ -c -x c:\\users\\bob\\hashes\\hashes.xml" " PS>.\\chkhash.ps1 c:\\users\\alice\\pictures\\sunset.jpg -a -x c:\\users\\alice\\hashes\\pictureshashes.xml" " PS>.\\chkhash.ps1 c:\\users\\eve\\documents d:\\media\\movies -x c:\\users\\eve\\hashes\\private.xml" "" "Note: files in subdirectories of any specified directory are automatically processed." exit } if ($args2[$i] -like "-u*") {$upd=$true;continue} # Update and Add new files to database? if ($args2[$i] -like "-c*") {$create=$true;continue} # Create database specified? if ($args2[$i] -like "-x*") {$i++;$hashespath=$args2[$i];continue} # Get hashes xml database path $args3+=@($args2[$i]) # Add files/dirs } "ChkHash.ps1 - .\\chkhash.ps1 -h for usage." "" if ($args3.count -eq 0) {exit} # Get list of files and SHA512 hash them. "Enumerating files from specified locations..." $files=@(dir $args3 -recurse -ea 0 | ?{$_.mode -notmatch "d"}) # Get list of files if ($files.count -eq 0) {"No files found. Exiting."; exit} if ($create -eq $true -or !(test-path $hashespath)) # Create database? { # Create SHA512 hashes of files and write to new database $files = $files | %{write-host "Hashing $($_.fullname) ...";add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru} $files |export-clixml $hashespath "Created $hashespath" "$($files.count) file hashes saved. Exiting." exit } $xfiles=@(import-clixml $hashespath) "Loaded $($xfiles.count) file hash(es) from $hashespath" $hash=@{} for($x=0;$x -lt $xfiles.count; $x++) { if ($hash.contains($xfiles[$x].fullname)) {continue} $hash.Add($xfiles[$x].fullname,$x) } foreach($f in $files) { $n=($hash.($f.fullname)) if ($n -eq $null) { $nu++ # increment needs/needed updating count if ($upd -eq $false) {"Needs to be added: `"$($f.fullname)`"";continue} # if not updating, then continue "Hashing $($f.fullname) ..." # Create SHA512 hash of file $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru} $xfiles+=@($f) # then add file + hash to list continue } $f=$f |%{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $(get-SHA512 $_.fullname) -passthru} # Update and continue is specified. $fc++ # increment files checked. if ($xfiles[$n].SHA512 -eq $f.SHA512) # Check SHA512 for mixmatch. { continue } $errs++ # increment mixmatches if ($upd -eq $true) { $xfiles[$n]=$f; "Updated `"$($f.fullname)`"";continue} "Bad SHA-512 found: `"$($f.fullname)`"" } if ($upd -eq $true) # if database updated { $xfiles|export-clixml $hashespath # write xml database "Updated $hashespath" "$nu file hash(es) added to database." "$errs file hash(es) updated in database." exit } "$errs SHA-512 mixmatch(es) found." "$fc file(s) SHA512 matched." if ($nu -ne 0) {"$nu file(s) need to be added [run with -u option to Add file hashes to database]."}
PowerShellCorpus/PoshCode/PowerOAuth 1.1.ps1
PowerOAuth 1.1.ps1
#requires -Version 2.0 ##requires -Module HttpRest -Version 1.2 # http://poshcode.org/1262 Set-StrictMode -Version 2.0 $null = [Reflection.Assembly]::LoadWithPartialName('System.Web') $safeChars = [char[]]'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~' function Get-OAuthBase { #.Synopsis # Get the basic OAuth Authorization values #.Parameter ConsumerKey # The OAuth Consumer Key #.Parameter AccessToken # The OAuth Access token #.Parameter AccessVerifier # The OAuth Access verifier from the user's interaction with the web site ... #.ReturnValue # A HashTable containing the key-value pairs needed for further requests, including the # oauth_consumer_key, oauth_signature_method, oauth_timestamp, oauth_nonce, oauth_version, and optionally, the oauth_token. PARAM( [Parameter(Mandatory=$true)]$ConsumerKey , [Parameter(Mandatory=$false)]$AccessToken , [Parameter(Mandatory=$false)]$AccessVerifier , [Parameter(Mandatory=$false)] [ValidateSet("HMAC-SHA1", "PLAINTEXT")] [String] $SignatureMethod = "HMAC-SHA1" ) END { @{ oauth_consumer_key = Format-OAuth $ConsumerKey oauth_signature_method = $SignatureMethod # The signature method the Consumer used to sign the request oauth_timestamp = [int]((Get-Date).ToUniversalTime() - (Get-Date 1/1/1970)).TotalSeconds oauth_nonce = [guid]::NewGuid().GUID -replace '-' oauth_version = '1.0' # OPTIONAL: If present, value MUST be 1.0 } + $(if($AccessToken){ @{oauth_token = $AccessToken } } else { @{} } ) + $(if($AccessVerifier){ @{oauth_verifier = $AccessVerifier } } else { @{} }) # $FFAccessToken.oauth_token }} function Format-OAuth { #.Synopsis # UrlEncode, but with upper-case hex #.Parameter value # The text to encode PARAM([Parameter(ValueFromPipeline=$true)][string]$value) PROCESS { $result = New-Object System.Text.StringBuilder foreach($c in $value.ToCharArray()){ if($safeChars -notcontains $c) { $null = $result.Append( ('%{0:X2}' -f [int]$c) ) } else { $null = $result.Append($c) } } write-output $result.ToString() }} function ConvertTo-Hashtable { #.Synopsis # Convert a query string into a hashtable #.Parameter string # The query string to convert #.Parameter PairSeparator # The string separating each set of key=value pairs #.Parameter KeyValueSeparator # The string separating the keys from the values #.ReturnValue # The hashtable created from reading the query string PARAM( [Parameter(ValueFromPipeline=$true, Position=0, Mandatory=$true)] [String] $string , [Parameter(Position=1)] [String] $PairSeparator = '&' , [Parameter(Position=2)] [String] $KeyValueSeparator = '=' ) PROCESS { $result = @{} foreach($w in $string.split($pairSeparator) ) { $k,$v = $w.split($KeyValueSeparator,2) $result.Add($k,$v) } write-output $result } } function ConvertFrom-Hashtable { #.Synopsis # Convert a hashtable into a query string #.Description # Converts a hashtable into a query string by joining the keys to the values, and then joining all the pairs together #.Parameter values # The hashtable to convert #.Parameter PairSeparator # The string used to concatenate the sets of key=value pairs, defaults to "&" #.Parameter KeyValueSeparator # The string used to concatenate the keys to the values, defaults to "=" #.ReturnValue # The query string created by joining keys to values and then joining them all together into a single string PARAM( [Parameter(ValueFromPipeline=$true, Position=0, Mandatory=$true)] [Hashtable] $Values , [Parameter(Position=1)] [String] $pairSeparator = '&' , [Parameter(Position=2)] [String] $KeyValueSeparator = '=' , [string[]]$Sort ) PROCESS { [string]::join($pairSeparator, @( if($Sort) { foreach( $kv in $Values.GetEnumerator() | Sort $Sort) { if($kv.Name) { '{0}{1}{2}' -f $kv.Name, $KeyValueSeparator, $kv.Value } } } else { foreach( $kv in $Values.GetEnumerator()) { if($kv.Name) { '{0}{1}{2}' -f $kv.Name, $KeyValueSeparator, $kv.Value } } } )) }} function ConvertTo-OAuthSignatureBase { #.Synopsis # An internal function to build up the string needed for the OAuth Signature PARAM( [Parameter(Mandatory=$true)] [Uri] $Uri , [Parameter(Mandatory=$false)] [hashtable] $Parameters =@{} , [Parameter(Mandatory=$false)] [ValidateSet("POST", "GET", "PUT", "DELETE", "HEAD", "OPTIONS")] [string] $Verb = "GET" # , # [System.Management.Automation.PSCredential] # $Credential ) BEGIN { trap { continue } if(!$Uri.IsAbsoluteUri) { $Uri= Join-Url $global:url $Uri Write-Verbose "Relative URL, appending to $($global:url) to get: $Uri" } } END { $normalizedUrl = ("{0}://{1}" -f $Uri.Scheme, $Uri.Host).ToLower() if (!(($Uri.Scheme -eq "http" -and $Uri.Port -eq 80) -or ($Uri.Scheme -eq "https" -and $Uri.Port -eq 443))) { $normalizedUrl += ":" + $Uri.Port } $normalizedUrl += $Uri.AbsolutePath write-output $normalizedUrl if($Uri.Query) { $Parameters += $(ConvertTo-Hashtable $Uri.Query.trim("?")) } $normalizedRequestParameters = Format-OAuth (ConvertFrom-Hashtable $Parameters -Sort "Name","Value") ## DEBUG Write-Host $normalizedRequestParameters -fore yellow write-output $normalizedRequestParameters $result = New-Object System.Text.StringBuilder $null = $result.AppendFormat("{0}&", $verb.ToUpper() ) $null = $result.AppendFormat("{0}&", $(Format-OAuth $normalizedUrl) ) $null = $result.AppendFormat("{0}", $normalizedRequestParameters) ## DEBUG Write-Host $result.ToString() -fore cyan write-output $result.ToString(); } } function Get-OAuthSignature { #.Synopsis # An internal function to calculate the OAuth Signature using the HMAC-SHA1 algorithm #.Parameter Verb # The HTTP verb which will be invoked is the first part of the OAuth Signature string (defaults to GET) #.Parameter Uri # The URI which will be queried is the second part of the OAuth Signature string #.Parameter Parameters # All of the parameters which will be passed (regardless of how they will be passed) in hashtable format. The OAuth Base Authorization parameters are not included here, they will be set by this function #.Parameter ConsumerKey # The OAuth Consumer Key (a key specific to the application requesting access) #.Parameter ConsumerSecret # The OAuth Consumer Secret (the secret part of the application's consumer key shouldn't be given to end users) #.Parameter AccessToken # The OAuth Access Token (if you're already authenticated) #.Parameter ConsumerSecret # The OAuth Access Secret (the secret part of the access token, if you're already authenticated) PARAM( [Parameter(Mandatory=$true)] [Uri] $Uri , [Parameter(Mandatory=$false)] [hashtable] $Parameters =@{} , [Parameter(Mandatory=$true)] [string] $ConsumerKey = "key" , [Parameter(Mandatory=$true)] [string] $ConsumerSecret = "secret" , [Parameter(Mandatory=$false)] [string] $AccessToken = "" , [Parameter(Mandatory=$false)] [string] $AccessSecret = "" , [Parameter(Mandatory=$false)] [string] $AccessVerifier = "" , [Parameter(Mandatory=$false)] [ValidateSet("POST", "GET", "PUT", "DELETE", "HEAD", "OPTIONS")] [string] $Verb = "GET" , [ValidateSet("HMAC-SHA1", "PLAINTEXT")] [String] $SignatureMethod = "HMAC-SHA1" # , # [System.Management.Automation.PSCredential] # $Credential ) END { @($Parameters.Keys) | % { $Parameters.$_ = @($Parameters.$_) | %{ Format-OAuth $_ } } $Parameters += Get-OAuthBase $ConsumerKey $AccessToken $AccessVerifier -SignatureMethod $SignatureMethod $url, $query, $sigbase = ConvertTo-OAuthSignatureBase -Uri $Uri -Parameters $Parameters -Verb $Verb Write-Verbose ([System.Web.HttpUtility]::URLDecode( $sigbase ) -split "&" -join "`n") Write-Output $url, $Parameters if($SignatureMethod -eq "HMAC-SHA1") { $sha = new-object System.Security.Cryptography.HMACSHA1 $sha.Key = [System.Text.Encoding]::Ascii.GetBytes( ('{0}&{1}' -f $(Format-OAuth $ConsumerSecret),$(Format-OAuth $AccessSecret)) ) Write-Output $([Convert]::ToBase64String( $sha.ComputeHash( [System.Text.Encoding]::Ascii.GetBytes( $sigbase ) ) )) } else { Write-Output ('{0}&{1}' -f $(Format-OAuth $ConsumerSecret),$(Format-OAuth $AccessSecret)) } }} function Invoke-OAuthHttp { #.Synopsis # The primary OAuth function #.Parameter Uri # The URI which will be invoked against #.Parameter Parameters # All of the additional parameters which will be passed (regardless of how they will be passed) in hashtable format. Obviously the OAuth Base access parameters are not included here, they will be set by this function #.Parameter ConsumerKey # The OAuth Consumer Key (a key specific to the application requesting access) #.Parameter ConsumerSecret # The OAuth Consumer Secret (the secret part of the application's consumer key shouldn't be given to end users) #.Parameter AccessToken # The OAuth Access Token (if you're already authenticated) #.Parameter ConsumerSecret # The OAuth Access Secret (the secret part of the access token, if you're already authenticated) #.Parameter Verb # The HTTP verb which will be invoked (defaults to GET) [CmdletBinding()] PARAM( [Parameter(Mandatory=$true)] [Uri] $Uri , [Parameter(Mandatory=$false)] [HashTable] $Parameters =@{} , [Parameter(Mandatory=$true)] [string] $ConsumerKey = "key" , [Parameter(Mandatory=$true)] [string] $ConsumerSecret = "secret" , [Parameter(Mandatory=$false)] [string] $AccessToken = "" , [Parameter(Mandatory=$false)] [string] $AccessSecret = "" , [Parameter(Mandatory=$false)] [string] $AccessVerifier = "" , [Parameter(Mandatory=$false)] [ValidateSet("POST", "GET", "PUT", "DELETE", "HEAD", "OPTIONS")] [string] $Verb = "GET" , [ValidateSet("HMAC-SHA1", "PLAINTEXT")] [String] $SignatureMethod = "HMAC-SHA1" , [ValidateSet("Xml", "File", "Text","Bytes")] [Alias("As")] $Output = "Xml" , [AllowEmptyString()] [string]$Path ) END { $parameters.format = "xml" if($AccessToken -and $AccessSecret) { $script:url, $script:Headers, $script:sig = Get-OAuthSignature -Uri $Uri -Parameters $Parameters ` -ConsumerKey $ConsumerKey ` -ConsumerSecret $ConsumerSecret ` -AccessToken $AccessToken ` -AccessSecret $AccessSecret ` -AccessVerifier $AccessVerifier ` -Verb $Verb.ToUpper() ` -SignatureMethod $SignatureMethod } else { $script:url, $script:Headers, $script:sig = Get-OAuthSignature -Uri $Uri -Parameters $Parameters ` -ConsumerKey $ConsumerKey ` -ConsumerSecret $ConsumerSecret ` -Verb $Verb.ToUpper() ` -SignatureMethod $SignatureMethod } $Headers += @{ oauth_signature = Format-OAuth $sig } $Parameters.Keys | %{ $Headers.Remove($_) } $WithHeader = @{ Authorization="OAuth {0}`"" -f $(ConvertFrom-Hashtable $Headers "`", " "=`"") } Write-Verbose $( $WithHeader | fl | Out-String ) switch($Verb) { "POST" { $plug = Get-DreamPlug $Uri.AbsoluteUri -Headers $WithHeader $global:debugplug = $plug $script:result = Invoke-Http "POST" -Plug $plug -Content ([HashTable]$Parameters) | Receive-Http $Output -Path $Path } "GET" { $plug = Get-DreamPlug $Uri.AbsoluteUri -Headers $WithHeader -With $Parameters $global:debugplug = $plug $script:result = Invoke-Http "GET" -Plug $plug | Receive-Http $Output -Path $Path } } ## Freakydeaky magic pulls an access hashtable out of it's hat if(!$AccessToken -and $result -is [System.Xml.XmlDocument] -and $result.SelectNodes("html") -and $result.SelectNodes("html") -match "oauth_token_secret") { $result.html | ConvertTo-Hashtable } elseif($result -is [System.Xml.XmlDocument]){ $result.SelectSingleNode("//*") } else { $result } } } # http`://oauth.net/core/1.0#auth_step3 # # A good place to practice: http`://term.ie/oauth/example/ # # The reason I started playing: http`://friendfeed.com/api/documentation # http`://friendfeed.com/api/applications/6a3c26fe1af047bb9553b3098bee5867 # # The docs for Yammer were also involved: https://www.yammer.com/api_doc.html # # One other resource I found helpful (I had to make a few enhancements to HttpRest): # http`://blog.developer.mindtouch.com/2009/08/05/async-io-dream-vs-parallel-extensions/ # And thanks to http`://oauth.googlecode.com/svn/code/csharp/ # And thanks to http`://oauth.googlecode.com/svn/code/python/oauth/ #################################################################################################### ### This is *MY* application stuff $global:PoshOAuthToken = @{ oauth_consumer_key = # You must put your oauth key here oauth_consumer_secret = # You must put your oauth secret here } $global:OAuthUris = @{ AccessToken = "https://www.yammer.com/oauth/access_token" RequestToken = "https://www.yammer.com/oauth/request_token" Authorize = "https://www.yammer.com/oauth/access_token" } function Get-OAuthAccessToken { [CmdletBinding()] param() #.Synopsis # OAuth Web Browser Authentication if(!(Test-Path Variable:Global:OAuthAccessToken) -or !$global:OAuthAccessToken) { $RequestToken = Invoke-OAuthHttp ` -Uri $OAuthUris.RequestToken ` -ConsumerKey $PoshOAuthToken.oauth_consumer_key ` -ConsumerSecret $PoshOAuthToken.oauth_consumer_secret ` -Verb "POST" -SignatureMethod 'HMAC-SHA1' if(!$RequestToken) { return } $Global:DebugToken = $RequestToken Write-Warning "Starting browser for interactive authorization" $AuthURL = ("https://www.yammer.com/oauth/authorize?oauth_token={0}" -f $RequestToken.oauth_token) Start $AuthURL $AccessVerifier = Read-Host "Please enter the token from the web site: $AuthURL" $global:OAuthAccessToken = Invoke-OAuthHttp ` -Uri $OAuthUris.AccessToken ` -ConsumerKey $PoshOAuthToken.oauth_consumer_key ` -ConsumerSecret $PoshOAuthToken.oauth_consumer_secret ` -AccessToken $RequestToken.oauth_token ` -AccessSecret $RequestToken.oauth_token_secret ` -AccessVerifier $AccessVerifier ` -Verb "POST" } return $global:OAuthAccessToken } function Invoke-OAuthorized { [CmdletBinding()] PARAM( [Parameter(Mandatory=$true)] [Uri] $Uri , [Parameter(Mandatory=$false,ValueFromPipeline=$true)] [hashtable] $Parameters =@{} , [Parameter(Mandatory=$false)] [IO.FileInfo[]] $File , [Parameter(Mandatory=$false)] [ValidateSet("POST", "GET", "PUT", "DELETE", "HEAD", "OPTIONS")] [string] $Verb = "GET" , [ValidateSet("Xml", "File", "Text","Bytes")] [Alias("As")] $Output = "Xml" , [AllowEmptyString()] [string]$Path ) BEGIN { if(!(Test-Path Variable:Global:OAuthAccessToken) -or !$global:OAuthAccessToken) { Write-Warning "Must fetch new Access Token" $Global:OAuthAccessToken = Get-OAuthAccessToken } } PROCESS { Write-Verbose "Fetching URI: $Uri" Invoke-OAuthHttp -Parameters $Parameters -Uri $Uri ` -ConsumerKey $Global:PoshOAuthToken.oauth_consumer_key ` -ConsumerSecret $Global:PoshOAuthToken.oauth_consumer_secret ` -AccessToken $Global:OAuthAccessToken.oauth_token ` -AccessSecret $Global:OAuthAccessToken.oauth_token_secret ` -Verb $Verb -Output $Output -Path $Path }} function Get-AccessTokenForIAA { #.Synopsis # Installed Application Authentication param($Credential) if(!(Test-Path Variable:Global:IAAccessToken)) { if(!$Credential) { $Credential = Get-Credential } $global:IAAccessToken = Invoke-OAuthHttp -Parameters @{ ff_username = $Credential.GetNetworkCredential().Username # the user's username ff_password = $Credential.GetNetworkCredential().Password # the user's password } -Uri $FriendFeedUris.AccessToken ` -ConsumerKey $global:PoshFFToken.oauth_consumer_key ` -ConsumerSecret $global:PoshFFToken.oauth_consumer_secret -Verb "POST" } return $global:IAAccessToken } # function get-messages { # Invoke-OAuthorized https://www.yammer.com/api/v1/messages | tee -var messages # $global:newestyammer = $messages.messages.message[0].id # while($messages.messages.message.count -eq 20) { # $global:oldestyammer = $messages.messages.message[-1].id # sleep -sec 10 # Invoke-OAuthorized https://www.yammer.com/api/v1/messages -parameter @{ older_than = $oldestyammer } | tee -var messages # if(!$?) { break } # } # } # get-messages | Select sender-id, thread-id, attachments, created-at, client-type | Export-CSV Messages.csv
PowerShellCorpus/PoshCode/finddupe_20.ps1
finddupe_20.ps1
function Get-SHA512([System.IO.FileInfo] $file = $(throw 'Usage: Get-MD5 [System.IO.FileInfo]')) { $stream = $null; $cryptoServiceProvider = [System.Security.Cryptography.SHA512CryptoServiceProvider]; $hashAlgorithm = new-object $cryptoServiceProvider $stream = $file.OpenRead(); $hashByteArray = $hashAlgorithm.ComputeHash($stream); $stream.Close(); ## We have to be sure that we close the file stream if any exceptions are thrown. trap { if ($stream -ne $null) { $stream.Close(); } break; } foreach ($byte in $hashByteArray) { if ($byte -lt 16) {$result += “0{0:X}” -f $byte } else { $result += “{0:X}” -f $byte }} return [string]$result; } $starttime=[datetime]::now write-host "FindDupe.ps1 - find and optionally delete duplicates. FindDupe.ps1 -help or FindDupe.ps1 -h for usage options." $matches = 0 # initialize number of matches for summary. $filesdeleted = 0 # number of files deleted. $bytesrec = 0 # Number of bytes recovered. if ($args -eq "-help" -or $args -eq "-h") # check for help request, if found display usage options... { "" "Usage:" " PS>.\\FindDupe.ps1 <directory/file #1> <directory/file #2> ... <directory/file #N> [-delete] [-noprompt] [-recurse] [-help]" "Options:" " -recurse recurses through all subdirectories of any specified directories." " -delete prompts to delete duplicates (but not originals.)" " -delete with -noprompt deletes duplicates without prompts (but again not originals.)" " -hidden checks hidden files, default is to ignore hidden files." " -help displays this usage option data, and ignores all other arguments." "" "Examples:" " PS>.\\finddupe.ps1 c:\\data d:\\finance -recurse" " PS>.\\finddupe.ps1 d: -recurse -delete -noprompt" " PS>.\\finddupe.ps1 c:\\users\\alice\\pictures\\ -recurse -delete" exit } # build list of files, by running dir on $args minus elements that have FindDupe.ps1 switches, recursively if specified. $files=(dir ($args | ?{$_ -ne "-delete" -and $_ -ne "-noprompt" -and $_ -ne "-recurse" -and $_ -ne "-hidden"}) -recurse:$([bool]($args -eq "-recurse")) -force:$([bool]($args -eq "-hidden")) |?{$_.psiscontainer -eq $false}) if ($files.count -lt 2) # if the number of files is less than 2, then exit { "Need at least two files to check.`a" exit } for ($i=0;$i -ne $files.count; $i++) # Cycle thru all files { if ($files[$i] -eq $null) {continue} # file was already identified as a duplicate if $null, so do next file $filecheck = $files[$i] # backup file object $files[$i] = $null # erase file object from object database, so it is not matched against itself for ($c=$i+1;$c -lt $files.count; $c++) # cycle through all files again { if ($files[$c] -eq $null) {continue} # $null = file was already checked/matched. if ($filecheck.fullname -eq $files[$c].fullname) {$files[$c]=$null;continue} # If referencing the same file, skip if ($filecheck.length -eq $files[$c].length) # if files match size then check SHA512's { if ($filecheck.SHA512 -eq $null) # if SHA512 is not already computed, compute it { $SHA512 = (get-SHA512 $filecheck.fullname) $filecheck = $filecheck | %{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $SHA512 -passthru} } if ($files[$c].SHA512 -eq $null) # resulting in no file being SHA512'ed twice. { $SHA512 = (get-SHA512 $files[$c].fullname) $files[$c] = $files[$c] | %{add-member -inputobject $_ -name SHA512 -membertype noteproperty -value $SHA512 -passthru} } if ($filecheck.SHA512 -eq $files[$c].SHA512) # Size already matched, if SHA512 matches, then it's a duplicate. { write-host "Size and SHA512 match: " -fore red -nonewline write-host "`"$($filecheck.fullname)`" and `"$($files[$c].fullname)`"" $matches += 1 # Number of matches ++ if ($args -eq "-delete") # check if user specified to delete the duplicate { if ($args -eq "-noprompt") # if -delete select, and -noprompt selected { del $files[$c].fullname # then delete the file without prompting write-host "Deleted duplicate: " -f red -nonewline write-host "`"$($files[$c].fullname).`"" } else { del $files[$c].fullname -confirm # otherwise prompt for confirmation to delete } if ((get-item -ea 0 $files[$c].fullname) -eq $null) # check if file was deleted. { $filesdeleted += 1 # update records $bytesrec += $files[$c].length } } $files[$c] = $null # erase file object so it is not checked/matched again. } } } # And loop to next inner loop file } # And loop to next file in outer/original loop write-host "" write-host "Number of Files checked: $($files.count)." # Display useful info; files checked and matches found. write-host "Number of duplicates found: $matches." Write-host "Number of duplicates deleted: $filesdeleted." # Display number of duplicate files deleted and bytes recovered. write-host "$bytesrec bytes recovered." write-host "" write-host "Time to run: $(([datetime]::now)-$starttime|select hours, minutes, seconds, milliseconds)" write-host ""
PowerShellCorpus/PoshCode/Add EventLogs to Mongo.ps1
Add EventLogs to Mongo.ps1
<# .NOTES AUTHOR: Sunny Chakraborty(sunnyc7@gmail.com) WEBSITE: http://tekout.wordpress.com CREATED: 8/20/2012 Requires: a) PowerShell v2 or better b) Requires Mongo Official C# driver https://github.com/mongodb/mongo-csharp-driver/downloads Tested using 1.5.0.X c) Thanks to Justin Dearing for this: https://gist.github.com/854911 blog post- http://www.justaprogrammer.net/2012/04/19/powershell-3-0-ordered-and-mongodb/ The reg lookup to find mongo install path doesnt work in v1.5.x of C# Driver .DESCRIPTION Insert event logs in mongodB. You can watch the events using MongoVue http://www.mongovue.com/ #> $mongoDriverPath = 'C:\\Program Files (x86)\\MongoDB\\CSharpDriver 1.5' Add-Type -Path "$($mongoDriverPath)\\MongoDB.Bson.dll"; Add-Type -Path "$($mongoDriverPath)\\MongoDB.Driver.dll"; $db = [MongoDB.Driver.MongoDatabase]::Create('mongodb://localhost/eventmonitor'); $collection = $db['events']; # I just grabbed first 10 from Application. Feel free to filter using Error/Warning etc. $events = get-eventlog Application -newest 10 for ($i = 0; $i -le $events.Count-1; $i++) { # I am not sure why, but I had to use these temp variables to insert documents into mongodB as JSON # without temp variables, the rows were getting inserted as System.Diagnostic.EventLogEntry. I know it looks kinda uncool. # please suggest better options $a = $events[$i].Index $b= $events[$i].EntryType $c= $events[$i].InstanceID $d= $events[$i].Category $e= $events[$i].ReplacementStrings $f= $events[$i].Source $g= $events[$i].TimeGenerated $h= $events[$i].EventID $msg = $events[$i].Message [MongoDB.Bson.BsonDocument] $doc = @{ "_id"= [MongoDB.Bson.ObjectId]::GenerateNewId(); "Index"= "$a"; "EntryType"= "$b"; "InstanceID"= "$c"; "Category"= "$d"; "ReplacementStrings"= "$e"; "Source"= "$f"; "TimeGenerated"= "$g"; "EventID"= "$h"; "Message"= "$msg"; }; $collection.Insert($doc); }
PowerShellCorpus/PoshCode/get-SQLInstanceInfo_1.ps1
get-SQLInstanceInfo_1.ps1
function get-SQLInstanceInfo2 { param ( [Parameter(Mandatory=$True)][string]$ComputerName ) $InstanceInfos = @() $Instances = (new-object 'microsoft.sqlserver.management.smo.Wmi.ManagedComputer' "$ComputerName").Services | where-object{$_.type -eq 'SqlServer'} foreach($Instance in $Instances ) { [psobject]$InstanceInfo = "" | Select-Object DisplayName, Name, Clustered, ` InstanceID, FileVersion, Version, ` VirtualName, Instance, Port, ServiceState, ` ServiceAccount, Edition, AuditLevel, LoginMode, ` PhysicalMemory, Processors, Product, ProductLevel, ` MajorVersion, MinorVersion, Build, Release,NamedPipesEnabled write-verbose "Processing SQL Instance: $($Instance.Name)" $InstanceInfo.DisplayName = $Instance.DisplayName $InstanceInfo.Name = $Instance.Name $InstanceInfo.Clustered = $Instance.AdvancedProperties['CLUSTERED'].Value $InstanceInfo.InstanceID = $Instance.AdvancedProperties['INSTANCEID'].Value $InstanceInfo.FileVersion = $Instance.AdvancedProperties['FILEVERSION'].Value $InstanceInfo.Version = $Instance.AdvancedProperties['VERSION'].Value if($Instance.AdvancedProperties['VSNAME'].Value -eq ''){ $InstanceInfo.VirtualName = $(hostname) } else { $InstanceInfo.VirtualName = $Instance.AdvancedProperties['VSNAME'].Value } if($Instance.Name.Split('$')[1] -eq $Null){ [string]$InstanceName = 'MSSQLSERVER' } else { [string]$InstanceName = $Instance.Name.Split('$')[1] } $InstanceInfo.Instance = $InstanceName $InstanceInfo.Port = $Instance.Parent.ServerInstances[$InstanceName].ServerProtocols['Tcp'].IPAddresses['IPALL'].IPAddressProperties['TcpPort'].Value $InstanceInfo.NamedPipesEnabled = $Instance.Parent.ServerInstances[$InstanceName].ServerProtocols['Np'].IsEnabled $InstanceInfo.ServiceAccount = $Instance.ServiceAccount $InstanceInfo.ServiceState = $Instance.ServiceState if($InstanceInfo.Clustered){ $SQLInstanceName = "$($InstanceInfo.VirtualName),$($InstanceInfo.Port)" } else { $SQLInstanceName = "$ComputerName,$($InstanceInfo.Port)" } write-verbose "SQL InstanceName: $SQLInstanceName" [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") |out-null $SQL = new-object "Microsoft.SQLServer.Management.SMO.Server" $SQLInstanceName $InstanceInfo.Edition = $SQL.Edition $InstanceInfo.AuditLevel = $SQL.AuditLevel $InstanceInfo.LoginMode = $SQL.LoginMode $InstanceInfo.PhysicalMemory = $SQL.PhysicalMemory $InstanceInfo.Processors = $SQL.Processors $InstanceInfo.Product = $SQL.Product $InstanceInfo.ProductLevel = $SQL.ProductLevel $InstanceInfo.MajorVersion = $SQL.Version.Major $InstanceInfo.MinorVersion = $SQL.Version.Minor $InstanceInfo.Build = $SQL.Version.Build if($SQL.Version.Major -eq 10) { switch($SQL.Version.Minor) { 0 { $InstanceInfo.Release = 'Gold' } 50 { $InstanceInfo.Release = 'R2' } else { throw "Could not convert minor version into release. Version number $($SQL.Versioin.Minor)" } } } else { $InstanceInfo.Release = 'Gold' } $InstanceInfos += $InstanceInfo } write-verbose "Showing results" $InstanceInfos }
PowerShellCorpus/PoshCode/Get-CalendarWeek.ps1
Get-CalendarWeek.ps1
# Get-CalendarWeek by Holger Adam # Simple function to retrieve the calendar week to a given or the current date. # The function always assumes a calendar week rule of at least four days and the week starting with monday. function Get-CalendarWeek { param( $Date ) # check date input if ($Date -eq $null) { $Date = Get-Date } # create calendar object $Calendar = New-Object System.Globalization.GregorianCalendar # retrieve calendar week $Calendar.GetWeekOfYear($Date, [System.Globalization.CalendarWeekRule]::FirstFourDayWeek, [System.DayOfWeek]::Monday) }
PowerShellCorpus/PoshCode/Get-LogicalDiskInfo.ps1
Get-LogicalDiskInfo.ps1
# ======================================================================== # # NAME: Get-LogicalDiskInfo.ps1 # # AUTHOR: Alex Ocampo , Daptiv Solutions LLC # DATE : 7/19/2011 # # COMMENT: Using WMI, script check logical disk information of a single # server or a group of servers. Script send email notification if any # logical disk free space falls below minimum free disk space # ($minFreeSpace). # # # Syntax: # # Check logicalDisks info on a single host in this case "computer1" # PS C:\\Scripts> .\\Get-LogicalDiskInfo.ps1 -computerNames "computer1" # # Running script without passing a parameter checks logicalDisks of all # computers or servers listed on C:\\Scripts\\Computers.txt. Script stop # execution if no parameter is passed and Computers.txt is not present. # # Sample (Computers.txt), add computers/servers to check as needed... # SERVER1 # SERVER2 # SERVER3 # # ======================================================================== param ( [string[]] $computerNames ) Set-Location -Path ([System.Environment]::GetEnvironmentVariable("SystemDrive") + "\\Scripts") # Test that parameters exists if ($computerNames -eq $null) { if (Test-Path -LiteralPath ".\\Computers.txt" -PathType "leaf") { $computerNames = Get-Content -Path ".\\Computers.txt" } else { Write-Host "missing parameters..." exit } } # ratio x = $_.freespace/$_.size : higher value translate to # a lower maxDiskUsed and reports more drives meeting criteria [double] $minFreeSpace=.25 # [double] $minFreeSpace=.75 function notify { param ( [string] $subject, [string] $message, [string] $to="DL Team IT <distributionGroup@mydomain.com>", [string] $from="IT Notification <itNotification@mydomain.com>", [string] $smtpserver="mailServer.mydomain.com" ) Send-MailMessage -From $from -To $to -Subject $subject -Body $message -SmtpServer $smtpserver } function existTest { param ([string] $node2Chk) $pathStr="\\\\$node2Chk\\ADMIN$" return Test-Path -LiteralPath $pathStr } function chkDisk { param ( [string] $node ) # $messageBody string = "WARNING: Drive C: is 85% full..." [string] $messageBody="WARNING: Immediate action required...`r`n`r`n" Get-WmiObject Win32_LogicalDisk -ComputerName $node | ` Where-Object {$_.DriveType -eq 3} | ` ForEach-Object { If (($_.FreeSpace/$_.Size) -le $minFreeSpace) { ` $result="Drive " + $_.DeviceID + " is " + (100 - [math]::Round(($_.FreeSpace/$_.Size)*100, 2)) + "% full..." # $result=$node + ": " + $_.DeviceID + " - Free disk space: " + [math]::Round($_.FreeSpace/1GB, 2) + "GB" $messageBody="$messageBody" + "`t$result`r`n" } } # do not call function if variable is equals to initial value if ($messageBody -ne "WARNING: Immediate action required...`n`n") { notify -subject "RE: \\\\$node" -message "$messageBody" } } function main { param ( [bool] $validNode ) foreach ($computer in $computerNames) { # Test if computer exists $validNode = existTest $computer if ($validNode) { chkDisk $computer } } } # call main function main
PowerShellCorpus/PoshCode/Kill Outlook + CopyPST_1.ps1
Kill Outlook + CopyPST_1.ps1
$rep_du_user = $env:userprofile $repertoire_pst = ($rep_du_user+"\\AppData\\Local\\Microsoft\\Outlook") $repertoire_sauvegarde = "directory" #Kill de outlook Get-Process | Where { $_.Name -Eq "outlook" } | stop-process #wait and see :) sleep 10 #copy des pst xcopy $repertoire_pst $repertoire_sauvegarde /D /E /C /R /H /I /K /Y /G
PowerShellCorpus/PoshCode/Expand-Alias 2.0.ps1
Expand-Alias 2.0.ps1
#requires -version 2.0 ## ResolveAlias Module v2.0 ######################################################################################################################## ## Version History ## 1.0 - First Version. "It worked on my sample script" ## 1.1 - Now it parses the $(...) blocks inside strings ## 1.2 - Some tweaks to spacing and indenting (I really gotta get some more test case scripts) ## 1.3 - I went back to processing the whole script at once (instead of a line at a time) ## Processing a line at a time makes it impossible to handle Here-Strings... ## I'm considering maybe processing the tokens backwards, replacing just the tokens that need it ## That would mean I could get rid of all the normalizing code, and leave the whitespace as-is ## 1.4 - Now resolves parameters too ## 1.5 - Fixed several bugs with command resolution (the ? => ForEach-Object problem) ## - Refactored the Resolve-Line filter right out of existence ## - Created a test script for validation, and ## 1.6 - Added resolving parameter ALIASES instead of just short-forms ## 1.7 - Minor tweak to make it work in CTP3 ## 2.0 - Modularized and v3 compatible ## * *TODO:* Put back the -FullPath option to resolve cmdlets with their snapin path ## * *TODO:* Add an option to put #requires statements at the top for each snapin used ######################################################################################################################## function Resolve-Command { param( [string]$command ) # aliases, functions, cmdlets, scripts, executables, normal files $cmds = @(Get-Command $command -EA "SilentlyContinue") if($cmds.Count -gt 1) { $cmd = @( $cmds | Where-Object { $_.Name -match "^$([Regex]::Escape($command))" })[0] } else { $cmd = $cmds[0] } if(!$cmd) { $cmd = @(Get-Command "Get-$command" -EA "SilentlyContinue" | Where-Object { $_.Name -match "^Get-$([Regex]::Escape($command))" })[0] } if( $cmd.CommandType -eq "Alias" ) { $cmd = Resolve-Command $cmd.Definition } return $cmd } function Expand-Alias { #.Synopsis # Expands aliases and short parameters #.Description # Expands all aliases (recursively) to actual functions/cmdlets/executables # Expands all short-form parameter names to their full versions # Works on files or strings, and can expand "inplace" on a file #.Parameter Script # The script you want to expand aliases in #.Parameter File # The script file you want to expand aliases in #.Parameter InPlace # Enables replacing aliases in-place on files instead of into a new file #.Parameter Unqualified # Allows you to leave the namespace (module name) off of commands # By default Expand-Alias will expand 'gc' to 'Microsoft.PowerShell.Management\\Get-Content' # If you specify the Unqualified flag, it will expand to just 'Get-Content' instead. [CmdletBinding(ConfirmImpact="low",DefaultParameterSetName="Files")] param ( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Text")] [string]$Script , [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Files")] [Alias("FullName","PSChildName","PSPath")] [IO.FileInfo]$File , [Parameter( ParameterSetName="Files")] [Switch]$InPlace , [Parameter()] [Switch]$Unqualified ) begin { Write-Debug $PSCmdlet.ParameterSetName } process { if($PSCmdlet.ParameterSetName -eq "Files") { if($File -is [System.IO.FileInfo]){ $Script = (Get-Content $File -Delim ([char]0)) } } $Errors = $Null $Tokens = [System.Management.Automation.PSParser]::Tokenize($Script,[ref]$Errors) if($Errors) { foreach($er in $Errors) { Write-Error $er } throw "There was an error parsing script (See above). We cannot expand aliases until the script parses without errors." } for($t = $Tokens.Count; $t -ge 0; $t--) { $token = $Tokens[$t] # DEBUG $token | fl * | out-host switch($token.Type) { "Command" { $cmd = Resolve-Command $token.Content Write-Verbose "Command $($token.Content) => $($cmd.Name)" if(!$Unqualified -and $cmd.ModuleName) { $command = '{0}\\{1}' -f $cmd.ModuleName, $cmd.Name } else { $command = $cmd.Name } $Script = $Script.Remove( $token.Start, $token.Length ).Insert( $token.Start, $command ) } "CommandParameter" { for($c = $t; $c -ge 0; $c--) { if( $Tokens[$c].Type -eq "Command" ) { $cmd = Resolve-Command $Tokens[$c].Content $short = $token.Content -replace "^-?","^" $parameters = $cmd.ParameterSets | Select -expand Parameters $param = @($parameters | Where-Object { $_.Name -match $short -or $_.Aliases -match $short} | Select -Expand Name -Unique) if($param.Count -eq 1) { Write-Verbose "Parameter $($token.Content) => -$($param[0])" $Script = $Script.Remove( $token.Start, $token.Length ).Insert( $token.Start, "-$($param[0])" ) } break } } } } } switch($PSCmdlet.ParameterSetName) { "Text" { $Script } "Files" { switch($File.GetType()) { "System.IO.FileInfo" { if($InPlace) { $Script | Set-Content $File } else { $Script } } default { throw "We can't resolve a whole folder at once yet" } } } default { throw "ParameterSet: $($PSCmdlet.ParameterSetName)" } } } } Set-Alias Resolve-Alias Expand-Alias Export-ModuleMember -Function * -Alias *
PowerShellCorpus/PoshCode/Get-Weather 2.2.ps1
Get-Weather 2.2.ps1
#require -version 2.0 #require -shellid PoshConsole ################################################################################################### ## Get-Weather ## Parse and display the current weather and forecast from yahoo RSS ## Note that you _could_ modify this a bit to return "current condition" and "forecast" objects ## but for now, it just prints them out in a relatively nice format ################################################################################################### ## Version History: ## 2.2 - removed reference to "Out-WPF" which is just a function now ## 2.1 - Updated for New-BootsWindow 2.0, can show -Popup graphics even in PowerShell.exe (with New-BootsWindow) ## 2.0 - Updated for New-BootsWindow and PoshConsole, now shows inline graphics in PoshConsole, ## 1.1 - Added TempColor function ## 1.0 - My initial cleanup of a script from ## http`://fortheloveofcode.wordpress.com/2008/04/28/powershell-webservice-client/ ######### ## ToDo: Color code the "text": Showers/Rain/Snow/... ## ToDo: Pull out extreme weather *Warnings* ## ToDo: Parse wind and show the wind-chill when temp is cold ################################################################################################### # function get-weather { param($zip=14586,[switch]$celcius,[switch]$Popup) $url = "http`://weather.yahooapis.com/forecastrss?p={0}{1}" -f $zip, $(if($celcius){"&u=c"}) $channel = ([xml](New-Object Net.WebClient).DownloadString($url)).rss.channel function TempColor ($temp) { if($celcius) { if( $temp -lt 0 ) { "blue" } elseif( $temp -le 10 ) { "cyan" } elseif( $temp -le 21 ) { "blue" } elseif( $temp -lt 27 ) { "green" } else { "red" } } else { if( $temp -lt 5 ) { "blue" } elseif( $temp -le 50 ) { "cyan" } elseif( $temp -le 70 ) { "blue" } elseif( $temp -lt 80 ) { "green" } else { "red" } } } if($channel) { if( ($Host.PrivateData.GetType().Name -eq "PoshOptions") -OR ( $Popup -AND (Get-Command New-BootsWindow -Type Cmdlet -EA SilentlyContinue))) { # alternate images: http`://l.yimg.com/us.yimg.com/i/us/we/52/ $template = @" <StackPanel xmlns="http`://schemas.microsoft.com/winfx/2006/xaml/presentation" > <TextBlock FontFamily="Constantia" FontSize="12pt">{0}, {1} {2}</TextBlock> <StackPanel Orientation="Horizontal"> <StackPanel VerticalAlignment="Top" Margin="6,2,6,2" ToolTip="{3}"> <Image Source="http`://image.weather.com/web/common/wxicons/52/{4}.png" Stretch="Uniform" Width="{{Binding Source.PixelWidth,RelativeSource={{RelativeSource Self}}}}" Height="{{Binding Source.PixelHeight,RelativeSource={{RelativeSource Self}}}}" /> <TextBlock TextAlignment="Center"><Run FontWeight="700" Text="Now: " /><Run Foreground="{5}"> {6}{7}</Run></TextBlock> </StackPanel> <StackPanel VerticalAlignment="Top" Margin="6,2,6,2" ToolTip="{8}"> <Image Source="http`://image.weather.com/web/common/wxicons/52/{9}.png" Stretch="Uniform" Width="{{Binding Source.PixelWidth,RelativeSource={{RelativeSource Self}}}}" Height="{{Binding Source.PixelHeight,RelativeSource={{RelativeSource Self}}}}" /> <TextBlock TextAlignment="Center"> <Run FontWeight="700">{10}</Run><LineBreak/> <Run Foreground="{11}">{12}{7}</Run> - <Run Foreground="{13}">{14}{7}</Run></TextBlock> </StackPanel> <StackPanel VerticalAlignment="Top" Margin="6,2,6,2" ToolTip="{15}"> <Image Source="http`://image.weather.com/web/common/wxicons/52/{16}.png" Stretch="Uniform" Width="{{Binding Source.PixelWidth,RelativeSource={{RelativeSource Self}}}}" Height="{{Binding Source.PixelHeight,RelativeSource={{RelativeSource Self}}}}" /> <TextBlock TextAlignment="Center"> <Run FontWeight="700">{17}</Run><LineBreak/> <Run Foreground="{18}">{19}{7}</Run> - <Run Foreground="{20}">{21}{7}</Run></TextBlock> </StackPanel> </StackPanel> </StackPanel> "@ $template = ($template -f $channel.location.city, $channel.location.region, $channel.lastBuildDate, $channel.item.condition.text, $channel.item.condition.code, (TempColor $channel.item.condition.temp), $channel.item.condition.temp, $channel.units.temperature, $channel.item.forecast[0].text, $channel.item.forecast[0].code, $channel.item.forecast[0].day, (TempColor $channel.item.forecast[0].low), $channel.item.forecast[0].low, (TempColor $channel.item.forecast[0].high), $channel.item.forecast[0].high, $channel.item.forecast[1].text, $channel.item.forecast[1].code, $channel.item.forecast[1].day, (TempColor $channel.item.forecast[1].low), $channel.item.forecast[1].low, (TempColor $channel.item.forecast[1].high), $channel.item.forecast[1].high) $template | out-clipboard ## Work around defect in New-BootsWindow that hides -Popup when -Popup is implied. Silly of me. if(!$Popup -and $Host.PrivateData.GetType().Name -eq "PoshOptions") { New-BootsWindow -SourceTemplate $template -Inline {} } else { New-BootsWindow -SourceTemplate $template {} -Async } } else { # "ConsoleColorProxy" $current = $channel.item.condition Write-Host Write-Host ("Location: {0}" -f $channel.location.city) Write-Host ("Last Update: {0}" -f $channel.lastBuildDate) Write-Host ("Weather: {0}" -f $current.text)-NoNewline Write-Host (" {0}°{1}" -f $current.temp, $(if($celcius){"C"}else{"F"})) -ForegroundColor $(TempColor $current.temp) Write-Host Write-Host "Forecasts" Write-Host "---------" foreach ($f in $channel.item.forecast) { Write-Host ("`t{0}, {1}: {2}" -f $f.day, $f.date, $f.text) -NoNewline Write-Host (" {0}-{1}°{2}" -f $f.low, $f.high, $(if($celcius){"C"}else{"F"})) -ForegroundColor $(TempColor $f.High) } Write-Host } } #}
PowerShellCorpus/PoshCode/Deleted-Folders.ps1
Deleted-Folders.ps1
function Deleted-Folders(){ param ( $Computer, [String[]]$SeachFoldersDeleted ) $Info = $null $Disks = $null trap {Write-Host "Error WmiObject $Computer";Continue} $Disks += Get-WmiObject win32_logicaldisk -ComputerName $Computer | Where-Object {$_.Size -ne $null} foreach ($Disk in $Disks){ if ($Disk.Name -like "*:*") { $Disk = $Disk.Name.replace(":","$") } trap {Write-Host "Error ChildItem $Computer";Continue} $Info += Get-ChildItem "\\\\$Computer\\$Disk\\*" -recurse -ErrorAction SilentlyContinue if ($Info -ne $null){ foreach ($Folder in $SeachFoldersDeleted){ $Info | Where-Object {$_.Name -like $Folder} | % {remove-item $_.fullname -Recurse -Force -ErrorAction SilentlyContinue} } } } }
PowerShellCorpus/PoshCode/Compare-TwitterNames.ps1
Compare-TwitterNames.ps1
#This script will compare the names of the people you follow on Twitter #and the people following you. It returns a comparison object consisting #of the Twitter name of a subject and a side indicator - #"<=" means that you are following a subject who is not following you, #"=>" means that you are followed by someone who you are not following. function GetTwitterNames([string]$query) { $wc = new-object System.Net.WebClient $wc.Credentials = $script:credential.GetNetworkCredential() $nbrofpeople = 0 $page = "&page=" $names = @() do { $url = $query if ($nbrofpeople -gt 0) { $url = $url+$page+($nbrofpeople/100 +1) } [xml]$nameslist = $wc.DownloadString($url) $names += $nameslist.users.user | select name $nbrofpeople += 100 } while ($names.count -eq $nbrofpeople) return $names } $twitter = "http://twitter.com/statuses/" $friends = $twitter + "friends.xml?lite=true" $followers = $twitter + "followers.xml?lite=true" $credential = Get-Credential $friendslist = GetTwitterNames($friends) $followerslist = GetTwitterNames($followers) compare-object $friendslist $followerslist -SyncWindow (($friendslist.count)/2) -Property name