full_path
stringlengths
31
232
filename
stringlengths
4
167
content
stringlengths
0
48.3M
PowerShellCorpus/PoshCode/Disable-SSLValidation.ps1
Disable-SSLValidation.ps1
function Disable-SSLValidation { <# .SYNOPSIS Disables SSL certificate validation .DESCRIPTION Disable-SSLValidation disables SSL certificate validation by using reflection to implement the System.Net.ICertificatePolicy class. Author: Matthew Graeber (@mattifestation) License: BSD 3-Clause .NOTES Reflection is ideal in situations when a script executes in an environment in which you cannot call csc.ese to compile source code. If compiling code is an option, then implementing System.Net.ICertificatePolicy in C# and Add-Type is trivial. .LINK http://www.exploit-monday.com #> Set-StrictMode -Version 2 # You have already run this function if ([System.Net.ServicePointManager]::CertificatePolicy.ToString() -ne 'IgnoreCerts') { Return } # Don't bother defining a new assembly if one is already defined try { [IgnoreCerts] | Out-Null } catch { Return } $Domain = [AppDomain]::CurrentDomain $DynAssembly = New-Object System.Reflection.AssemblyName('IgnoreCerts') $AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run) $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('IgnoreCerts', $false) $TypeBuilder = $ModuleBuilder.DefineType('IgnoreCerts', 'AutoLayout, AnsiClass, Class, Public, BeforeFieldInit', [System.Object], [System.Net.ICertificatePolicy]) $TypeBuilder.DefineDefaultConstructor('PrivateScope, Public, HideBySig, SpecialName, RTSpecialName') | Out-Null $MethodInfo = [System.Net.ICertificatePolicy].GetMethod('CheckValidationResult') $MethodBuilder = $TypeBuilder.DefineMethod($MethodInfo.Name, 'PrivateScope, Public, Virtual, HideBySig, VtableLayoutMask', $MethodInfo.CallingConvention, $MethodInfo.ReturnType, ([Type[]] ($MethodInfo.GetParameters() | % {$_.ParameterType}))) $ILGen = $MethodBuilder.GetILGenerator() $ILGen.Emit([Reflection.Emit.Opcodes]::Ldc_I4_1) $ILGen.Emit([Reflection.Emit.Opcodes]::Ret) $TypeBuilder.CreateType() | Out-Null # Disable SSL certificate validation [System.Net.ServicePointManager]::CertificatePolicy = New-Object IgnoreCerts }
PowerShellCorpus/PoshCode/Get-SQLSaturdaySessions_1.ps1
Get-SQLSaturdaySessions_1.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 } } #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/04180226-a26b-47be-abbd-9eb998596807.ps1
04180226-a26b-47be-abbd-9eb998596807.ps1
<#===================================================== SYNOPSIS Create an Excel workbook for a teacher. The workbook contains a worksheet for each class. =====================================================#> <#===================================================== RETRIEVE CURRENT USER'S LOGON Prefer API to $env:username. http://www.leeholmes.com/blog/2009/...lkthrough/ http://www.pinvoke.net/ LOCAL: $signature $type IN: OUT: $logon =====================================================#> $signature = @' [DllImport("mpr.dll", CharSet=CharSet.Auto, SetLastError=true)] public static extern int WNetGetUser( [MarshalAs(UnmanagedType.LPTStr)] string lpName, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder lpUserName, ref int lpnLength); '@ $type = Add-Type -MemberDefinition $signature -Name GetLogonString -Namespace WNetGetUser -Using System.Text -PassThru $logon = New-Object System.Text.StringBuilder 32 # Current user's logon is returned as a null-terminated string in this buffer. $type::WNetGetUser("", $logon, [ref]$logon.Capacity) <#===================================================== RETRIEVE CURRENT USER'S SFKEY The SFKey is the database UID - four chars. Test current user's logon first. If OK, open a .NET connection and get the SFKey that matches the logon. Allows identity impersonation. LOCAL: $cmdSFKey IN: $logon OUT: $cnnNET $sfkey =====================================================#> Switch($logon.Length) { 0 {throw "Error retrieving Windows logon."} default { $cnnNET = New-Object System.Data.SqlClient.SqlConnection $cnnNET.ConnectionString = "Server=HOMEPC\\SQLEXPRESS;Database=Keeper;Integrated Security=SSPI" $cnnNET.Open() $cmdSFKey = New-Object System.Data.SqlClient.SqlCommand $cmdSFKey.Connection = $cnnNET $cmdSFKey.CommandType = [System.Data.CommandType]"StoredProcedure" $cmdSFKey.CommandText = "SELMainSFKey" $cmdSFKey.Parameters.Add("@LogonName",[System.Data.SqlDbType]"varchar",30) $cmdSFKey.Parameters["@LogonName"].Value = $logon.ToString() $cmdSFKey.Parameters.Add("@SFKey",[System.Data.SqlDbType]"varchar",4) $cmdSFKey.Parameters["@SFKey"].Direction = [System.Data.ParameterDirection]"Output" $cmdSFKey.ExecuteNonQuery() [string] $sfkey = $cmdSFKey.Parameters["@SFKey"].Value <#===================================================== RETRIEVE TIMETABLE PERIOD AND WORKBOOK SAVE LOCATION Test current user's SFKey first. If OK, retrieve two values from single-row lookup table: 1. $ttperiod is reqd to look up teacher's classes. 2. $xlpath is required to save the Excel workbook. Nested switch statements end in this block. LOCAL: $cmdAdmin $adpAdmin $tblAdmin $rowAdmin IN: $sfkey $cnnNET OUT: $ttperiod $xlpath =====================================================#> Switch($sfkey.Length) { 0 {throw "Error retrieving teacher key."} default { $cmdAdmin = New-Object System.Data.SqlClient.SqlCommand $cmdAdmin.Connection = $cnnNET $cmdAdmin.CommandType = [System.Data.CommandType]"StoredProcedure" $cmdAdmin.CommandText = "SELMainAdmin" $adpAdmin = New-Object System.Data.SqlClient.SqlDataAdapter $adpAdmin.SelectCommand = $cmdAdmin $tblAdmin = New-Object System.Data.DataTable $adpAdmin.Fill($tblAdmin) $rowAdmin = $tblAdmin.Rows foreach ($rowAdmin in $tblAdmin) { [string] $ttperiod = $rowAdmin.Item("CurrentTTPeriod") [string] $xlpath = $rowAdmin.Item("KeeperPath") } # End foreach } # End Switch $sfkey default } # End Switch $sfkey.length } # End Switch $logon default } # End Switch $logon.length <#===================================================== RETRIEVE CURRENT USER'S CLASSES Test Admin values first. If OK, retrieve teacher's classes into a DataTable. A "class" has two pieces: 1. subject key (e.g., 08ENG1). 2. class number (e.g., 6). LOCAL: $test $cmdClasses $adpClasses IN: $ttperiod $xlpath $cnnNET $sfkey OUT: $rowClasses $tblClasses =====================================================#> [int] $test = 0 $test = $ttperiod.Length if ($test = 0) {throw "Error retrieving timetable period."} $test = $xlpath.Length if ($test = 0) {throw "Error retrieving XL pathname."} $cmdClasses = New-Object System.Data.SqlClient.SqlCommand $cmdClasses.Connection = $cnnNET $cmdClasses.CommandType = [System.Data.CommandType]"StoredProcedure" $cmdClasses.CommandText = "SELKeeperClassesForTeacher" $cmdClasses.Parameters.Add("@ttperiod",[System.Data.SqlDbType]"varchar",6) $cmdClasses.Parameters["@ttperiod"].Value = $ttperiod $cmdClasses.Parameters.Add("@SFKey",[System.Data.SqlDbType]"varchar",4) $cmdClasses.Parameters["@SFKey"].Value = $sfkey $adpClasses = New-Object System.Data.SqlClient.SqlDataAdapter $adpClasses.SelectCommand = $cmdClasses $tblClasses = New-Object System.Data.DataTable $adpClasses.Fill($tblClasses) $rowClasses = $tblClasses.Rows <#===================================================== CREATE EXCEL OBJECTS Application and workbook. Create workbook with a worksheet for each class. LOCAL: $xl IN: $tblClasses OUT: $wb =====================================================#> $xl = New-Object -ComObject Excel.Application $xl.SheetsInNewWorkbook = $tblClasses.Rows.Count $wb = $xl.Workbooks.Add() $xl.Visible = $True <#===================================================== CREATE ADODB OBJECTS An ADODB recordset is reqd by Excel's CopyFromRecordset. LOCAL: $ad [int] constants $cnnADO $prmTTPeriod IN: $ttperiod OUT: $prmSUKey $prmClass $cmdStudents $rstStudents =====================================================#> [int] $adCmdStoredProc = 4 [int] $adVarChar = 200 [int] $adSmallInt = 2 [int] $adParamInput = 1 [int] $adOpenForwardOnly = 0 # Default. [int] $adOpenStatic = 3 [int] $adLockReadOnly = 1 # Default. [int] $adLockOptimistic = 3 [int] $adUseServer = 2 # Default. [int] $adUseClient = 3 $cnnADO = New-Object -ComObject ADODB.Connection $cnnADO.Open("Provider=SQLOLEDB; Data Source=HOMEPC\\SQLEXPRESS; Initial Catalog=Keeper; Integrated Security=SSPI") $cmdStudents = New-Object -ComObject ADODB.Command $cmdStudents.ActiveConnection = $cnnADO $cmdStudents.CommandType = $adCmdStoredProc $cmdStudents.CommandText = "SELKeeperStudentsForClass" $prmTTPeriod = New-Object -ComObject ADODB.Parameter $prmTTPeriod = $cmdStudents.CreateParameter("@ttperiod",$adVarChar,$adParamInput,6,$ttperiod) # This parameter doesn't change; assign value here. $cmdStudents.Parameters.Append($prmTTPeriod) $prmSUKey = New-Object -ComObject ADODB.Parameter $prmSUKey = $cmdStudents.CreateParameter("@SUKey",$adVarChar,$adParamInput,7) # This parameter changes; assign value in ForEach. $cmdStudents.Parameters.Append($prmSUKey) $prmClass = New-Object -ComObject ADODB.Parameter $prmClass = $cmdStudents.CreateParameter("@class",$adSmallInt,$adParamInput) # This parameter changes; assign value in ForEach. $cmdStudents.Parameters.Append($prmClass) $rstStudents = New-Object -ComObject ADODB.Recordset $rstStudents.CursorLocation = $adUseServer $rstStudents.CursorType = $adOpenForwardOnly $rstStudents.LockType = $adLockReadOnly <#===================================================== RETRIEVE STUDENTS Place students in separate worksheets, one for each class, in a fabricated Excel workbook. Use an ADODB recordset to take advantage of Excel's speedy CopyFromRecordset function. LOCAL: $ix: indexes worksheets. $subj: student's subject code. $class: student's class number. $ws: current worksheet. $subcode: current worksheet's new name (subj + class). $rangeData: Excel range for column sizing. IN: $rowClasses, $tblClasses: data source for teacher's classes iterated by foreach loop. $prmSUKey, $prmClass: refreshed with new values during each iteration. $cmdStudents, $rstStudents: retrieve new class during each iteration. $wb: current workbook, one per teacher. OUT: =====================================================#> # Seed index for worksheets. [int] $ix = 1 # Iterate each class. foreach ($rowClasses in $tblClasses) { # Assign subject and class values to typed variables. [string] $subj = $rowClasses.Item("subj") [int] $class = $rowClasses.Item("class") # Rename worksheet. [string] $subcode = $subj + $class $ws = $wb.Sheets.item($ix) $ws.Name = $subcode # Assign typed variables to ADODB parameters. $prmSUKey.Value = $subj $prmClass.Value = $class # Assign result set to ADODB recordset. $rstStudents = $cmdStudents.Execute() # Copy result set to current worksheet. Adjust entry cell as reqd. $wb.Sheets.item($subcode).Cells.item(2,1).CopyFromRecordset($rstStudents) # Size columns. $rangeData = $wb.Sheets.item($subcode).UsedRange [void] $rangeData.EntireColumn.Autofit() # Increment index for worksheets. $ix++ } # End foreach <#===================================================== SAVE WORKBOOK LOCAL: $pathname IN: $xlpath $sfkey $ttperiod $wb OUT: ===================================================== #> [string] $pathname = $xlpath + $sfkey + $ttperiod + ".xlsx" $wb.SaveAs($pathname) <#===================================================== CLEANUP =====================================================#> function Release-Ref ($ref) { # ===================================================== # Author: Kent Finkle # http://gallery.technet.microsoft.co...8a41a680a7 # ===================================================== ([System.Runtime.InteropServices.Marshal]::ReleaseComObject( [System.__ComObject]$ref) -gt 0) [System.GC]::Collect() [System.GC]::WaitForPendingFinalizers() } # Close connections. $cnnNET.Close $cnnADO.Close # Get rid of COM objects. $k = Release-Ref($ws) $k = Release-Ref($wb) $k = Release-Ref($xl) $k = Release-Ref($rstStudents) $k = Release-Ref($cmdStudents) $k = Release-Ref($prmTTPeriod) $k = Release-Ref($prmSUKey) $k = Release-Ref($prmClass) $k = Release-Ref($cnnADO) # Get rid of .NET objects. $cmdSFKey.Dispose Remove-Variable cmdSFKey $cmdAdmin.Dispose Remove-Variable cmdAdmin $adpAdmin.Dispose Remove-Variable adpAdmin $tblAdmin.Dispose Remove-Variable tblAdmin $rowAdmin.Dispose Remove-Variable rowAdmin $cmdClasses.Dispose Remove-Variable cmdClasses $adpClasses.Dispose Remove-Variable adpClasses $tblClasses.Dispose Remove-Variable tblClasses $rowClasses.Dispose Remove-Variable rowClasses $cnnNET.Dispose Remove-Variable cnnNET # Get rid of Excel process. # Idea from blub, http://www.powershellcommunity.org/...fault.aspx $ExcelProcess=get-process excel $ExcelProcess | foreach {stop-process ($_.id)} [System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl) | out-null
PowerShellCorpus/PoshCode/Test-Certificate_1.ps1
Test-Certificate_1.ps1
##################################################################### # Test-Certificate.ps1 # Version 0.9 # # Tests specified certificate for certificate chain and revocation # # Vadims Podans (c) 2009 # http://www.sysadmins.lv/ ##################################################################### #requires -Version 2.0 function Test-Certificate { <# .Synopsis Tests specified certificate for certificate chain and revocation .Description Tests specified certificate for certificate chain and revocation status for each certificate in chain exluding Root certificates .Parameter Certificate Specifies the certificate to test certificate chain. This parameter may accept X509Certificate, X509Certificate2 objects or physical file path. this paramter accept pipeline input .Parameter Password Specifies PFX file password. Password must be passed as SecureString. .Parameter CRLMode Sets revocation check mode. May contain on of the following values: Online - perform revocation check downloading CRL from CDP extension ignoring cached CRLs. Default value Offline - perform revocation check using cached CRLs if they are already downloaded NoCheck - specified certificate will not checked for revocation status (not recommended) .Parameter CRLFlag Sets revocation flags for chain elements. May contain one of the following values: ExcludeRoot - perform revocation check for each certificate in chain exluding root. Default value EntireChain - perform revocation check for each certificate in chain including root. (not recommended) EndCertificateOnly - perform revocation check for specified certificate only. .Parameter VerificationFlags Sets verification checks that will bypassed performed during certificate chaining engine check. You may specify one of the following values: NoFlag - No flags pertaining to verification are included (default). IgnoreNotTimeValid - Ignore certificates in the chain that are not valid either because they have expired or they are not yet in effect when determining certificate validity. IgnoreCtlNotTimeValid - Ignore that the certificate trust list (CTL) is not valid, for reasons such as the CTL has expired, when determining certificate verification. IgnoreNotTimeNested - Ignore that the CA (certificate authority) certificate and the issued certificate have validity periods that are not nested when verifying the certificate. For example, the CA cert can be valid from January 1 to December 1 and the issued certificate from January 2 to December 2, which would mean the validity periods are not nested. IgnoreInvalidBasicConstraints - Ignore that the basic constraints are not valid when determining certificate verification. AllowUnknownCertificateAuthority - Ignore that the chain cannot be verified due to an unknown certificate authority (CA). IgnoreWrongUsage - Ignore that the certificate was not issued for the current use when determining certificate verification. IgnoreInvalidName - Ignore that the certificate has an invalid name when determining certificate verification. IgnoreInvalidPolicy - Ignore that the certificate has invalid policy when determining certificate verification. IgnoreEndRevocationUnknown - Ignore that the end certificate (the user certificate) revocation is unknown when determining certificate verification. IgnoreCtlSignerRevocationUnknown - Ignore that the certificate trust list (CTL) signer revocation is unknown when determining certificate verification. IgnoreCertificateAuthorityRevocationUnknown - Ignore that the certificate authority revocation is unknown when determining certificate verification. IgnoreRootRevocationUnknown - Ignore that the root revocation is unknown when determining certificate verification. AllFlags - All flags pertaining to verification are included. .Example Get-ChilItem cert:\\CurrentUser\\My | Test-Certificate -CRLMode "NoCheck" Will check certificate chain for each certificate in current user Personal container. Certificates will not checked for revocation status. .Example Test-Certificate C:\\Certs\\certificate.cer -CRLFlag "EndCertificateOnly" Will check certificate chain for certificate that is located in C:\\Certs and named as Certificate.cer and revocation checking will be performed for specified certificate only .Outputs This script return general info about certificate chain status #> [CmdletBinding()] param( [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)] $Certificate, [System.Security.SecureString]$Password, [System.Security.Cryptography.X509Certificates.X509RevocationMode]$CRLMode = "Online", [System.Security.Cryptography.X509Certificates.X509RevocationFlag]$CRLFlag = "ExcludeRoot", [System.Security.Cryptography.X509Certificates.X509VerificationFlags]$VerificationFlags = "NoFlag" ) begin { $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $chain = New-Object System.Security.Cryptography.X509Certificates.X509Chain $chain.ChainPolicy.RevocationFlag = $CRLFlag $chain.ChainPolicy.RevocationMode = $CRLMode $chain.ChainPolicy.VerificationFlags = $VerificationFlags function _getstatus_ ($status, $chain, $cert) { if ($status) { Write-Host Current certificate $cert.SerialNumber chain and revocation status is valid -ForegroundColor Green } else { Write-Warning "Current certificate $($cert.SerialNumber) chain is invalid due of the following errors:" $chain.ChainStatus | %{Write-Host $_.StatusInformation.trim() -ForegroundColor Red} } } } process { if ($_ -is [System.Security.Cryptography.X509Certificates.X509Certificate2]) { $status = $chain.Build($_) _getstatus_ $status $chain $_ } else { if (!(Test-Path $Certificate)) {Write-Warning "Specified path is invalid"; return} else { if ((Resolve-Path $Certificate).Provider.Name -ne "FileSystem") { Write-Warning "Spicifed path is not recognized as filesystem path. Try again"; return } else { $Certificate = gi $(Resolve-Path $Certificate) switch -regex ($Certificate.Extension) { "\\.CER|\\.DER|\\.CRT" {$cert.Import($Certificate.FullName)} "\\.PFX" { if (!$Password) {$Password = Read-Host "Enter password for PFX file $certificate" -AsSecureString} $cert.Import($Certificate.FullName, $password, "UserKeySet") } "\\.P7B|\\.SST" { $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection $cert.Import([System.IO.File]::ReadAllBytes($Certificate.FullName)) } default {Write-Warning "Looks like your specified file is not a certificate file"; return} } $cert | %{ $status = $chain.Build($_) _getstatus_ $status $chain $_ } $cert.Reset() $chain.Reset() } } } } }
PowerShellCorpus/PoshCode/vSphere Resultant Privs_1.ps1
vSphere Resultant Privs_1.ps1
# Need the Quest ActiveRoles cmdlets for this one. Add-PSSnapin Quest.ActiveRoles* -ea SilentlyContinue function Get-Groups { param($principal) # Start with this principal's base set of groups. Write-Verbose "Checking principal $principal" $groups = Get-QADUser $principal | Get-QADMemberOf # Groups can be members of groups, so iterate until the list size remains fixed. do { $startLength = $groups.length Write-Verbose ("Start length " + $startLength) $groups += $groups | Get-QADMemberOf $groups = $groups | Sort -Unique $endLength = $groups.length Write-Verbose ("End length " + $endLength) } while ($endLength -ne $startLength) Write-Output $groups } # Get the resultant privileges that a user has for a given object. function Get-ResultantPrivileges { param($principal, $viobject) # Use the NT Account name. $account = (Get-QADUser $principal).NTAccountName if ($relevantPerms -eq $null) { throw "$principal not found, please check your spelling." } # Get the groups for this user. $groups = Get-Groups -principal $account $groupNames = $groups | Foreach { $_.Name } # Get the full permission set for this object. $perms = $viobject | Get-VIPermission # Determine the list of roles that apply to this principal. $relevantPerms = $perms | Where { (($_.IsGroup -eq $true) -and ($groupNames -contains $_.Principal)) -or ($_.Principal -eq $account) } # Retrieve all these roles. $roleNames = $relevantPerms | Foreach { $_.Role } | Sort -Unique Write-Verbose "Rolenames are $roleNames" $roleObjects = Get-VIRole $roleNames $roleCount = ($roleObjects | Measure-Object).Count # The resultant set is the intersection of the privileges within the role. $roleObjects | Foreach { $_.PrivilegeList } | Group | Where { $_.Count -eq $roleCount } | Select Name } # Example: # Get-ResultantPrivileges -principal "VMWORLD\\cshanklin" -viobject (Get-VM OpenFiler)
PowerShellCorpus/PoshCode/Get MOSS User Profile_2.ps1
Get MOSS User Profile_2.ps1
function Get-UserProfile($accountName) { [reflection.assembly]::LoadWithPartialName("Microsoft.SharePoint") | out-null [reflection.assembly]::LoadWithPartialName("Microsoft.Office.Server") | out-null $upm =[Microsoft.Office.Server.UserProfiles.UserProfileManager]( [Microsoft.Office.Server.ServerContext]::Default) $upm.GetUserProfile($accountName) } function Get-UserProfileData($profile) { $propsToDisplay = $upm.Properties | ? { $_.IsSystem -eq $false -and $_.IsSection -eq $false } $o = new-object PSObject $propsToDisplay | foreach { add-member -inp $o -membertype NoteProperty -name $_.Name -value $profile[$_.Name].Value } $o } @@ @@ @@#USAGE 1: (update one profile) @@# $up = Get-UserProfile "spadmin" @@# $up["YourCustomField"].Value = "new value" @@# $up.Commit() @@# @@#USAGE 2: (export profile data to CSV) @@# @@# $upm = [Microsoft.Office.Server.UserProfiles.UserProfileManager]( @@# [Microsoft.Office.Server.ServerContext]::Default) @@# $unrolledProfilesCollection = $upm | foreach { $_ } @@# $unrolledProfilesCollection | foreach { Get-UserProfileData $_ } | export-csv -NoTypeInformation "C:\\temp\\profiles.txt" @@ @@ @@ #
PowerShellCorpus/PoshCode/SharpSsh Functions_1.ps1
SharpSsh Functions_1.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( $RSAKeyFile, [switch]$Passthru) $cred = $host.UI.PromptForCredential("SSH Login Credentials", "Please specify credentials in user@host format", "$UserName@$HostName","") 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 { $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 } $global:LastSshSession.WriteLine("") sleep -milli 500 $global:defaultPrompt = [regex]::Escape( $global:LastSshSession.Expect().Split("`n")[-1] ) } 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 = $global:defaultPrompt## 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/repr_2.ps1
repr_2.ps1
function repr { [CmdletBinding()] [OutputType([string])] Param( [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)] $InputObject) process { if($null -eq $InputObject) { $PSCmdlet.WriteObject('$null') } elseif($InputObject -is [bool]) { $PSCmdlet.WriteObject('$' + $InputObject.ToString().ToLowerInvariant()) } elseif($InputObject -is [scriptblock]) { $PSCmdlet.WriteObject("{$InputObject}") } elseif($InputObject -is [string]) { $PSCmdlet.WriteObject("'$InputObject'") } else { $PSCmdlet.WriteObject($InputObject.ToString()) } } }
PowerShellCorpus/PoshCode/Exchange PST Export.ps1
Exchange PST Export.ps1
#Load Exchange PS Snapin If (@(Get-PSSnapin -Registered | Where-Object {$_.Name -eq "Microsoft.Exchange.Management.PowerShell.E2010"} ).count -eq 1) { If (@(Get-PSSnapin | Where-Object {$_.Name -eq "Microsoft.Exchange.Management.PowerShell.E2010"} ).count -eq 0) { Write-Host "Loading Exchange Snapin Please Wait...."; Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010} } #Load Exchange PS Snapin If (@(Get-PSSnapin -Registered | Where-Object {$_.Name -eq "Microsoft.Exchange.Management.PowerShell.Admin"} ).count -eq 1){ If (@(Get-PSSnapin | Where-Object {$_.Name -eq "Microsoft.Exchange.Management.PowerShell.Admin"} ).count -eq 0) { Write-Host "Loading Exchange Snapin Please Wait...."; Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin} } Write-Host "`n`n`t`t Export Mailbox To PST `n`n" #Variables $path = "\\\\file\\share" $admin = [Environment]::UserName $list=Read-Host "Do you want to read from a file? (Y/N)" IF ($list -eq "N") { $user = Read-Host "Enter A User Name" Add-MailboxPermission -Identity $user -User $admin -AccessRights FullAccess Export-Mailbox $user -PSTFolderPath $path\\$user.pst -Confirm:$false } IF ($list -eq "Y") { $file = Read-Host "Enter File Path/Name" $users = Get-Content $file Foreach ($user in $users) { #Add-MailboxPermission -Identity $user -User $admin -AccessRights FullAccess Export-Mailbox $user -PSTFolderPath $path\\$user.pst -Confirm:$false } }
PowerShellCorpus/PoshCode/Activation Context API.ps1
Activation Context API.ps1
<# By Adam Driscoll 12/14/2012 Twitter: @adamdriscoll More Information: http://csharpening.net/?p=1427 Description: Functions for entering and exiting an activation context. This provides support for registration free COM in PowerShell. #> Add-Type -TypeDefinition ' namespace Driscoll { using System; using System.ComponentModel; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; public class ActivationContext { IntPtr hActCtx; uint cookie; public void CreateAndActivate(string manifest) { var actCtx = new ACTCTX(); actCtx.cbSize = Marshal.SizeOf(typeof(ACTCTX)); actCtx.dwFlags = 0; actCtx.lpSource = manifest; actCtx.lpResourceName = null; hActCtx = CreateActCtx(ref actCtx); if(hActCtx == new IntPtr(-1)) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Failed to create activation context."); } if (!ActivateActCtx(hActCtx, out cookie)) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Failed to activate activation context."); } } public void DeactivateAndFree() { DeactivateActCtx(0, cookie); ReleaseActCtx(hActCtx); } [DllImport("kernel32.dll")] private static extern IntPtr CreateActCtx(ref ACTCTX actctx); [StructLayout(LayoutKind.Sequential)] private struct ACTCTX { public int cbSize; public uint dwFlags; public string lpSource; public ushort wProcessorArchitecture; public ushort wLangId; public string lpAssemblyDirectory; public string lpResourceName; public string lpApplicationName; } [DllImport("Kernel32.dll", SetLastError = true)] private extern static bool ActivateActCtx(IntPtr hActCtx, out uint lpCookie); [DllImport("Kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DeactivateActCtx(int dwFlags, uint lpCookie); [DllImport("Kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool ReleaseActCtx(IntPtr hActCtx); private const uint ACTCTX_FLAG_PROCESSOR_ARCHITECTURE_VALID = 0x001; private const uint ACTCTX_FLAG_LANGID_VALID = 0x002; private const uint ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID = 0x004; private const uint ACTCTX_FLAG_RESOURCE_NAME_VALID = 0x008; private const uint ACTCTX_FLAG_SET_PROCESS_DEFAULT = 0x010; private const uint ACTCTX_FLAG_APPLICATION_NAME_VALID = 0x020; private const uint ACTCTX_FLAG_HMODULE_VALID = 0x080; private const UInt16 RT_MANIFEST = 24; private const UInt16 CREATEPROCESS_MANIFEST_RESOURCE_ID = 1; private const UInt16 ISOLATIONAWARE_MANIFEST_RESOURCE_ID = 2; private const UInt16 ISOLATIONAWARE_NOSTATICIMPORT_MANIFEST_RESOURCE_ID = 3; private const uint FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100; private const uint FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; private const uint FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; } } ' function Enter-ActivationContext { param($manifest) $global:ActivationContext = New-Object Driscoll.ActivationContext $global:ActivationContext.CreateAndActivate($manifest) } function Exit-ActivationContext { $global:ActivationContext.DeactivateAndFree() }
PowerShellCorpus/PoshCode/Get-RecentLogons.ps1
Get-RecentLogons.ps1
Add-PSSnapin -Name Quest.ActiveRoles.ADManagement -ErrorAction SilentlyContinue # Location of the CSV file created. $fileLocation = "C:\\temp\\logon.csv" # Get the Current Date $CURRENTDATE=GET-DATE # Number of days to check $COMPAREDATE = $CURRENTDATE.AddDays(-30) # Your AD Domain $server = "ad.domain.com" Get-QADUser -Service $server -SizeLimit 0 |where {$_.LastLogon -gt $COMPAREDATE }| select lastlogon,lastname,firstname,logonname,whencreated,description |Export-Csv $fileLocation
PowerShellCorpus/PoshCode/Check HBA status .ps1
Check HBA status .ps1
########################################################################################### # Title: Check HBA status # Filename: Check-HBA.ps1 # Created by: Alberto Damiano # Date: June 2009 # Version: 1.0 ########################################################################################### # Virtual Center Server FQDN $VCServerName = "YOUR SERVER" # Some variables $CLUSTERS = @() $portvc="443" $VC = Connect-VIServer $VCServerName -ErrorAction Stop -port $portvc $CLUSTERS = Get-Cluster | Select-Object Name ForEach ($ClusterName in $CLUSTERS) { # Generate list of ESX into cluster $ClusterName.Name $VMHosts = Get-VMHost -Location $ClusterName.Name | Sort-Object Name Function Generate-Report { Write-Output "<body>" ForEach ($VMHost in $VMHosts) { $Report = @() $ESX = Get-VMHost $VMHost get-vmhoststorage -RescanAllHba -VMHost $ESX > $null $PROPVMHOST = Get-View $ESX.id $storageSystem = Get-View $PROPVMHOST.ConfigManager.StorageSystem $VMHBAs = $PROPVMHOST.Config.StorageDevice.ScsiTopology.Adapter $lista = $storageSystem.StorageDeviceInfo.MultipathInfo.Lun # Write hostname ESX Write-Output "<table><tr class=""Title""><td colspan=""5"">$($VMhost.Name)</td></tr><tr class="Title"><td>LunID </td><td>Vmhba </td><td> WWN SAN </td><td>SCSI Target </td><td>State </td></tr>" ForEach ($lun in $lista) { $lun.Path | %{ if ($_.Adapter.Contains("FibreChannelHba")) { $OUT = {} | Select Lunid, Vmhba, wwnt, target, state $temp = $lun.id.Split(":")[2] $OUT.Lunid = [Convert]::Todecimal($temp) $OUT.Vmhba = $_.Name.Split(":")[0] $elenco = $storageSystem.StorageDeviceInfo.HostBusAdapter | select Device, PortWorldWideName ForEach ($ele in $elenco) { if ($ele.Device -eq $OUT.Vmhba) { break } } $wwnhex = "{0:x}" -f $ele.PortWorldWideName $OUT.Vmhba = $_.Name.Split(":")[0] + " " + $wwnhex $OUT.wwnt = "{0:x}" -f $_.Transport.PortWorldWideName $OUT.target = $_.Name.Split(":")[1] $OUT.state = $_.PathState $Report += $OUT } } } $Report = $Report | Sort-Object Lunid $old = $Report[1].Lunid $flag = $true $bg="#C0C0FF" Foreach ($rep in $Report) { if ($rep.Lunid -ne $old) { $flag = !($flag) $old = $rep.Lunid if ($flag) { $bg="#C0C0FF" } else { $bg="#FFFF66" } } if ($rep.state -like "dead") { Write-Output "<tr bgcolor=$($bg)><td>$($rep.Lunid)</td><td>$($rep.Vmhba)</td><td>$($rep.wwn)</td><td><center>$($rep.target)</center></td><td class="Error">$($rep.state)</td></tr>" } else { Write-Output "<tr bgcolor=$($bg)><td>$($rep.Lunid)</td><td>$($rep.Vmhba)</td><td>$($rep.wwnt)</td><td><center>$($rep.target)</center></td><td>$($rep.state)</td></tr>" } } Write-Output "</table>" Write-Output "<BR>" } Write-Output "</body></html>" } Write-Output "<html><head><title></title><style type=""text/css"">.Error {color:#FF0000;font-weight: bold;}.Title {background: #0077D4;color: #FFFFFF;text-align:center;font-weight: bold;}.Normal {}</style></head>" > "c:\\temp\\SAN_Path_$($ClusterName.Name).html" #Specify the path where to store the HTML output Generate-Report >> "c:\\temp\\SAN_Path_$($ClusterName.Name).html" }
PowerShellCorpus/PoshCode/Select-CSVString.ps1
Select-CSVString.ps1
# NAME # Select-CSVString # # SYNOPSIS # Convert CSV files to custom objects with properties # # SYNTAX # Select-CSVString -pattern <string[]> -files (ls *) [-StartDate <DateTime>] [-EndDate <DateTime>] param ([regex]$pattern,$files=("$($exinstall)TransportRoles\\Logs\\AgentLog","$($exinstall.substring(0,1)):\\Program Files (x86)\\Microsoft Forefront Protection for Exchange Server\\Data\\FSEAgentLog"|%{ls $_}|Sort-Object LastWriteTime), [string]$StartDate, [string]$EndDate) # Check start and end dates $local:erroractionpreference = "Stop" If(!$StartDate -and !$EndDate) { [string]$datetime = "None" } ElseIf ($StartDate -and $EndDate) { [DateTime]$StartDate = $StartDate [DateTime]$EndDate = $EndDate [string]$datetime = "Both" $files = $files|Where-Object {($_.CreationTime -ge $StartDate -or $_.LastWriteTime -ge $StartDate) -and $_.CreationTime -le $EndDate} } ElseIf ($StartDate -and !$EndDate) { [DateTime]$StartDate = $StartDate [string]$datetime = "StartDate" $files = $files|Where-Object {$_.CreationTime -ge $StartDate -or $_.LastWriteTime -ge $StartDate} } ElseIf (!$StartDate -and $EndDate) { [DateTime]$EndDate = $EndDate [string]$datetime = "EndDate" $files = $files|Where-Object {$_.CreationTime -le $EndDate -or $_.LastWriteTime -le $EndDate} } $local:erroractionpreference = "Continue" # Get columns $columns = @($files)[0]|Get-Content -TotalCount 5 foreach($col in $columns) { $col = $col -Replace "^#Fields: ","" If ($col -notmatch "^#") { $columns = $col.Split(',') break } } # Get Results foreach($file in $files) { Write-Debug "File: $($file.FullName)" trap { Write-Debug "File Locked" $script:lines = $file|Get-Content|Select-String $pattern continue } $lines = $file|Select-String $pattern -ErrorAction Stop foreach($l in $lines) { Write-Debug "Line: $($l.Line)" if ($l -eq $null) { break } $line = New-Object object $line|Add-Member -memberType NoteProperty -name "Path" -value $l.Path # ---------- Delimiter magic inside ---------- # It has been asked, why not dump select-string to a # file and import-csv the whole thing? To get realtime # results and avoid temporary files, thats why. $z = [char](222) $from = "," $tmp = $l.Line -replace "(?:`"((?:(?:[^`"]|`"`"))+)(?:`"$from|`"`$))|(?:$from)|(?:((?:.(?!$from))*.)(?:$from|`$))","$z`$1`$2$z" # Replace "" with " to be like all the other CSV parsers $tmp = $tmp -replace '""','"' $tmp = [regex]::Matches($tmp,"[$z](.*?)[$z]") $row = @() $tmp | foreach { $row += $_.Groups[1].Value } # ---------- Delimiter magic inside ---------- 0..($columns.Count-1)|Foreach-Object { # Convert timestamps to datetime objects If($columns[$_] -match "(timestamp|date-time)") {$row[$_] = [DateTime]$row[$_]} $line|Add-Member -memberType NoteProperty -name $columns[$_] -Value $row[$_] } # Determine if the line meets datetime requirements If($datetime -eq "None") {Write-Output $line} ElseIf($datetime -eq "EndDate" -and $EndDate -ge $line.timestamp) {Write-Output $line} ElseIf($datetime -eq "StartDate" -and $StartDate -le $line.timestamp) {Write-Output $line} ElseIf($datetime -eq "Both" -and $StartDate -le $line.timestamp -and $EndDate -ge $line.timestamp) {Write-Output $line} } }
PowerShellCorpus/PoshCode/Beginner event 10 _2.ps1
Beginner event 10 _2.ps1
# # Summer 2009 Scripting games # Beginner Event 10 - The 1,500-Meter race # http://blogs.technet.com/heyscriptingguy/archive/2009/06/18/hey-scripting-guy-2009-scripting-games-event-10-details-beginner-and-advanced-1-500-meter-race.aspx # # ToDo: In this event, you must write a script that will count down from three minutes # to zero seconds. When the three minutes have expired, # display a message indicating that the given amount of time has elapsed. # # This solution uses the .Net System.Windows.Form and ...Drawing classes to produce a kind # of GUI with a "stop-watch touch" # # The Start-Button starts the countdwon ... not very surpisingly :-) # The countdown can be suspended by pressing the Stop-Button ... obviously # You can Set the countdown timer in a range up to an hour ( 59:59 [mm:ss] ) # using the Set-Button. After entering a new valid mm:ss value press the Set-Button again # to take these new values into effect # I won't tell you, what the Exit-button might do for us :-) # # All the positioning and sizing has been done using the VS2008 designer too to avoid me # having a heart attack trying to adjust pixelwise ... # But I'm no artist, so I didn't spent too much time beautifying the layout! # # Klaus Schulte, 06/26/2009 # mailto:Klaus@Marischu.de # It'll be a three minutes countdown $Script:countdownTime = 3*60 # # This is the usual more a less VStudio 2008 designer generated "don't touch me" part of the code # used to define the Form derived visual components # function InitializeComponent () { # load the required additional GUI assemblies [void][reflection.assembly]::LoadWithPartialName("System.Windows.Forms") [void][reflection.assembly]::LoadWithPartialName("System.Drawing") # We will have the form itself, a textbox displaying the remainig time, # four buttons to control the countdown and ( surprise, surprise! ) a timer :-) # It is good to have a timer for the heavy work that allows us to asynchronically # react on timer events that would otherwise block the GUI and make it unresponsive # if we use busy, active wait loops or a Sleep command to control the clock $formCountdown = New-Object System.Windows.Forms.Form $tbRemainingTime = New-Object System.Windows.Forms.TextBox $btnStart = New-Object System.Windows.Forms.Button $btnStop = New-Object System.Windows.Forms.Button $btnSet = New-Object System.Windows.Forms.Button $btnExit = New-Object System.Windows.Forms.Button $timer1 = New-Object System.Windows.Forms.Timer $formCountdown.SuspendLayout() # # tbRemainingTime # I used the Algerian font, size 72 here, which you can easily change to your gusto # The digits should be red on black background # Only up to 5 chars can be entered into this textbox # $tbRemainingTime.BackColor = [System.Drawing.Color]::Black $tbRemainingTime.Font = New-Object System.Drawing.Font "Algerian", 72 $tbRemainingTime.ForeColor = [System.Drawing.Color]::Red $tbRemainingTime.Location = New-Object System.Drawing.Point(0, 0) $tbRemainingTime.MaxLength = 5 $tbRemainingTime.Name = "tbRemainingTime" $tbRemainingTime.Size = New-Object System.Drawing.Size(270, 134) $tbRemainingTime.TabIndex = 0 # # btnStart # There is a lightgreen Start-button with a btnStart_Click eventhandler # $btnStart.BackColor = [System.Drawing.Color]::LightGreen $btnStart.Font = New-Object System.Drawing.Font "Courier New", 12 $btnStart.Location = New-Object System.Drawing.Point(269, 0) $btnStart.Name = "btnStart" $btnStart.Size = New-Object System.Drawing.Size(82, 32) $btnStart.TabIndex = 0 $btnStart.Text = "Start" $btnStart.UseVisualStyleBackColor = $false $btnStart.Add_Click({btnStart_Click}) # # btnStop # ... there is a salmon(lighted) Start-button with a btnStop_Click eventhandler # $btnStop.BackColor = [System.Drawing.Color]::Salmon $btnStop.Enabled = $false $btnStop.Font = New-Object System.Drawing.Font "Courier New", 12 $btnStop.Location = New-Object System.Drawing.Point(269, 32) $btnStop.Name = "btnStop" $btnStop.Size = New-Object System.Drawing.Size(82, 32) $btnStop.TabIndex = 1 $btnStop.Text = "Stop" $btnStop.UseVisualStyleBackColor = $false $btnStop.Add_Click({btnStop_Click}) # # btnSet # ... there is a yellow Set-button with a btnSet_Click eventhandler # $btnSet.BackColor = [System.Drawing.Color]::Yellow $btnSet.Font = New-Object System.Drawing.Font "Courier New", 12 $btnSet.Location = New-Object System.Drawing.Point(269, 64) $btnSet.Name = "btnSet" $btnSet.Size = New-Object System.Drawing.Size(82, 32) $btnSet.TabIndex = 2 $btnSet.Text = "Set" $btnSet.UseVisualStyleBackColor = $false $btnSet.Add_Click({btnSet_Click}) # # btnExit # ... and a white Exit-button with a btnExit_Click eventhandler # $btnExit.BackColor = [System.Drawing.Color]::White $btnExit.Font = New-Object System.Drawing.Font "Courier New", 12 $btnExit.Location = New-Object System.Drawing.Point(269, 96) $btnExit.Name = "btnExit" $btnExit.Size = New-Object System.Drawing.Size(82, 32) $btnExit.TabIndex = 3 $btnExit.Text = "Exit" $btnExit.UseVisualStyleBackColor = $false $btnExit.Add_Click({btnExit_Click}) # # timer1 # the timer has an eventhadler timer1_tick attached to it # $timer1.Add_Tick({timer1_Tick}) $timer1.Stop() # # # frmCountdown # The rest of the form is defined here # and all the previously defined controls are added to it # $formCountdown.BackColor = [System.Drawing.Color]::Black $formCountdown.ClientSize = New-Object System.Drawing.Size(349, 127) # $formCountdown.ControlBox = $false $formCountdown.Controls.Add($btnExit) $formCountdown.Controls.Add($btnSet) $formCountdown.Controls.Add($btnStop) $formCountdown.Controls.Add($btnStart) $formCountdown.Controls.Add($tbRemainingTime) $formCountdown.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle $formCountdown.MaximizeBox = $false $formCountdown.MinimizeBox = $false $formCountdown.Name = "formCountdown" $formCountdown.SizeGripStyle = [System.Windows.Forms.SizeGripStyle]::Hide $formCountdown.Text = "Countdown" $formCountdown.ResumeLayout($false) $formCountdown.PerformLayout() $formCountdown.Load # # To have a well defined start state, we preset some properties of the controls here # $btnStart.Enabled = $true $btnStop.Enabled = $false $btnSet.Enabled = $true $btnExit.Enabled = $true $tbRemainingTime.ReadOnly = $true DisplayCountdownTime($Script:countdownTime) $formCountdown.ShowDialog() } # # The Exit Button eventhandler just closes the form which shutsdown the application # All the cleanup stuff could be done here especially if COM objects have been allocated # you should release them somewhere before you shut the application down. # function btnExit_Click() { $formCountdown.Close() } # # the Set Button event handler distinguishes between two "modes" # depending on the readonly property of the (remaing countdowntime) textbox # If you press the Set Button once, you enter edit mode to change the value # of the countdown. Having changed the value you should hit the Set-button again # to commit the changes. Before the commit is performed the string is checked # against the regular expression $TimePattern to validate it. if it is invalid # you are prompted with an error message and stay in set mode, otherwise the new # value is used to start the countdown. # function btnSet_Click() { $TimePattern = "[0-5][0-9]:[0-5][0-9]" if ($tbRemainingTime.ReadOnly) { $btnStart.Enabled = $false $btnStop.Enabled = $false $btnSet.Enabled = $true $btnExit.Enabled = $true $tbRemainingTime.ReadOnly = $false $tbRemainingTime.BackColor = [System.Drawing.Color]::White $tbRemainingTime.Focus } else { if (!([regex]::IsMatch($tbRemainingTime.Text, $TimePattern))) { [Windows.Forms.MessageBox]::Show("Please enter a time value in the form of 'mm:ss`r`n" ` + "where 'mm' and 'ss' are less or equal to '59'") return } $Script:countdownTime = 60 * [int]($tbRemainingTime.Text.Substring(0, 2)) + [int]($tbRemainingTime.Text.Substring(3, 2)) DisplayCountdownTime($Script:countdownTime) $btnStart.Enabled = $true $btnStop.Enabled = $false $btnSet.Enabled = $true $btnExit.Enabled = $true $tbRemainingTime.BackColor = [System.Drawing.Color]::Black $tbRemainingTime.ReadOnly = $true } } # # Pressing the Stop-Button will pause the countdown # function btnStop_Click() { $timer1.Stop() $btnStart.Enabled = $true $btnStop.Enabled = $false $btnSet.Enabled = $true $btnExit.Enabled = $true [Windows.Forms.MessageBox]::Show("Countdown paused!") } # # Pressing the Start-Button will start the countdown # The Timer interval is set to 1000 ms, which allows us to see a change of the countdown value # each second # function btnStart_Click() { $btnStart.Enabled = $false $btnStop.Enabled = $true $btnSet.Enabled = $false $btnExit.Enabled = $true $timer1.Interval = 1000 $timer1.Start() } # # just a helper function to convert an [int] to the display format: 'mm:ss' # Values greater or equal to an hour are SilentlyIgnored :-) # function DisplayCountdownTime($seconds) { if ($seconds -lt 60*60) { $tbRemainingTime.Text = [string]::Format("{0:00}:{1:00}", [Math]::floor($seconds / 60), $seconds % 60) } } # # this function just decrents the remaining time to countdown by one and displays the new value # if the remaining time is greater than zero. If it is zero, the countdown is over and the requested # message is displayed. The countdown could be restarted setting another value now. # function Countdown() { $Script:countdownTime-- DisplayCountdownTime($Script:countdownTime) if ($Script:countdownTime -le 0) { $timer1.Stop() $btnStart.Enabled = $false $btnStop.Enabled = $false $btnSet.Enabled = $true $btnExit.Enabled = $true [Windows.Forms.MessageBox]::Show("Countdown finished!") } } # # The timer event handler fires each second and calls Countdown to do the work # function timer1_Tick() { Countdown } # # The main entry point to to what it is called ,.. # InitializeComponent
PowerShellCorpus/PoshCode/sudo for Powershell_3.ps1
sudo for Powershell_3.ps1
## sudo.ps1 # # Authors: rbellamy, pezhore, mrigns, This guy: http://tsukasa.jidder.de/blog/2008/03/15/scripting-sudo-with-powershell, # other powershell peoples # # Sources: # http://tsukasa.jidder.de/blog/2008/03/15/scripting-sudo-with-powershell # http://www.ainotenshi.org/%E2%80%98sudo%E2%80%99-for-powershell-sorta # # Version: # 1.0 Initial version # 1.1 added -ps flag, cleaned up passed $file/$script full path # 1.2 Comments # 1.3 Fixed passing working directory to powershell/auto closing # 1.4 Added hidden window, with Export/Import-Clixml to pull results into current window # Doesn't deal well with input PS commands (e.g. 'sudo $Local:WindowsPrincipal.IsInRole("Administrators")') # is broken. param ( [switch]$ps = $true, # Switch for running args as powershell script [string]$file, # Script/Program to run [string]$arguments = $args # Arguments to program/script ) $tempPath = "$env:TEMP:\\PoSH-sudo-$PID.xml"; # Find our powershell full path $powershell = (Get-Command powershell).Definition; # Get current directory $dir = Get-Location; # File verification if([System.IO.File]::Exists("$(Get-Location)\\$file")) { # Get full path $file = (Get-ChildItem $file).Fullname; } if ($ps) { #If we're running this as a elevated powershell script # Create a powershell process $psi = New-Object System.Diagnostics.ProcessStartInfo $powershell; $psi.WorkingDirectory = Get-Location; # Combine the script and its arguments $sArgs = $file + " " + $arguments; # Set the arguments to be the ps script and it's arguments $psi.Arguments = " -Command Set-Location $dir; $sArgs"; # NOT using the shell to execute! $psi.UseShellExecute = $false; # Magic to run as elevated $psi.Verb = "RunAs"; } else { # We're running something other than a powershells script # Same as above, create proccess/working directory/arguments/runas $psi = New-Object System.Diagnostics.ProcessStartInfo $file; $psi.Arguments = $arguments; # Magic to run as elevated $psi.Verb = "RunAs"; } $psi.Arguments = $psi.Arguments + " | Export-Clixml -Path `"$tempPath`""; $psi.WindowStyle = "Hidden"; # Execute the process [System.Diagnostics.Process]::Start($psi).WaitForExit(); Import-Clixml -Path "$tempPath"; Remove-Item $tempPath;
PowerShellCorpus/PoshCode/Fix VPC Console.ps1
Fix VPC Console.ps1
# Fix the VPC options left and top position for console $today = get-date -Format "yyyyMMdd" $now = Get-Date -format "hhmmss" $today_now = Get-Date -format "yyyyMMdd_hhmmss" @" Fix the Virtual PC Console options for left and top position " Makes a backup copy of "${env:appdata}\\Microsoft\\Virtual PC\\Options.xml") And calls it "${env:appdata}\\Microsoft\\Virtual PC\\Options_${today_now}.xml" "@ copy-item ("${env:appdata}\\Microsoft\\Virtual PC\\Options.xml") ("${env:appdata}\\Microsoft\\Virtual PC\\Options_${today_now}.xml") [XML]$opt = get-content ("${env:appdata}\\Microsoft\\Virtual PC\\Options.xml") -Encoding unicode $opt.preferences.window.console.left_position.set_InnerText("20") $opt.preferences.window.console.top_position.set_InnerText("20") $opt.Save("${env:appdata}\\Microsoft\\Virtual PC\\Options.xml") # TODO: Fix save as unicode
PowerShellCorpus/PoshCode/get-lockedtime.ps1
get-lockedtime.ps1
param ( [parameter(position=0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] $ComputerName ) Begin { $alreadybegan = $false; function WmiDateToDotnet { param($date); if($date.length -ne 25) { throw New-Object ArgumentOutOfRangeException; } return New-Object datetime @(([int]$date.substring(0,4)), ([int]$date.substring(4,2)), ([int]$date.substring(6,2)), ([int]$date.substring(8,2)), ([int]$date.substring(10,2)), ([int]$date.substring(12,2)), ([datetimekind]::Local)) } function getData { param($cn); $qwinsta_res = qwinsta.ps1 $cn $processes = gwmi -Class win32_process -ComputerName $cn $logonuis = $processes | ?{$_.Name -match "logonui"} for($i = 0; $i -lt $logonuis.Length; $i++) { Add-Member -Force -in $logonuis[$i] -MemberType NoteProperty -Name OwnerData -Value ($qwinsta_res | ?{$_.ID -eq $logonuis[$i].SessionId}) Add-Member -Force -in $logonuis[$i] -MemberType ScriptProperty -Name Owner -Value {return $this.OwnerData.UserName;} Add-Member -Force -in $logonuis[$i] -MemberType NoteProperty -Name LockTime -Value (WmiDateToDotnet $logonuis[$i].creationdate) } $logonuis } if($ComputerName -ne $null) { $alreadybegan = $true; getData $ComputerName; } } Process { if($alreadybegan -eq $true) { continue; } if($_ -eq $null) { throw New-Object exception "not a valid object to get a computer name from"; } elseif($_.gettype().equals([string])) { $cn = $_; } elseif($_.computername -ne $null) { $cn = $_.computername } elseif($_.machinename -ne $null) { $cn = $_.machinename } elseif($_.hostname -ne $null) { $cn = $_.hostname } else { throw New-Object exception "not a valid object to get a computer name from"; } getData $cn; }
PowerShellCorpus/PoshCode/SearchZIP_2.psm1 .ps1
SearchZIP_2.psm1 .ps1
function SearchZIPfiles { <# .SYNOPSIS Search for (filename) strings inside compressed ZIP or RAR files (V2.2). .DESCRIPTION In any directory containing a large number of ZIP/RAR compressed Web Page files this procedure will search each individual file name for simple text strings, listing both the source RAR/ZIP file and the individual file name containing the string. The relevant RAR/ZIP can then be subsequently opened in the usual way. Using the '-Table' switch will show the results with the Out-GridView display. .EXAMPLE extract -find 'library' -path d:\\scripts Searching for 'library' - please wait... (Use CTRL+C to quit) [Editor.zip] File: Windows 7 Library Procedures.mht [Editor.rar] File: My Library collection from 1974 Idi Amin.html [Test2.rar] File: Playlists from library - Windows 7 Forums.mht [Test3.rar] File: Module library functions UserGroup.pdf A total of 4 matches for 'library' found in folder 'D:\\Scripts'. .EXAMPLE extract -find 'backup' -path desktop Searching for 'backup' - please wait... (Use CTRL+C to quit) [Web.zip] File: How To Backup User and System Files.mht [Pages.rar] File: Create an Image Backup.pdf A total of 2 matches for 'backup' found in folder 'C:\\Users\\Sam\\Desktop'. .NOTES The first step will find any lines containing the selected pattern (which can be anywhere in the line). Each of these lines will then be split into 2 headings: Source and Filename. Note that there may be the odd occasion where a 'non-readable' character in the returned string slips through the net! .LINK Web Address Http://www.SeaStarDevelopment.BraveHost.com #> [CmdletBinding()] param([string][string][Parameter(Mandatory=$true)]$Find, [string][ValidateNotNullOrEmpty()]$path = $pwd, [switch][alias("GRIDVIEW")]$table) [int]$count = 0 if ($path -like 'desk*') { $path = Join-Path $home 'desktop\\*' } else { $xpath = Join-Path $path '*' -ea 0 if (!($?) -or !(Test-Path $path)) { Write-Warning "Path '$path' is invalid - resubmit" return } $path = $xpath } $folder = $path.Replace('*','') $lines = @{} $regex = '(?s)^(?<zip>.+?\\.(?:zip|rar)):(?:\\d+):.*\\\\(?<file>.*\\.(mht|html?|pdf))(.*)$' Get-ChildItem $path -include '*.rar','*.zip' | Select-String -SimpleMatch -Pattern $find | foreach-Object ` -begin { Write-Host "Searching for '$find' - please wait... (Use CTRL+C to quit)" } ` -process { $_ = $_ -replace '/','\\' if ( $_ -match $regex ) { $source = $matches.zip -replace [regex]::Escape($folder) $file = $matches.file $file = $file -replace '\\s+',' ' #Single space words. $file = $file -replace '\\p{S}',' ' #Remove some 'Dingbats'. if ($table) { $key = "{0:D4}" -f $count $lines["$key $source"] = $file #Create a unique key. } else { Write-Host "[$source] File: $file" } $count++ } } ` -end { $title = "A total of $($count) matches for '$find' found in host folder '$($path.Replace('\\*',''))'." if ($table -and $lines.count -gt 0) { $lines.GetEnumerator() | Select-Object @{name = 'Source';expression = {$_.Key.SubString(5)}}, @{name = 'File' ;expression = {$_.Value}} | Sort-Object File | Out-GridView -Title $title } else { Write-Host $title } } } #End function. New-Alias extract SearchZIPfiles -Description 'Find Web files inside ZIP/RAR' Export-ModuleMember -Function SearchZIPfiles -Alias Extract
PowerShellCorpus/PoshCode/Spin-Busy_1.ps1
Spin-Busy_1.ps1
## Spin-Busy displays a "spinning" character with each step reflecting an individual pipeline object being passed through. ## The current cursor position, fg/bg colors, screen width, etc. can be specified or automatically detected. ## ## This is *very* loosly adapted from Out-Working by Joel Bennett (http://powershellcentral.com/scripts/105). ## ## Parameters: ## -msWait Can be specified in order to insert a delay (in ms) after each character is written ## -spinStr Can be specified in order to use an alternate set of "spin" characters (see below) ## -spinChars Can be specified in order to use an alternate set of "spin" characters (see below) ## -rawUI Can be specified if an alternate console window is to be used ## -bgColor Can be specified to use a background color different than the current configuration ## -fgColor Can be specified to use a foreground color different than the current configuration ## -curPos Can be specified to spin in a different location than the current cursor position ## -startX Can be specified to start spinning at a different "X" coordinate than the current cursor position ## -maxX Can be specified to limit spinning to less than the current window width ## -trails Can be used to leave a "trail" of characters to help with longer term waits ## ## If specified, -spinStr is passed as a string of characters with the last 2 characters being the trailing and blank character, respectively. ## Default: '-\\|/. ', spinning '-\\|/', trailing with '.' and blanking empty cells with ' ' when complete. ## ## If specified, -spinChars is passed as an array of characters with the last 2 elements being the trailing and blank character, respectively. ## Default: @('-', '\\', '|', '/', '.', ' '), spinning '-\\|/', trailing with '.' and blanking empty cells with ' ' when complete. ## ## Examples: ## $t = (0..1000 | Spin-Busy) ## $t = (0..1000 | Spin-Busy -trails) ## $t = (0..1000 | Spin-Busy -mswait 1 -trails) ## $t = (0..1000 | Spin-Busy -mswait 1 -spinStr "123456789. " -trails) ## $t = (0..1000 | Spin-Busy 1 -fgColor "Red" -trails) ## $t = (0..1000 | Spin-Busy 1 -fgColor "Red" -bgColor "Black" -trails) function Spin-Busy { param( [Int] $msWait = 0, [String] $spinStr = '-\\|/. ', [Char[]] $spinChars = [Char[]] ($spinStr.ToCharArray()), [System.Management.Automation.Host.PSHostRawUserInterface] $rawUI = (Get-Host).UI.RawUI, [ConsoleColor] $bgColor = $rawUI.BackgroundColor, [ConsoleColor] $fgColor = $rawUI.ForegroundColor, [System.Management.Automation.Host.Coordinates] $curPos = $rawUI.Get_CursorPosition(), [Int32] $startX = $curPos.X, [Int32] $maxX = $rawUI.WindowSize.Width, [Switch] $trails ) begin { $trailCell = $rawUI.NewBufferCellArray(@($spinChars[-2]), $fgColor, $bgColor); $blankCell = $rawUI.NewBufferCellArray(@($spinChars[-1]), $fgColor, $bgColor); $spinCells = $spinChars[0..($spinChars.Count - 3)]; for ($i=0; $i -lt ($spinCells.Count); ++$i) { $spinCells[$i] = $rawUI.NewBufferCellArray(@($spinCells[$i]), $fgColor, $bgColor) } $charNdx = 0; } process { if ($charNdx -lt $spinCells.Count) { $rawUI.SetBufferContents($curPos, $spinCells[$charNdx++]); } else { $charNdx = 0; $rawUI.SetBufferContents($curPos, $trailCell); if ($trails) { if (++$curPos.X -gt $maxX) { do { --$curPos.X; $rawUI.SetBufferContents($curPos, $blankCell) } until ($curPos.X -le $startX) } } } Start-Sleep -milliseconds $msWait $_ } end { do { $rawUI.SetBufferContents($curPos, $blankCell); } until (--$curPos.X -le $startX) } }
PowerShellCorpus/PoshCode/Select-CSVString_2.ps1
Select-CSVString_2.ps1
# # NAME # Select-CSVString # # SYNOPSIS # Convert CSV files to custom objects with properties # # SYNTAX # Select-CSVString -pattern <string[]> -files (ls *) [-StartDate <DateTime>] [-EndDate <DateTime>] param ([regex]$pattern,$files=("$($exinstall)TransportRoles\\Logs\\AgentLog","$($exinstall.substring(0,1)):\\Program Files (x86)\\Microsoft Forefront Protection for Exchange Server\\Data\\FSEAgentLog"|%{ls $_}|Sort-Object LastWriteTime), [string]$StartDate, [string]$EndDate) # Check start and end dates $local:erroractionpreference = "Stop" If(!$StartDate -and !$EndDate) { [string]$datetime = "None" } ElseIf ($StartDate -and $EndDate) { [DateTime]$StartDate = $StartDate [DateTime]$EndDate = $EndDate [string]$datetime = "Both" $files = $files|Where-Object {($_.CreationTime -ge $StartDate -or $_.LastWriteTime -ge $StartDate) -and $_.CreationTime -le $EndDate} } ElseIf ($StartDate -and !$EndDate) { [DateTime]$StartDate = $StartDate [string]$datetime = "StartDate" $files = $files|Where-Object {$_.CreationTime -ge $StartDate -or $_.LastWriteTime -ge $StartDate} } ElseIf (!$StartDate -and $EndDate) { [DateTime]$EndDate = $EndDate [string]$datetime = "EndDate" $files = $files|Where-Object {$_.CreationTime -le $EndDate -or $_.LastWriteTime -le $EndDate} } $local:erroractionpreference = "Continue" # Get columns $columns = @($files)[0]|Get-Content -TotalCount 5 foreach($col in $columns) { $col = $col -Replace "^#Fields: ","" If ($col -notmatch "^#") { $columns = $col.Split(',') break } } # Get Results foreach($file in $files) { Write-Debug "File: $($file.FullName)" trap { Write-Debug "File Locked" $script:lines = $file|Get-Content|Select-String $pattern continue } $lines = $file|Select-String $pattern -ErrorAction Stop foreach($l in $lines) { Write-Debug "Line: $($l.Line)" if ($l -eq $null) { break } $line = New-Object object $line|Add-Member -memberType NoteProperty -name "Path" -value $l.Path # ---------- Delimiter magic inside ---------- # It has been asked, why not dump select-string to a # file and import-csv the whole thing? To get realtime # results and avoid temporary files, thats why. $z = [char](222) $from = "," $tmp = $l.Line -replace "(?:`"((?:(?:[^`"]|`"`"))+)(?:`"$from|`"`$))|(?:$from)|(?:((?:.(?!$from))*.)(?:$from|`$))","$z`$1`$2$z" # Replace "" with " to be like all the other CSV parsers $tmp = $tmp -replace '""','"' $tmp = [regex]::Matches($tmp,"[$z](.*?)[$z]") $row = @() $tmp | foreach { $row += $_.Groups[1].Value } # ---------- Delimiter magic inside ---------- 0..($columns.Count-1)|Foreach-Object { # Convert timestamps to datetime objects If($columns[$_] -match "(timestamp|date-time)") {$row[$_] = [DateTime]$row[$_]} $line|Add-Member -memberType NoteProperty -name $columns[$_] -Value $row[$_] } # Determine if the line meets datetime requirements If($datetime -eq "None") {Write-Output $line} ElseIf($datetime -eq "EndDate" -and $EndDate -ge $line.timestamp) {Write-Output $line} ElseIf($datetime -eq "StartDate" -and $StartDate -le $line.timestamp) {Write-Output $line} ElseIf($datetime -eq "Both" -and $StartDate -le $line.timestamp -and $EndDate -ge $line.timestamp) {Write-Output $line} } }
PowerShellCorpus/PoshCode/SharpSSH Module.ps1
SharpSSH Module.ps1
################################################## # cmdlets ################################################## #------------------------------------------------- # New-SharpSession #------------------------------------------------- # Usage: New-SharpSession -? #------------------------------------------------- function New-SharpSession { <# .Synopsis Used to open an SSH or SCP Session to the specified server. .Description Uses SharpSSH to open an SSH or SCP Session to the specified server. .Parameter Host The hostname or IP address that you want to connect to. .Parameter UserName The username string used for the connection. .Parameter Key The switch that tells function to execute with key parameters. .Parameter KeyFile The path and file name to the key file used for key based authentication. .Parameter User The switch that tells function to execute with user parameters. .Parameter Password The password string used for the connection. #> [CmdletBinding(DefaultParameterSetName="KeySet")] param( [Parameter(Mandatory=$True)][String]$Host, [Parameter(Mandatory=$True)][String]$UserName, [Parameter(ParameterSetName="KeySet")][Switch]$Key, [Parameter(ParameterSetName="KeySet", Mandatory=$True)][String]$KeyFile, [Parameter(ParameterSetName="User")][Switch]$User, [Parameter(ParameterSetName="User", Mandatory=$True)][String]$Password, [Switch]$SCP, [Switch]$PassThru ) try { # Default will always be to do SSH... if ($SCP){ $ConnectType = "Tamir.SharpSsh.scp" } else{ $ConnectType = "Tamir.SharpSsh.SshShell" } if ($Key -and (Test-Path $KeyFile)){ $Global:SharpSession = New-Object $ConnectType $Host, $UserName $Global:SharpSession.AddIdentityFile((Resolve-Path $KeyFile)) } else{ $Global:SharpSession = New-Object $ConnectType $Host, $UserName, $Password } $Global:SharpSession.Connect() if ($ConnectType -eq "Tamir.SharpSsh.SshShell"){ $Global:SharpSession.RemoveTerminalEmulationCharacters = $True } if($PassThru){ return $Global:SharpSession } } catch { throw $Error[0] } } #------------------------------------------------- # Transfer-SharpFile #------------------------------------------------- # Usage: Transfer-SharpFile -? #------------------------------------------------- function Transfer-SharpFile { <# .Synopsis Used to tranfser(get or put) a file using a valid SCP SharpSession. .Description Uses SharpSSH to tranfer (get or put) a file via SCP. .Parameter From The full path and file name to the file you are transferring. .Parameter To The full path and file name to where you want to copy the file to. #> param( [Parameter(Mandatory=$True)][String]$From, [Parameter(Mandatory=$True)][String]$To, [Switch]$Get, [Switch]$Put ) try { if (!($Get -or $Put)) { throw Write-Host "Get or Put must be defined!" -ForeGroundColor Red } if ($SharpSession.GetType().Fullname -ne "Tamir.SharpSsh.Scp"){ throw Write-Host "Not currently connected using SCP!" -ForeGroundColor Red } else{ # The action scriptblock for an EventObject must have # things defined in the Global scope. Yuck! $Global:SharpSessiontransferDone = $Null $Global:SharpSessiontotalBytes = $Null $Global:SharpSessiontransferredBytes = $Null [void] (Register-ObjectEvent -InputObject $SharpSession -EventName OnTransferProgress -SourceIdentifier Scp.OnTransferProgress ` -Action {$Global:SharpSessiontotalBytes = $args[3]; $Global:SharpSessiontransferredBytes = $args[2]}) [void] (Register-ObjectEvent -InputObject $SharpSession -EventName OnTransferEnd -SourceIdentifier Scp.OnTransferEnd ` -Action {$Global:SharpSessiontransferDone = $True}) # Default is always to get. if ($Get){ $SharpSession.Get($From, $To) try{ do {Write-Progress -Activity "Get - $($From)" -Status "Copying" ` -PercentComplete (($SharpSessiontransferredBytes/$SharpSessiontotalBytes)*100)} while ($SharpSessiontransferDone -eq $Null) } catch{ Write-Warning "File is not there..." } } else{ $SharpSession.Put($From, $To) try{ do {Write-Progress -Activity "Get - $($From)" -Status "Copying" ` -PercentComplete (($SharpSessiontransferredBytes/$SharpSessiontotalBytes)*100)} while ($SharpSessiontransferDone -eq $Null) } catch{ Write-Warning "File is not there..." } } } } catch { throw $Error[0] } finally { if (Get-EventSubscriber -SourceIdentifier Scp.OnTransferProgress){ [void] (Unregister-Event -SourceIdentifier Scp.OnTransferProgress) } if (Get-EventSubscriber -SourceIdentifier Scp.OnTransferEnd){ [void] (Unregister-Event -SourceIdentifier Scp.OnTransferEnd) } } } #------------------------------------------------- # Remove-SharpSession #------------------------------------------------- # Usage: Remove-SharpSession -? #------------------------------------------------- function Remove-SharpSession { <# .Synopsis Used to close an active SSH or SCP Session. .Description Uses SharpSSH to close an active SSH or SCP Session. #> try { if($SharpSession){ if ($SharpSession.GetType().Fullname -eq "Tamir.SharpSsh.SshShell"){ $SharpSession.WriteLine("exit") sleep -milli 500 if($SharpSession.ShellOpened) { Write-Warning "Shell didn't exit cleanly, closing anyway." } $SharpSession.Close() } else{ $SharpSession.Close() } } else{ throw "There is no session to remove!" } } catch { throw $Error[0] } finally { $Global:SharpSession = $Null } } ################################################## # Main ################################################## Export-ModuleMember New-SharpSession Export-ModuleMember Transfer-SharpFile Export-ModuleMember Remove-SharpSession
PowerShellCorpus/PoshCode/Get-FSMORoleOwner_3.ps1
Get-FSMORoleOwner_3.ps1
Function Get-FSMORoleOwner { <# .SYNOPSIS Retrieves the list of FSMO role owners of a forest and domain .DESCRIPTION Retrieves the list of FSMO role owners of a forest and domain .NOTES Name: Get-FSMORoleOwner Author: Boe Prox DateCreated: 06/9/2011 .EXAMPLE Get-FSMORoleOwner DomainNamingMaster : dc1.rivendell.com Domain : rivendell.com RIDOwner : dc1.rivendell.com Forest : rivendell.com InfrastructureOwner : dc1.rivendell.com SchemaMaster : dc1.rivendell.com PDCOwner : dc1.rivendell.com Description ----------- Retrieves the FSMO role owners each domain in a forest. Also lists the domain and forest. #> [cmdletbinding()] Param () Try { $forest = [system.directoryservices.activedirectory.Forest]::GetCurrentForest() ForEach ($domain in $forest.domains) { $forestproperties = @{ Forest = $Forest.name Domain = $domain.name SchemaMaster = $forest.SchemaRoleOwner DomainNamingMaster = $forest.NamingRoleOwner RIDOwner = $Domain.RidRoleOwner PDCOwner = $Domain.PdcRoleOwner InfrastructureOwner = $Domain.InfrastructureRoleOwner } $newobject = New-Object PSObject -Property $forestproperties $newobject.PSTypeNames.Insert(0,"ForestRoles") $newobject } } Catch { Write-Warning "$($Error)" } }
PowerShellCorpus/PoshCode/get-SQLInstanceInfo_2.ps1
get-SQLInstanceInfo_2.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/ActiveDirectoryFunctions_1.ps1
ActiveDirectoryFunctions_1.ps1
#.SYNOPSIS # Gets a directory entry from ActiveDirectory based on the login user name function Get-ADUser { [CmdletBinding()] param([string]$UserName=${Env:userName}) $ads = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'') $ads.filter = "(&(objectClass=Person)(samAccountName=$UserName))" $ads.FindAll().GetEnumerator() | %{ $_.GetDirectoryEntry() } } function Get-NTAccountName { [CmdletBinding()] param( [Parameter(ValueFromPipelineByPropertyName=$true)] [string]$Name ) process { $ads = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'') $ads.filter = "(|(name=$Name)(samAccountName=$Name))" $distinguishedName = $ads.FindOne().Properties["distinguishedname"] # Use the NameTranslate object. $objTrans = New-Object -comObject "NameTranslate" $objNT = $objTrans.GetType() # Invoke the Init method to Initialize NameTranslate by locating # the Global Catalog. Note the constant 3 is ADS_NAME_INITTYPE_GC. $objNT.InvokeMember("Init", "InvokeMethod", $Null, $objTrans, (3, $Null)) # Use the Set method to specify the Distinguished Name of the current domain. # Note the constant 1 is ADS_NAME_TYPE_1779. $objNT.InvokeMember("Set", "InvokeMethod", $Null, $objTrans, (1, "$distinguishedName")) # Use the Get method to retrieve the NetBIOS name of the current domain. # Note the constant 3 is ADS_NAME_TYPE_NT4. # The value retrieved includes a trailing backslash. $objNT.InvokeMember("Get", "InvokeMethod", $Null, $objTrans, 3) }} function Get-SID { [CmdletBinding()] param( [Parameter(ValueFromPipelineByPropertyName=$true)] [string]$Name ) process { $ads = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'') $ads.filter = "(|(name=$Name)(samAccountName=$Name))" new-object security.principal.securityidentifier $ads.FindOne().Properties["objectSID"][0], 0 }} #.SYNOPSIS # Gets a directory entry from ActiveDirectory based on the computer name function Get-ADComputer { [CmdletBinding()] param( [Parameter(ValueFromPipelineByPropertyName=$true)] [string]$ComputerName=${Env:ComputerName} ) $ads = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'') $ads.filter = "(&(objectClass=Computer)(name=$ComputerName))" $ads.FindAll().GetEnumerator() | %{ $Computer = $_.GetDirectoryEntry() $Computer = Resolve-PropertyValueCollection -InputObject $Computer Add-Member -InputObject $Computer -Type NoteProperty -Name SID -Value (new-object security.principal.securityidentifier $Computer.objectSID, 0) Add-Member -InputObject $Computer -Type NoteProperty -Name GUID -Value (new-object GUID (,[byte[]]$Computer.objectGUID)) Add-Member -InputObject $Computer -Type NoteProperty -Name CreatorSID -Value (new-object security.principal.securityidentifier $Computer."mS-DS-CreatorSID", 0) Add-Member -InputObject $Computer -Type NoteProperty -Name NTAccountName -Value (Get-NTAccountName $ComputerName) $Computer } } #.SYNOPSIS # Gets a directory entry from ActiveDirectory based on the group's friendly name function Get-ADGroup { [CmdletBinding()] param([string]$UserName) $ads = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'') $ads.filter = "(&(objectClass=Group)(samAccountName=$UserName))" $ads.FindAll().GetEnumerator() | %{ $_.GetDirectoryEntry() } } #.SYNOPSIS # Look up a DN from a user's (login) name function Get-DistinguishedName { [CmdletBinding()] param([string]$UserName) (Get-ADUser $UserName).DistinguishedName } #.SYNOPSIS # Get Active Directory group membership recursively #.EXAMPLE # $groups = Get-GroupMembership (Get-DistinguishedName Jaykul) #.EXAMPLE # $groups = Get-GroupMembership (Get-DistinguishedName Jaykul) -RecurseLimit 0 # # Gets the groups the user belongs to without recursing function Get-GroupMembership { [CmdletBinding()] param([string]$Name,[int]$RecurseLimit=-1) if(!$Name.StartsWith("CN=","InvariantCultureIgnoreCase")) { $Name = Get-DistinguishedName $Name } $groups = ([adsi]"LDAP://$Name").MemberOf if ($groups -and $RecurseLimit) { Foreach ($gr in $groups) { $groups += @(Get-GroupMembership $gr -RecurseLimit:$($RecurseLimit-1) | ? {$groups -notcontains $_}) } } return $groups | Convert-DistinguishedName } function Convert-DistinguishedName { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Position=0)] [string]$name ) process { if(!$Name.StartsWith("CN=","InvariantCultureIgnoreCase")) { $Name = Get-DistinguishedName $Name } $name -replace "CN=","Name=" -replace "DC=","Domain=" -replace "OU=","Org=" | ConvertFrom-PropertyString -Delimiter "," | ForEach { $_.Domain = $_.Domain -join "."; $_ } | Add-Member NoteProperty DN $name -passthru } } function Resolve-PropertyValueCollection { param( [Parameter(ValueFromPipeline=$true)] $InputObject ) process { $SingleMembers = @() $MultiMembers = @() $InputObject | Get-Member -Type Property | ForEach-Object { $Name = $_.Name if($InputObject.($Name).Count -le 1) { $SingleMembers += $Name } else { $MultiMembers += $Name } } $OutputObject = Select-Object -InputObject $InputObject -Property $MultiMembers foreach($member in $singleMembers) { Add-Member -InputObject $OutputObject -Type NoteProperty -Name $Member -Value ($InputObject.$Member)[0] } $OutputObject } } #. SYNOPSIS # Pretty-print the vitals on a user... function Select-UserInfo { [CmdletBinding()] param( [Parameter(Mandatory=$true,Position=0,ParameterSetName="Input",ValueFromPipeline=$true)] [System.DirectoryServices.DirectoryEntry[]]$InputObject , [Parameter(Mandatory=$true,Position=0,ParameterSetName="Name",ValueFromPipelineByPropertyName=$true)] [string[]]$name ) process { switch($PSCmdlet.ParameterSetName) { "Name" { foreach($n in $Name) { Write-Verbose "Getting $n User Info" Get-ADUser $n | Resolve-PropertyValueCollection } } "Input" { foreach($io in $InputObject) { Write-Verbose "Converting User Info for $($io.displayName)" Resolve-PropertyValueCollection -InputObject $io } } } } } function Get-GroupMembers { [CmdletBinding()] param( [Parameter(Mandatory=$true,Position=0,ParameterSetName="Input",ValueFromPipeline=$true)] [string]$GroupName ) process { Foreach ($member in (Get-ADGroup $GroupName).Members() ) { new-object System.DirectoryServices.DirectoryEntry $member | Resolve-PropertyValueCollection } } }
PowerShellCorpus/PoshCode/Run-Defrag_3.ps1
Run-Defrag_3.ps1
# Run-Defrag # Defragments the targeted hard drives. # # Args: # $server: A target Server 2003 or 2008 system # $drive: An optional drive letter. If this is blank then all # drives are defragmented # $force: If this switch is set then a defrag will be forced # even if the drive is low on space # # Returns: # The result description for each drive. function Run-Defrag { param([string]$server, [string]$drive, [switch]$force) [string]$query = 'Select * from Win32_Volume where DriveType = 3' if ($drive) { $query += " And DriveLetter LIKE '$drive%'" } $volumes = Get-WmiObject -Query $query -ComputerName $server foreach ($volume in $volumes) { Write-Host "Defragmenting $($volume.DriveLetter)..." -noNewLine $result = ($volume.Defrag($force)).ReturnValue switch ($result) { 0 {Write-Host 'Success'} 1 {Write-Host 'Access Denied'} 2 {Write-Host 'Not Supported'} 3 {Write-Host 'Volume Dirty Bit Set'} 4 {Write-Host 'Not Enough Free Space'} 5 {Write-Host 'Corrupt MFT Detected'} 6 {Write-Host 'Call Cancelled'} 7 {Write-Host 'Cancellation Request Requested Too Late'} 8 {Write-Host 'Defrag In Progress'} 9 {Write-Host 'Defrag Engine Unavailable'} 10 {Write-Host 'Defrag Engine Error'} 11 {Write-Host 'Unknown Error'} } } }
PowerShellCorpus/PoshCode/Colorize Subversion SVN.ps1
Colorize Subversion SVN.ps1
## SVN STAT colorizer - http://www.overset.com/2008/11/18/colorized-subversion-svn-stat-powershell-function/ function ss () { $c = @{ "A"="Magenta"; "D"="Red"; "C"="Yellow"; "G"="Blue"; "M"="Cyan"; "U"="Green"; "?"="DarkGray"; "!"="DarkRed" } foreach ( $svno in svn stat ) { if ( $c.ContainsKey($svno.ToString().SubString(0,1).ToUpper()) ) { write-host $svno -Fore $c.Get_Item($svno.ToString().SubString(0,1).ToUpper()).ToString() } else { write-host $svno } } }
PowerShellCorpus/PoshCode/be1eed1f-2503-4aa5-b552-787f15259255.ps1
be1eed1f-2503-4aa5-b552-787f15259255.ps1
@@---------------------logoff_clientside_interactive.ps1----------------- #powershell -ExecutionPolicy Unrestricted logoff_clientside_interactive.ps1 $ErrorActionPreference = "silentlycontinue" $mycreds = (Get-Credential) Invoke-Command -ComputerName terminalserver -Credential $mycreds { &"C:\\Program Files\\internal\\logoff_serverside.ps1" } @@---------------------logoff_clientside_interactive.ps1----------------- or even simpler @@---------------------logoff_clientside_same_user.ps1------------------- $ErrorActionPreference = "silentlycontinue" Invoke-Command -ComputerName terminalserver { &"C:\\Program Files\\internal\\logoff_serverside.ps1" } @@---------------------logoff_clientside_same_user.ps1------------------- @@---------------------logoff_serverside.ps1----------------------------- # http://psterminalservices.codeplex.com/ - Powershell Module for Terminalserver # http://blogs.technet.com/b/heyscriptingguy/archive/2011/01/05/simplify-desktop-configuration-by-using-a-shared-powershell-module.aspx # Module installation to %windir%\\System32\\WindowsPowerShell\\v1.0\\Modules # activate Powershell remoteing for non-Administrators # Set-PSSessionConfiguration -Name Microsoft.PowerShell -showSecurityDescriptorUI -force # add remote desktop users Import-module PSTerminalServices $myId=[System.Security.Principal.WindowsIdentity]::GetCurrent() $data=$myID.name.split('\\') $data=$data[1] Get-TSSession -ComputerName localhost -Filter {$_.Username -eq $data} | Stop-TSSession –Force @@---------------------logoff_serverside.ps1-----------------------------
PowerShellCorpus/PoshCode/Get Exchange DB Stats.ps1
Get Exchange DB Stats.ps1
# requires -version 2.0 # # get-exstats.ps1 # # returns various statistics on databases # # Author: rfoust@duke.edu # Modified: March 12, 2012 # # This has only been tested with Exchange 2010 param([string]$server=$env:computername.tolower(), [string]$database="NotSpecified", [switch]$all, [switch]$noemail, [switch]$nologcheck) #Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin if (!(get-pssnapin Microsoft.Exchange.Management.PowerShell.E2010 -erroraction silentlycontinue)) { Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 } # found this really cool function here: http://www.olavaukan.com/tag/powershell/ function Util-Convert-FileSizeToString { param ( [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)] [int64]$sizeInBytes ) switch ($sizeInBytes) { {$sizeInBytes -ge 1TB} {"{0:n$sigDigits}" -f ($sizeInBytes/1TB) + " TB" ; break} {$sizeInBytes -ge 1GB} {"{0:n$sigDigits}" -f ($sizeInBytes/1GB) + " GB" ; break} {$sizeInBytes -ge 1MB} {"{0:n$sigDigits}" -f ($sizeInBytes/1MB) + " MB" ; break} {$sizeInBytes -ge 1KB} {"{0:n$sigDigits}" -f ($sizeInBytes/1KB) + " KB" ; break} Default { "{0:n$sigDigits}" -f $sizeInBytes + " Bytes" } } } # specifying only a single database using -database makes the script run faster for testing if ($database -eq "NotSpecified") { # $dbs = get-mailboxdatabase -status | ? { $_.replicationtype -eq "Remote" } | select-object servername,name,databasesize,mounted | sort servername,name $dbs = get-mailboxdatabase -status | ? { $_.replicationtype -eq "Remote" } | sort servername,name } else { $dbs = get-mailboxdatabase $database -status | sort servername,name } $fragments = @() # array to hold html fragments $data = @() # array to hold the psobjects $prettydata = @() # array to hold pretty data (strings, not raw bytes) foreach ($db in $dbs) { write-host "Processing $db." $raw = new-object psobject $pretty = new-object psobject write-host "Gathering count of mailboxes on $db." $mailboxes = (get-mailbox -database $db.name -resultsize unlimited).count #get copy status $copystatus = (get-mailboxdatabasecopystatus $db.name | ? { $_.activecopy -eq $false }).status if (-not $nologcheck) { #figure out how much space the logs are consuming # $drive will probably end up being D$ in all cases, but might as well do the logic to figure it out write-host "Finding out how much disk space the log files are using for $db ..." $drive = $db.logfolderpath.tostring().substring(0,1) + "$" $substring = $db.logfolderpath.tostring().substring(0,2) $uncpath = "\\\\$($db.server)\\" + $drive + ($db.logfolderpath.tostring().replace($substring,"")) + "\\*.log" $logsize = (ls $uncpath | measure-object -property length -sum).sum $logsizetotal += $logsize $logsize = util-convert-filesizetostring $logsize } #calculate average mailbox size Write-Host "Calculating average mailbox size ..." $avg = get-mailboxstatistics -database $db | % { $_.totalitemsize.value.tobytes() } $avg = ($avg | Measure-Object -Average).average $avgTotal += $avg if ($avg) { $avgPretty = util-convert-filesizetostring $avg } #calculate deleted mailbox size Write-Host "Calculating deleted mailbox size ..." $deletedMBsize = get-mailboxstatistics -database $db | ? { $_.DisconnectDate -ne $null } | % { $_.totalitemsize.value.tobytes() } $deletedMBsize = ($deletedMBsize | Measure-Object -Sum).sum $deletedMBsizeTotal += $deletedMBsize if ($deletedMBsize) { $deletedMBsizePretty = util-convert-filesizetostring $deletedMBsize } #calculate dumpster size Write-Host "Calculating dumpster size ..." $dumpster = get-mailboxstatistics -database $db | % { $_.totaldeleteditemsize.value.tobytes() } $dumpster = ($dumpster | Measure-Object -Sum).sum $dumpsterTotal += $dumpster if ($dumpster) { $dumpsterPretty = util-convert-filesizetostring $dumpster } #get a shorter db size $dbsize = $db.databasesize.tobytes() $dbsizetotal += $dbsize if ($dbsize) { $dbsizePretty = util-convert-filesizetostring $dbsize } #get free space on the mountpoint volume $freespace = (gwmi win32_volume -computer $db.server | where { $_.name -eq ($db.logfolderpath.tostring() + "\\") }).freespace $freespacetotal += $freespace if ($freespace) { $freespacePretty = util-convert-filesizetostring $freespace } #get capacity on the mountpoint volume $capacity = (gwmi win32_volume -computer $db.server | where { $_.name -eq ($db.logfolderpath.tostring() + "\\") }).capacity $capacitytotal += $capacity if ($capacity) { $capacityPretty = util-convert-filesizetostring $capacity } #get a shorter whitespace size $whitespace = $db.availablenewmailboxspace.tobytes() $whitespacetotal += $whitespace if ($whitespace) { $whitespacePretty = util-convert-filesizetostring $whitespace } # create psobject with raw bytes $raw | add-member NoteProperty "ServerName" $db.servername $raw | add-member NoteProperty "Database" $db.name $raw | add-member NoteProperty "Mailboxes" $mailboxes $raw | add-member NoteProperty "CopyStatus" $copystatus $raw | add-member NoteProperty "DBSize" $dbsize # $raw | add-member NoteProperty "Mounted" $db.mounted $raw | add-member NoteProperty "LogSize" $logsize $raw | add-member NoteProperty "FreeSpace" $freespace $raw | add-member NoteProperty "TotalSpace" $capacity $raw | add-member NoteProperty "Whitespace" $whitespace $raw | add-member NoteProperty "Deleted Mbox" $deletedMBsize $raw | add-member NoteProperty "Dumpster" $dumpster $raw | add-member NoteProperty "Avg Mbox" $avgPretty $raw | add-member NoteProperty "Last Full Backup" $db.lastfullbackup $raw | add-member NoteProperty "Last Incr Backup" $db.lastincrementalbackup $data += $raw # create psobject with pretty display sizes (MB, GB, etc) $pretty | add-member NoteProperty "ServerName" $db.servername $pretty | add-member NoteProperty "Database" $db.name $pretty | add-member NoteProperty "Mailboxes" $mailboxes $pretty | add-member NoteProperty "CopyStatus" $copystatus $pretty | add-member NoteProperty "DBSize" $dbsizePretty # $pretty | add-member NoteProperty "Mounted" $db.mounted $pretty | add-member NoteProperty "LogSize" $logsize $pretty | add-member NoteProperty "FreeSpace" $freespacePretty $pretty | add-member NoteProperty "TotalSpace" $capacityPretty $pretty | add-member NoteProperty "Whitespace" $whitespacePretty $pretty | add-member NoteProperty "Deleted Mbox" $deletedMBsizePretty $pretty | add-member NoteProperty "Dumpster" $dumpsterPretty $pretty | add-member NoteProperty "Avg Mbox" $avgPretty $pretty | add-member NoteProperty "Last Full Backup" $db.lastfullbackup $pretty | add-member NoteProperty "Last Incr Backup" $db.lastincrementalbackup $prettydata += $pretty } # add a "total" row $thingy = new-object psobject write-host; write-host "Calculating totals ..." $mailboxes = ($data | measure-object mailboxes -sum).sum $deletedMBsizetotal = ($deletedMBsizetotal | Measure-Object -Sum).sum $thingy | add-member NoteProperty "ServerName" "Total" $thingy | add-member NoteProperty "Database" $data.count $thingy | add-member NoteProperty "DBSize" (util-convert-filesizetostring $dbsizetotal) $thingy | add-member NoteProperty "Mailboxes" $mailboxes if (-not $nologcheck) { $thingy | add-member NoteProperty "LogSize" (util-convert-filesizetostring $logsizetotal) } $thingy | add-member NoteProperty "FreeSpace" (util-convert-filesizetostring $freespacetotal) $thingy | add-member NoteProperty "TotalSpace" (util-convert-filesizetostring $capacitytotal) $thingy | add-member NoteProperty "Whitespace" (util-convert-filesizetostring $whitespacetotal) $thingy | Add-Member NoteProperty "Deleted Mbox" (util-convert-filesizetostring $deletedMBsizeTotal) $thingy | Add-Member NoteProperty "Dumpster" (util-convert-filesizetostring $dumpsterTotal) #$thingy | Add-Member NoteProperty "Avg Mbox" (util-convert-filesizetostring $avgTotal) $prettyData += $thingy # add raw data total row $thingy = new-object psobject $mailboxes = ($data | measure-object mailboxes -sum).sum $deletedMBsizetotal = ($deletedMBsizetotal | Measure-Object -Sum).sum $thingy | add-member NoteProperty "ServerName" "Total" $thingy | add-member NoteProperty "Database" $data.count $thingy | add-member NoteProperty "DBSize" $dbsizetotal $thingy | add-member NoteProperty "Mailboxes" $mailboxes if (-not $nologcheck) { $thingy | add-member NoteProperty "LogSize" $logsizetotal } $thingy | add-member NoteProperty "FreeSpace" $freespacetotal $thingy | add-member NoteProperty "TotalSpace" $capacitytotal $thingy | add-member NoteProperty "Whitespace" $whitespacetotal $thingy | Add-Member NoteProperty "Deleted Mbox" $deletedMBsizeTotal $thingy | Add-Member NoteProperty "Dumpster" $dumpsterTotal #$thingy | Add-Member NoteProperty "Avg Mbox" $avgTotal $data += $thingy # dump pretty data out to screen $prettyData # bullet graph idea came from here: http://www.usrecordings.com/test-lab/bullet-graph.htm # powershell html chart was inspired by: http://jdhitsolutions.com/blog/2012/02/create-html-bar-charts-from-powershell/ $style = "<style type=`"text/css`"> html * { margin: 0; padding: 0; border: 0; } body { text-align: left; font: 10pt Arial, sans-serif; } TH { border-width: 1px; padding: 0px; border-style: solid; border-color: black; background-color: thistle } h1 { font: 30pt Arial, sans-serif; padding: 10px 0 5px 0; width: 540px; margin: 0 auto 10px auto; border-bottom: 1px solid #8f8f8f; text-align: left; } h2 { font: 20pt Arial, sans-serif; } p#contact { font: 10pt Arial, sans-serif; width: 398px; margin: 0 auto; padding-top: 7px; text-align: left; line-height: 140%; } a:link, a:visited, a:hover { color: rgb(32,108,223); font-weight: bold; text-decoration: none; } a:hover { color: #cc0000; font-weight: bold; } div#container { position: relative; margin: 0px 50px; padding: 0; text-align: left; top: 80px; width: 250px; } /* BULLET GRAPH */ div.box-wrap { position: relative; width: 200px; height: 21px; top: 0; left: 0; margin: 0; padding: 0; } /* CHANGE THE WIDTH AND BACKGROUND COLORS AS NEEDED */ div.box1 { position: absolute; height: 20px; width: 30%; left: 0; background-color: #eeeeee; z-index: 1; font-size: 0; } div.box2 { position: absolute; height: 20px; width: 30%; left: 30%; background-color: #dddddd; z-index: 1; font-size: 0; } div.box3 { position: absolute; height: 20px; width: 30%; left: 60%; background-color: #bbbbbb; z-index: 1; font-size: 0; } div.box4 { position: absolute; height: 20px; width: 10%; left: 90%; background-color: #bbbbbb; z-index: 1; font-size: 0; } /* RED LINE */ div.target { position: absolute; height: 20px; width: 1px; left: 32px; top: 0; background-color: #cc0000; z-index: 7; font-size: 0; } /* ONE SEGMENT ONLY */ div.actual { position: absolute; height: 8px; left: 0px; top: 6px; background-color: #000000; font-size: 0; z-index: 5; font-size: 0; } /* TWO SEGMENTS */ div.actualWhitespace { position: absolute; height: 8px; left: 0px; top: 6px; background-color: #b580fe; font-size: 0; z-index: 5; font-size: 0; } div.actualDeleted { position: absolute; height: 8px; left: 0px; top: 6px; background-color: #2d006b; font-size: 0; z-index: 5; font-size: 0; } div.actualDumpster { position: absolute; height: 8px; left: 0px; top: 6px; background-color: #dabffe; font-size: 0; z-index: 5; font-size: 0; } div.actualData { position: absolute; height: 8px; left: 0px; top: 6px; background-color: #400099; font-size: 0; z-index: 5; font-size: 0; } div.mylabel { position: relative; height: 20px; width: 145px; left: -155px; top: 2px; background-color: #fff; z-index: 7; font-size: 0; color: #000000; font: 10pt Arial, sans-serif; text-align: right; } div.scale-tb1 { padding: 0; margin: 0; font-size: 0; width: 200px; border: 0; position: relative; top: 10px; left: 0px; border-top: 1px solid #8f8f8f; } div.scale-tb2 { padding: 0; margin: 0; font-size: 0; width: 200px; border: 0; position: relative; top: 0px; left: 0px; } /* SCALE MARKS */ div.sc21 { position: absolute; height: 7px; width: 1px; left: 0px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } div.sc22 { position: absolute; height: 7px; width: 1px; left: 39px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } div.sc23 { position: absolute; height: 7px; width: 1px; left: 79px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } div.sc24 { position: absolute; height: 7px; width: 1px; left: 119px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } div.sc25 { position: absolute; height: 7px; width: 1px; left: 159px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } div.sc26 { position: absolute; height: 7px; width: 1px; left: 199px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } div.sc31 { position: absolute; height: 7px; width: 1px; left: 0px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } div.sc32 { position: absolute; height: 7px; width: 1px; left: 39px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } div.sc33 { position: absolute; height: 7px; width: 1px; left: 79px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } div.sc34 { position: absolute; height: 7px; width: 1px; left: 119px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } div.sc35 { position: absolute; height: 7px; width: 1px; left: 159px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } div.sc36 { position: absolute; height: 7px; width: 1px; left: 199px; top: 0px; background-color: #8f8f8f; z-index: 7; font-size: 0; } /* SCALE TEXT */ div.cap21 { position: absolute; top: 40px; left: -2px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } div.cap22 { position: absolute; top: 40px; left: 35px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } div.cap23 { position: absolute; top: 40px; left: 71px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } div.cap24 { position: absolute; top: 40px; left: 112px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } div.cap25 { position: absolute; top: 40px; left: 152px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } div.cap26 { position: absolute; top: 40px; left: 191px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } div.cap31 { position: absolute; top: 29px; left: -2px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } div.cap32 { position: absolute; top: 29px; left: 35px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } div.cap33 { position: absolute; top: 29px; left: 71px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } div.cap34 { position: absolute; top: 29px; left: 112px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } div.cap35 { position: absolute; top: 29px; left: 152px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } div.cap36 { position: absolute; top: 29px; left: 191px; width: 15px; font: 8pt Arial, sans-serif; text-align: center; color: #575757; } </style>" $fragments += "<H2>Exchange 2010 Statistics</H2>" $fragments += $prettyData | ConvertTo-Html -fragment # $fragments += "<br>" $html = @() $html += "<div id=`"container`">" $html += "Database Size Graph" foreach ($db in $data) { if ($db.servername -ne "Total") { $html += "<div class=`"box-wrap`"> <div class=`"box1`"></div> <div class=`"box2`"></div> <div class=`"box3`"></div> <div class=`"box4`"></div> <div class=`"target`" style=`"left: $([math]::round((($db.totalspace - $db.freespace) / $db.totalspace) * 100))%`"></div> <div class=`"actualWhitespace`" style=`"width: $([math]::round((($db.dbsize) / $db.totalspace)*100))%`"></div> <div class=`"actualDeleted`" style=`"width: $([math]::round((($db.dbsize - $db.whitespace) / $db.totalspace)*100))%`"></div> <div class=`"actualDumpster`" style=`"width: $([math]::round((($db.dbsize - $db.whitespace - $db.'deleted mbox') / $db.totalspace)*100))%`"></div> <div class=`"actualData`" style=`"width: $([math]::round((($db.dbsize - $db.dumpster - $db.'deleted mbox' - $db.whitespace) / $db.totalspace)*100))%`"></div> <div class=`"mylabel`">$($db.database)</div> <div class=`"cap31`">0%</div> <div class=`"cap32`">20%</div> <div class=`"cap33`">40%</div> <div class=`"cap34`">60%</div> <div class=`"cap35`">80%</div> <div class=`"cap36`">100%</div> <div class=`"scale-tb2`"> <div class=`"sc31`"></div> <div class=`"sc32`"></div> <div class=`"sc33`"></div> <div class=`"sc34`"></div> <div class=`"sc35`"></div> <div class=`"sc36`"></div> </div> </div> <p style=`"height: 30px;`"></p>" } else # total row { $html += "<div class=`"box-wrap`"> <div class=`"box1`"></div> <div class=`"box2`"></div> <div class=`"box3`"></div> <div class=`"box4`"></div> <div class=`"target`" style=`"left: $([math]::round((($db.totalspace - $db.freespace) / $db.totalspace) * 100))%`"></div> <div class=`"actualWhitespace`" style=`"width: $([math]::round((($db.dbsize) / $db.totalspace)*100))%`"></div> <div class=`"actualDeleted`" style=`"width: $([math]::round((($db.dbsize - $db.whitespace) / $db.totalspace)*100))%`"></div> <div class=`"actualDumpster`" style=`"width: $([math]::round((($db.dbsize - $db.whitespace - $db.'deleted mbox') / $db.totalspace)*100))%`"></div> <div class=`"actualData`" style=`"width: $([math]::round((($db.dbsize - $db.dumpster - $db.'deleted mbox' - $db.whitespace) / $db.totalspace)*100))%`"></div> <div class=`"mylabel`">Total</div> <div class=`"cap31`">0%</div> <div class=`"cap32`">20%</div> <div class=`"cap33`">40%</div> <div class=`"cap34`">60%</div> <div class=`"cap35`">80%</div> <div class=`"cap36`">100%</div> <div class=`"scale-tb2`"> <div class=`"sc31`"></div> <div class=`"sc32`"></div> <div class=`"sc33`"></div> <div class=`"sc34`"></div> <div class=`"sc35`"></div> <div class=`"sc36`"></div> </div> </div> <p style=`"height: 30px;`"></p>" } } # show a graph key $html += "<div class=`"box-wrap`"> <div class=`"box1`"></div> <div class=`"box2`"></div> <div class=`"box3`"></div> <div class=`"box4`"></div> <div class=`"target`" style=`"left: 90%`"></div> <div class=`"actualWhitespace`" style=`"width: 100%`"></div> <div class=`"actualDeleted`" style=`"width: 75%`"></div> <div class=`"actualDumpster`" style=`"width: 50%`"></div> <div class=`"actualData`" style=`"width: 25%`"></div> <div class=`"mylabel`">Key:</div> </div> MBs - Dumpster - Del MB - Whitespace<br> Red Line: Used Disk Space </div> <p style=`"height: 30px;`"></p>" $html += "</div><!-- container -->" $fragments += $html $emailbody = convertto-html -head $style -Body $fragments $date = get-date -uformat "%Y-%m-%d" if (-not $noemail) { $smtpServer = "your.smtpserver.com" $msg = new-object Net.Mail.MailMessage $smtp = new-object Net.Mail.SmtpClient($smtpServer) $msg.From = "somebody@somewhere.com" $msg.To.Add("you@somewhere.com") $msg.Subject = "Exchange 2010 Daily Statistics" $msg.Body = $emailbody $msg.IsBodyHtml = $true $smtp.Send($msg) }
PowerShellCorpus/PoshCode/Get-BinarySum.ps1
Get-BinarySum.ps1
function Get-BinarySum { <# .SYNOPSIS Performs binary addition of two Int32 values. .DESCRIPTION If a numeric overflow occurs in PowerShell, an error is generated making it impossible to perform binary addition. Get-BinarySum will add two Int32 numbers together and if the result exceeds [Int32]::MaxValue, the sum will wrap. This function emulates C-style addition. .EXAMPLE PS> Get-BinarySum 0xFFFFFFFF 2 1 .EXAMPLE PS> Get-BinarySum 2 (-bnot 3 + 1) -1 Description ----------- Performs the equivalent of binary subtraction of 2 - 3 .OUTPUTS System.Int32 The sum of the addition. The Int32 will wrap if the result is greater than 0xFFFFFFFF .LINK http://www.exploit-monday.com/ #> Param ( [Parameter(Mandatory = $True, Position = 0)] [Int32] $Num1, [Parameter(Mandatory = $True, Position = 1)] [Int32] $Num2 ) # The number of bits in an Int32 (DWORD) $BitWidth = 32 # Convert each number to its binary equivalent [Char[]] $Num1Array = ([Convert]::ToString($Num1, 2)).PadLeft($BitWidth,'0') [Char[]] $Num2Array = ([Convert]::ToString($Num2, 2)).PadLeft($BitWidth,'0') # Initialize the sum to zero [Char[]] $Sum = '0' * $BitWidth $Carry = 0 # Calculate sum for each bit and carry, if necessary for ($i = ($BitWidth-1); $i -ge 0; $i--) { $BxorResult = [Convert]::ToInt32($Num1Array[$i], 2) -bxor [Convert]::ToInt32($Num2Array[$i], 2) $BandResult = [Convert]::ToInt32($Num1Array[$i], 2) -band [Convert]::ToInt32($Num2Array[$i], 2) $Sum[$i] = ($BxorResult -bxor $Carry).ToString() $Carry = $BandResult -bor ($Carry -band $BxorResult) } # Return the result as an Int32 [Convert]::ToInt32($Sum -join '', 2) }
PowerShellCorpus/PoshCode/iSCSI Module.ps1
iSCSI Module.ps1
# Copyright (c) 2011 Code Owls LLC, All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy of this # software and associated documentation files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or # substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF # CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE # OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # http://www.opensource.org/licenses/mit-license.php # # PowerShell module for iSCSI management # # author: # jim christopher <jimchristopher@gmail.com> # # notes: # #Target Mappings: # <Target Lun> is the LUN value the target uses to expose the LUN. # It must be in the form 0x0123456789abcdef # <OS Bus> is the bus number the OS should use to surface the LUN # <OS Target> is the target number the OS should use to surface the LUN # <OS LUN> is the LUN number the OS should use to surface the LUN # #CHAP secrets, CHAP passwords and IPSEC preshared keys can be specified as #a text string or as a sequence of hexadecimal values. The value specified on #the command line is always considered a string unless the first two characters #0x in which case it is considered a hexadecimal value. # #For example 0x12345678 specifies a 4 byte secret # #All numerical values are assumed decimal unless preceeded by 0x. If #preceeded by 0x then value is assumed to be hex # #iscsicli can also be run in command line mode where iscsicli commands #can be entered directly from the console. To enter command line #mode, just run iscsicli without any parameters ########################################################### ## flags and enumerations #Payload Id Type: # ID_IPV4_ADDR is 1 - Id format is 1.2.3.4 # ID_FQDN is 2 - Id format is ComputerName # ID_IPV6_ADDR is 5 - Id form is IPv6 Address # $payloadIPV4 = 1; $payloadFQDN = 2; $payloadIPV6 = 5; #Security Flags: # TunnelMode is 0x00000040 # TransportMode is 0x00000020 # PFS Enabled is 0x00000010 # Aggressive Mode is 0x00000008 # Main mode is 0x00000004 # IPSEC/IKE Enabled is 0x00000002 # Valid Flags is 0x00000001 # $securityTunnelMode = 0x40; $securityTransportMode = 0x20; $securityPFSEnable = 0x10; $securityAggressiveMode = 0x08; $securityMainMode = 0x04; $securityIPSECIKEEnabled = 0x02; $securityValidFlags = 0x01; #Login Flags: # ISCSI_LOGIN_FLAG_REQUIRE_IPSEC 0x00000001 # IPsec is required for the operation # # ISCSI_LOGIN_FLAG_MULTIPATH_ENABLED 0x00000002 # Multipathing is enabled for the target on this initiator # $loginRequireIPSEC = 0x01; $loginMultipathEnabled = 0x02; #AuthType: # ISCSI_NO_AUTH_TYPE = 0, # No iSCSI in-band authentication is used # # ISCSI_CHAP_AUTH_TYPE = 1, # One way CHAP (Target authenticates initiator is used) # # ISCSI_MUTUAL_CHAP_AUTH_TYPE = 2 # Mutual CHAP (Target and Initiator authenticate each other is used) # $authTypeNone = 0; $authTypeChap = 1; $authTypeMutualChap = 2; #Target Flags: # ISCSI_TARGET_FLAG_HIDE_STATIC_TARGET 0x00000002 # If this flag is set then the target will never be reported unless it # is also discovered dynamically. # # ISCSI_TARGET_FLAG_MERGE_TARGET_INFORMATION 0x00000004 # If this flag is set then the target information passed will be # merged with any target information already statically configured for # the target # $targetHideStaticTarget = 0x02; $targetMergeTargetInfo = 0x04; ########################################################### ## cmdlets #iscsicli AddTarget <TargetName> <TargetAlias> <TargetPortalAddress> # <TargetPortalSocket> <Target flags> # <Persist> <Login Flags> <Header Digest> <Data Digest> # <Max Connections> <DefaultTime2Wait> # <DefaultTime2Retain> <Username> <Password> <AuthType> # <Mapping Count> <Target Lun> <OS Bus> <Os Target> # <OS Lun> ... # #iscsicli QAddTarget <TargetName> <TargetPortalAddress> # function Add-Target { [CmdletBinding(SupportsShouldProcess=$true)] param( [Parameter(Mandatory=$true)] [Alias("Name")] [string] # the name of the target $targetName, [Parameter(Mandatory=$true)] [Alias("Address")] [string] # the IP or DNS address of the target portal $targetPortalAddress ) process { & iscsicli qaddtarget $targetName, $targetPortalAddress; } } #iscsicli RemoveTarget <TargetName> # #RemovePersistentTarget <Initiator Name> <TargetName> # <Initiator Port Number> # <Target Portal Address> # <Target Portal Socket> # function Remove-Target { <# This command will remove a target from the list of persisted targets. Boot Configuration Known Issues (Windows Server 2003 Boot Initiator) The Microsoft iSCSI Software Initiator boot version GUI does not allow you to view which adapter is set to boot. In order to determine which adapter the system is set to boot with, you can use the following command: From a command prompt type “iscsibcg /showibf” to find the MAC address of the boot adapter Then run the command “ipconfig /all” Compare the MAC address of the adapter to those listed with ipconfig /all MPIO Failover in an iSCSI boot configuration using the Microsoft iSCSI Software Initiator In Fail Over Only, no load balancing is performed. The primary path functions as the active path and all other paths are standby paths. The active path is used for sending all I/O. If the active path fails, one of the standby paths becomes the active path. When the formerly active path is reconnected, it becomes a standby path and a "failback" does not occur. This behavior is due to Media Sensing is disabled by default in the boot version of the Microsoft iSCSI Software Initiator and is by design. However, the registry key can be changed to enable fail back. For more information, please see For more information: 239924 How to disable the Media Sensing feature for TCP/IP in Windows http://support.microsoft.com/default.aspx?scid=kb;EN-US;239924 #> [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='high')] param( [Parameter(Mandatory=$true,ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)] [Alias("Name")] [string] # the name of the target to remove $targetName, [Parameter(ValueFromPipelineByPropertyName=$true)] [Alias("Address")] [string] # the IP or DNS address of the target portal $targetPortalAddress, [Parameter(ValueFromPipelineByPropertyName=$true)] [Alias('Port')] [int] #the TCP port number of the target portal. Typically this is 3260, which is the well-known port number defined for use by iSCSI. $TargetPortalSocket = 3260, [Parameter(ValueFromPipelineByPropertyName=$true)] [Alias( "InitiatorInstanceName" )] [string] #the name of the initiator via which the SendTargets operation is performed. If not specified then the initiator used is selected by the iSCSI initiator service. $InitiatorName, [Parameter(ValueFromPipelineByPropertyName=$true)] [string] #is the physical port number on the initiator via which the SendTargets operation is performed. If not specified then the kernel mode initiator driver chooses the initiator port used. $InitiatorPort = '*', [Parameter()] [switch] # specify to remove a persistent connection $persist, [Parameter()] [switch] # specify to bypass standard PowerShell confirmation procedures $force ) process { Write-Verbose "remove-target ..."; Write-Verbose " TargetName: $targetName"; Write-Verbose " TargetPortalAddress: $targetPortalAddress"; Write-Verbose " TargetPortalSocket: $targetPortalSocket"; Write-Verbose " InitiatorInstanceName: $InitiatorName"; Write-Verbose " InitiatorPort: $initiatorPort"; Write-Verbose " Persist: $persist"; Write-Verbose " Force: $force"; if( -not ( $force -or $pscmdlet.ShouldProcess( $targetName, 'Remove iSCSI target' ) ) ) { return; } if( $persist -and $InitiatorName ) { $iscsi = "iscsicli removepersistenttarget $InitiatorName $targetName $InitiatorPort $targetPortalAddress $TargetPortalSocket" Write-Verbose $iscsi; invoke-expression $iscsi } else { $iscsi = "iscsicli removetarget $targetName"; Write-Verbose $iscsi; invoke-expression $iscsi } } } #iscsicli AddTargetPortal <TargetPortalAddress> <TargetPortalSocket> # [HBA Name] [Port Number] # <Security Flags> # <Login Flags> <Header Digest> <Data Digest> # <Max Connections> <DefaultTime2Wait> # <DefaultTime2Retain> <Username> <Password> <AuthType> # #iscsicli QAddTargetPortal <TargetPortalAddress> # [CHAP Username] [CHAP Password] # function Add-TargetPortal { <# This command will add a target portal to the list of persisted target portals. The iSCSI initiator service will perform a SendTargets operation to each target portal in the list whenever the service starts and whenever a full refresh of the target list is requested. #> #[CmdletBinding(SupportsShouldProcess=$true)] param( [Parameter(Mandatory=$true)] [Alias("Address")] [string] # the IP or DNS address of the target portal. $targetPortalAddress, [Parameter()] [string] #Username is the string that should be used as the CHAP username when logging into the target. By specifying * for this parameter, the iSCSI initiator service will use the initiator node name as the CHAP username. $username, [Parameter()] [string] #Password is the string that should be used as the target’s CHAP secret when logging into the target. The initiator will use this secret to compute a hash value based on the challenge sent by the target. $password ) process { if( $username ) { & iscsicli qaddtargetportal $targetPortalAddress $username $password; } else { & iscsicli qaddtargetportal $targetPortalAddress; } } } #iscsicli RemoveTargetPortal <TargetPortalAddress> <TargetPortalSocket> [HBA Name] [Port Number] # function Remove-TargetPortal { <# This command will remove a target portal from the list of persisted target portals. The iSCSI initiator service will perform a SendTargets operation to each target portal in the list whenever the service starts and whenever a full refresh of the target list is requested. Note that the command does not purge the targets discovered via this target portal from the list of targets maintained by the service. #> [CmdletBinding(SupportsShouldProcess=$true)] param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [Alias('Name')] [string] # the IP or DNS address of the target portal. $targetPortalAddress, [Parameter()] [Alias('Port')] [int] #the TCP port number of the target portal. Typically this is 3260, which is the well-known port number defined for use by iSCSI. $TargetPortalSocket = 3260, [Parameter()] [string] #the name of the initiator via which the SendTargets operation is performed. If not specified then the initiator used is selected by the iSCSI initiator service. $InitiatorName = '', [Parameter()] [string] #is the physical port number on the initiator via which the SendTargets operation is performed. If not specified then the kernel mode initiator driver chooses the initiator port used. $InitiatorPort = '' ) process { & iscsicli removetargetportal $targetPortalAddress $TargetPortalSocket $InitiatorName $InitiatorPort } } #iscsicli RefreshTargetPortal <TargetPortalAddress> <TargetPortalSocket> [HBA Name] [Port Number] # function Update-TargetPortal { <# This command will perform a SendTargets operation to the target portal and include the discovered targets into the list of targets maintained by the service. It does not add the target portal to the persistent list. #> [CmdletBinding(SupportsShouldProcess=$true)] param( [Parameter(Mandatory=$true)] [Alias("Address")] [string] # the IP or DNS address of the target portal. $targetPortalAddress, [Parameter()] [Alias("Port")] [int] #the TCP port number of the target portal. Typically this is 3260, which is the well-known port number defined for use by iSCSI. $TargetPortalSocket = 3260, [Parameter()] [string] #the name of the initiator via which the SendTargets operation is performed. If not specified then the initiator used is selected by the iSCSI initiator service. $InitiatorName, [Parameter()] [int] #is the physical port number on the initiator via which the SendTargets operation is performed. If not specified then the kernel mode initiator driver chooses the initiator port used. $InitiatorPort ) process { & iscsicli refreshtargetportal $targetPortalAddress $TargetPortalSocket $InitiatorName $InitiatorPort } } #iscsicli ListTargets [ForceUpdate] # #iscsicli ListPersistentTargets # function Get-Target { <# This command will display the list of persistent targets configured for all initiators. #> [CmdletBinding(DefaultParameterSetName='Local')] param( [Parameter( ParameterSetName='Persistent' )] [switch] # specify to get persistent targets $persistent, [Parameter( ParameterSetName='Local' )] [switch] # specify to force refresh of target list during retrieval $force ) process { if( $persistent ) { $data = & iscsicli ListPersistentTargets | Out-String; $data | Write-Verbose; $data -replace "[`r`n]+","=" -split "==" | where { $_ -match ':\\s+' } | foreach { $_ | convertFrom-iSCSIOutput # Write-Verbose "section $_"; # $a = @{}; # $_ -split '=' | Select-String '^\\s+[\\S\\s]+:\\s+' | foreach{ # Write-Verbose "item entry $_"; # $k,$v = $_ -split ':',2 # $a[$k.trim(' ')] = $v.trim(' '); # # #todo - massage to match remove-target inputs # } # new-object psobject -Property $a; } } else { if( $force ) { $data = & iscsicli ListTargets T } else { $data = & iscsicli ListTargets } $data | Select-String '^\\s+\\S+:\\S+$' | foreach{ $_ -replace '^\\s+','' -replace '\\s+$','' }; } } } #iscsicli ListTargetPortals # function Get-TargetPortal { [CmdletBinding()] param() process { $data = & iscsicli ListTargetPortals | Out-String; $data | Write-Verbose; $data -replace "[`r`n]+","=" -split "==" | where { $_ -match ':\\s+' } | foreach { $_ | convertFrom-iSCSIOutput # Write-Debug "section $_"; # $a = @{}; # $_ -split '=' | Select-String '^\\s+[\\S\\s]+:\\s+' | foreach{ # Write-Debug "item entry $_"; # $k,$v = $_ -split ':',2 # $a[$k.trim(' ')] = $v.trim(' '); # } # new-object psobject -Property $a; } } } #iscsicli TargetInfo <TargetName> [Discovery Mechanism] # function Get-TargetInfo { <# This command will return information about the target specified by TargetName. The iSCSI initiator service maintains a separate set of information about every target organized by each mechanism by which it was discovered. This means that each instance of a target can have different information such as target portal groups. Discovery Mechanism is an optional parameter and if not specified then only the list of discovery mechanisms for the target are displayed. If Discovery Mechanism is specified then information about the target instance discovered by that mechanism is displayed. #> [CmdletBinding()] param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [string] $targetName, [Parameter()] [string] $discoveryMechanism ) process { } } #iscsicli LoginTarget <TargetName> <ReportToPNP> # <TargetPortalAddress> <TargetPortalSocket> # <InitiatorInstance> <Port number> <Security Flags> # <Login Flags> <Header Digest> <Data Digest> # <Max Connections> <DefaultTime2Wait> # <DefaultTime2Retain> <Username> <Password> <AuthType> <Key> # <Mapping Count> <Target Lun> <OS Bus> <Os Target> # <OS Lun> ... # #iscsicli PersistentLoginTarget <TargetName> <ReportToPNP> # <TargetPortalAddress> <TargetPortalSocket> # <InitiatorInstance> <Port number> <Security Flags> # <Login Flags> <Header Digest> <Data Digest> # <Max Connections> <DefaultTime2Wait> # <DefaultTime2Retain> <Username> <Password> <AuthType> <Key> # <Mapping Count> <Target Lun> <OS Bus> <Os Target> # <OS Lun> ... # #iscsicli QLoginTarget <TargetName> [CHAP Username] [CHAP Password] # function Connect-Target { <# This command will login to a target #> #iscsicli persistentlogintarget $t T * * * * * * * * * * * [* * *] * 0 [CmdletBinding( SupportsShouldProcess=$true )] param( [Parameter(Mandatory=$true,ValueFromPipeline=$true)] [Alias("Name")] [string] # the name of the target $targetName, [Parameter()] [string] # Username is the string that should be used as the CHAP username when logging into the target. By specifying * for this parameter, the iSCSI initiator service will use the initiator node name as the CHAP username. $username, [Parameter()] [string] # Password is the string that should be used as the target’s CHAP secret when logging into the target. The initiator will use this secret to compute a hash value based on the challenge sent by the target. $password, [Parameter()] [switch] # specify to persist the login information upon reboot $persist ) process { if( $username ) { $data = & iscsicli qlogintarget $targetName $username $password Write-Verbose "Raw iSCSIcli output: $data"; } else { $data = & iscsicli qlogintarget $targetName Write-Verbose "Raw iSCSIcli output: $data"; $username = '*'; $password = '*'; } Write-Verbose "Raw iSCSIcli output: $data"; if( $data -match 'already.+logged' ) { $s = get-session | where { $_.targetname -eq $targetName }; New-Object psobject -Property @{ SessionId=$s.SessionId; ConnectionId=$s.Connection.ConnectionID }; } else { # Session Id is 0xfffffa800f7900a8-0x4000013700000015 # Connection Id is 0xfffffa800f7900a8-0x23 ( $data | Out-String ) -replace '0x','' -replace "[`r`n]+",'=' | convertFrom-iSCSIOutput -field ' is '; } if( $persist ) { & iscsicli persistentlogintarget $targetName T * * * * * * * * * * * $username $password * * 0 | Out-Null } } } #iscsicli LogoutTarget <SessionId> # function Disconnect-Session { <# This command will attempt to logout of a target which was logged in via the session specified by SessionId. The iSCSI initiator service will not logout of a session if any devices exposed by it are currently in use. If the command fails then consult the system eventlog for additional information about the component that is using the device. #> [CmdletBinding( SupportsShouldProcess=$true, ConfirmImpact='high' )] param( [Parameter( Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )] [string] $sessionId, [Parameter()] [switch] # specify to bypass standard PowerShell confirmation processes $force ) process { if( -not( $force -or $pscmdlet.shouldProcess( $sessionId, "Disconnect Session" ) ) ) { return; } $data = & iscsicli logouttarget $sessionId | Out-String; if( $data -notmatch 'success' ) { throw $data; } } } #iscsicli ListInitiators # function Get-Initiators { <# This command will display the list of initiator instance names that are running and operating with the iSCSI initiator service. #> [CmdletBinding()] param() process { & iscsicli listinitiators } } #iscsicli SessionList <Show Session Info> # function Get-Session { <# This command displays the list of active sessions for all initiators. Note that a session that has no connections is not connected to the target and is in a retry state. Microsoft iSCSI Initiator Version 6.1 Build 7601 Total of 2 sessions Session Id : fffffa800f7900a8-400001370000000d Initiator Node Name : iqn.1991-05.com.microsoft:archimedes Target Node Name : (null) Target Name : iqn.2008-08.com.starwindsoftware:127.0.0.1-target1 ISID : 40 00 01 37 00 00 TSID : 27 00 Number Connections : 1 Connections: Connection Id : fffffa800f7900a8-1b Initiator Portal : 0.0.0.0/58847 Target Portal : 192.168.1.108/3260 CID : 01 00 Devices: Device Type : Disk Device Number : 1 Storage Device Type : 7 Partition Number : 0 Friendly Name : ROCKET RAM DISK 1024 M SCSI Disk Device Device Description : Disk drive Reported Mappings : Port 1, Bus 0, Target Id 0, LUN 0 Location : Bus Number 0, Target Id 0, LUN 0 Initiator Name : ROOT\\ISCSIPRT\\0000_0 Target Name : iqn.2008-08.com.starwindsoftware:127.0.0.1-target1 Device Interface Name : \\\\?\\scsi#disk&ven_rocket&prod_ram_disk_1024_m#1&1c121344&0&000000#{53f56307-b6bf-11d0-9 4f2-00a0c91efb8b} Legacy Device Name : \\\\.\\PhysicalDrive1 Device Instance : 0x82c Volume Path Names : E:\\ Session Id : fffffa800f7900a8-400001370000000f Initiator Node Name : iqn.1991-05.com.microsoft:archimedes Target Node Name : (null) Target Name : iqn.2008-08.com.starwindsoftware:127.0.0.1-scratch ISID : 40 00 01 37 00 00 TSID : 2b 00 Number Connections : 1 Connections: Connection Id : fffffa800f7900a8-1d Initiator Portal : 0.0.0.0/59359 Target Portal : 192.168.1.106/3260 CID : 01 00 Devices: Device Type : Disk Device Number : 2 Storage Device Type : 7 Partition Number : 0 Friendly Name : ROCKET RAM DISK 256 MB SCSI Disk Device Device Description : Disk drive Reported Mappings : Port 1, Bus 0, Target Id 1, LUN 0 Location : Bus Number 0, Target Id 1, LUN 0 Initiator Name : ROOT\\ISCSIPRT\\0000_0 Target Name : iqn.2008-08.com.starwindsoftware:127.0.0.1-scratch Device Interface Name : \\\\?\\scsi#disk&ven_rocket&prod_ram_disk_256_mb#1&1c121344&0&000100#{53f56307-b6bf-11d0-9 4f2-00a0c91efb8b} Legacy Device Name : \\\\.\\PhysicalDrive2 Device Instance : 0x8ac #> [CmdletBinding()] param( [Parameter( ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true )] [string] $sessionId = '.*' ) process { Write-Verbose "Session ID filter: $sessionId"; $data = ( & iscsicli sessionlist ) | out-string; $data = $data -replace "[`r`n]+",'=' Write-Verbose "raw sessionlist info : $data"; $sessions = $data -split "Session Id\\s+:\\s+"; $sessions = $sessions | where { $_ -match "Connections:" } | foreach { $session, $data = ( "Session Id : " + $_ ) -split 'Connections:', 2; $connection, $device = $data -split "Devices:", 2; Write-Verbose "session $session"; Write-Verbose "connection $connection"; Write-Verbose "device $device"; $session, $connection, $device = $session, $connection, $device | convertFrom-iSCSIOutput; $session | Add-Member -PassThru -MemberType NoteProperty -Name Connection -Value $connection | Add-Member -MemberType NoteProperty -Name Device -Value $device; $session; } if( -not $sessions ) { Write-Verbose "no sessions found" return; } $sessions | write-verbose; $sessions | where { write-verbose "filtering $($_.SessionId) by $sessionId"; $_.SessionId -match $sessionId } } } function convertFrom-iSCSIOutput { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true)] [string] $data, [Parameter()] [string] $itemDelimiter = '=', [Parameter()] [string] $fieldSeparator = ':' ) process { Write-Debug "convertFrom-iSCSIOutput ..." Write-Debug " Data: $data"; Write-Debug " Item Delimiter: $itemdelimiter"; Write-Debug " Field Separator: $fieldSeparator"; $a = @{}; $data -split $itemDelimiter | where { $_ -match "$fieldSeparator\\s*" } | foreach { function add-ToA( $k, $v ) { $k = $k -replace ' ',''; Write-Debug "item key $k; value $v"; $a[$k] = $v; } Write-Debug "item entry $_"; $k,$v = $_ -split "\\s*$fieldSeparator\\s*",2; if( $k -match ' and ' ) { $k1, $k2 = $k -split ' and '; $v1, $v2 = $v -split '\\s+',2; add-ToA $k1 $v1 add-ToA $k2 $v2 } else { add-ToA $k $v } } new-object psobject -Property $a; } } ########################################################### ## initialization Export-ModuleMember -Function '*';
PowerShellCorpus/PoshCode/Update VM Tools_1.ps1
Update VM Tools_1.ps1
######################################################## # Created by Brian English # for Charlotte County Government # No warranty suggested or implied ######################################################## ######################################################## #connect to VirtualCenter server (i.e. virtual-center-1) if ($args[0] -eq $null) {$hostName = Read-Host "What host do you want to connect to?"} else {$hostName = $args[0]} #connect to selected Virtualcenter or host server Connect-VIServer $hostName ######################################################## #get all vms listed in virtualcenter $vms = get-vm ######################################################## #check power state on each vm #if 'On' update tools Foreach ($i in $vms) { #if virtualcenter is virtualized skip it # a system restart would stop this script if ((get-vm -name $i).Name -eq $hostname) {"Skipping " + $hostname} #if primary DC or DNS is virtualized skip it too #elseif ((get-vm -name $i).Name -eq "DNS/DC/DHCP") #{"Skipping DNS/DC/DHCP server name"} else { if ((get-vm -name $i).PowerState -eq "PoweredOn") { $i Get-Date -format "hh:mm:ss" update-tools -guest (get-vmguest -vm (get-vm -name $i)) Get-Date -format "hh:mm:ss" }#if #}#if }#foreach
PowerShellCorpus/PoshCode/Resizer of pictures_2.ps1
Resizer of pictures_2.ps1
[reflection.assembly]::LoadWithPartialName("System.Drawing") $SizeLimit=1280 # required size of picture's long side $logfile="resizelog.txt" # log file for errors $toresize=$args[0] # list of directories to find and resize images. can be empty if ([string]$toresize -eq &#8220;&#8221;) { # if script startup parameter empty, use some default values $toresize=@("n:\\path1", "n:\\path2\\", "s:\\path3") } echo $toresize # visual control #Write-Host -NoNewLine ("Press any key.") # Optional "Press any key" #$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") #Write-Host "" $error.clear() # first part. find and resize jpgs Get-ChildItem -recurse $toresize -include *.jpg | foreach { $OldBitmap = new-object System.Drawing.Bitmap $_.FullName # open found jpg if ($error.count -ne 0) { # error handling $error | out-file $logfile -append -encoding default $error[($error.count-1)].TargetObject | out-file $logfile -append -encoding default echo $_>>$logfile $error.clear() } $LongSide=$OldBitmap.Width # locating long side of picture if ($OldBitmap.Width -lt $OldBitmap.Height) { $LongSide=$OldBitmap.Height } if ($LongSide -gt $SizeLimit) { # if long side is greater than our limit, process jpg if ($OldBitmap.Width -lt $OldBitmap.Height) { # calculate dimensions of picture resize to $newH=$SizeLimit $newW=[int]($OldBitmap.Width*$SizeLimit/$OldBitmap.Height) } else { $newW=$SizeLimit $newH=[int]($OldBitmap.Height*$newW/$OldBitmap.Width) } $NewBitmap = new-object System.Drawing.Bitmap $newW,$newH # create new bitmap $g=[System.Drawing.Graphics]::FromImage($NewBitmap) $g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic # use high quality resize algorythm $g.DrawImage($OldBitmap, 0, 0, $newW, $newH) # resize our picture $name=$_.DirectoryName+"\\"+$_.name+".new" # generating name for new picture $NewBitmap.Save($name, ([system.drawing.imaging.imageformat]::jpeg)) # save newly created resized jpg $NewBitmap.Dispose() # cleaning up our mess $OldBitmap.Dispose() $n=get-childitem $name if ($n.length -ge $_.length) { # if resized jpg has greater size than original Write-host -NoNewLine "+" # draw "+" $n.delete() # and delete it } else { # if resized jpg is smaller than original if ($n.Exists -and $_.Exists) { $name=$_.FullName $_.Delete() # delete original $n.MoveTo($name) # rename new file to original name (replace old file with new) echo ($Name + " " + $LongSide) # write its name for visual control } } } else { # if long side is smaller than limit, draw dot for visual Write-host -NoNewLine "." $OldBitmap.Dispose() } } #second part. process other than jpgs bitmaps Get-ChildItem -recurse $toresize -include *.bmp, *.tif, *.gif | foreach { $OldBitmap = new-object System.Drawing.Bitmap $_.FullName # open picture if ($error.count -ne 0) { # handle errors if any $error | out-file $logfile -append -encoding default $error[($error.count-1)].TargetObject | out-file $logfile -append -encoding default $error.clear() } $LongSide=$OldBitmap.Width # find picture's long side if ($OldBitmap.Width -lt $OldBitmap.Height) { $LongSide=$OldBitmap.Height } if ($LongSide -gt $SizeLimit) { # if long side is greater than our limit, process picture if ($OldBitmap.Width -lt $OldBitmap.Height) { # calculating new dimensions $newH=$SizeLimit $newW=[int]($OldBitmap.Width*$SizeLimit/$OldBitmap.Height) } else { $newW=$SizeLimit $newH=[int]($OldBitmap.Height*$newW/$OldBitmap.Width) } $NewBitmap = new-object System.Drawing.Bitmap $newW,$newH # create new bitmap $g=[System.Drawing.Graphics]::FromImage($NewBitmap) $g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic $g.DrawImage($OldBitmap, 0, 0, $newW, $newH) # copy resized image to it $name=$_.DirectoryName+"\\"+$_.name.substring(0, $_.name.indexof($_.extension))+".jpg" # generating new name, jpg extension $NewBitmap.Save($name, ([system.drawing.imaging.imageformat]::jpeg)) # save new file $NewBitmap.Dispose() $OldBitmap.Dispose() $n=get-childitem $name if ($n.length -ge $_.length) { # if new file is longer than original, $n.delete() # delete new file Write-host -NoNewLine "+" # and draw "+" for beauty } else { # if new file is shorter than original (as we expect) echo ($Name + " " + $LongSide) # draw its name $_.Delete() # delete oroginal } } else { # if long side is less than our limit, try to recompress it to jpg $name=$_.DirectoryName+"\\"+$_.name.substring(0, $_.name.indexof($_.extension))+".jpg" $OldBitmap.Save($name, ([system.drawing.imaging.imageformat]::jpeg)) $OldBitmap.Dispose() $n=get-childitem $name if ($n.length -ge $_.length) { # if new jpg is greater than original $n.delete() # delete new jpg Write-host -NoNewLine "-" # draw "-" for visual control } else { echo ($Name + " " + $LongSide) # draw new file name $_.Delete() # delete original } } }
PowerShellCorpus/PoshCode/60e46e16-ef39-4620-84a5-bc955433e811.ps1
60e46e16-ef39-4620-84a5-bc955433e811.ps1
[void]([reflection.assembly]::LoadWithPartialName("Microsoft.office.server")) $serverContext = [Microsoft.Office.Server.ServerContext]::Default $upm = [Microsoft.Office.Server.UserProfiles.UserProfileManager]$serverContext @@ $upm.psbase.properties | ? { $_.isvisibleonviewer } | select DisplayName, name, displayorder, managedpropertyname | % { "<SPSWC:ProfilePropertyCheckValue PropertyNames=""$($_.Name)"" runat=""server"" Text=""&lt;tr&gt;&lt;td class=&quot;ms-profilelabel&quot;gt;$($_.DisplayName): &lt;/td&gt;&lt;td width=&quot;65%&quot; valign=&quot;top&quot;&gt;""/><SPSWC:ProfilePropertyValue PropertyName=""$($_.name)"" class=""ms-profilevalue"" runat=""server"" /><SPSWC:ProfilePropertyCheckValue PropertyNames=""$($_.Name)"" runat=""server"" Text=""&lt;/td&gt;&lt;/tr&gt;""/>" } >a.txt; ii a.txt
PowerShellCorpus/PoshCode/Get-WebSite_5.ps1
Get-WebSite_5.ps1
function Get-WebSite { <# .SYNOPSIS Retrieves information about a website. .DESCRIPTION Retrieves information about a website. .PARAMETER Url URL of the website to test access to. .PARAMETER UseDefaultCredentials Use the currently authenticated user's credentials .PARAMETER Proxy Used to connect via a proxy .PARAMETER TimeOut Timeout to connect to site, in milliseconds .PARAMETER Credential Provide alternate credentials .NOTES Name: Get-WebSite Author: Boe Prox DateCreated: 08Feb2011 .EXAMPLE Get-WebSite -url "http://www.bing.com" Description ------------ Returns information about Bing.Com to include StatusCode and type of web server being used to host the site. #> [cmdletbinding( DefaultParameterSetName = 'url', ConfirmImpact = 'low' )] Param( [Parameter( Mandatory = $True, Position = 0, ParameterSetName = '', ValueFromPipeline = $True)] [string][ValidatePattern("^(http|https)\\://*")]$Url, [Parameter( Position = 1, Mandatory = $False, ParameterSetName = 'defaultcred')] [switch]$UseDefaultCredentials, [Parameter( Mandatory = $False, ParameterSetName = '')] [string]$Proxy, [Parameter( Mandatory = $False, ParameterSetName = '')] [Int]$Timeout, [Parameter( Mandatory = $False, ParameterSetName = 'altcred')] [switch]$Credential ) Begin { $psBoundParameters.GetEnumerator() | % { Write-Verbose "Parameter: $_" } #Create the initial WebRequest object using the given url Write-Verbose "Creating the web request object" $webRequest = [net.WebRequest]::Create($url) #Use Proxy address if specified If ($PSBoundParameters.ContainsKey('Proxy')) { #Create Proxy Address for Web Request Write-Verbose "Creating proxy address and adding into Web Request" $webRequest.Proxy = New-Object -TypeName Net.WebProxy($proxy,$True) } #Set timeout If ($PSBoundParameters.ContainsKey('TimeOut')) { #Setting the timeout on web request Write-Verbose "Setting the timeout on web request" $webRequest.Timeout = $timeout } #Determine if using Default Credentials If ($PSBoundParameters.ContainsKey('UseDefaultCredentials')) { #Set to True, otherwise remains False Write-Verbose "Using Default Credentials" $webrequest.UseDefaultCredentials = $True } #Determine if using Alternate Credentials If ($PSBoundParameters.ContainsKey('Credentials')) { #Prompt for alternate credentals Write-Verbose "Prompt for alternate credentials" $wc.Credential = (Get-Credential).GetNetworkCredential() } #Set TimeStamp prior to attempting connection $then = get-date } Process { Try { #Make connection to gather response from site $response = $webRequest.GetResponse() #If successful, get the date for comparison $now = get-date #Generate report Write-Verbose "Generating report from website connection and response" $report = @{ URL = $url StatusCode = $response.Statuscode -as [int] StatusDescription = $response.StatusDescription ResponseTime = "$(($now - $then).totalseconds)" WebServer = $response.Server Size = $response.contentlength } } Catch { #Get timestamp of failed attempt $now = get-date #Put the current error into a variable for later use $errorstring = "$($error[0])" #Generate report $report = @{ URL = $url StatusCode = ([regex]::Match($errorstring,"\\b\\d{3}\\b")).value StatusDescription = (($errorstring.split('\\)')[2]).split('.\\')[0]).Trim() ResponseTime = "$(($now - $then).totalseconds)" WebServer = $response.Server Size = $response.contentlength } } } End { #Display Report New-Object PSObject -property $report } }
PowerShellCorpus/PoshCode/Bulk Change AD Passwords.ps1
Bulk Change AD Passwords.ps1
#------------------------------------------------------------- # install http://www.quest.com/powershell/activeroles-server.aspx Add-PSSnapin Quest.ActiveRoles.ADManagement # CSV Format : NTAccountName,oldpassword,newpassword $UserList = Import-Csv c:\\temp\\users.csv # | select-object -first 2 $userlist | foreach-object { Write-output ----------------------------------------------- Write-output $_.NTAccountName $ADUser= Get-QADUser $_.NTAccountName $ADSIUser = [adsi] $ADUser.Path Write-output $ADSIUser.displayName Write-output "Changing password from $($_.OldPassword) to $($_.NewPassword) ...." $result = $ADSIUser.psbase.invoke("ChangePassword",$_.OldPassword, $_.NewPassword) Write-output "Password change result $result" ## Error and success handling is needed 0 is OK the rest is an error ## http://msdn.microsoft.com/en-us/library/aa772195(v=VS.85).aspx }
PowerShellCorpus/PoshCode/Get-WindowsExperience.ps1
Get-WindowsExperience.ps1
function Get-WindowsExperienceRating { #.Synopsis # Gets the Windows Experience Ratings #.Parameter ComputerName # The name(s) of the computer(s) to get the Windows Experience (WinSat) numbers for. [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]]$ComputerName='localhost' ) process { $winSat = Get-WmiObject -ComputerName $ComputerName Win32_WinSAT if($WinSat.WinSatAssessmentState -ne 1) { Write-Warning "WinSAT data for '$($winSat.__SERVER)' is out of date ($($winSat.WinSatAssessmentState))" } Select-Object -Input $winSat -Property @{name="Computer";expression={$_.__SERVER}}, *Score #, WinSPRLevel } }
PowerShellCorpus/PoshCode/validate an IP address_1.ps1
validate an IP address_1.ps1
# validate given IP address in $ip1 variable $ip1 = "192.168.22.455" ($ip1.split(".") | where-object { $_ -ge 1 -and $_ -le 255 } | Where-Object { $_ -match "\\d{1,3}"} | Measure-Object).count -eq 4
PowerShellCorpus/PoshCode/Findup_20.ps1
Findup_20.ps1
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.Runtime.InteropServices; using Microsoft.Win32; using System.IO; using System.Text.RegularExpressions; namespace Findup { public class FileLengthComparer : IComparer<FileInfo> { public int Compare(FileInfo x, FileInfo y) { return (x.Length.CompareTo(y.Length)); } } class Findup { public static Dictionary<string, List<string>> optionspaths = new Dictionary<string, List<string>> { {"-x", new List<string>()},{"-i",new List<string>()},{"-xf",new List<string>()},{"-if",new List<string>()}, {"-xd",new List<string>()},{"-id",new List<string>()},{"-paths",new List<string>()} }; public static Dictionary<string, Boolean> optionsbools = new Dictionary<string, bool> { { "-recurse", false }, { "-regex", false }, { "-noerr", false }, {"-delete",false} }; public static long numOfDupes = 0; // number of duplicate files found. public static long dupeBytes = 0; // number of bytes in duplicates. public static long bytesrecovered = 0; // Bytes recovered from deleting dupes. public static long deletedfiles = 0; // Number of deleted dupes. public static string delconfirm; public static void Main(string[] args) { Console.WriteLine("Findup.exe v2.0 - By James Gentile - JamesRaymondGentile@gmail.com - 2012."); Console.WriteLine(" "); string optionspathskey = "-paths"; List<FileInfo> files = new List<FileInfo>(); int i = 0; for (i = 0; i < args.Length; i++) { string argitem=args[i].ToLower(); if ((System.String.Compare(argitem, "-help", true) == 0) || (System.String.Compare(argitem, "-h", true) == 0)) { Console.WriteLine("Usage: findup.exe <file/directory #1..#N> [-recurse] [-noerr] [-x/-i/-xd/-id/-xf/-if] <files/directories/regex> [-regex] [-delete]"); Console.WriteLine(" "); Console.WriteLine("Options: -help - displays this help message."); Console.WriteLine(" -recurse - recurses through subdirectories when directories or file specifications (e.g. *.txt) are specified."); Console.WriteLine(" -noerr - discards error messages."); Console.WriteLine(" -delete - delete each duplicate file with confirmation."); Console.WriteLine(" -x - eXcludes if full file path starts with (or RegEx matches if -regex supplied) one of the items following this switch until another switch is used."); Console.WriteLine(" -i - include if full file path starts with (or Regex matches if -regex supplied) one of the items following this switch until another switch is used."); Console.WriteLine(" -xd - eXcludes all directories (using RegEx if -regex supplied) including subdirs following this switch until another switch is used."); Console.WriteLine(" -id - Include only directories (using RegEx if -regex supplied) including subdirs following this switch until another switch is used."); Console.WriteLine(" -xf - eXcludes all files (using RegEx if -regex supplied) following this switch until another switch is used."); Console.WriteLine(" -if - Include only files (using RegEx if -regex supplied) following this switch until another switch is used."); Console.WriteLine(" -regex - Use Regex notation for exclude (-x) and include (-i) option."); Console.WriteLine(" -paths - not needed unless you want to specify files/dirs after an include/exclude without using another non-exclude/non-include option."); Console.WriteLine(" "); Console.WriteLine("Examples: findup.exe c:\\\\finances -recurse -noerr"); Console.WriteLine(" - Find dupes in c:\\\\finance."); Console.WriteLine(" - recurse all subdirs of c:\\\\finance."); Console.WriteLine(" - suppress error messages."); Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data -recurse -x d:\\\\data\\\\webpics"); Console.WriteLine(" - Find dupes in c:\\\\users\\\\alice\\\\plan.txt, d:\\\\data"); Console.WriteLine(" - recurse subdirs in d:\\\\data."); Console.WriteLine(" - exclude any files in d:\\\\data\\\\webpics and subdirs."); Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\quarter.doc -x \\"(jim)\\" -regex"); Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\quarter.doc"); Console.WriteLine(" - exclude any file with 'jim' in the name as specified by the Regex item \\"(jim)\\""); Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\bobsmithquarter.doc -x \\"[bf]\\" -i \\"(smith)\\" -regex"); Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\bobsmithquarter.doc"); Console.WriteLine(" - Include only files with 'smith' and exclude any file with letters b or f in the name as specified by the Regex items \\"[bf]\\",\\"(smith)\\""); Console.WriteLine("Note: Exclude takes precedence over Include."); Console.WriteLine(" -xd,-id,-xf,-if are useful if for instance you want to apply a RegEx to only file names but not directory names or vice versa."); Console.WriteLine(" if for instance you wanted all files that contained the letter \\"d\\" on your D: drive but didn't want the d:\\\\ to cause all files on the d:\\\\ "); Console.WriteLine(" drive to be included, you would specify:"); Console.WriteLine(" findup.exe d:\\\\ -recurse -noerr -regex -if \\"[d]\\" "); return; } if (optionsbools.ContainsKey(argitem)) { optionsbools[argitem] = true; optionspathskey = "-paths"; continue; } if (optionspaths.ContainsKey(argitem)) { optionspathskey = argitem; continue; } optionspaths[optionspathskey].Add(argitem); } if (optionspaths["-paths"].Count == 0) { WriteErr("No files, file specifications, or directories specified. Try findup.exe -help. Assuming current directory."); optionspaths["-paths"].Add("."); } Console.Write("Getting file info and sorting file list..."); getFiles(optionspaths["-paths"], "*.*", optionsbools["-recurse"], files); if (files.Count < 2) { WriteErr("\\nFindup.exe needs at least 2 files to compare. Try findup.exe -help"); return; } files.Sort(new FileLengthComparer()); Console.WriteLine("Completed!"); Console.Write("Building dictionary of file sizes, SHA512 hashes and full paths..."); var SizeHashName = new Dictionary<long, Dictionary<string,List<string>>>(); for (i = 0; i < (files.Count - 1); i++) { if (files[i].Length != files[i + 1].Length) { continue; } var breakout = false; while (true) { var _SHA512 = SHA512.Create(); try { using (var fstream = File.OpenRead(files[i].FullName)) { _SHA512.ComputeHash(fstream); } System.Text.Encoding enc = System.Text.Encoding.ASCII; string SHA512string = enc.GetString(_SHA512.Hash); if (!SizeHashName.ContainsKey(files[i].Length)) SizeHashName.Add(files[i].Length, new Dictionary<string,List<string>>()); if (!SizeHashName[files[i].Length].ContainsKey(SHA512string)) SizeHashName[files[i].Length][SHA512string] = new List<string>() {}; SizeHashName[files[i].Length][SHA512string].Add(files[i].FullName); } catch (Exception e) { WriteErr("Hash error: " + e.Message); } if (breakout == true) {break;} i++; if (i == (files.Count - 1)) { breakout = true; continue; } breakout = (files[i].Length != files[i + 1].Length); } } Console.WriteLine("Completed!"); foreach (var SizeGroup in SizeHashName) { foreach (var HashGroup in SizeGroup.Value) { var SGK = (long)SizeGroup.Key; var HGVC = (int)HashGroup.Value.Count; if (HGVC > 1) { Console.WriteLine("{0:N0} Duplicate files. {1:N0} Bytes each. {2:N0} Bytes total : ", HGVC, SGK, SGK*HGVC); foreach (var FileName in HashGroup.Value) { Console.WriteLine(FileName); numOfDupes++; if (optionsbools["-delete"]) if (DeleteDupe(FileName)) { bytesrecovered += SGK; } } dupeBytes += SGK * HGVC; } } } Console.WriteLine("\\n "); Console.WriteLine("Files checked : {0:N0}", files.Count); Console.WriteLine("Duplicate files : {0:N0}", numOfDupes); Console.WriteLine("Duplicate bytes : {0:N0}", dupeBytes); Console.WriteLine("Deleted duplicates : {0:N0}", deletedfiles); Console.WriteLine("Bytes recovered : {0:N0}", bytesrecovered); return; // Exit after displaying statistics. } private static void WriteErr(string Str) { if (!optionsbools["-noerr"]) Console.WriteLine(Str); } private static Boolean DeleteDupe(string FileName) { Console.Write("Delete this file <y/N> <ENTER>?"); delconfirm = Console.ReadLine(); if ((delconfirm[0] == 'Y') || (delconfirm[0] == 'y')) { try { File.Delete(FileName); Console.WriteLine("File Successfully deleted."); deletedfiles++; return true; } catch (Exception e) { Console.WriteLine("File could not be deleted: " + e.Message); } } return false; } private static Boolean CheckAll(string full) { if (!CheckWorker(full, optionspaths["-x"])) return false; if ((optionspaths["-i"].Count > 0) == CheckWorker(full, optionspaths["-i"])) return false; var filePart = Path.GetFileName(full); var dirPart = Path.GetDirectoryName(full); if (!CheckWorker(filePart, optionspaths["-xf"])) return false; if (!CheckWorker(dirPart, optionspaths["-xd"])) return false; if ((optionspaths["-if"].Count > 0) == CheckWorker(filePart, optionspaths["-if"])) return false; if ((optionspaths["-id"].Count > 0) == CheckWorker(dirPart, optionspaths["-id"])) return false; return true; } private static Boolean CheckWorker(string full, List<string> pathsitems) { foreach (var x in pathsitems) { if (optionsbools["-regex"]) { try { Regex rgx = new Regex(x); if (rgx.IsMatch(full)) return false; } catch (Exception e) { WriteErr("Invalid regex used: " + x + " exception: " + e); } } else { if (full.ToLower().StartsWith(x)) { return false; } } } return true; } private static void getFiles(List<string> pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList) { foreach (string d in pathRec) { getFiles(d, searchPattern, recursiveFlag, returnList); } return; } private static void getFiles(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList) { foreach (string d in pathRec) { getFiles(d, searchPattern, recursiveFlag, returnList); } return; } private static void getFiles(string pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList) { string dirPart; string filePart; if (File.Exists(pathRec)) { try { FileInfo addf = (new FileInfo(pathRec)); if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) && CheckAll(addf.FullName)) returnList.Add(addf); } catch (Exception e) { WriteErr("Add file error: " + e.Message); } } else if (Directory.Exists(pathRec)) { try { DirectoryInfo Dir = new DirectoryInfo(pathRec); foreach (FileInfo addf in (Dir.GetFiles(searchPattern))) { if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) && CheckAll(addf.FullName)) returnList.Add(addf); } } catch (Exception e) { WriteErr("Add files from Directory error: " + e.Message); } if (recursiveFlag) { try { getFiles((Directory.GetDirectories(pathRec)), searchPattern, recursiveFlag, returnList); } catch (Exception e) { WriteErr("Add Directory error: " + e.Message); } } } else { try { filePart = Path.GetFileName(pathRec); dirPart = Path.GetDirectoryName(pathRec); } catch (Exception e) { WriteErr("Parse error on: " + pathRec); WriteErr(@"Make sure you don't end a directory with a \\ when using quotes. The console arg parser doesn't accept that."); WriteErr("Exception: " + e.Message); return; } if (filePart.IndexOfAny(new char[] {'?','*'}) >= 0) { if ((dirPart == null) || (dirPart == "")) dirPart = Directory.GetCurrentDirectory(); if (Directory.Exists(dirPart)) { getFiles(dirPart, filePart, recursiveFlag, returnList); return; } } WriteErr("Invalid file path, directory path, file specification, or program option specified: " + pathRec); } } } }
PowerShellCorpus/PoshCode/Note, open Notepad++.ps1
Note, open Notepad++.ps1
# Limited Notepad++ support with the simple call 'Note' So long Notepad! function Note { <# .Synopsis Opens Notepad++ .Description Opens Notepad++ .Parameter File File name(s) to open, accepts wildcards. (absolute or relative path name) .Parameter MultiInstance Launch another Notepad++ instance .Parameter PluginsOff Launch Notepad++ without plugins, good for debugging cause of a crash, Notepad++ or plugins? .Parameter Language Launch Notepad++ by applying indicated language to the file to open. .Parameter SessionOff Launch Notepad++ without any session. (without loading files opened when notepad++ was last in use.) .Parameter TabBarOff Launch Notepad++ without tabbar. .Example Note -Language xml -MultiInstance -TabBarOff -File C:\\Script\\MyScript.ps1 Opens file 'MyScript.ps1' as xml file in a new instance of Notepad++ with no tab bar. .Link http://notepad-plus.sourceforge.net/uk/cmdLine-HOWTO.php .Link http://notepad-plus.sourceforge.net/ .Link http://poshcode.org/notepad++lexer/ .Link http://sourceforge.net/apps/mediawiki/notepad-plus/index.php?title=Command_Line_Switches .Notes Most of this script is courtesy of PoshCode. Added a couple features to handle the lack of a -File parameter as well as creation of a file. #> [CmdletBinding()] Param ( [Parameter(ValueFromPipeline=$true,Position=1)] [Alias("FileName","LitteralPath","Path")] [string[]] $File , [Parameter()] [string]$Language , [Parameter()] [Switch]$MultiInstance , [Parameter()] [Switch]$PluginsOff , [Parameter()] [Switch]$SessionOff , [Parameter()] [Switch]$TabBarOff ) BEGIN { $NPP = "C:\\Program Files (x86)\\Notepad++\\Notepad++.exe" $Param = @( if($Language) {"-l$Language"} if($MultiInstance) {"-multiInst"} if($PluginsOff) {"-noPlugins"} if($SessionOff) {"-nosession"} if($TabBarOff) {"-notabbar"} " " )-join " " } Process { ### # No -File parameter was received, opens Notepad++ anyway ### if($File -eq $null){ Write-Host "hmmm....`nOpening Notepad++" -foregroundcolor "green" Write-Verbose "$NPP $param" [void][Diagnostics.Process]::Start($NPP,$param).WaitForInputIdle(500) }elseif(Test-Path $File){ ForEach($Path in $File){ ForEach($f in Convert-Path (Resolve-Path $Path)){ $parameters = $param + """" + $f + """" Write-Verbose "$NPP $parameters" [void][Diagnostics.Process]::Start($NPP,$parameters).WaitForInputIdle(500) } } ### # A nonexistent -File parameter was received. # Query user to attempt creation or not. ### }elseif(!(Test-Path $File)){ $Title = "File did not exist." $Message = "Would you like to attempt to create?" $Yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes",` "Passes file name to Notepad++ to attempt creation." $No = New-Object System.Management.Automation.Host.ChoiceDescription "&No",` "Does not pass file name to Notepad++. Face it, you misspelled something =(" $Options = [System.Management.Automation.Host.ChoiceDescription[]]($Yes, $No) $Result = $Host.UI.PromptForChoice($Title, $Message, $Options, 0) Switch($Result){ 0{ $Parameters = $Param + $File Write-Verbose "$NPP $Parameters" [void][Diagnostics.Process]::Start($NPP,$Parameters).WaitForInputIdle(500) } 1{ Write-Host "Yes, well..." -foregroundcolor "Green" } } } } } # I just wanted 120 lines =P
PowerShellCorpus/PoshCode/Prevent-Screensaver.ps1
Prevent-Screensaver.ps1
######################################################### # Prevent-Screensaver ######################################################### # This script "presses" a keyboard key every minute # for specified number of minutes which makes # Windows "think" you are at your desktop # so the screensaver does not start and the desktop # does not get locked. ######################################################### # Usage: # & c:\\filepath\\Prevent-Screensaver.ps1 -Minutes 120 # Makes the script press "." for 120 minutes. # Start notepad or another app and put focus there # to see the dots appear and prevent beeping ######################################################## # (c) Dmitry Sotnikov # http://dmitrysotnikov.wordpress.com ######################################################## param($minutes = 60) $myshell = New-Object -com "Wscript.Shell" for ($i = 0; $i -lt $minutes; $i++) { Start-Sleep -Seconds 60 $myshell.sendkeys(".") }
PowerShellCorpus/PoshCode/TabExpansion_12.ps1
TabExpansion_12.ps1
## Tab-Completion ################# ## Please dot souce this script file. ## In first loading, it may take a several minutes, in order to generate ProgIDs and TypeNames list. ## ## What this can do is: ## ## [datetime]::n<tab> ## [datetime]::now.d<tab> ## $a = New-Object "Int32[,]" 2,3; $b = "PowerShell","PowerShell" ## $c = [ref]$a; $d = [ref]$b,$c ## $d[0].V<tab>[0][0].Get<tab> ## $d[1].V<tab>[0,0].tos<tab> ## $function:a<tab> ## $env:a<tab> ## [System.Type].a<tab> ## [datetime].Assembly.a<tab> ## ).a<tab> # shows System.Type properties and methods... ## #native command name expansion ## fsu<tab> ## #command option name expansion (for fsutil ipconfig net powershell only) ## fsutil <tab> ## ipconfig <tab> ## net <tab> ## powershell <tab> ## #TypeNames and Type accelerators expansion ## [Dec<tab> ## [system.Man<tab>.auto<tab>.p<tab> ## New-Object -TypeName IO.Dir<tab> ## New-Object System.win<tab>.for<tab>.bu<tab> ## #ProgIDs expansion ## New-Object -Com shel<tab> ## #Enum option expansion ## Set-ExecutionPolicy <tab> ## Set-ExecutionPolicy All<tab> ## Set-ExcusionPolisy -ex <tab> ## Get-TraceSource Inte<tab> ## iex -Errora <tab> -wa Sil<tab> ## #WmiClasses expansion ## Get-WmiObject -class Win32_<tab> ## gwmi __Instance<tab> ## #Encoding expansion ## [Out-File | Export-CSV | Select-String | Export-Clixml] -enc <tab> ## [Add-Content | Get-Content | Set-Content} -Encoding Big<tab> ## #PSProvider name expansion ## [Get-Location | Get-PSDrive | Get-PSProvider | New-PSDrive | Remove-PSDrive] -PSProvider <tab> ## Get-PSProvider <tab> ## pwd -psp al<tab> ## #PSDrive name expansion ## [Get-PSDrive | New-PSDrive | Remove-PSDrive] [-Name] <tab> ## Get-PSDrive <tab> ## pwd -psd <tab> ## #PSSnapin name expansion ## [Add-PSSnapin | Get-PSSnapin | Remove-PSSnapin ] [-Name] <tab> ## Get-Command -PSSnapin <tab> ## Remove-PSSnapin <tab> ## Get-PSSnapin M<tab> ## #Eventlog name and expansion ## Get-Eventlog -Log <tab> ## Get-Eventlog w<tab> ## #Eventlog's entrytype expansion ## Get-EventLog -EntryType <tab> ## Get-EventLog -EntryType Er<tab> ## Get-EventLog -Ent <tab> ## #Service name expansion ## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-Name] <tab> ## New-Service -DependsOn <tab> ## New-Service -Dep e<tab> ## Get-Service -n <tab> ## Get-Service <tab>,a<tab>,p<tab> ## gsv <tab> ## #Service display name expansion ## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-DisplayName] <tab> ## Get-Service -Dis <tab> ## gsv -Dis <tab>,w<tab>,b<tab> ## #Cmdlet and Topic name expansion (this also support default help function and man alias) ## Get-Help [-Name] about_<tab> ## Get-Help <tab> ## #Category name expansion (this also support default help function and man alias) ## Get-Help -Category c<tab>,<tab> ## #Command name expansion ## Get-Command [-Name] <tab> ## Get-Command -Name <tab> ## gcm a<tab>,<tab> ## #Scope expansion ## [Clear-Variable | Export-Alias | Get-Alias | Get-PSDrive | Get-Variable | Import-Alias ## New-Alias | New-PSDrive | New-Variable | Remove-Variable | Set-Alias | Set-Variable] -Scope <tab> ## Clear-Variable -Scope G<tab> ## Set-Alias -s <tab> ## #Process name expansion ## [Get-Process | Stop-Process] [-Name] <tab> ## Stop-Process -Name <tab> ## Stop-Process -N pow<tab> ## Get-Process <tab> ## ps power<tab> ## #Trace sources expansion ## [Trace-Command | Get-TraceSource | Set-TraceSource] [-Name] <tab>,a<tab>,p<tab> ## #Trace -ListenerOption expansion ## [Set-TraceSource | Trace-Command] -ListenerOption <tab> ## Set-TraceSource -Lis <tab>,n<tab> ## #Trace -Option expansion ## [Set-TraceSource | Trace-Command] -Option <tab> ## Set-TraceSource -op <tab>,con<tab> ## #ItemType expansion ## New-Item -Item <tab> ## ni -ItemType d<tab> ## #ErrorAction and WarningAction option expansion ## CMDLET [-ErrorAction | -WarningAction] <tab> ## CMDLET -Errora s<tab> ## CMDLET -ea con<tab> ## CMDLET -wa <tab> ## #Continuous expansion with comma when parameter can treat multiple option ## # if there are spaces, occur display bug in the line ## # if strings contains '$' or '-', not work ## Get-Command -CommandType <tab>,<tab><tab>,cm<tab> ## pwd -psp <tab>,f<tab>,va<tab> ## Get-EventLog -EntryType <tab>,i<tab>,s<tab> ## #Enum expansion in method call expression ## # this needs one or more spaces after left parenthesis or comma ## $str = "day night" ## $str.Split( " ",<space>rem<tab> ## >>> $str.Split( " ", "RemoveEmptyEntries" ) <Enter> ERROR ## $str.Split( " ", "RemoveEmptyEntries" -as<space><tab> ## >>> $str.Split( " ", "RemoveEmptyEntries" -as [System.StringSplitOptions] ) <Enter> Success ## $type = [System.Type] ## $type.GetMembers(<space>Def<tab> ## [IO.Directory]::GetFiles( "C:\\", "*",<space>All<tab> ## # this can do continuous enum expansion with comma and no spaces ## $type.GetMembers( "IgnoreCase<comma>Dec<tab><comma>In<tab>" ## [IO.Directory]::GetAccessControl( "C:\\",<space>au<tab><comma>ac<tab><comma>G<tab> ## #Better '$_.' expansion when cmdlet output objects or method return objects ## ls |group { $_.Cr<tab>.Tost<tab>"y")} | tee -var foo| ? { $_.G<tab>.c<tab> -gt 5 } | % { md $_.N<tab> ; copy $_.G<tab> $_.N<tab> } ## [IO.DriveInfo]::GetDrives() | ? { $_.A<tab> -gt 1GB } ## $Host.UI.RawUI.GetBufferContents($rect) | % { $str += $_.c<tab> } ## gcm Add-Content |select -exp Par<tab>| select -ExpandProperty Par<tab> | ? { $_.Par<tab>.N<tab> -eq "string" } ## $data = Get-Process ## $data[2,4,5] | % { $_.<tab> ## #when Get-PipeLineObject failed, '$_.' shows methods and properties name of FileInfo and String and Type ## #Property name expansion by -Property parameter ## [ Format-List | Format-Custom | Format-Table | Format-Wide | Compare-Object | ## ConvertTo-Html | Measure-Object | Select-Object | Group-Object | Sort-Object ] [-Property] <tab> ## Select-Object -ExcludeProperty <tab> ## Select-Object -ExpandProperty <tab> ## gcm Get-Acl|select -exp Par<tab> ## ps |group na<tab> ## ls | ft A<tab>,M<tab>,L<tab> ## #Hashtable key expansion in the variable name and '.<tab>' ## Get-Process | Get-Unique | % { $hash += @{$_.ProcessName=$_} } ## $hash.pow<tab>.pro<tab> ## #Parameter expansion for function, filter and script ## man -f<tab> ## 'param([System.StringSplitOptions]$foo,[System.Management.Automation.ActionPreference]$bar,[System.Management.Automation.CommandTypes]$baz) {}' > foobar.ps1 ## .\\foobar.ps1 -<tab> -b<tab> ## #Enum expansion for function, filter and scripts ## # this can do continuous enum expansion with comma and no spaces ## .\\foobar.ps1 -foo rem<tab> -bar <tab><comma>c<tab><comma>sc<tab> -ea silent<tab> -wa con<tab> ## #Enum expansion for assignment expression ## #needs space(s) after '=' and comma ## #strongly-typed with -as operator and space(s) ## $ErrorActionPreference =<space><tab> ## $cmdtypes = New-Object System.Management.Automation.CommandTypes[] 3 ## $cmdtypes =<space><tab><comma><space>func<tab><comma><space>cmd<tab> -as<space><tab> ## #Path expansion with variable and '\\' or '/' ## $PWD\\../../<tab>\\<tab> ## "$env:SystemDrive/pro<tab>/<tab> ## #Operator expansion which starts with '-' ## "Power","Shell" -m<tab> "Power" -r<tab> '(Pow)(er)','$1d$2' ## 1..9 -co<tab> 5 ## #Keyword expansion ## fu<tab> test { p<tab> $foo, $bar ) b<tab> "foo" } pr<tab> $_ } en<tab> "$bar" } } ## #Variable name expansion (only global scope) ## [Clear-Variable | Get-Variable | New-Variable | Remove-Variable | Set-Variable] [-Name] <tab> ## [Cmdlet | Function | Filter | ExternalScript] -ErrorVariable <tab> ## [Cmdlet | Function | Filter | ExternalScript] -OutVariable <tab> ## Tee-Object -Variable <tab> ## gv pro<tab>,<tab> ## Remove-Variable -Name out<tab>,<tab>,ps<tab> ## ... | ... | tee -v <tab> ## #Alias name expansion ## [Get-Alias | New-Alias | Set-Alias] [-Name] <tab> ## Export-Alias -Name <tab> ## Get-Alias i<tab>,e<tab>,a<tab> ## epal -n for<tab> ## #Property name expansion with -groupBy parameter ## [Format-List | Format-Custom | Format-Table | Format-Wide] -groupBy <tab> ## ps | ft -g <tab> ## gcm | Format-Wide -GroupBy Par<tab> ## #Type accelerators expansion with no charactors ## [<tab> ## New-Object -typename <tab> ## New-Object <tab> ## # File glob expansion with '@' ## ls *.txt@<tab> ## ls file.txt, foo1.txt, 'bar``[1``].txt', 'foo bar .txt' # 1 <tab> expanding with comma ## ls * -Filter *.txt # 2 <tab> refactoring ## ls *.txt # 3 <tab> (or 1 <tab> & 1 <shift>+<tab>) return original glob pattern ## This can also use '^'(hat) or '~'(tilde) for Excluding ## ls <hat>*.txt@<tab> ## ls foo.ps1, 'bar``[1``].xml' # 1 <tab> expanding with comma ## ls * -Filter * -Excluding *.txt # 2 <tab> refactoring ## *.txt<tilde>foo*<tilde>bar*@<tab> ## ls file.txt # 1 <tab> expanding with comma ## ls * -Filter *.txt -Excluding foo*, bar* # 2 <tab> refactoring ## # Ported history expansion from V2CTP3 TabExpansion with '#' ( #<pattern> or #<id> ) ## ls * -Filter * -Excluding foo*, bar*<Enter> ## #ls<tab> ## #1<tab> ## # Command buffer stack with ';'(semicolon) ## ls * -Filter * -Excluding foo*, bar*<semicolon><tab> # push command1 ## echo "PowerShell"<semicolon><tab> # push command2 ## get-process<semicolon><tab> # push command3 ## {COMMAND}<Enter> # execute another command ## get-process # Auto pop command3 from stack by LIFO ## This can also hand-operated pop with ';,'(semicolon&comma) or ';:'(semicolon&colon) ## get-process; <semicolon><comma><tab> ## get-process; echo "PowerShell" # pop command2 from stack by LIFO ## # Function name expansion after 'function' or 'filter' keywords ## function cl<tab> ## #Switch syntax option expansion ## switch -w<tab> -f<tab> ## #Better powershell.exe option expansion with '-' ## powershell -no<tab> -<tab> -en<tab> ## #A part of PowerShell attributes expansion ( CmdletBinding, Parameter, Alias, Validate*, Allow* ) ## [par<tab> ## [cmd<tab> ## #Member expansion for CmdletBinding and Parameter attributes ## [Parameter(man<tab>,<tab>1,val<tab>$true)] ## [CmdletBinding( <tab>"foo", su<tab>$true)] ## #Several current date/time formats with Ctrl+D ## <Ctrl+D><tab><tab><tab><tab><tab>... ## #Hand-operated pop from command buffer with Ctrl+P (this is also available with ';:' or ';,') ## <command>;<tab> # push command ## <Ctrl+D><tab> # pop ## #Paste clipboard with Ctrl+V ## <Ctrl+V><tab> ## # Cut current line with Ctrl+X ## <command><Ctrl+X><tab> ## # Cut words with a charactor after Ctrl+X until the charactor ## 1: PS > dir -Filter *.txt<Ctrl+X>-<tab> # Cut words until '-' ## 2: PS > dir - ## 3: PS > dir -<Ctrl+V><tab> # Paste words that were copyed now ## # Cut last word in current line with Ctrl+Z ## 1: PS > Get-ChildItem *.txt<Ctrl+Z><tab> # Cut last word in current line ## 2: PS > Get-ChildItem ## 3: PS > Get-ChildItem -Exclude <Ctrl+V><tab> # Paste last word that was copyed now ### Generate ProgIDs list... if ( Test-Path $PSHOME\\ProgIDs.txt ) { $_ProgID = type $PSHOME\\ProgIDs.txt -ReadCount 0 } else { $_HKCR = [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\") $_ProgID = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) ) foreach ( $_subkey in $_HKCR.GetSubKeyNames() ) { foreach ( $_i in [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\$_subkey\\ProgID") ) { if ($_i -ne $null) { $_ProgID.Add($_i.GetValue("")) } } } '$_ProgID was updated...' | Out-Host $_ProgID = $_ProgID|sort -Unique Set-Content -Value $_ProgID -Path $PSHOME\\ProgIDs.txt -Verbose } ### Generate TypeNames list... if ( Test-Path $PSHOME\\TypeNames.txt ) { $_TypeNames = type $PSHOME\\TypeNames.txt -ReadCount 0 } else { $_TypeNames = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) ) foreach ( $_asm in [AppDomain]::CurrentDomain.GetAssemblies() ) { foreach ( $_type in $_asm.GetTypes() ) { $_TypeNames.Add($_type.FullName) } } '$_TypeNames was updated...' | Out-Host $_TypeNames = $_TypeNames | sort -Unique Set-Content -Value $_TypeNames -Path $PSHOME\\TypeNames.txt -Verbose } if ( Test-Path $PSHOME\\TypeNames_System.txt ) { $_TypeNames_System = type $PSHOME\\TypeNames_System.txt -ReadCount 0 } else { $_TypeNames_System = $_TypeNames -like "System.*" -replace '^System\\.' '$_TypeNames_System was updated...' | Out-Host Set-Content -Value $_TypeNames_System -Path $PSHOME\\TypeNames_System.txt -Verbose } ### Generate WMIClasses list... if ( Test-Path $PSHOME\\WMIClasses.txt ) { $_WMIClasses = type $PSHOME\\WMIClasses.txt -ReadCount 0 } else { $_WMIClasses = New-Object ( [System.Collections.Generic.List``1].MakeGenericType([String]) ) foreach ( $_class in gwmi -List ) { $_WMIClasses.Add($_class.Name) } $_WMIClasses = $_WMIClasses | sort -Unique '$_WMIClasses was updated...' | Out-Host Set-Content -Value $_WMIClasses -Path $PSHOME\\WMIClasses.txt -Verbose } [Reflection.Assembly]::LoadWithPartialName( "System.Windows.Forms" ) | Out-Null $global:_cmdstack = New-Object Collections.Stack $global:_snapin = $null $global:_TypeAccelerators = "ADSI", "Array", "Bool", "Byte", "Char", "Decimal", "Double", "float", "hashtable", "int", "Long", "PSObject", "ref", "Regex", "ScriptBlock", "Single", "String", "switch", "Type", "WMI", "WMIClass", "WMISearcher", "xml" iex (@' function prompt { if ($_cmdstack.Count -gt 0) { $line = $global:_cmdstack.Pop() -replace '([[\\]\\(\\)+{}?~%])','{$1}' [System.Windows.Forms.SendKeys]::SendWait($line) } '@ + @" ${function:prompt} } "@) function Write-ClassNames ( $data, $i, $prefix='', $sep='.' ) { $preItem = "" foreach ( $class in $data -like $_opt ) { $Item = $class.Split($sep) if ( $preItem -ne $Item[$i] ) { if ( $i+1 -eq $Item.Count ) { if ( $prefix -eq "[" ) { $suffix = "]" } elseif ( $sep -eq "_" ) { $suffix = "" } else { $suffix = " " } } else { $suffix = "" } $prefix + $_opt.Substring(0, $_opt.LastIndexOf($sep)+1) + $Item[$i] + $suffix $preItem = $Item[$i] } } } function Get-PipeLineObject { $i = -2 $property = $null do { $str = $line.Split("|") $_cmdlet = [regex]::Split($str[$i], '[|;=]')[-1] $_cmdlet = $_cmdlet.Trim().Split()[0] if ( $_cmdlet -eq "?" ) { $_cmdlet = "Where-Object" } $global:_exp = $_cmdlet # now get the info object for it... $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0] } if ( "Select-Object" -eq $_cmdlet ) { if ( $str[$i] -match '\\s+-Exp\\w*[\\s:]+(\\w+)' ) { $property = $Matches[1] + ";" + $property } } $i-- } while ( "Get-Unique", "Select-Object", "Sort-Object", "Tee-Object", "Where-Object" -contains $_cmdlet ) if ( $global:_forgci -eq $null ) { $a = @(ls "Alias:\\")[0] $e = @(ls "Env:\\")[0] $f = @(ls "Function:\\")[0] $h = @(ls "HKCU:\\")[0] $v = @(ls "Variable:\\")[0] $c = @(ls "cert:\\")[0] $global:_forgci = gi $PSHOME\\powershell.exe | Add-Member 'NoteProperty' CommandType $f.CommandType -P | Add-Member 'NoteProperty' Definition $a.Definition -P | Add-Member 'NoteProperty' Description $a.Description -P | Add-Member 'NoteProperty' Key $e.Key -P | Add-Member 'NoteProperty' Location $c.Location -P | Add-Member 'NoteProperty' LocationName $c.LocationName -P | Add-Member 'NoteProperty' Options $a.Options -P | Add-Member 'NoteProperty' ReferencedCommand $a.ReferencedCommand -P | Add-Member 'NoteProperty' ResolvedCommand $a.ResolvedCommand -P | Add-Member 'NoteProperty' ScriptBlock $f.ScriptBlock -P | Add-Member 'NoteProperty' StoreNames $c.StoreNames -P | Add-Member 'NoteProperty' SubKeyCount $h.SubKeyCount -P | Add-Member 'NoteProperty' Value $e.Value -P | Add-Member 'NoteProperty' ValueCount $h.ValueCount -P | Add-Member 'NoteProperty' Visibility $a.Visibility -P | Add-Member 'NoteProperty' Property $h.Property -P | Add-Member 'NoteProperty' ResolvedCommandName $a.ResolvedCommandName -P | Add-Member 'ScriptMethod' Close {} -P | Add-Member 'ScriptMethod' CreateSubKey {} -P | Add-Member 'ScriptMethod' DeleteSubKey {} -P | Add-Member 'ScriptMethod' DeleteSubKeyTree {} -P | Add-Member 'ScriptMethod' DeleteValue {} -P | Add-Member 'ScriptMethod' Flush {} -P | Add-Member 'ScriptMethod' GetSubKeyNames {} -P | Add-Member 'ScriptMethod' GetValue {} -P | Add-Member 'ScriptMethod' GetValueKind {} -P | Add-Member 'ScriptMethod' GetValueNames {} -P | Add-Member 'ScriptMethod' IsValidValue {} -P | Add-Member 'ScriptMethod' OpenSubKey {} -P | Add-Member 'ScriptMethod' SetValue {} -P } if ( $global:_mix -eq $null ) { $f = gi $PSHOME\\powershell.exe $t = [type] $s = "" $global:_mix = ` Add-Member -InputObject (New-Object PSObject) 'NoteProperty' Mode $f.Mode -P | Add-Member 'NoteProperty' Assembly $t.Assembly -P | Add-Member 'NoteProperty' AssemblyQualifiedName $t.AssemblyQualifiedName -P | Add-Member 'NoteProperty' Attributes $f.Attributes -P | Add-Member 'NoteProperty' BaseType $t.BaseType -P | Add-Member 'NoteProperty' ContainsGenericParameters $t.ContainsGenericParameters -P | Add-Member 'NoteProperty' CreationTime $f.CreationTime -P | Add-Member 'NoteProperty' CreationTimeUtc $f.CreationTimeUtc -P | Add-Member 'NoteProperty' DeclaringMethod $t.DeclaringMethod -P | Add-Member 'NoteProperty' DeclaringType $t.DeclaringType -P | Add-Member 'NoteProperty' Exists $f.Exists -P | Add-Member 'NoteProperty' Extension $f.Extension -P | Add-Member 'NoteProperty' FullName $f.FullName -P | Add-Member 'NoteProperty' GenericParameterAttributes $t.GenericParameterAttributes -P | Add-Member 'NoteProperty' GenericParameterPosition $t.GenericParameterPosition -P | Add-Member 'NoteProperty' GUID $t.GUID -P | Add-Member 'NoteProperty' HasElementType $t.HasElementType -P | Add-Member 'NoteProperty' IsAbstract $t.IsAbstract -P | Add-Member 'NoteProperty' IsAnsiClass $t.IsAnsiClass -P | Add-Member 'NoteProperty' IsArray $t.IsArray -P | Add-Member 'NoteProperty' IsAutoClass $t.IsAutoClass -P | Add-Member 'NoteProperty' IsAutoLayout $t.IsAutoLayout -P | Add-Member 'NoteProperty' IsByRef $t.IsByRef -P | Add-Member 'NoteProperty' IsClass $t.IsClass -P | Add-Member 'NoteProperty' IsCOMObject $t.IsCOMObject -P | Add-Member 'NoteProperty' IsContextful $t.IsContextful -P | Add-Member 'NoteProperty' IsEnum $t.IsEnum -P | Add-Member 'NoteProperty' IsExplicitLayout $t.IsExplicitLayout -P | Add-Member 'NoteProperty' IsGenericParameter $t.IsGenericParameter -P | Add-Member 'NoteProperty' IsGenericType $t.IsGenericType -P | Add-Member 'NoteProperty' IsGenericTypeDefinition $t.IsGenericTypeDefinition -P | Add-Member 'NoteProperty' IsImport $t.IsImport -P | Add-Member 'NoteProperty' IsInterface $t.IsInterface -P | Add-Member 'NoteProperty' IsLayoutSequential $t.IsLayoutSequential -P | Add-Member 'NoteProperty' IsMarshalByRef $t.IsMarshalByRef -P | Add-Member 'NoteProperty' IsNested $t.IsNested -P | Add-Member 'NoteProperty' IsNestedAssembly $t.IsNestedAssembly -P | Add-Member 'NoteProperty' IsNestedFamANDAssem $t.IsNestedFamANDAssem -P | Add-Member 'NoteProperty' IsNestedFamily $t.IsNestedFamily -P | Add-Member 'NoteProperty' IsNestedFamORAssem $t.IsNestedFamORAssem -P | Add-Member 'NoteProperty' IsNestedPrivate $t.IsNestedPrivate -P | Add-Member 'NoteProperty' IsNestedPublic $t.IsNestedPublic -P | Add-Member 'NoteProperty' IsNotPublic $t.IsNotPublic -P | Add-Member 'NoteProperty' IsPointer $t.IsPointer -P | Add-Member 'NoteProperty' IsPrimitive $t.IsPrimitive -P | Add-Member 'NoteProperty' IsPublic $t.IsPublic -P | Add-Member 'NoteProperty' IsSealed $t.IsSealed -P | Add-Member 'NoteProperty' IsSerializable $t.IsSerializable -P | Add-Member 'NoteProperty' IsSpecialName $t.IsSpecialName -P | Add-Member 'NoteProperty' IsUnicodeClass $t.IsUnicodeClass -P | Add-Member 'NoteProperty' IsValueType $t.IsValueType -P | Add-Member 'NoteProperty' IsVisible $t.IsVisible -P | Add-Member 'NoteProperty' LastAccessTime $f.LastAccessTime -P | Add-Member 'NoteProperty' LastAccessTimeUtc $f.LastAccessTimeUtc -P | Add-Member 'NoteProperty' LastWriteTime $f.LastWriteTime -P | Add-Member 'NoteProperty' LastWriteTimeUtc $f.LastWriteTimeUtc -P | Add-Member 'NoteProperty' MemberType $t.MemberType -P | Add-Member 'NoteProperty' MetadataToken $t.MetadataToken -P | Add-Member 'NoteProperty' Module $t.Module -P | Add-Member 'NoteProperty' Name $t.Name -P | Add-Member 'NoteProperty' Namespace $t.Namespace -P | Add-Member 'NoteProperty' Parent $f.Parent -P | Add-Member 'NoteProperty' ReflectedType $t.ReflectedType -P | Add-Member 'NoteProperty' Root $f.Root -P | Add-Member 'NoteProperty' StructLayoutAttribute $t.StructLayoutAttribute -P | Add-Member 'NoteProperty' TypeHandle $t.TypeHandle -P | Add-Member 'NoteProperty' TypeInitializer $t.TypeInitializer -P | Add-Member 'NoteProperty' UnderlyingSystemType $t.UnderlyingSystemType -P | Add-Member 'NoteProperty' PSChildName $f.PSChildName -P | Add-Member 'NoteProperty' PSDrive $f.PSDrive -P | Add-Member 'NoteProperty' PSIsContainer $f.PSIsContainer -P | Add-Member 'NoteProperty' PSParentPath $f.PSParentPath -P | Add-Member 'NoteProperty' PSPath $f.PSPath -P | Add-Member 'NoteProperty' PSProvider $f.PSProvider -P | Add-Member 'NoteProperty' BaseName $f.BaseName -P | Add-Member 'ScriptMethod' Clone {} -P | Add-Member 'ScriptMethod' CompareTo {} -P | Add-Member 'ScriptMethod' Contains {} -P | Add-Member 'ScriptMethod' CopyTo {} -P | Add-Member 'ScriptMethod' Create {} -P | Add-Member 'ScriptMethod' CreateObjRef {} -P | Add-Member 'ScriptMethod' CreateSubdirectory {} -P | Add-Member 'ScriptMethod' Delete {} -P | Add-Member 'ScriptMethod' EndsWith {} -P | Add-Member 'ScriptMethod' FindInterfaces {} -P | Add-Member 'ScriptMethod' FindMembers {} -P | Add-Member 'ScriptMethod' GetAccessControl {} -P | Add-Member 'ScriptMethod' GetArrayRank {} -P | Add-Member 'ScriptMethod' GetConstructor {} -P | Add-Member 'ScriptMethod' GetConstructors {} -P | Add-Member 'ScriptMethod' GetCustomAttributes {} -P | Add-Member 'ScriptMethod' GetDefaultMembers {} -P | Add-Member 'ScriptMethod' GetDirectories {} -P | Add-Member 'ScriptMethod' GetElementType {} -P | Add-Member 'ScriptMethod' GetEnumerator {} -P | Add-Member 'ScriptMethod' GetEvent {} -P | Add-Member 'ScriptMethod' GetEvents {} -P | Add-Member 'ScriptMethod' GetField {} -P | Add-Member 'ScriptMethod' GetFields {} -P | Add-Member 'ScriptMethod' GetFiles {} -P | Add-Member 'ScriptMethod' GetFileSystemInfos {} -P | Add-Member 'ScriptMethod' GetGenericArguments {} -P | Add-Member 'ScriptMethod' GetGenericParameterConstraints {} -P | Add-Member 'ScriptMethod' GetGenericTypeDefinition {} -P | Add-Member 'ScriptMethod' GetInterface {} -P | Add-Member 'ScriptMethod' GetInterfaceMap {} -P | Add-Member 'ScriptMethod' GetInterfaces {} -P | Add-Member 'ScriptMethod' GetLifetimeService {} -P | Add-Member 'ScriptMethod' GetMember {} -P | Add-Member 'ScriptMethod' GetMembers {} -P | Add-Member 'ScriptMethod' GetMethod {} -P | Add-Member 'ScriptMethod' GetMethods {} -P | Add-Member 'ScriptMethod' GetNestedType {} -P | Add-Member 'ScriptMethod' GetNestedTypes {} -P | Add-Member 'ScriptMethod' GetObjectData {} -P | Add-Member 'ScriptMethod' GetProperties {} -P | Add-Member 'ScriptMethod' GetProperty {} -P | Add-Member 'ScriptMethod' GetTypeCode {} -P | Add-Member 'ScriptMethod' IndexOf {} -P | Add-Member 'ScriptMethod' IndexOfAny {} -P | Add-Member 'ScriptMethod' InitializeLifetimeService {} -P | Add-Member 'ScriptMethod' Insert {} -P | Add-Member 'ScriptMethod' InvokeMember {} -P | Add-Member 'ScriptMethod' IsAssignableFrom {} -P | Add-Member 'ScriptMethod' IsDefined {} -P | Add-Member 'ScriptMethod' IsInstanceOfType {} -P | Add-Member 'ScriptMethod' IsNormalized {} -P | Add-Member 'ScriptMethod' IsSubclassOf {} -P | Add-Member 'ScriptMethod' LastIndexOf {} -P | Add-Member 'ScriptMethod' LastIndexOfAny {} -P | Add-Member 'ScriptMethod' MakeArrayType {} -P | Add-Member 'ScriptMethod' MakeByRefType {} -P | Add-Member 'ScriptMethod' MakeGenericType {} -P | Add-Member 'ScriptMethod' MakePointerType {} -P | Add-Member 'ScriptMethod' MoveTo {} -P | Add-Member 'ScriptMethod' Normalize {} -P | Add-Member 'ScriptMethod' PadLeft {} -P | Add-Member 'ScriptMethod' PadRight {} -P | Add-Member 'ScriptMethod' Refresh {} -P | Add-Member 'ScriptMethod' Remove {} -P | Add-Member 'ScriptMethod' Replace {} -P | Add-Member 'ScriptMethod' SetAccessControl {} -P | Add-Member 'ScriptMethod' Split {} -P | Add-Member 'ScriptMethod' StartsWith {} -P | Add-Member 'ScriptMethod' Substring {} -P | Add-Member 'ScriptMethod' ToCharArray {} -P | Add-Member 'ScriptMethod' ToLower {} -P | Add-Member 'ScriptMethod' ToLowerInvariant {} -P | Add-Member 'ScriptMethod' ToUpper {} -P | Add-Member 'ScriptMethod' ToUpperInvariant {} -P | Add-Member 'ScriptMethod' Trim {} -P | Add-Member 'ScriptMethod' TrimEnd {} -P | Add-Member 'ScriptMethod' TrimStart {} -P | Add-Member 'NoteProperty' Chars $s.Chars -P } 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 = @(iex $str[$i+1])[0] } if ( "Get-Content" -eq $_cmdlet ) { $global:_dummy = (type $PSHOME\\profile.ps1)[0] } if ( "Get-Credential" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Culture" -eq $_cmdlet ) { $global:_dummy = Get-Culture } if ( "Get-Date" -eq $_cmdlet ) { $global:_dummy = Get-Date } if ( "Get-Event" -eq $_cmdlet ) { $global:_dummy = (Get-Event)[0] } if ( "Get-EventLog" -eq $_cmdlet ) { $global:_dummy = Get-EventLog Windows` PowerShell -Newest 1 } if ( "Get-ExecutionPolicy" -eq $_cmdlet ) { $global:_dummy = Get-ExecutionPolicy } if ( "Get-Help" -eq $_cmdlet ) { $global:_dummy = Get-Help Add-Content } if ( "Get-History" -eq $_cmdlet ) { $global:_dummy = Get-History -Count 1 } if ( "Get-Host" -eq $_cmdlet ) { $global:_dummy = Get-Host } if ( "Get-Item" -eq $_cmdlet ) { $global:_dummy = $global:_forgci } if ( "Get-ItemProperty" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Location" -eq $_cmdlet ) { $global:_dummy = Get-Location } if ( "Get-Member" -eq $_cmdlet ) { $global:_dummy = (1|Get-Member)[0] } if ( "Get-Module" -eq $_cmdlet ) { $global:_dummy = (Get-Module)[0] } if ( "Get-PfxCertificate" -eq $_cmdlet ) { $global:_dummy = $null } if ( "Get-Process" -eq $_cmdlet ) { $global:_dummy = ps powershell } if ( "Get-PSBreakpoint" -eq $_cmdlet ) { $global:_dummy = Add-Member -InputObject (New-Object PSObject) 'NoteProperty' Action '' -P | Add-Member 'NoteProperty' Command '' -P | Add-Member 'NoteProperty' Enabled '' -P | Add-Member 'NoteProperty' HitCount '' -P | Add-Member 'NoteProperty' Id '' -P | Add-Member 'NoteProperty' Script '' -P } if ( "Get-PSCallStack" -eq $_cmdlet ) { $global:_dummy = Get-PSCallStack } if ( "Get-PSDrive" -eq $_cmdlet ) { $global:_dummy = Get-PSDrive Function } if ( "Get-PSProvider" -eq $_cmdlet ) { $global:_dummy = Get-PSProvider FileSystem } if ( "Get-PSSnapin" -eq $_cmdlet ) { $global:_dummy = Get-PSSnapin Microsoft.PowerShell.Core } if ( "Get-Service" -eq $_cmdlet ) { $global:_dummy = (Get-Service)[0] } if ( "Get-TraceSource" -eq $_cmdlet ) { $global:_dummy = Get-TraceSource AddMember } if ( "Get-UICulture" -eq $_cmdlet ) { $global:_dummy = Get-UICulture } if ( "Get-Variable" -eq $_cmdlet ) { $global:_dummy = Get-Variable _ } if ( "Get-WmiObject" -eq $_cmdlet ) { $global:_dummy = @(iex $str[$i+1])[0] } if ( "Group-Object" -eq $_cmdlet ) { $global:_dummy = 1 | group } if ( "Measure-Command" -eq $_cmdlet ) { $global:_dummy = Measure-Command {} } if ( "Measure-Object" -eq $_cmdlet ) { $global:_dummy = Measure-Object } if ( "New-PSDrive" -eq $_cmdlet ) { $global:_dummy = Get-PSDrive Alias } if ( "New-TimeSpan" -eq $_cmdlet ) { $global:_dummy = New-TimeSpan } if ( "Resolve-Path" -eq $_cmdlet ) { $global:_dummy = $PWD } if ( "Select-String" -eq $_cmdlet ) { $global:_dummy = " " | Select-String " " } if ( "Set-Date" -eq $_cmdlet ) { $global:_dummy = Get-Date } if ( $property -ne $null) { foreach ( $name in $property.Split(";", "RemoveEmptyEntries" -as [System.StringSplitOptions]) ) { $global:_dummy = @($global:_dummy.$name)[0] } } } function TabExpansion { param($line, $lastWord) & { # Helper function to write out the matching set of members. It depends # on dynamic scoping to get $_base, _$expression and $_pat function Write-Members ($sep='.') { # evaluate the expression to get the object to examine... Invoke-Expression ('$_val=' + $_expression) if ( $_expression -match '^\\$global:_dummy' ) { $temp = $_expression -replace '^\\$global:_dummy(.*)','$1' $_expression = '$_' + $temp } $_method = [Management.Automation.PSMemberTypes] ` 'Method,CodeMethod,ScriptMethod,ParameterizedProperty' if ($sep -eq '.') { $members = ( [Object[]](Get-Member -InputObject $_val.PSextended $_pat) + [Object[]](Get-Member -InputObject $_val.PSadapted $_pat) + [Object[]](Get-Member -InputObject $_val.PSbase $_pat) ) if ( $_val -is [Hashtable] ) { [Microsoft.PowerShell.Commands.MemberDefinition[]]$_keys = $null foreach ( $_name in $_val.Keys ) { $_keys += ` New-Object Microsoft.PowerShell.Commands.MemberDefinition ` [int],$_name,"Property",0 } $members += [Object[]]$_keys | ? { $_.Name -like $_pat } } foreach ($_m in $members | sort membertype,name -Unique) { if ($_m.MemberType -band $_method) { # Return a method... $_base + $_expression + $sep + $_m.name + '(' } else { # Return a property... $_base + $_expression + $sep + $_m.name } } } else { foreach ($_m in Get-Member -Static -InputObject $_val $_pat | Sort-Object membertype,name) { if ($_m.MemberType -band $_method) { # Return a method... $_base + $_expression + $sep + $_m.name + '(' } else { # Return a property... $_base + $_expression + $sep + $_m.name } } } } switch ([int]$line[-1]) { # Ctrl+D several date/time formats 4 { "[DateTime]::Now" [DateTime]::Now [DateTime]::Now.ToString("yyyyMMdd") [DateTime]::Now.ToString("MMddyyyy") [DateTime]::Now.ToString("yyyyMMddHHmmss") [DateTime]::Now.ToString("MMddyyyyHHmmss") 'd f g m o r t u y'.Split(" ") | % { [DateTime]::Now.ToString($_) } break; } # Ctrl+P hand-operated pop from command buffer stack 16 { $_base = $lastword.SubString(0, $lastword.Length-1) $_buf = $global:_cmdstack.Pop() if ( $_buf.Contains("'") ) { $line = ($line.SubString(0, $line.Length-1) + $_buf) -replace '([[\\]\\(\\)+{}?~%])','{$1}' [System.Windows.Forms.SendKeys]::SendWait("{Esc}$line") } else { $_base + $_buf } break; } # Ctrl+R $Host.UI.RawUI. 18 { '$Host.UI.RawUI.' '$Host.UI.RawUI' break; } # Ctrl+V paste clipboard 22 { $_base = $lastword.SubString(0, $lastword.Length-1) $global:_clip = New-Object System.Windows.Forms.TextBox $global:_clip.Multiline = $true $global:_clip.Paste() $line = ($line.SubString(0, $line.Length-1) + $global:_clip.Text) -replace '([[\\]\\(\\)+{}?~%])','{$1}' [System.Windows.Forms.SendKeys]::SendWait("{Esc}$line") break; } # Ctrl+X cut current line 24 { $_clip = new-object System.Windows.Forms.TextBox; $_clip.Multiline = $true; $_clip.Text = $line.SubString(0, $line.Length-1) $_clip.SelectAll() $_clip.Copy() [System.Windows.Forms.SendKeys]::SendWait("{ESC}") break; } # Ctrl+Z cut last word in current line 26 { $line.SubString(0, $line.Length-1) -match '(^(.*\\s)([^\\s]*)$)|(^[^\\s]*$)' | Out-Null $_clip = new-object System.Windows.Forms.TextBox; $_clip.Multiline = $true; $_clip.Text = $Matches[3] $_clip.SelectAll() $_clip.Copy() [System.Windows.Forms.SendKeys]::SendWait("{ESC}") $line = $Matches[2] -replace '([[\\]\\(\\)+{}?~%])','{$1}' [System.Windows.Forms.SendKeys]::SendWait($line) break; } } switch ( [int]$line[-2] ) { # Ctrl+X cut words with a charactor after Ctrl+X until the charactor 24 { $line.SubString(0, $line.Length-2) -match "(^(.*$($line[-1]))([^$($line[-1])]*)`$)|(^[^\\$($line[-1])]*`$)" | Out-Null $_clip = new-object System.Windows.Forms.TextBox; $_clip.Multiline = $true; $_clip.Text = $Matches[3] $_clip.SelectAll() $_clip.Copy() [System.Windows.Forms.SendKeys]::SendWait("{ESC}") $line = $Matches[2] -replace '([[\\]\\(\\)+{}?~%])','{$1}' [System.Windows.Forms.SendKeys]::SendWait($line) break; } } switch -regex ($lastWord) { # Handle property and method expansion at '$_' '(^.*)(\\$_\\.)(\\w*)$' { $_base = $matches[1] $_expression = '$global:_dummy' $_pat = $matches[3] + '*' $global:_dummy = $null Get-PipeLineObject if ( $global:_dummy -eq $null ) { if ( $global:_exp -match '^\\$.*\\(.*$' ) { $type = ( iex $_exp.Split("(")[0] ).OverloadDefinitions[0].Split(" ")[0] -replace '\\[[^\\[\\]]*\\]$' -as [type] if ( $_expression -match '^\\$global:_dummy' ) { $temp = $_expression -replace '^\\$global:_dummy(.*)','$1' $_expression = '$_' + $temp } foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } ) { if ($_m.MemberType -eq "Method") { $_base + $_expression + '.' + $_m.name + '(' } else { $_base + $_expression + '.' + $_m.name } } break; } elseif ( $global:_exp -match '^\\[.*\\:\\:.*\\(.*$' ) { $tname, $mname = $_exp.Split(":(", "RemoveEmptyEntries"-as [System.StringSplitOptions])[0,1] $type = @(iex ($tname + '.GetMember("' + $mname + '")'))[0].ReturnType.FullName -replace '\\[[^\\[\\]]*\\]$' -as [type] if ( $_expression -match '^\\$global:_dummy' ) { $temp = $_expression -replace '^\\$global:_dummy(.*)','$1' $_expression = '$_' + $temp } foreach ( $_m in $type.GetMembers() | sort membertype,name | group name | ? { $_.Name -like $_pat } | % { $_.Group[0] } ) { if ($_m.MemberType -eq "Method") { $_base + $_expression + '.' + $_m.name + '(' } else { $_base + $_expression + '.' + $_m.name } } break; } elseif ( $global:_exp -match '^(\\$\\w+(\\[[0-9,\\.]+\\])*(\\.\\w+(\\[[0-9,\\.]+\\])*)*)$' ) { $global:_dummy = @(iex $Matches[1])[0] } else { $global:_dummy = $global:_mix } } Write-Members break; } # Handle property and method expansion rooted at variables... # e.g. $a.b.<tab> '(^.*)(\\$(\\w|\\.)+)\\.(\\w*)$' { $_base = $matches[1] $_expression = $matches[2] [void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock] $_pat = $matches[4] + '*' if ( $_expression -match '^\\$_\\.' ) { $_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1') } Write-Members break; } # Handle simple property and method expansion on static members... # e.g. [datetime]::n<tab> '(^.*)(\\[(\\w|\\.)+\\])\\:\\:(\\w*)$' { $_base = $matches[1] $_expression = $matches[2] $_pat = $matches[4] + '*' Write-Members '::' break; } # Handle complex property and method expansion on static members # where there are intermediate properties... # e.g. [datetime]::now.d<tab> '(^.*)(\\[(\\w|\\.)+\\]\\:\\:(\\w+\\.)+)(\\w*)$' { $_base = $matches[1] # everything before the expression $_expression = $matches[2].TrimEnd('.') # expression less trailing '.' $_pat = $matches[5] + '*' # the member to look for... Write-Members break; } # Handle variable name expansion... '(^.*\\$)(\\w+)$' { $_prefix = $matches[1] $_varName = $matches[2] foreach ($_v in Get-ChildItem ('variable:' + $_varName + '*')) { $_prefix + $_v.name } break; } # Handle env&function drives variable name expansion... '(^.*\\$)(.*\\:)(\\w+)$' { $_prefix = $matches[1] $_drive = $matches[2] $_varName = $matches[3] if ($_drive -eq "env:" -or $_drive -eq "function:") { foreach ($_v in Get-ChildItem ($_drive + $_varName + '*')) { $_prefix + $_drive + $_v.name } } break; } # Handle array's element property and method expansion # where there are intermediate properties... # e.g. foo[0].n.b<tab> '(^.*)(\\$((\\w+\\.)|(\\w+(\\[(\\w|,)+\\])+\\.))+)(\\w*)$' { $_base = $matches[1] $_expression = $matches[2].TrimEnd('.') $_pat = $Matches[8] + '*' [void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock] if ( $_expression -match '^\\$_\\.' ) { $_expression = $_expression -replace '^\\$_(.*)',('$global:_dummy' + '$1') } Write-Members break; } # Handle property and method expansion rooted at type object... # e.g. [System.Type].a<tab> '(^\\[(\\w|\\.)+\\])\\.(\\w*)$' { if ( $(iex $Matches[1]) -isnot [System.Type] ) { break; } $_expression = $Matches[1] $_pat = $Matches[$matches.Count-1] + '*' Write-Members break; } # Handle complex property and method expansion on type object members # where there are intermediate properties... # e.g. [datetime].Assembly.a<tab> '^(\\[(\\w|\\.)+\\]\\.(\\w+\\.)+)(\\w*)$' { $_expression = $matches[1].TrimEnd('.') # expression less trailing '.' $_pat = $matches[4] + '*' # the member to look for... if ( $(iex $_expression) -eq $null ) { break; } Write-Members break; } # Handle property and method expansion rooted at close parenthes... # e.g. (123).a<tab> '^(.*)\\)((\\w|\\.)*)\\.(\\w*)$' { $_base = $Matches[1] + ")" if ( $matches[3] -eq $null) { $_expression = '[System.Type]' } else { $_expression = '[System.Type]' + $Matches[2] } $_pat = $matches[4] + '*' iex "$_expression | Get-Member $_pat | sort MemberType,Name" | % { if ( $_.MemberType -like "*Method*" -or $_.MemberType -like "*Parameterized*" ) { $parenthes = "(" } if ( $Matches[2] -eq "" ) { $_base + "." + $_.Name + $parenthes } else { $_base + $Matches[2] + "." + $_.Name + $parenthes } } break; } # Handle .NET type name expansion ... # e.g. [Microsoft.PowerShell.Com<tab> '^\\[(\\w+(\\.\\w*)*)$' { $_opt = $matches[1] + '*' if ( $_opt -eq "*" ) { $_TypeAccelerators -like $_opt -replace '^(.*)$', '[$1]' } else { $_TypeAccelerators -like $_opt -replace '^(.*)$', '[$1]' Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1) '[' Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1) '[' } break; } # Handle file/directory name which contains $env: variable # e.g. $env:windir\\<tab> '^\\$(env:)?\\w+([\\\\/][^\\\\/]*)*$' { $path = iex ('"' + $Matches[0] + '"') if ( $Matches[2].Length -gt 1 ) { $parent = Split-Path $path -Parent $leaf = (Split-Path $path -Leaf) + '*' } else { $parent = $path $leaf = '*' } if ( Test-Path $parent ) { $i = $Matches[0].LastIndexOfAny("/\\") $_base = $Matches[0].Substring(0,$i+1) [IO.Directory]::GetFileSystemEntries( $parent, $leaf ) | % { $_base + ($_.Split("\\/")[-1] -replace '([\\$\\s&])','`$1' -replace '([[\\]])', '````$1') } } } # Handle file glob expansion ... # e.g. *.txt~about*@<tab> '^(\\^?([^~]+))(~(.*))*@$' { if ( $Matches[1] -notlike "^*" ) { $include = $Matches[2] -replace '``','`' if ( $Matches[3] ) { $exclude = $Matches[3].Split("~", "RemoveEmptyEntries" -as [System.StringSplitOptions]) -replace '``','`' } } else { $include = "*" $exclude = $Matches[2] -replace '``','`' } $fse = [IO.Directory]::GetFileSystemEntries($PWD) $fse = $fse -replace '.*[\\\\/]([^/\\\\]*)$','$1' % -in ($fse -like $include) { $fse = $_; $exclude | % { $fse = $fse -notlike $_ } } $fse = $fse -replace '^.*\\s.*$', ('"$0"') $fse = $fse -replace '([\\[\\]])', '````$1' -replace '^.*([\\[\\]]).*$', ('"$0"') $fse = $fse -replace '""', '"' $OFS = ", "; "$fse" $OFS = ", "; "* -Filter $include " + $(if($exclude){"-Exclude $exclude"}) $Matches[0].Substring(0, $Matches[0].Length-1) break; } # Handle command buffer stack... '(.*);(.?)$' { $_base = $Matches[1] if ( $Matches[2] -eq ":" -or $Matches[2] -eq "," ) { if ( $_cmdstack.Count -gt 0 ) { $_buf = $global:_cmdstack.Pop() if ( $_buf.Contains("'") ) { $line = ($line.SubString(0, $line.Length-1) + $_buf) -replace '([[\\]\\(\\)+{}?~%])','{$1}' [System.Windows.Forms.SendKeys]::SendWait("{Esc}$line") } else { $_base + $_buf } } else { "" } } elseif ( $Matches[2] -eq "" ) { $global:_cmdstack.Push($line.SubString(0,$line.Length-1)) [System.Windows.Forms.SendKeys]::SendWait("{ESC}") } } # Do completion on parameters... '^-([\\w0-9]*)' { $_pat = $matches[1] + '*' # extract the command name from the string # first split the string into statements and pipeline elements # This doesn't handle strings however. $_cmdlet = [regex]::Split($line, '[|;=]')[-1] # Extract the trailing unclosed block e.g. ls | foreach { cp if ($_cmdlet -match '\\{([^\\{\\}]*)$') { $_cmdlet = $matches[1] } # Extract the longest unclosed parenthetical expression... if ($_cmdlet -match '\\(([^()]*)$') { $_cmdlet = $matches[1] } # take the first space separated token of the remaining string # as the command to look up. Trim any leading or trailing spaces # so you don't get leading empty elements. $_cmdlet = $_cmdlet.Trim().Split()[0] # now get the info object for it... $_cmdlet = @(Get-Command -type 'All' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'All' $_cmdlet.Definition)[0] } if ( $_cmdlet.name -eq "powershell.exe" ) { if ( $global:_PSexeOption ) { $global:_PSexeOption -like "-$_pat" -replace '^(-[^,]+).*$', '$1' | sort } else { ($global:_PSexeOption = powershell.exe -?) -like "-$_pat" -replace '^(-[^,]+).*$', '$1' | sort } break; } if ( $_cmdlet.CommandType -eq "Cmdlet" ) { # expand the parameter sets and emit the matching elements foreach ($_n in $_cmdlet.ParameterSets | Select-Object -expand parameters | Sort-Object -Unique name) { $_n = $_n.name if ($_n -like $_pat) { '-' + $_n } } break; } elseif ( "ExternalScript", "Function", "Filter" -contains $_cmdlet.CommandType ) { if ( $_cmdlet.CommandType -eq "ExternalScript" ) { $_fsr = New-Object IO.StreamReader $_cmdlet.Definition $_def = "Function _Dummy { $($_fsr.ReadToEnd()) }" $_fsr.Close() iex $_def $_cmdlet = "_Dummy" } if ( ((gi "Function:$_cmdlet").Definition -replace '\\n').Split("{")[0] -match 'param\\((.*\\))\\s*[;\\.&a-zA-Z]*\\s*$' ) { ( ( ( $Matches[1].Split('$', "RemoveEmptyEntries" -as [System.StringSplitOptions]) -replace ` '^(\\w+)(.*)','$1' ) -notmatch '^\\s+$' ) -notmatch '^\\s*\\[.*\\]\\s*$' ) -like $_pat | sort | % { '-' + $_ } } break; } elseif ( $line -match 'switch\\s+(-\\w+\\s+)*-(\\w*)$') { $_pat = $Matches[2] + '*' "regex", "wildcard", "exact", "casesensitive", "file" -like $_pat -replace '^(.*)$', '-$1' break; } elseif ( $_cmdlet -eq $null ) { "-and", "-as", "-band", "-bnot", "-bor", "-bxor", "-ccontains", "-ceq", "-cge", "-cgt", "-cle", "-clike", "-clt", "-cmatch", "-cne", "-cnotcontains", "-cnotlike", "-cnotmatch", "-contains", "-creplace", "-csplit", "-eq", "-f", "-ge", "-gt", "-icontains", "-ieq", "-ige", "-igt", "-ile", "-ilike", "-ilt", "-imatch", "-ine", "-inotcontains", "-inotlike", "-inotmatch", "-ireplace", "-is", "-isnot", "-isplit", "-join", "-le", "-like", "-lt", "-match", "-ne", "-not", "-notcontains", "-notlike", "-notmatch", "-or", "-replace", "-split", "-xor" -like "-$_pat" } break; } # Tab complete against history either #<pattern> or #<id> '^#(\\w*)' { $_pattern = $matches[1] if ($_pattern -match '^[0-9]+$') { Get-History -ea SilentlyContinue -Id $_pattern | Foreach { $_.CommandLine } } else { $_pattern = '*' + $_pattern + '*' Get-History | Sort-Object -Descending Id| Foreach { $_.CommandLine } | where { $_ -like $_pattern } } break; } # try to find a matching command... default { $lastex = [regex]::Split($line, '[|;]')[-1] if ( $lastex -match '^\\s*(\\$\\w+(\\[[0-9,]+\\])*(\\.\\w+(\\[[0-9,]+\\])*)*)\\s*=\\s+(("\\w+"\\s*,\\s+)*)"\\w+"\\s*-as\\s+$' ) { if ( $Matches[6] -ne $nul ) { $brackets = "[]" } '['+ $global:_enum + $brackets + ']' break; } if ( $lastex -match '^\\s*(\\$\\w+(\\[[0-9,]+\\])*(\\.\\w+(\\[[0-9,]+\\])*)*)\\s*=\\s+(("\\w+"\\s*,\\s+)*)\\s*(\\w*)$' ) { $_pat = $Matches[7] + '*' $_type = @(iex $Matches[1])[0].GetType() if ( $_type.IsEnum ) { $global:_enum = $_type.FullName [Enum]::GetValues($_type) -like $_pat -replace '^(.*)$','"$1"' break; } } $lastex = [regex]::Split($line, '[|;=]')[-1] if ($lastex -match '[[$].*\\w+\\(.*-as\\s*$') { '['+ $global:_enum + ']' } elseif ( $lastex -match '([[$].*(\\w+))\\((.*)$' ) { $_method = $Matches[1] if ( $Matches[3] -match "(.*)((`"|')(\\w+,)+(\\w*))$" ) { $continuous = $true $_opt = $Matches[5] + '*' $_base = $Matches[2].TrimStart('"') -replace '(.*,)\\w+$','$1' $position = $Matches[1].Split(",").Length } else { $continuous = $false $_opt = ($Matches[3].Split(',')[-1] -replace '^\\s*','') + "*" $position = $Matches[3].Split(",").Length } if ( ($_mdefs = iex ($_method + ".OverloadDefinitions")) -eq $null ) { $tname, $mname = $_method.Split(":", "RemoveEmptyEntries" -as [System.StringSplitOptions]) $_mdefs = iex ($tname + '.GetMember("' + $mname + '") | % { $_.ToString() }') } foreach ( $def in $_mdefs ) { [void] ($def -match '\\((.*)\\)') foreach ( $param in [regex]::Split($Matches[1], ', ')[$position-1] ) { if ($param -eq $null -or $param -eq "") { continue; } $type = $param.split()[0] if ( $type -like '*`[*' -or $type -eq "Params" -or $type -eq "" ) { continue; } $fullname = @($_typenames -like "*$type*") foreach ( $name in $fullname ) { if ( $continuous -eq $true -and ( $name -as [System.Type] ).IsEnum ) { $output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$',($_base + '$1') $output | sort } elseif ( ( $name -as [System.Type] ).IsEnum ) { $global:_enum = $name $output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$','"$1"' $output | sort } } } } if ( $output -ne $null ) { break; } } if ( $line -match '(function|filter)\\s+(\\w*)$') { $_pat = 'function:\\' + $Matches[2] + '*' Get-ChildItem $_pat| % { $_.Name } break; } if ( $line[-1] -eq " " ) { $_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-1] $_cmdlet = @(Get-Command -type 'cmdlet,alias,function' $_cmdlet)[0] while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias,function' $_cmdlet.Definition)[0] } if ( "Set-ExecutionPolicy" -eq $_cmdlet.Name ) { "Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" | sort break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ) { Get-TraceSource | % { $_.Name } | sort -Unique break; } if ( "New-Object" -eq $_cmdlet.Name ) { $_TypeAccelerators break; } if ( $_cmdlet.Noun -like "*WMI*" ) { $_WMIClasses break; } if ( "Get-Process" -eq $_cmdlet.Name ) { Get-Process | % { $_.Name } | sort break; } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name ) { if ( $global:_snapin -ne $null ) { $global:_snapin break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin break; } } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" ) { Get-PSDrive | sort break; } if ( "Get-Eventlog" -eq $_cmdlet.Name ) { Get-EventLog -List | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name -or "help" -eq $_cmdlet.Name -or "man" -eq $_cmdlet.Name ) { Get-Help -Category all | % { $_.Name } | sort -Unique break; } if ( "Get-Service", "Restart-Service", "Resume-Service", "Start-Service", "Stop-Service", "Suspend-Service" ` -contains $_cmdlet.Name ) { Get-Service | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name ) { Get-Command -CommandType All | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object", "ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" ` -contains $_cmdlet.Name ) { Get-PipeLineObject $_dummy | Get-Member -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name ) { Get-Variable -Scope Global | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name ) { Get-Alias | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( $line[-1] -eq " " ) { $_cmdlet = [regex]::Split($line, '[|;=]')[-1] # Extract the trailing unclosed block e.g. ls | foreach { cp if ($_cmdlet -match '\\{([^\\{\\}]*)$') { $_cmdlet = $matches[1] } if ($_cmdlet -match '\\(([^()]*)$') { $_cmdlet = $matches[1] } $_cmdlet = $_cmdlet.Trim().Split()[0] $_cmdlet = @(Get-Command -type 'Application' $_cmdlet)[0] if ( $_cmdlet.Name -eq "powershell.exe" ) { "-PSConsoleFile", "-Version", "-NoLogo", "-NoExit", "-Sta", "-NoProfile", "-NonInteractive", "-InputFormat", "-OutputFormat", "-EncodedCommand", "-File", "-Command" | sort break; } if ( $_cmdlet.Name -eq "fsutil.exe" ) { "behavior query", "behavior set", "dirty query", "dirty set", "file findbysid", "file queryallocranges", "file setshortname", "file setvaliddata", "file setzerodata", "file createnew", "fsinfo drives", "fsinfo drivetype", "fsinfo volumeinfo", "fsinfo ntfsinfo", "fsinfo statistics", "hardlink create", "objectid query", "objectid set", "objectid delete", "objectid create", "quota disable", "quota track", "quota enforce", "quota violations", "quota modify", "quota query", "reparsepoint query", "reparsepoint delete", "sparse setflag", "sparse queryflag", "sparse queryrange", "sparse setrange", "usn createjournal", "usn deletejournal", "usn enumdata", "usn queryjournal", "usn readdata", "volume dismount", "volume diskfree" | sort break; } if ( $_cmdlet.Name -eq "net.exe" ) { "ACCOUNTS ", " COMPUTER ", " CONFIG ", " CONTINUE ", " FILE ", " GROUP ", " HELP ", "HELPMSG ", " LOCALGROUP ", " NAME ", " PAUSE ", " PRINT ", " SEND ", " SESSION ", "SHARE ", " START ", " STATISTICS ", " STOP ", " TIME ", " USE ", " USER ", " VIEW" | sort break; } if ( $_cmdlet.Name -eq "ipconfig.exe" ) { "/?", "/all", "/renew", "/release", "/flushdns", "/displaydns", "/registerdns", "/showclassid", "/setclassid" break; } } if ( $line -match '\\w+\\s+(\\w+(\\.|[^\\s\\.])*)$' ) { $_cmdlet = $line.TrimEnd(" ").Split(" |(;={")[-2] $_opt = $Matches[1].Split(" ,")[-1] + '*' $_base = $Matches[1].Substring(0,$Matches[1].Length-$Matches[1].Split(" ,")[-1].length) $_cmdlet = @(Get-Command -type 'cmdlet,alias,function' $_cmdlet)[0] while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias,function' $_cmdlet.Definition)[0] } if ( "Set-ExecutionPolicy" -eq $_cmdlet.Name ) { "Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" -like $_opt | sort break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ) { Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "New-Object" -eq $_cmdlet.Name ) { $_TypeAccelerators -like $_opt Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1) Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1) break; } if ( $_cmdlet.Name -like "*WMI*" ) { Write-ClassNames $_WMIClasses ($_opt.Split("_").Count-1) -sep '_' break; } if ( "Get-Process" -eq $_cmdlet.Name ) { Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name ) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-PSProvider" -eq $_cmdlet.Name ) { Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Eventlog" -eq $_cmdlet.Name ) { Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name -or "help" -eq $_cmdlet.Name -or "man" -eq $_cmdlet.Name ) { Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique break; } if ( "Get-Service", "Restart-Service", "Resume-Service", "Start-Service", "Stop-Service", "Suspend-Service" ` -contains $_cmdlet.Name ) { Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name ) { Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object", "ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" ` -contains $_cmdlet.Name ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name ) { Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name ) { Get-Alias -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( $line -match '(-(\\w+))\\s+([^-]*$)' ) { $_param = $matches[2] + '*' $_opt = $Matches[3].Split(" ,")[-1] + '*' $_base = $Matches[3].Substring(0,$Matches[3].Length-$Matches[3].Split(" ,")[-1].length) $_cmdlet = [regex]::Split($line, '[|;=]')[-1] # Extract the trailing unclosed block e.g. ls | foreach { cp if ($_cmdlet -match '\\{([^\\{\\}]*)$') { $_cmdlet = $matches[1] } # Extract the longest unclosed parenthetical expression... if ($_cmdlet -match '\\(([^()]*)$') { $_cmdlet = $matches[1] } $_cmdlet = $_cmdlet.Trim().Split()[0] $_cmdlet = @(Get-Command -type 'cmdlet,alias,ExternalScript,Filter,Function' $_cmdlet)[0] while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias,ExternalScript,Filter,Function' $_cmdlet.Definition)[0] } if ( $_param.TrimEnd("*") -eq "ea" -or $_param.TrimEnd("*") -eq "wa" ) { "SilentlyContinue", "Stop", "Continue", "Inquire" | ? { $_ -like $_opt } | sort -Unique break; } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide" -contains $_cmdlet.Name ` -and "groupBy" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_.Name } break; } if ( $_param.TrimEnd("*") -eq "ev" -or $_param.TrimEnd("*") -eq "ov" -or "ErrorVariable" -like $_param -or "OutVariable" -like $_param) { Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort break; } if ( "Tee-Object" -eq $_cmdlet.Name -and "Variable" -like $_param ) { Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort break; } if ( "Clear-Variable", "Get-Variable", "New-Variable", "Remove-Variable", "Set-Variable" -contains $_cmdlet.Name ` -and "Name" -like $_param) { Get-Variable -Scope Global -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Export-Alias", "Get-Alias", "New-Alias", "Set-Alias" -contains $_cmdlet.Name ` -and "Name" -like $_param) { Get-Alias -Name $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Out-File","Export-CSV","Select-String","Export-Clixml" -contains $_cmdlet.Name ` -and "Encoding" -like $_param) { "Unicode", "UTF7", "UTF8", "ASCII", "UTF32", "BigEndianUnicode", "Default", "OEM" | ? { $_ -like $_opt } | sort -Unique break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ` -and "Name" -like $_param) { Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "New-Object" -like $_cmdlet.Name ) { if ( "ComObject" -like $_param ) { $_ProgID -like $_opt | % { $_ -replace '\\s','` ' } break; } if ( "TypeName" -like $_param ) { if ( $_opt -eq "*" ) { $_TypeAccelerators -like $_opt } else { $_TypeAccelerators -like $_opt Write-ClassNames $_TypeNames_System ($_opt.Split(".").Count-1) Write-ClassNames $_TypeNames ($_opt.Split(".").Count-1) } break; } } if ( "New-Item" -eq $_cmdlet.Name ) { if ( "ItemType" -like $_param ) { "directory", "file" -like $_opt break; } } if ( "Get-Location", "Get-PSDrive", "Get-PSProvider", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name ` -and "PSProvider" -like $_param ) { Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Location" -eq $_cmdlet.Name -and "PSDrive" -like $_param ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" -like $_param ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name -and "PSSnapin" -like $_param) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + $_ } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" ` -contains $_cmdlet.Name -and "Name" -like $_param ) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + $_ } break; } } if ( "Clear-Variable", "Export-Alias", "Get-Alias", "Get-PSDrive", "Get-Variable", "Import-Alias", "New-Alias", "New-PSDrive", "New-Variable", "Remove-Variable", "Set-Alias", "Set-Variable" ` -contains $_cmdlet.Name -and "Scope" -like $_param ) { "Global", "Local", "Script" -like $_opt break; } if ( "Get-Process", "Stop-Process", "Wait-Process" -contains $_cmdlet.Name -and "Name" -like $_param ) { Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Eventlog" -eq $_cmdlet.Name -and "LogName" -like $_param ) { Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name -or "help" -eq $_cmdlet.Name -or "man" -eq $_cmdlet.Name ) { if ( "Name" -like $_param ) { Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique break; } if ( "Category" -like $_param ) { "Alias", "Cmdlet", "Provider", "General", "FAQ", "Glossary", "HelpFile", "All" -like $_opt | sort | % { $_base + $_ } break; } } if ( "Get-Service", "Restart-Service", "Resume-Service", "Start-Service", "Stop-Service", "Suspend-Service" ` -contains $_cmdlet.Name ) { if ( "Name" -like $_param ) { Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "DisplayName" -like $_param ) { Get-Service -Name $_opt | sort DisplayName | % { $_base + ($_.DisplayName -replace '\\s','` ') } break; } } if ( "New-Service" -eq $_cmdlet.Name -and "dependsOn" -like $_param ) { Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Get-EventLog" -eq $_cmdlet.Name -and "EntryType" -like $_param ) { "Error", "Information", "FailureAudit", "SuccessAudit", "Warning" -like $_opt | sort | % { $_base + $_ } break; } if ( "Get-Command" -eq $_cmdlet.Name -and "Name" -like $_param ) { Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( $_cmdlet.Noun -like "*WMI*" ) { if ( "Class" -like $_param ) { Write-ClassNames $_WMIClasses ($_opt.Split("_").Count-1) -sep '_' break; } } if ( "Format-List", "Format-Custom", "Format-Table", "Format-Wide", "Compare-Object", "ConvertTo-Html", "Measure-Object", "Select-Object", "Group-Object", "Sort-Object" ` -contains $_cmdlet.Name -and "Property" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Select-Object" -eq $_cmdlet.Name ) { if ( "ExcludeProperty" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "ExpandProperty" -like $_param ) { Get-PipeLineObject $_dummy | Get-Member -Name $_opt -MemberType Properties,ParameterizedProperty | sort membertype | % { $_.Name } break; } } if ( "ExternalScript", "Function", "Filter" -contains $_cmdlet.CommandType ) { if ( $_cmdlet.CommandType -eq "ExternalScript" ) { $_fsr = New-Object IO.StreamReader $_cmdlet.Definition $_def = "Function _Dummy { $($_fsr.ReadToEnd()) }" $_fsr.Close() iex $_def $_cmdlet = "_Dummy" } if ( ((gi "Function:$_cmdlet").Definition -replace '\\n').Split("{")[0] -match 'param\\((.*\\))\\s*[;\\.&a-zA-Z]*\\s*$' ) { $Matches[1].Split(',', "RemoveEmptyEntries" -as [System.StringSplitOptions]) -like "*$_param" | % { $_.Split("$ )`r`n", "RemoveEmptyEntries" -as [System.StringSplitOptions])[0] -replace '^\\[(.*)\\]$','$1' -as "System.Type" } | ? { $_.IsEnum } | % { [Enum]::GetNames($_) -like $_opt | sort } | % { $_base + $_ } } break; } select -InputObject $_cmdlet -ExpandProperty ParameterSets | select -ExpandProperty Parameters | ? { $_.Name -like $_param } | ? { $_.ParameterType.IsEnum } | % { [Enum]::GetNames($_.ParameterType) } | ? { $_ -like $_opt } | sort -Unique | % { $_base + $_ } } if ( $line[-1] -match "\\s" ) { break; } if ( $lastWord -ne $null -and $lastWord.IndexOfAny('/\\') -eq -1 ) { $command = $lastWord.Substring( ($lastWord -replace '([^\\|\\(;={]*)$').Length ) $_base = $lastWord.Substring( 0, ($lastWord -replace '([^\\|\\(;={]*)$').Length ) $pattern = $command + "*" "begin {", "break", "catch {", "continue", "data {", "do {", "else {", "elseif (", "end {", "exit", "filter ", "for (", "foreach ", "from", "function ", "if (", "in", "param (", "process {", "return", "switch ", "throw ", "trap ", "until (", "while (" ` -like $pattern | % { $_base + $_ } gcm -Name $pattern -CommandType All | % { $_base + $_.Name } | sort -Unique } } } } }
PowerShellCorpus/PoshCode/Migrate UserFolder_3.ps1
Migrate UserFolder_3.ps1
param( $RootFolder = "\\\\server1\\users", $NewRootFolder = "\\\\server2\\users", $LogFolder = "C:\\Projects\\HomeDirs", $NewSubFolders = @("Documents","Favorites","Desktop","Links","Contacts"), $domain = "domain", [switch]$SetACL ) $UserFolders = gci -Path $RootFolder | ?{$_.PSIsContainer} $UserFolders | foreach-object -Process { #create new homedrive $NewUserFolder = $NewRootFolder + "\\" + $_.name New-Item -Path $NewUserFolder -ItemType "Directory" if ($SetACL){ #set ACL rules for new homedrive $acl = Get-Acl $NewUserFolder $Owner = New-Object System.Security.Principal.NTAccount($domain, $_.name) #$acl.SetOwner($Owner) #not possible with set-acl $rule = New-Object System.Security.AccessControl.FileSystemAccessRule($Owner,"Modify", "ContainerInherit, ObjectInherit", "None", "Allow") $acl.SetAccessRule($rule) Set-Acl $NewUserFolder $acl } #create required subfolders per homedrive $NewSubFolders | foreach{New-Item -Path $($NewUserFolder + "\\" + $_) -type directory} #build robocopy job per homedrive $LogFile = $LogFolder + "\\" + $_.name + ".log" $JobName = $_.name + "_RCsync" $CommandString = "robocopy $($_.FullName) $($NewUserFolder + "\\Documents") /COPYALL /MIR /FFT /Z /Log+:$LogFile" start-job -Scriptblock {invoke-Expression $input} -name $JobName -InputObject $CommandString } #Wait for all jobs Get-Job | Wait-Job #Get all job results Get-Job | Receive-Job
PowerShellCorpus/PoshCode/Invoke-SqlCmd_5.ps1
Invoke-SqlCmd_5.ps1
####################### <# .SYNOPSIS Runs a T-SQL script. .DESCRIPTION Runs a T-SQL script. Invoke-Sqlcmd2 only returns message output, such as the output of PRINT statements when -verbose parameter is specified .INPUTS None You cannot pipe objects to Invoke-Sqlcmd2 .OUTPUTS System.Data.DataTable .EXAMPLE Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -Query "SELECT login_time AS 'StartTime' FROM sysprocesses WHERE spid = 1" This example connects to a named instance of the Database Engine on a computer and runs a basic T-SQL query. StartTime ----------- 2010-08-12 21:21:03.593 .EXAMPLE Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -InputFile "C:\\MyFolder\\tsqlscript.sql" | Out-File -filePath "C:\\MyFolder\\tsqlscript.rpt" This example reads a file containing T-SQL statements, runs the file, and writes the output to another file. .EXAMPLE Invoke-Sqlcmd2 -ServerInstance "MyComputer\\MyInstance" -Query "PRINT 'hello world'" -Verbose This example uses the PowerShell -Verbose parameter to return the message output of the PRINT command. VERBOSE: hello world .NOTES Version History v1.0 - Chad Miller - Initial release v1.1 - Chad Miller - Fixed Issue with connection closing v1.2 - Chad Miller - Added inputfile, SQL auth support, connectiontimeout and output message handling. Updated help documentation v1.3 - Chad Miller - Added As parameter to control DataSet, DataTable or array of DataRow Output type #> function Invoke-Sqlcmd2 { [CmdletBinding()] param( [Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance, [Parameter(Position=1, Mandatory=$false)] [string]$Database, [Parameter(Position=2, Mandatory=$false)] [string]$Query, [Parameter(Position=3, Mandatory=$false)] [string]$Username, [Parameter(Position=4, Mandatory=$false)] [string]$Password, [Parameter(Position=5, Mandatory=$false)] [Int32]$QueryTimeout=600, [Parameter(Position=6, Mandatory=$false)] [Int32]$ConnectionTimeout=15, [Parameter(Position=7, Mandatory=$false)] [ValidateScript({test-path $_})] [string]$InputFile, [Parameter(Position=8, Mandatory=$false)] [ValidateSet("DataSet", "DataTable", "DataRow")] [string]$As="DataRow" ) if ($InputFile) { $filePath = $(resolve-path $InputFile).path $Query = [System.IO.File]::ReadAllText("$filePath") } $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 #Following EventHandler is used for PRINT and RAISERROR T-SQL statements. Executed when -Verbose parameter specified by caller if ($PSBoundParameters.Verbose) { $conn.FireInfoMessageEventOnUserErrors=$true $handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] {Write-Verbose "$($_)"} $conn.add_InfoMessage($handler) } $conn.Open() $cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn) $cmd.CommandTimeout=$QueryTimeout $ds=New-Object system.Data.DataSet $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd) [void]$da.fill($ds) $conn.Close() switch ($As) { 'DataSet' { Write-Output ($ds) } 'DataTable' { Write-Output ($ds.Tables) } 'DataRow' { Write-Output ($ds.Tables[0]) } } } #Invoke-Sqlcmd2
PowerShellCorpus/PoshCode/Export top n SQLPlans.ps1
Export top n SQLPlans.ps1
<# ALZDBA SQLServer_Export_SQLPlans_SMO.ps1 Export top n consuming sqlplans (avg_worker_time=cpu) for a given SQLServer (SQL2005+) Instance #> #requires -version 2 #SQLServer instance $SQLInstance = 'yourserver\\yourinstance' #What number of plans to export per db ? [int]$nTop = 50 trap { # Handle all errors not handled by try\\catch $err = $_.Exception write-verbose "Trapped error: $err.Message" while( $err.InnerException ) { $err = $err.InnerException write-host $err.Message -ForegroundColor Black -BackgroundColor Red }; # End the script. break } Clear-Host # databases of which we do not want sqlplans [string[]]$ExcludedDb = 'tempdb' , 'model' #recipient $AllDbSQLPlan = $null $SampleTime = Get-Date -Format 'yyyyMMdd_HHmm' #Load SQLServer SMO libraries [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null $serverInstance = New-Object ("Microsoft.SqlServer.Management.Smo.Server") $SQLInstance #Oh please put some application info in your connection metadata ! $serverInstance.ConnectionContext.ApplicationName = "DBA_Export_SQLPlans" $serverInstance.ConnectionContext.WorkstationId = $env:COMPUTERNAME # connecting should take less than 5 seconds ! $serverInstance.ConnectionContext.ConnectTimeout = 5 #connect before processing $serverInstance.ConnectionContext.Connect() $Query = '' if ( $serverInstance.VersionMajor -lt 9 ) { write-host $('{0} is of a Non-supported SQLServer version [{1}].' -f $SQLInstance, $serverInstance.VersionString) -ForegroundColor Black -BackgroundColor Red # End the script. break } elseif ( $serverInstance.VersionMajor -lt 10 ) { # SQL2005 $Query = $('WITH XMLNAMESPACES ( ''http://schemas.microsoft.com/sqlserver/2004/07/showplan'' AS PLN ) SELECT TOP ( {0} ) db_name() as Db_Name , Object_schema_name(qp.objectid ) as Schema , Object_name(qp.objectid ) AS [Object_Name] , ISNULL(qs.total_elapsed_time / qs.execution_count, 0) AS [Avg_Elapsed_Time] , qs.execution_count AS [Execution_Count] , qs.total_worker_time AS [Total_Worker_Time] , qs.total_worker_time / qs.execution_count AS [Avg_Worker_Time] , ISNULL(qs.execution_count / DATEDIFF(SS, qs.creation_time, GETDATE()), 0) AS [Calls_per_Second] , qs.max_logical_reads , qs.max_logical_writes , qp.query_plan.exist(''/PLN:ShowPlanXML//PLN:MissingIndex'') as Missing_Indexes , DATEDIFF( SS, qs.cached_time, getdate()) as Time_In_Cache_SS , row_number() over ( order by qs.total_elapsed_time / qs.execution_count DESC ) [Row_Number] , qp.query_plan FROM sys.dm_exec_query_stats AS qs WITH ( NOLOCK ) CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp WHERE qp.dbid = DB_ID() and qs.execution_count > 5 and Object_name(qp.objectid ) not like ''spc_DBA%'' and qs.total_worker_time / qs.execution_count > 50000 /* in microseconds */ ORDER BY Avg_Elapsed_Time DESC OPTION ( RECOMPILE ) ; ' -f $nTop ) } elseif ( $serverInstance.VersionMajor -eq 10 -and $serverInstance.VersionMinor -lt 50 ) { # SQL2008 $Query = $('WITH XMLNAMESPACES ( ''http://schemas.microsoft.com/sqlserver/2004/07/showplan'' AS PLN ) SELECT TOP ( {0} ) db_name() as Db_Name , Object_schema_name(qp.objectid ) as Schema , Object_name(qp.objectid ) AS [Object_Name] , ISNULL(qs.total_elapsed_time / qs.execution_count, 0) AS [Avg_Elapsed_Time] , qs.execution_count AS [Execution_Count] , qs.total_worker_time AS [Total_Worker_Time] , qs.total_worker_time / qs.execution_count AS [Avg_Worker_Time] , ISNULL(qs.execution_count / DATEDIFF(SS, qs.creation_time, GETDATE()), 0) AS [Calls_per_Second] , qs.max_logical_reads , qs.max_logical_writes , qp.query_plan.exist(''/PLN:ShowPlanXML//PLN:MissingIndex'') as Missing_Indexes , DATEDIFF( SS, qs.cached_time, getdate()) as Time_In_Cache_SS , row_number() over ( order by qs.total_elapsed_time / qs.execution_count DESC ) [Row_Number] , qp.query_plan FROM sys.dm_exec_query_stats AS qs WITH ( NOLOCK ) CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp WHERE qp.dbid = DB_ID() and qs.execution_count > 5 and Object_name(qp.objectid ) not like ''spc_DBA%'' and qs.total_worker_time / qs.execution_count > 50000 /* in microseconds */ ORDER BY Avg_Elapsed_Time DESC OPTION ( RECOMPILE ) ; ' -f $nTop ) } else { # SQL2008R2 and up $Query = $('WITH XMLNAMESPACES ( ''http://schemas.microsoft.com/sqlserver/2004/07/showplan'' AS PLN ) SELECT TOP ( {0} ) db_name() as Db_Name , Object_schema_name(p.object_id ) as [Schema] , p.name AS [Object_Name] , qs.total_elapsed_time / qs.execution_count AS [avg_elapsed_time] , qs.total_elapsed_time , qs.execution_count , cast(ISNULL(qs.execution_count * 1.00 / DATEDIFF(SS, qs.cached_time, GETDATE()), 0) as decimal(9,3)) AS [CallsPerSecond] , qs.total_worker_time / qs.execution_count AS [Avg_Worker_Time] , qs.total_worker_time AS [Total_Worker_Time] , qp.query_plan.exist(''/PLN:ShowPlanXML//PLN:MissingIndex'') as Missing_Indexes , qs.cached_time , DATEDIFF( SS, qs.cached_time, getdate()) as Time_In_Cache_SS , row_number() over ( order by qs.total_elapsed_time / qs.execution_count DESC ) [Row_Number] , qp.query_plan FROM sys.procedures AS p WITH ( NOLOCK ) INNER JOIN sys.dm_exec_procedure_stats AS qs WITH ( NOLOCK ) ON p.[object_id] = qs.[object_id] CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) AS qp WHERE qs.database_id = DB_ID() and qs.execution_count > 5 /* only non-ms sprocs */ and p.is_ms_shipped = 0 and p.name not like ''spc_DBA%'' and qs.total_worker_time / qs.execution_count > 50000 /* in microseconds */ ORDER BY avg_elapsed_time DESC OPTION ( RECOMPILE ) ;' -f $nTop ) } $i = 0 foreach($db in $serverInstance.Databases){ if ( $ExcludedDb -notcontains $db.Name ) { $i += 1 $pct = 100 * $i / $serverInstance.Databases.Count Write-progress -Status "Processing DBs - $($db.Name)" -Activity "Collection SQLPlans $SQLInstance" -PercentComplete $pct try { $DbSQLPlans = $db.ExecuteWithResults("$Query").Tables[0] if ( !( $AllDbSQLPlan )) { $AllDbSQLPlan = $DbSQLPlans.clone() } if ( $DbSQLPlans.rows.count -gt 0 ) { $AllDbSQLPlan += $DbSQLPlans } } catch { #just neglect this error Write-Verbose $_.Exception.Message } } else { Write-Verbose "Excluded Db $db.name" } } #Take control: do it yourself ! $serverInstance.ConnectionContext.Disconnect() if ( $AllDbSQLPlan -and $AllDbSQLPlan.Count -gt 0 ) { $TargetPath = "c:\\tempo\\Powershell" if ( !(Test-Path $TargetPath) ) { md $TargetPath | Out-Null } Write-progress -Status "Exporting Consumption Data" -Activity "Exporting SQLPlans $SQLInstance" -PercentComplete 15 $TargetFile = $('{0}-{1}_AllDbSQLPlan.csv' -f $SampleTime, $($SQLInstance -replace '\\\\', '_') ) $AllDbSQLPlan | Select Db_Name, Row_Number, Schema, Object_Name, avg_elapsed_time, total_elapsed_time, execution_count, Calls_Per_Second, Avg_Worker_Time, Total_Worker_Time, Missing_Indexes, cached_time, Time_In_Cache_SS | sort Db_Name, Row_Number | Export-Csv -Path $( Join-Path -Path $TargetPath -ChildPath $TargetFile ) -Delimiter ';' -NoTypeInformation $i = 0 foreach ( $p in $AllDbSQLPlan ) { $i += 1 $pct = 100 * $i / $AllDbSQLPlan.Count Write-progress -Status "Exporting SQLPlan - $($p.Object_Name)" -Activity "Exporting SQLPlans $SQLInstance" -PercentComplete $pct $TargetFileName = $('{0}-{1}-{2}-{3}-{4}-{5}.SQLPlan' -f $SampleTime, $($SQLInstance.Replace('\\','_')) , $p.Db_Name, $p.Row_Number, $p.Schema , $p.Object_Name ) Write-verbose $TargetFileName Out-File -FilePath $( Join-Path -Path $TargetPath -ChildPath $TargetFileName ) -InputObject $p.query_plan } #open explorer at target path Invoke-Item "$TargetPath" } else { Write-Host "No SQLPlans to be exported ! " -ForegroundColor Black -BackgroundColor Yellow }
PowerShellCorpus/PoshCode/Split-Job Version 1.2.ps1
Split-Job Version 1.2.ps1
#requires -version 1.0 ################################################################################ ## Run commands in multiple concurrent pipelines ## by Arnoud Jansveld - www.jansveld.net/powershell ## ## Basic "drop in" usage examples: ## - Functions that accept pipelined input: ## Without Split-Job: ## Get-Content hosts.txt | MyFunction | Export-Csv results.csv ## With Split-Job: ## Get-Content hosts.txt | Split-Job {MyFunction} | Export-Csv results.csv ## - Functions that do not accept pipelined input (use foreach): ## Without Split-Job: ## Get-Content hosts.txt |% { .\\MyScript.ps1 -ComputerName $_ } | Export-Csv results.csv ## With Split-Job: ## Get-Content hosts.txt | Split-Job {%{ .\\MyScript.ps1 -ComputerName $_ }} | Export-Csv results.csv ## ## Example with an imported function: ## function Test-WebServer ($ComputerName) { ## $WebRequest = [System.Net.WebRequest]::Create("http://$ComputerName") ## $WebRequest.GetResponse() ## } ## Get-Content hosts.txt | Split-Job {%{Test-WebServer $_ }} -Function Test-WebServer | Export-Csv results.csv ## ## Version History ## 1.0 First version posted on poshcode.org ## Additional runspace error checking and cleanup ## 0.93 Improve error handling: errors originating in the Scriptblock now ## have more meaningful output ## Show additional info in the progress bar (thanks Stephen Mills) ## Add SnapIn parameter: imports (registered) PowerShell snapins ## Add Function parameter: imports functions ## Add SplitJobRunSpace variable; allows scripts to test if they are ## running in a runspace ## 0.92 Add UseProfile switch: imports the PS profile ## Add Variable parameter: imports variables ## Add Alias parameter: imports aliases ## Restart pipeline if it stops due to an error ## Set the current path in each runspace to that of the calling process ## 0.91 Revert to v 0.8 input syntax for the script block ## Add error handling for empty input queue ## 0.9 Add logic to distinguish between scriptblocks and cmdlets or scripts: ## if a ScriptBlock is specified, a foreach {} wrapper is added ## 0.8 Adds a progress bar ## 0.7 Stop adding runspaces if the queue is already empty ## 0.6 First version. Inspired by Gaurhoth's New-TaskPool script ################################################################################ function Split-Job { param ( $Scriptblock = $(throw 'You must specify a command or script block!'), [int]$MaxPipelines=10, [switch]$UseProfile, [string[]]$Variable, [string[]]$Function = @(), [string[]]$Alias = @(), [string[]]$SnapIn ) function Init ($InputQueue){ # Create the shared thread-safe queue and fill it with the input objects $Queue = [Collections.Queue]::Synchronized([Collections.Queue]@($InputQueue)) $QueueLength = $Queue.Count # Do not create more runspaces than input objects if ($MaxPipelines -gt $QueueLength) {$MaxPipelines = $QueueLength} # Create the script to be run by each runspace $Script = "Set-Location '$PWD'; " $Script += { $SplitJobQueue = $($Input) & { trap {continue} while ($SplitJobQueue.Count) {$SplitJobQueue.Dequeue()} } | }.ToString() + $Scriptblock # Create an array to keep track of the set of pipelines $Pipelines = New-Object System.Collections.ArrayList # Collect the functions and aliases to import $ImportItems = ($Function -replace '^','Function:') + ($Alias -replace '^','Alias:') | Get-Item | select PSPath, Definition $stopwatch = New-Object System.Diagnostics.Stopwatch $stopwatch.Start() } function Add-Pipeline { # This creates a new runspace and starts an asynchronous pipeline with our script. # It will automatically start processing objects from the shared queue. $Runspace = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace($Host) $Runspace.Open() if (!$?) {throw "Could not open runspace!"} $Runspace.SessionStateProxy.SetVariable('SplitJobRunSpace', $True) function CreatePipeline { param ($Data, $Scriptblock) $Pipeline = $Runspace.CreatePipeline($Scriptblock) if ($Data) { $Null = $Pipeline.Input.Write($Data, $True) $Pipeline.Input.Close() } $Null = $Pipeline.Invoke() $Pipeline.Dispose() } # Optionally import profile, variables, functions and aliases from the main runspace if ($UseProfile) { CreatePipeline -Script "`$PROFILE = '$PROFILE'; . `$PROFILE" } if ($Variable) { foreach ($var in (Get-Variable $Variable -Scope 2)) { trap {continue} $Runspace.SessionStateProxy.SetVariable($var.Name, $var.Value) } } if ($ImportItems) { CreatePipeline $ImportItems { foreach ($item in $Input) {New-Item -Path $item.PSPath -Value $item.Definition} } } if ($SnapIn) { CreatePipeline (Get-PSSnapin $Snapin -Registered) {$Input | Add-PSSnapin} } $Pipeline = $Runspace.CreatePipeline($Script) $Null = $Pipeline.Input.Write($Queue) $Pipeline.Input.Close() $Pipeline.InvokeAsync() $Null = $Pipelines.Add($Pipeline) } function Remove-Pipeline ($Pipeline) { # Remove a pipeline and runspace when it is done $Runspace = $Pipeline.RunSpace $Pipeline.Dispose() $Runspace.Close() $Runspace.Dispose() $Pipelines.Remove($Pipeline) } # Main # Initialize the queue from the pipeline . Init $Input # Start the pipelines while ($Pipelines.Count -lt $MaxPipelines -and $Queue.Count) {Add-Pipeline} # Loop through the runspaces and pass their output to the main pipeline while ($Pipelines.Count) { # Show progress if (($stopwatch.ElapsedMilliseconds - $LastUpdate) -gt 1000) { $Completed = $QueueLength - $Queue.Count - $Pipelines.count $LastUpdate = $stopwatch.ElapsedMilliseconds $SecondsRemaining = $(if ($Completed) { (($Queue.Count + $Pipelines.Count)*$LastUpdate/1000/$Completed) } else {-1}) Write-Progress 'Split-Job' ("Queues: $($Pipelines.Count) Total: $($QueueLength) " + "Completed: $Completed Pending: $($Queue.Count)") ` -PercentComplete ([Math]::Max((100 - [Int]($Queue.Count + $Pipelines.Count)/$QueueLength*100),0)) ` -CurrentOperation "Next item: $(trap {continue}; if ($Queue.Count) {$Queue.Peek()})" ` -SecondsRemaining $SecondsRemaining } foreach ($Pipeline in @($Pipelines)) { if ( -not $Pipeline.Output.EndOfPipeline -or -not $Pipeline.Error.EndOfPipeline ) { $Pipeline.Output.NonBlockingRead() $Pipeline.Error.NonBlockingRead() | Out-Default } else { # Pipeline has stopped; if there was an error show info and restart it if ($Pipeline.PipelineStateInfo.State -eq 'Failed') { $Pipeline.PipelineStateInfo.Reason.ErrorRecord | Add-Member NoteProperty writeErrorStream $True -PassThru | Out-Default # Restart the runspace if ($Queue.Count -lt $QueueLength) {Add-Pipeline} } Remove-Pipeline $Pipeline } } Start-Sleep -Milliseconds 100 } }
PowerShellCorpus/PoshCode/Get Twitter RSS Feed_8.ps1
Get Twitter RSS Feed_8.ps1
param ([String] $ScreenName) $client = New-Object System.Net.WebClient $idUrl = "https://api.twitter.com/1/users/show.json?screen_name=$ScreenName" $data = $client.DownloadString($idUrl) $start = 0 $findStr = '"id":' do { $start = $data.IndexOf($findStr, $start + 1) if ($start -gt 0) { $start += $findStr.Length $end = $data.IndexOf(',', $start) $userId = $data.SubString($start, $end-$start) } } while ($start -le $data.Length -and $start -gt 0) $feed = "http://twitter.com/statuses/user_timeline/$userId.rss" $feed
PowerShellCorpus/PoshCode/FTP upload_1.ps1
FTP upload_1.ps1
$File = "D:\\Dev\\somefilename.zip" $ftp = "ftp://username:password@example.com/pub/incoming/somefilename.zip" "ftp url: $ftp" $webclient = New-Object System.Net.WebClient $uri = New-Object System.Uri($ftp) "Uploading $File..." $webclient.UploadFile($uri, $File)
PowerShellCorpus/PoshCode/Get-DNSZoneRecords.ps1
Get-DNSZoneRecords.ps1
#========================================================================== # # NAME: Get-DNSZoneRecords.ps1 # AUTHOR: Saehrig, Steven (trac3r726) # DATE : 10/17/2008 # @@Requires PSHX-Sapien to be loaded for the Read-inputbox cmdlet. # @@Requires Powershell CTP 2 # # COMMENT: # Just comment out the variable and enter the info you need for # computername, dnszonename, and remove the credential portion if not needed. # Otherwise on Execution you will be prompted for credentials and IP. #========================================================================== $cred = Get-Credential $computer = read-inputbox "Enter Server ip" $zonename = Get-WmiObject Win32_computersystem -computerName $computer -credential $cred $dnszonename = $zonename.domain get-wmiobject -namespace "root\\microsoftdns" -class microsoftdns_atype -computername $computer -credential $cred -filter "containername='$dnszonename'" | ft dnsservername, ownername, recorddata, ttl
PowerShellCorpus/PoshCode/Get-OwnerReport.ps1
Get-OwnerReport.ps1
##############################################################################\n##\n## Get-OwnerReport\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\nGets a list of files in the current directory, but with their owner added\nto the resulting objects.\n\n.EXAMPLE\n\nGet-OwnerReport | Format-Table Name,LastWriteTime,Owner\nRetrieves all files in the current directory, and displays the\nName, LastWriteTime, and Owner\n\n#>\n\nSet-StrictMode -Version Latest\n\n$files = Get-ChildItem\nforeach($file in $files)\n{\n $owner = (Get-Acl $file).Owner\n $file | Add-Member NoteProperty Owner $owner\n $file\n}
PowerShellCorpus/PoshCode/Get-ProcessCount_2.ps1
Get-ProcessCount_2.ps1
# Get-ProcessCount uses 2 main variables, server and process name. # Process name is typically the end exe, such as "svchost.exe" # Will accept unnamed args (Get-ProcessCount servername processname) # or named args (Get-ProcessCount -Computer servername -Process processname) Function Get-ProcessCount([string]$process, [string]$computer = "localhost", [switch]$guess) { if($guess) { $clause = [string]::Format("like '%{0}%'",$process) } else { $clause = [string]::Format("='{0}'",$process) } #using string.Format can be very nice to do variable substitution $selectstring = [string]::Format("select * from Win32_Process where name {0}", $clause) $result = get-wmiobject -query $selectstring -ComputerName $computer # I really like the group-object cmdlet for reporting stuff if($result) { $result | Group-Object Name } else { Write "Process $process could not be found" } }
PowerShellCorpus/PoshCode/Inventory.ps1
Inventory.ps1
############################################################################ # # Collect.ps1 # Version: 0.2 # Script to Collect Information from (1)Subnet of PCs, or (2)List of PCs # By: Brad Blaylock # For: St. Bernards RMC # Date: 3-25-2010 # ############################################################################ ############################################################################ # Collect.ps1 Script -- Output to OpenOffice Calc ############################################################################ # # #___________________________________________________________________________ ############################################################################ #__________________CREATE OPEN OFFICE CALC SHEET____________________________ [System.Reflection.Assembly]::LoadWithPartialName('cli_basetypes') [System.Reflection.Assembly]::LoadWithPartialName('cli_cppuhelper') [System.Reflection.Assembly]::LoadWithPartialName('cli_oootypes') [System.Reflection.Assembly]::LoadWithPartialName('cli_ure') [System.Reflection.Assembly]::LoadWithPartialName('cli_uretypes') $localContext = [uno.util.Bootstrap]::bootstrap() $multiComponentFactory = [unoidl.com.sun.star.uno.XComponentContext].getMethod('getServiceManager').invoke($localContext, @()) $desktop = [unoidl.com.sun.star.lang.XMultiComponentFactory].getMethod('createInstanceWithContext').invoke($multiComponentFactory, @('com.sun.star.frame.Desktop', $localContext)) $calc = [unoidl.com.sun.star.frame.XComponentLoader].getMethod('loadComponentFromURL').invoke($desktop, @('private:factory/scalc', '_blank', 0, $null)) $sheets = [unoidl.com.sun.star.sheet.XSpreadsheetDocument].getMethod('getSheets').invoke($calc, @()) $sheet = [unoidl.com.sun.star.container.XIndexAccess].getMethod('getByIndex').invoke($sheets, @(0)) #Cell definitions - Header Row $cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(0,0)) [unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @('IP Address')) $cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(1,0)) [unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @('Hostname')) $cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(2,0)) [unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @('Serial')) $cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(3,0)) [unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @('OS')) $cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(4,0)) [unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @('SvcPk')) $cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(5,0)) [unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @('CPU')) $cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(6,0)) [unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @('RAM')) $cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(7,0)) [unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @('C: Size')) $cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(8,0)) [unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @('C: Free')) $i=1 #Establish variable for Row Imcrementation. #___________________________END OPEN OFFICE DEFINE____________________________ #Establish Ping Object $ping = new-object System.Net.NetworkInformation.Ping; #Encorporate Error handling ri $env:temp\\*.txt -r -v –ea 0 #________________________________________________________________________________ # BEGIN GUI INTERFACE #________________________________________________________________________________ [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") $objForm = New-Object System.Windows.Forms.Form $objForm.Text = "Collect.ps1" $objForm.Size = New-Object System.Drawing.Size(200,300) $objForm.StartPosition = "CenterScreen" $objForm.KeyPreview = $True $objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter") {$subnet=$objTextBoxsub.Text;[int]$start=$objTextBoxstart.Text;$end=$objTextBoxend.Text;$objForm.Close()}}) $objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape") {$objForm.Close()}}) $OKButton = New-Object System.Windows.Forms.Button $OKButton.Location = New-Object System.Drawing.Size(15,220) $OKButton.Size = New-Object System.Drawing.Size(75,23) $OKButton.Text = "OK" $OKButton.Add_Click({$subnet=$objTextBoxsub.Text;[int]$start=$objTextBoxstart.Text;$end=$objTextBoxend.Text;$objForm.Close()}) $objForm.Controls.Add($OKButton) $CancelButton = New-Object System.Windows.Forms.Button $CancelButton.Location = New-Object System.Drawing.Size(105,220) $CancelButton.Size = New-Object System.Drawing.Size(75,23) $CancelButton.Text = "Cancel" $CancelButton.Add_Click({$objForm.Close()}) $objForm.Controls.Add($CancelButton) $objLabelsub = New-Object System.Windows.Forms.Label $objLabelsub.Location = New-Object System.Drawing.Size(10,20) $objLabelsub.Size = New-Object System.Drawing.Size(150,20) $objLabelsub.Text = "Enter Subnet (1st 3 octets):" $objForm.Controls.Add($objLabelsub) $objTextBoxsub = New-Object System.Windows.Forms.TextBox $objTextBoxsub.Location = New-Object System.Drawing.Size(10,40) $objTextBoxsub.Size = New-Object System.Drawing.Size(160,20) $objForm.Controls.Add($objTextBoxsub) $objLabelstart = New-Object System.Windows.Forms.Label $objLabelstart.Location = New-Object System.Drawing.Size(10,70) $objLabelstart.Size = New-Object System.Drawing.Size(150,20) $objLabelstart.Text = "Enter beginning node below:" $objForm.Controls.Add($objLabelstart) $objTextBoxstart = New-Object System.Windows.Forms.TextBox $objTextBoxstart.Location = New-Object System.Drawing.Size(10,90) $objTextBoxstart.Size = New-Object System.Drawing.Size(160,20) $objForm.Controls.Add($objTextBoxstart) $objLabelend = New-Object System.Windows.Forms.Label $objLabelend.Location = New-Object System.Drawing.Size(10,120) $objLabelend.Size = New-Object System.Drawing.Size(150,20) $objLabelend.Text = "Enter ending node below:" $objForm.Controls.Add($objLabelend) $objTextBoxend = New-Object System.Windows.Forms.TextBox $objTextBoxend.Location = New-Object System.Drawing.Size(10,140) $objTextBoxend.Size = New-Object System.Drawing.Size(160,20) $objForm.Controls.Add($objTextBoxend) $objForm.Topmost = $True $objForm.Add_Shown({$objForm.Activate();$objTextBoxsub.Focus()}) [Void] $objForm.ShowDialog() $objForm.Dispose() #________________________________________________________________________ # END GUI INTERFACE #________________________________________________________________________ #Main Script Section while ($start -le $end) { #----------------==Subnet Arguments==---------------------- $strAddress = "$subnet.$start" #*** #*** #_____________________________________________________________ $start++ $stat=$ping.Send($strAddress).status; if($stat -ne "Success") { #If Host is NOT online Exit here with message of unavailability. write-warning "$strAddress is not available <$stat>"; Write-Host Write-Host } else #Collect Desired Data from Live IP Addresses. { #Write IP Address to OpenOffice Calc $cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(0,$i)) [unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @($strAddress)) #Set $strComputer variable to Hostname. $ErrorActionPreference = "SilentlyContinue" $strComputer = [System.Net.Dns]::GetHostByAddress($strAddress).HostName | Foreach-Object {$_ -replace ".ma.dl.cox.net", ""} $ErrorActionPreference = "Continue" #Get Computer Name $ErrorActionPreference = "SilentlyContinue" $colPCName = get-wmiobject -class "Win32_BIOS" -namespace "root\\CIMV2" ` -computername $strComputer $ErrorActionPreference = "Continue" foreach ($objItem in $colPCName) { #Write Computer Name to OpenOffice Calc $cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(1,$i)) [unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @($strComputer)) } #Get System Serial Number from BIOS. $ErrorActionPreference = "SilentlyContinue" $colItems = get-wmiobject -class “Win32_BIOS” -computername $strComputer $ErrorActionPreference = "Continue" foreach ($objItem in $colItems) { $serial = $objItem.SerialNumber $cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(2,$i)) [unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @($serial)) } #Get Operating System and Service Pack. $ErrorActionPreference = "SilentlyContinue" $colItems = get-wmiobject -class “Win32_OperatingSystem” -computername $strComputer $ErrorActionPreference = "Continue" foreach ($objItem in $colItems) { $Opersys = $objItem.Caption $ServicePk = $objItem.CSDVersion #Write Operating System to OpenOffice Calc $cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(3,$i)) [unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @($Opersys)) #Write Service Pack to OpenOffice Calc $cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(4,$i)) [unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @($ServicePk)) } #Get Processor and Speed. $ErrorActionPreference = "SilentlyContinue" $colProcessor = get-wmiobject -class “Win32_Processor” -computername $strComputer $ErrorActionPreference = "Continue" foreach ($objItem in $colProcessor) { $cpu = $objItem.Name #Write CPU to OpenOffice Calc $cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(5,$i)) [unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @($cpu)) } #Get Memory Info. $ErrorActionPreference = "SilentlyContinue" $colItems = get-wmiobject -class “Win32_MemoryArray” -computername $strComputer $ErrorActionPreference = "Continue" foreach ($objItem in $colItems) { if ($objItem.EndingAddress -gt 4096) { $memory = "{0:N0}MB" -f($objItem.EndingAddress / 1024) #Write Memory to OpenOffice Calc $cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(6,$i)) [unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @($memory)) } } #Get Disk Information. $ErrorActionPreference = "SilentlyContinue" $colProcessor = get-wmiobject -class “Win32_LogicalDisk” -computername $strComputer $ErrorActionPreference = "Continue" foreach ($objItem in $colProcessor) { $drivename = $objItem.DeviceID $drivetype = $objItem.DriveType if ($drivename -ne "C:", $drivetype -eq 3) { #If not equal C: - Do Nothing. } if ($objItem.Size -gt 1073741824 -and $drivename -eq "C:") { $drivespace = "{0:N1}GB" -f($objItem.Size / 1073741824) $freespace = "{0:N1}GB" -f($objItem.FreeSpace / 1073741824) #Write C: Size to OpenOffice Calc $cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(7,$i)) [unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @($drivespace)) #Write C: Freespace to OpenOffice Calc $cell = [unoidl.com.sun.star.table.XCellRange].getMethod('getCellByPosition').invoke($sheet.Value, @(8,$i)) [unoidl.com.sun.star.table.XCell].getMethod('setFormula').invoke($cell, @($freespace)) } else { } } #Increment row $i=$i+1 } }
PowerShellCorpus/PoshCode/Set-WinSchedule.ps1
Set-WinSchedule.ps1
# Set-WinSchedule # Written by Tome Tanasovski # http://powertoe.wordpress.com # version 1.0 # Created March 2010 # # Please read through the synopsis->Description to see the list of features that I hope to get # in a final release. If you choose to work on any of the issues by all means, but please contact # me to let me know so that no effort is duplicated # Winform Assemblies [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null function Set-WinSchedule { <# .Synopsis Creates a winform to select a schedule and creates a scheduled task .Description Set-Computer gives a GUI to select a schedule and schedules a task using schtasks This is a beta. There are still a lot of features to implement: Need to have more scheduling options. I expect to have all options available in a recurring outlook calendar item Need to have methods for scheduling with all 3 providers: schtasks, wmi, and at. Currently it only uses schtasks Need to design the return object properties: Should contain the text paths for each provider type Should contain a date/time for start time Need to provide a method to overwrite an existing task if it has the same name and the user confirms that it is ok to overwrite. Should also provide a -force parameter for this option. Need to ensure that files piped from get-item will be scheduled Need a parameter to override ok box at the end .Example Set-Schedule c:\\windows\\notepad.exe .Parameter TaskRun The name of the command to be scheduled .Parameter ScheduleName The name that the scheduled task will be given. .Notes NAME: Set-Schedule AUTHOR: Tome Tanasovski LASTEDIT: 3/11/2010 KEYWORDS: .Link http://powertoe.wordpress.com #> param( [Parameter(Position=1,Mandatory=$true)] [string] $taskrun, [Parameter(Position=2,Mandatory=$true)] [string] $taskname ) $command = "& schtasks.exe /query /tn $taskname" $job = start-job $ExecutionContext.InvokeCommand.NewScriptBlock($command) Wait-Job $job if ($job.ChildJobs[0].output -ne "") { [System.windows.forms.messagebox]::show("A task named $taskname already exists. You must delete this task before you can use the name.") return } $SchedulePickerForm = New-Object System.Windows.Forms.Form $comboTime = New-Object System.Windows.Forms.ComboBox $label4 = New-Object System.Windows.Forms.Label $buttonCancel = New-Object System.Windows.Forms.Button $buttonOK = New-Object System.Windows.Forms.Button $group = New-Object System.Windows.Forms.GroupBox $checkSaturday = New-Object System.Windows.Forms.CheckBox $checkFriday = New-Object System.Windows.Forms.CheckBox $checkThursday = New-Object System.Windows.Forms.CheckBox $checkWednesday = New-Object System.Windows.Forms.CheckBox $checkTuesday = New-Object System.Windows.Forms.CheckBox $checkMonday = New-Object System.Windows.Forms.CheckBox $checkSunday = New-Object System.Windows.Forms.CheckBox $labelDays = New-Object System.Windows.Forms.Label $labelHours = New-Object System.Windows.Forms.Label $boxHourlyDaily = New-Object System.Windows.Forms.TextBox $labelEvery = New-Object System.Windows.Forms.Label $radioHourly = New-Object System.Windows.Forms.RadioButton $radioWeekly = New-Object System.Windows.Forms.RadioButton $radioDaily = New-Object System.Windows.Forms.RadioButton $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState $checkboxes = ($checkMonday,$checkTuesday,$checkWednesday,$checkThursday,$checkFriday,$checkSaturday,$checkSunday) function VisibleInvisibleCheckBoxes { Write-Host $checkboxes $checkboxes |foreach {$_.visible = -not $_.visible} } # Events $handler_radioButtonChanged = { switch ($true) { ($radioHourly.Checked) { $labelHours.Visible = $true $labelDays.Visible = $false $boxHourlyDaily.Visible = $true $checkboxes |foreach {$_.visible = $false} } ($radioDaily.Checked) { $labelHours.Visible = $false $labelDays.Visible = $true $boxHourlyDaily.Visible = $true $checkboxes |foreach {$_.visible = $false} } ($radioWeekly.Checked) { $labelHours.Visible = $false $labelDays.Visible = $false $boxHourlyDaily.Visible = $false $checkboxes |foreach {$_.visible = $true} } } } $buttonCancel_OnClick = { $SchedulePickerForm.Close() return $null } $buttonOK_OnClick = { $doit = $false switch ($true) { ($radioHourly.Checked -or $radioDaily.Checked) { try { $recurrence = [Convert]::ToInt32($boxHourlyDaily.Text) if ($recurrence -gt 0) { try { switch ($true) { ($radiohourly.checked) { if ($recurence -gt 23) { [System.windows.forms.messagebox]::show("Hourly recurrence must be 1-23 hours") $boxHourlyDaily.Focus() } else { & schtasks /create /tn $taskname /tr "$taskrun" /sc hourly /mo $boxHourlyDaily.Text /st $comboTime.Text /f [System.Windows.Forms.Messagebox]::show("Task has been scheduled") $SchedulePickerForm.Close() } } ($radioDaily.checked) { if ($recurence -gt 365) { [System.windows.forms.messagebox]::show("Hourly recurrence must be 1-365 hours") $boxhourlydaily.focus() } else { & schtasks /create /tn $taskname /tr $taskrun /sc daily /mo $boxHourlyDaily.Text /st $comboTime.Text /f $SchedulePickerForm.Close() } } } } catch { [System.windows.forms.messagebox]::show($error[0]) } } else { [System.windows.forms.messagebox]::show("Recurrence must be greater than 0") $boxHourlyDaily.Focus() } } catch { [System.windows.forms.messagebox]::show("You must enter a valid integer recurrence") $boxHourlyDaily.Focus() } } ($radioWeekly.Checked) { $dflag = "" $checkboxes|foreach { if ($_.checked) { $dflag += $_.text.substring(0,3) + "," } } if ($dflag -ne "") { $dflag = $dflag.substring(0,$dflag.length-1) & schtasks /create /tn $taskname /tr $taskrun /sc weekly /st $comboTime.Text /d "$dflag" /f $SchedulePickerForm.Close() } else { [System.windows.forms.messagebox]::show("You must select at least one day for weekly recurrence") } } } } $OnLoadForm_StateCorrection={ #Correct the initial state of the form to prevent the .Net maximized form issue $SchedulePickerForm.WindowState = $InitialFormWindowState } $SchedulePickerForm.Text = "Schedule Picker" $SchedulePickerForm.MaximizeBox = $False $SchedulePickerForm.Name = "SchedulePickerForm" $SchedulePickerForm.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 476 $System_Drawing_Size.Height = 157 $SchedulePickerForm.ClientSize = $System_Drawing_Size $SchedulePickerForm.FormBorderStyle = 5 $comboTime.FormattingEnabled = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 121 $System_Drawing_Size.Height = 21 $comboTime.Size = $System_Drawing_Size $comboTime.DataBindings.DefaultDataSourceUpdateMode = 0 $comboTime.Name = "comboTime" $comboTime.Items.Add("00:00")|Out-Null $comboTime.Items.Add("00:30")|Out-Null $comboTime.Items.Add("01:00")|Out-Null $comboTime.Items.Add("01:30")|Out-Null $comboTime.Items.Add("02:00")|Out-Null $comboTime.Items.Add("02:30")|Out-Null $comboTime.Items.Add("03:00")|Out-Null $comboTime.Items.Add("03:30")|Out-Null $comboTime.Items.Add("04:00")|Out-Null $comboTime.Items.Add("04:30")|Out-Null $comboTime.Items.Add("05:00")|Out-Null $comboTime.Items.Add("05:30")|Out-Null $comboTime.Items.Add("06:00")|Out-Null $comboTime.Items.Add("06:30")|Out-Null $comboTime.Items.Add("07:00")|Out-Null $comboTime.Items.Add("07:30")|Out-Null $comboTime.Items.Add("08:00")|Out-Null $comboTime.Items.Add("08:30")|Out-Null $comboTime.Items.Add("09:00")|Out-Null $comboTime.Items.Add("09:30")|Out-Null $comboTime.Items.Add("10:00")|Out-Null $comboTime.Items.Add("10:30")|Out-Null $comboTime.Items.Add("11:00")|Out-Null $comboTime.Items.Add("11:30")|Out-Null $comboTime.Items.Add("12:00")|Out-Null $comboTime.Items.Add("12:30")|Out-Null $comboTime.Items.Add("13:00")|Out-Null $comboTime.Items.Add("13:30")|Out-Null $comboTime.Items.Add("14:00")|Out-Null $comboTime.Items.Add("14:30")|Out-Null $comboTime.Items.Add("15:00")|Out-Null $comboTime.Items.Add("15:30")|Out-Null $comboTime.Items.Add("16:00")|Out-Null $comboTime.Items.Add("16:30")|Out-Null $comboTime.Items.Add("17:00")|Out-Null $comboTime.Items.Add("17:30")|Out-Null $comboTime.Items.Add("18:00")|Out-Null $comboTime.Items.Add("18:30")|Out-Null $comboTime.Items.Add("19:00")|Out-Null $comboTime.Items.Add("19:30")|Out-Null $comboTime.Items.Add("20:00")|Out-Null $comboTime.Items.Add("20:30")|Out-Null $comboTime.Items.Add("21:00")|Out-Null $comboTime.Items.Add("21:30")|Out-Null $comboTime.Items.Add("22:00")|Out-Null $comboTime.Items.Add("22:30")|Out-Null $comboTime.Items.Add("23:00")|Out-Null $comboTime.Items.Add("23:30")|Out-Null $comboTime.Text = "08:00" $comboTime.DropDownStyle = "DropDownList" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 53 $System_Drawing_Point.Y = 119 $comboTime.Location = $System_Drawing_Point $comboTime.TabIndex = 1 $SchedulePickerForm.Controls.Add($comboTime) $label4.TabIndex = 3 $label4.TextAlign = 16 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 35 $System_Drawing_Size.Height = 23 $label4.Size = $System_Drawing_Size $label4.Text = "Start:" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 12 $System_Drawing_Point.Y = 116 $label4.Location = $System_Drawing_Point $label4.DataBindings.DefaultDataSourceUpdateMode = 0 $label4.Name = "label4" $SchedulePickerForm.Controls.Add($label4) $buttonCancel.TabIndex = 3 $buttonCancel.Name = "buttonCancel" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 75 $System_Drawing_Size.Height = 23 $buttonCancel.Size = $System_Drawing_Size $buttonCancel.UseVisualStyleBackColor = $True $buttonCancel.Text = "Cancel" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 368 $System_Drawing_Point.Y = 119 $buttonCancel.Location = $System_Drawing_Point $buttonCancel.DataBindings.DefaultDataSourceUpdateMode = 0 $buttonCancel.add_Click($buttonCancel_OnClick) $SchedulePickerForm.Controls.Add($buttonCancel) $buttonOK.TabIndex = 2 $buttonOK.Name = "buttonOK" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 75 $System_Drawing_Size.Height = 23 $buttonOK.Size = $System_Drawing_Size $buttonOK.UseVisualStyleBackColor = $True $buttonOK.Text = "OK" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 287 $System_Drawing_Point.Y = 119 $buttonOK.Location = $System_Drawing_Point $buttonOK.DataBindings.DefaultDataSourceUpdateMode = 0 $buttonOK.add_Click($buttonOK_OnClick) $SchedulePickerForm.Controls.Add($buttonOK) $group.Name = "group" $group.Text = "Recurrence pattern" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 431 $System_Drawing_Size.Height = 101 $group.Size = $System_Drawing_Size $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 12 $System_Drawing_Point.Y = 12 $group.Location = $System_Drawing_Point $group.TabStop = $False $group.TabIndex = 0 $group.DataBindings.DefaultDataSourceUpdateMode = 0 $SchedulePickerForm.Controls.Add($group) $checkSaturday.UseVisualStyleBackColor = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 73 $System_Drawing_Size.Height = 24 $checkSaturday.Size = $System_Drawing_Size $checkSaturday.TabIndex = 13 $checkSaturday.Text = "Saturday" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 274 $System_Drawing_Point.Y = 64 $checkSaturday.Location = $System_Drawing_Point $checkSaturday.DataBindings.DefaultDataSourceUpdateMode = 0 $checkSaturday.Name = "checkSaturday" $checkSaturday.Visible = $False $group.Controls.Add($checkSaturday) $checkFriday.UseVisualStyleBackColor = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 64 $System_Drawing_Size.Height = 24 $checkFriday.Size = $System_Drawing_Size $checkFriday.TabIndex = 12 $checkFriday.Text = "Friday" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 204 $System_Drawing_Point.Y = 64 $checkFriday.Location = $System_Drawing_Point $checkFriday.DataBindings.DefaultDataSourceUpdateMode = 0 $checkFriday.Name = "checkFriday" $checkFriday.Visible = $False $group.Controls.Add($checkFriday) $checkThursday.UseVisualStyleBackColor = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 70 $System_Drawing_Size.Height = 24 $checkThursday.Size = $System_Drawing_Size $checkThursday.TabIndex = 11 $checkThursday.Text = "Thursday" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 129 $System_Drawing_Point.Y = 64 $checkThursday.Location = $System_Drawing_Point $checkThursday.DataBindings.DefaultDataSourceUpdateMode = 0 $checkThursday.Name = "checkThursday" $checkThursday.Visible = $False $group.Controls.Add($checkThursday) $checkWednesday.UseVisualStyleBackColor = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 83 $System_Drawing_Size.Height = 24 $checkWednesday.Size = $System_Drawing_Size $checkWednesday.TabIndex = 10 $checkWednesday.Text = "Wednesday" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 342 $System_Drawing_Point.Y = 44 $checkWednesday.Location = $System_Drawing_Point $checkWednesday.DataBindings.DefaultDataSourceUpdateMode = 0 $checkWednesday.Name = "checkWednesday" $checkWednesday.Visible = $False $group.Controls.Add($checkWednesday) $checkTuesday.UseVisualStyleBackColor = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 68 $System_Drawing_Size.Height = 24 $checkTuesday.Size = $System_Drawing_Size $checkTuesday.TabIndex = 9 $checkTuesday.Text = "Tuesday" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 274 $System_Drawing_Point.Y = 44 $checkTuesday.Location = $System_Drawing_Point $checkTuesday.DataBindings.DefaultDataSourceUpdateMode = 0 $checkTuesday.Name = "checkTuesday" $checkTuesday.Visible = $False $group.Controls.Add($checkTuesday) $checkMonday.UseVisualStyleBackColor = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 64 $System_Drawing_Size.Height = 24 $checkMonday.Size = $System_Drawing_Size $checkMonday.TabIndex = 8 $checkMonday.Text = "Monday" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 204 $System_Drawing_Point.Y = 44 $checkMonday.Location = $System_Drawing_Point $checkMonday.DataBindings.DefaultDataSourceUpdateMode = 0 $checkMonday.Name = "checkMonday" $checkMonday.Visible = $False $group.Controls.Add($checkMonday) $checkSunday.UseVisualStyleBackColor = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 104 $System_Drawing_Size.Height = 24 $checkSunday.Size = $System_Drawing_Size $checkSunday.TabIndex = 7 $checkSunday.Text = "Sunday" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 129 $System_Drawing_Point.Y = 44 $checkSunday.Location = $System_Drawing_Point $checkSunday.DataBindings.DefaultDataSourceUpdateMode = 0 $checkSunday.Name = "checkSunday" $checkSunday.Visible = $False $group.Controls.Add($checkSunday) $labelDays.TabIndex = 6 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 64 $System_Drawing_Size.Height = 18 $labelDays.Size = $System_Drawing_Size $labelDays.Visible = $False $labelDays.Text = "day(s)" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 189 $System_Drawing_Point.Y = 23 $labelDays.Location = $System_Drawing_Point $labelDays.DataBindings.DefaultDataSourceUpdateMode = 0 $labelDays.Name = "labelDays" $group.Controls.Add($labelDays) $labelHours.TabIndex = 5 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 100 $System_Drawing_Size.Height = 23 $labelHours.Size = $System_Drawing_Size $labelHours.Text = "hour(s)" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 189 $System_Drawing_Point.Y = 23 $labelHours.Location = $System_Drawing_Point $labelHours.DataBindings.DefaultDataSourceUpdateMode = 0 $labelHours.Name = "labelHours" $group.Controls.Add($labelHours) $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 28 $System_Drawing_Size.Height = 20 $boxHourlyDaily.Size = $System_Drawing_Size $boxHourlyDaily.DataBindings.DefaultDataSourceUpdateMode = 0 $boxHourlyDaily.Text = "1" $boxHourlyDaily.Name = "boxHourlyDaily" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 155 $System_Drawing_Point.Y = 20 $boxHourlyDaily.Location = $System_Drawing_Point $boxHourlyDaily.TabIndex = 4 $group.Controls.Add($boxHourlyDaily) $labelEvery.TabIndex = 3 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 67 $System_Drawing_Size.Height = 23 $labelEvery.Size = $System_Drawing_Size $labelEvery.Text = "Every" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 116 $System_Drawing_Point.Y = 23 $labelEvery.Location = $System_Drawing_Point $labelEvery.DataBindings.DefaultDataSourceUpdateMode = 0 $labelEvery.Name = "labelEvery" $group.Controls.Add($labelEvery) $radioHourly.TabIndex = 0 $radioHourly.Name = "radioHourly" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 104 $System_Drawing_Size.Height = 24 $radioHourly.Size = $System_Drawing_Size $radioHourly.UseVisualStyleBackColor = $True $radioHourly.Text = "Hourly" $radioHourly.Checked = $True $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 6 $System_Drawing_Point.Y = 17 $radioHourly.Location = $System_Drawing_Point $radioHourly.DataBindings.DefaultDataSourceUpdateMode = 0 $radioHourly.TabStop = $True $radioHourly.add_Click($handler_radioButtonChanged) $group.Controls.Add($radioHourly) $radioWeekly.TabIndex = 2 $radioWeekly.Name = "radioWeekly" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 104 $System_Drawing_Size.Height = 24 $radioWeekly.Size = $System_Drawing_Size $radioWeekly.UseVisualStyleBackColor = $True $radioWeekly.Text = "Weekly" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 6 $System_Drawing_Point.Y = 56 $radioWeekly.Location = $System_Drawing_Point $radioWeekly.DataBindings.DefaultDataSourceUpdateMode = 0 $radioWeekly.add_Click($handler_radioButtonChanged) $group.Controls.Add($radioWeekly) $radioDaily.TabIndex = 1 $radioDaily.Name = "radioDaily" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 104 $System_Drawing_Size.Height = 24 $radioDaily.Size = $System_Drawing_Size $radioDaily.UseVisualStyleBackColor = $True $radioDaily.Text = "Daily" $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 6 $System_Drawing_Point.Y = 37 $radioDaily.Location = $System_Drawing_Point $radioDaily.DataBindings.DefaultDataSourceUpdateMode = 0 $radioDaily.add_Click($handler_radioButtonChanged) $group.Controls.Add($radioDaily) $SchedulePickerForm.CancelButton = $buttonCancel $SchedulePickerForm.AcceptButton = $buttonOK #Save the initial state of the form $InitialFormWindowState = $SchedulePickerForm.WindowState #Init the OnLoad event to correct the initial state of the form $SchedulePickerForm.add_Load($OnLoadForm_StateCorrection) #Show the Form $SchedulePickerForm.ShowDialog() |out-null }
PowerShellCorpus/PoshCode/PowerBot _3.0.ps1
PowerBot _3.0.ps1
## PowerBot 2.0 ## A simple framework to get you started writing your own IRC bots in PowerShell #################################################################################################### ## Requires Meebey.SmartIrc4net.dll to be in your ...\\WindowsPowerShell\\Libraries\\ ## You can get Meebey.SmartIrc4net.dll from ## http://voxel.dl.sourceforge.net/sourceforge/smartirc4net/SmartIrc4net-0.4.0.bin.tar.bz2 #################################################################################################### ## Add-Type -path $ProfileDir\\Libraries\\Meebey.SmartIrc4net.dll $null = [Reflection.Assembly]::LoadFrom("$ProfileDir\\Libraries\\Meebey.SmartIrc4net.dll") function Start-PowerBot { PARAM( $server = "irc.freenode.net", [string[]]$channels = @("#PowerShell"), [string[]]$nick = @(Read-Host 'You must provide a nickname'), [string]$password, $realname = "PowerShell Bot", $port = 6667) if(!$global:irc) { $global:irc = New-Object Meebey.SmartIrc4net.IrcClient $irc.ActiveChannelSyncing = $true # $irc will track channels for us # $irc.Encoding = [Text.Encoding]::UTF8 # $irc.Add_OnError( {Write-Error $_.ErrorMessage} ) $irc.Add_OnQueryMessage( {PrivateMessage} ) $irc.Add_OnChannelMessage( {ChannelMessage} ) } $irc.Connect($server, $port) $irc.Login($nick, $realname, 0, $nick, $password) ## $channels | % { $irc.RfcJoin( $_ ) } foreach($channel in $channels) { $irc.RfcJoin( $channel ) } Resume-PowerBot # Shortcut so starting this thing up only takes one command } ## Note that PowerBot stops listening if you press a key ... ## You'll have to re-run Resume-Powerbot to get him to listen again function Resume-PowerBot { while(!$Host.UI.RawUI.KeyAvailable) { $irc.ListenOnce($false) } } function Stop-PowerBot { $irc.RfcQuit("If people listened to themselves more often, they would talk less.") $irc.Disconnect() } #################################################################################################### ## Event Handlers #################################################################################################### ## Event handlers in powershell have TWO automatic variables: $This and $_ ## In the case of SmartIrc4Net: ## $This - usually the connection, and such ... ## $_ - the IrcEventArgs, which just has the Data member: ## function PrivateMessage { $Data = $_.Data # Write-Verbose $Data.From # Write-Verbose $Data.Message # Write-Verbose $($Data | Out-String) $command, $params = $Data.MessageArray if($PowerBotCommands.ContainsKey($command)) { &$PowerBotCommands[$command] $params $Data | Out-String -width (510 - $Data.From.Length - $nick.Length - 3) | % { $_.Trim().Split("`n") | %{ $irc.SendMessage("Message", $Data.Channel, $_.Trim() ) }} } } function ChannelMessage { $Data = $_.Data # Write-Verbose $Data.From # Write-Verbose $Data.Channel # Write-Verbose $Data.Message # Write-Verbose $($Data | Out-String) $command, $params = $Data.MessageArray if($PowerBotCommands.ContainsKey($command)) { &$PowerBotCommands[$command] $params $Data | Out-String -width (510 - $Data.Channel.Length - $nick.Length - 3) | % { $_.Trim().Split("`n") | %{ $irc.SendMessage("Message", $Data.Channel, $_.Trim() ) }} } } #################################################################################################### ## The PowerBotCommands hashtable is extremely simple ... ## ## You register a "command" which must be the FIRST WORD of a message (either private, or channel) ## and you provide a scriptblock to process said message. ## The handler scriptblock gets two parameters, for convenience: ## $Params is the rest of the message text after the command word (which is probably all you need) ## $Data is the Data propert of the IrcEventArgs, which has everything in it that you could want ## ## You may do whatever you want in the scriptblock (this runs on your PC, after all), but the ## simplest thing is to respond by returning "something" which will be sent to wherever the message ## came from. ## ## NOTE 1: Evrything you return is output to Out-String and then the channel or user. Be careful! ## NOTE 2: 510 is the Max IRC Message Length, including the channel name etc. ## http`://www.faqs.org/rfcs/rfc1459.html ## $PowerBotCommands=@{} ## A sample command to get you started $PowerBotCommands."Hello" = {Param($Query,$Data) "Hello, $($Data.Nick)!" } ##$PowerBotCommands."!Echo" = {Param($Query,$Data) ## "$Query" ##} ## ##$PowerBotCommands."!Get-Help" = {Param($Query) ## $help = get-help $Query | Select Name,Synopsis,Syntax ## if($?) { ## if($help -is [array]) { ## "You're going to need to be more specific, I know all about $((($help | % { $_.Name })[0..($help.Length-2)] -join ', ') + ' and even ' + $help[-1].Name)" ## } else { ## @($help.Synopsis,($help.Syntax | Out-String -width 1000).Trim().Split("`n",4,"RemoveEmptyEntries")[0..3]) ## } ## } else { ## "I couldn't find the help file for '$Query', sorry. I probably don't have that snapin loaded." ## } ##}
PowerShellCorpus/PoshCode/Write-Output.ps1
Write-Output.ps1
######################################################################## ## Copyright (c) Joel Bennett, 2010 ## Free for use under MS-PL, MS-RL, GPL 2, or BSD license. Your choice. function Write-Output { [CmdletBinding()] param( [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)] [AllowEmptyCollection()] [AllowNull()] [System.Management.Automation.PSObject] ${InputObject} , [Parameter()] [Switch] $Passthru , [Parameter()] [Switch] $CollectInput ) begin { if($CollectInput) { $Collection = New-Object System.Collections.Generic.List[PSObject] } } process { if($InputObject) { if($CollectInput) { $Collection.AddRange( ([PSObject[]]@($InputObject)) ) } else { $PSCmdlet.WriteObject( $InputObject, !$Passthru ) } } } end { if($CollectInput) { $PSCmdlet.WriteObject( $Collection, !$Passthru ) } } <# .SYNOPSIS Sends the specified objects to the next command in the pipeline. If the command is the last command in the pipeline, the objects are displayed in the console. .DESCRIPTION The Write-Output function sends the specified object down the pipeline to the next command. If the command is the last command in the pipeline, the object is displayed in the console. Write-Output sends objects down the primary pipeline, also known as the "output stream" or the "success pipeline." To send error objects down the error pipeline, use Write-Error. This function provides a pair of enhancements to the built-in Write-Output. First, it offers the option of Passthru, which causes collections to be output without unrolling (that is, output as collections to the pipeline), and second, it includes an option to collect input from the pipeline and output it all at once at the end. .PARAMETER InputObject Specifies the objects to send down the pipeline. Enter a variable that contains the objects, or type a command or expression that gets the objects. .PARAMETER CollectInput Specifies that pipeline input should be collected and output all at once at the end. This effectively allows you to take streaming input and turn it into a collection. Note that this causes the output to be a List[PSObject]. .PARAMETER Passthru Specifies that the output should be "as-is" ... meaning that if you specify a collection as input, you'll get a collection as output, rather than having Write-Output output individual items one at a time. .EXAMPLE $p = get-process C:\\PS>write-output $p Description ----------- These commands get objects representing the processes running on the computer and display the objects on the console. .EXAMPLE $p = get-process | Select-Object -First 10 C:\\PS>write-output $p | ForEach-Object { $_.GetType() } IsPublic IsSerial Name BaseType -------- -------- ---- -------- True False Process System.ComponentModel.Component True False Process System.ComponentModel.Component True False Process System.ComponentModel.Component True False Process System.ComponentModel.Component True False Process System.ComponentModel.Component True False Process System.ComponentModel.Component True False Process System.ComponentModel.Component True False Process System.ComponentModel.Component True False Process System.ComponentModel.Component True False Process System.ComponentModel.Component C:\\PS>write-output $p -passthru | ForEach-Object { $_.GetType() } IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Object[] System.Array Description ----------- These commands demonstrate the difference between using and not using -passthru. Without it, each object passes through the ForEach and it's type is output. With -Passthru, only a single object is output, with a collection type of Object[]. .EXAMPLE Get-Process | Select-Object -First 10 | Write-Output -Passthru | ForEach-Object { $_.GetType() } Description ----------- This command pipes the first ten processes to the ForEach-Object, demonstrating that -Passthru will always force collection output. .EXAMPLE Get-Process | Write-Output -Passthru -CollectInput | ForEach-Object { $_.GetType() } Description ----------- This command collects all of the processes before outputting them to the ForEach-Object as a List[PSObject] #> }
PowerShellCorpus/PoshCode/WhoAmI_1.ps1
WhoAmI_1.ps1
function whoami { [System.Security.Principal.WindowsIdentity]::GetCurrent().Name }
PowerShellCorpus/PoshCode/Findup_22.ps1
Findup_22.ps1
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.Runtime.InteropServices; using Microsoft.Win32; using System.IO; using System.Text.RegularExpressions; namespace Findup { public class FileLengthComparer : IComparer<FileInfo> { public int Compare(FileInfo x, FileInfo y) { return (x.Length.CompareTo(y.Length)); } } class Findup { public static Dictionary<string, List<string>> optionspaths = new Dictionary<string, List<string>> { {"-x", new List<string>()},{"-i",new List<string>()},{"-xf",new List<string>()},{"-if",new List<string>()}, {"-xd",new List<string>()},{"-id",new List<string>()},{"-paths",new List<string>()} }; public static Dictionary<string, List<Regex>> optionsregex = new Dictionary<string, List<Regex>> { {"-xr", new List<Regex>()},{"-ir",new List<Regex>()},{"-xfr",new List<Regex>()},{"-ifr",new List<Regex>()}, {"-xdr",new List<Regex>()},{"-idr",new List<Regex>()} }; public static Dictionary<string, Boolean> optionsbools = new Dictionary<string, bool> { { "-recurse", false }, { "-noerr", false }, {"-delete",false} }; public static long numOfDupes, dupeBytes, bytesrecovered, deletedfiles = 0; // number of duplicate files foumd, bytes in duplicates, bytes recovered from deleting dupes, number of deleted dupes. public static string delconfirm; public static void Main(string[] args) { DateTime startTime = DateTime.Now; Console.WriteLine("Findup.exe v2.0 - By James Gentile - JamesRaymondGentile@gmail.com - 2012."); Console.WriteLine("Findup.exe matches sizes, then SHA512 hashes to identify duplicate files."); Console.WriteLine(" "); string optionskey = "-paths"; List<FileInfo> files = new List<FileInfo>(); int i = 0; for (i = 0; i < args.Length; i++) { string argitem=args[i].ToLower(); if ((System.String.Compare(argitem, "-help", true) == 0) || (System.String.Compare(argitem, "-h", true) == 0)) { Console.WriteLine("Usage: findup.exe <file/directory #1..#N> [-recurse] [-noerr] [-x/-i/-xd/-id/-xf/-if] <files/directories/regex> [-regex] [-delete]"); Console.WriteLine(" "); Console.WriteLine("Options: -help - displays this help message."); Console.WriteLine(" -recurse - recurses through subdirectories when directories or file specifications (e.g. *.txt) are specified."); Console.WriteLine(" -noerr - discards error messages."); Console.WriteLine(" -delete - delete each duplicate file with confirmation."); Console.WriteLine(" -x - eXcludes if full file path starts with (or RegEx matches if -xr) one of the items following this switch until another switch is used."); Console.WriteLine(" -i - include if full file path starts with (or Regex matches if -ir) one of the items following this switch until another switch is used."); Console.WriteLine(" -xd - eXcludes all directories (using RegEx if -xdr) including subdirs following this switch until another switch is used."); Console.WriteLine(" -id - Include only directories (using RegEx if -idr) including subdirs following this switch until another switch is used."); Console.WriteLine(" -xf - eXcludes all files (using RegEx if -xfr) following this switch until another switch is used."); Console.WriteLine(" -if - Include only files (using RegEx if -ifr) following this switch until another switch is used."); Console.WriteLine(" [r] - Use regex for include/exclude by appending an 'r' to the option, e.g. -ir, -ifr, -idr, -xr, -xfr, -xdr."); Console.WriteLine(" -paths - not needed unless you want to specify files/dirs after an include/exclude without using another non-exclude/non-include option."); Console.WriteLine(" "); Console.WriteLine("Examples: findup.exe c:\\\\finances -recurse -noerr"); Console.WriteLine(" - Find dupes in c:\\\\finance."); Console.WriteLine(" - recurse all subdirs of c:\\\\finance."); Console.WriteLine(" - suppress error messages."); Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data -recurse -x d:\\\\data\\\\webpics"); Console.WriteLine(" - Find dupes in c:\\\\users\\\\alice\\\\plan.txt, d:\\\\data"); Console.WriteLine(" - recurse subdirs in d:\\\\data."); Console.WriteLine(" - exclude any files in d:\\\\data\\\\webpics and subdirs."); Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\quarter.doc -xr \\"(jim)\\" -regex"); Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\quarter.doc"); Console.WriteLine(" - exclude any file with 'jim' in the name as specified by the Regex item \\"(jim)\\""); Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\*quarter.doc -xr \\"[bf]\\" -ir \\"(smith)\\" -regex"); Console.WriteLine(" - Find dupes in c:\\\\data, *.txt in current directory and c:\\\\reports\\\\*quarter.doc"); Console.WriteLine(" - Include only files with 'smith' and exclude any file with letters b or f in the name as specified by the Regex items \\"[bf]\\",\\"(smith)\\""); Console.WriteLine("Note: Exclude takes precedence over Include."); Console.WriteLine(" -xdr,-idr,-xfr,-ifr are useful if for instance you want to apply a RegEx to only file names but not directory names or vice versa."); Console.WriteLine(" if for instance you wanted all files that contained the letter \\"d\\" on your D: drive but didn't want the d:\\\\ to cause all files on the d:\\\\ "); Console.WriteLine(" drive to be included, you would specify:"); Console.WriteLine(" findup.exe d:\\\\ -recurse -noerr -regex -ifr \\"[d]\\" "); return; } if (optionsbools.ContainsKey(argitem)) { optionsbools[argitem] = true; optionskey = "-paths"; continue; } if (optionspaths.ContainsKey(argitem) || optionsregex.ContainsKey(argitem)) { optionskey = argitem; continue; } if (optionspaths.ContainsKey(optionskey)) optionspaths[optionskey].Add(argitem); else { try { Regex rgx = new Regex(argitem, RegexOptions.Compiled); optionsregex[optionskey].Add(rgx); } catch (Exception e) {WriteErr("Regex compilation failed: " + e.Message);} } } if (optionspaths["-paths"].Count == 0) { WriteErr("No files, file specifications, or directories specified. Try findup.exe -help. Assuming current directory."); optionspaths["-paths"].Add("."); } Console.Write("Getting file info and sorting file list..."); getFiles(optionspaths["-paths"], "*.*", optionsbools["-recurse"], files); if (files.Count < 2) { WriteErr("\\nFindup.exe needs at least 2 files to compare. Try findup.exe -help"); return; } files.Sort(new FileLengthComparer()); Console.WriteLine("Completed!"); Console.Write("Building dictionary of file sizes, SHA512 hashes and full paths..."); var SizeHashName = new Dictionary<long, Dictionary<string,List<FileInfo>>>(); for (i = 0; i < (files.Count - 1); i++) { if (files[i].Length != files[i + 1].Length) { continue; } var breakout = false; while (true) { try { var _SHA512 = SHA512.Create(); using (var fstream = File.OpenRead(files[i].FullName)) { _SHA512.ComputeHash(fstream); } string SHA512string = ""; foreach (var c in _SHA512.Hash) { SHA512string += String.Format("{0:x2}", c); } if (!SizeHashName.ContainsKey(files[i].Length)) SizeHashName.Add(files[i].Length, new Dictionary<string,List<FileInfo>>()); if (!SizeHashName[files[i].Length].ContainsKey(SHA512string)) SizeHashName[files[i].Length][SHA512string] = new List<FileInfo>() {}; SizeHashName[files[i].Length][SHA512string].Add(files[i]); } catch (Exception e) { WriteErr("Hash error: " + e.Message); } if (breakout == true) {break;} i++; if (i == (files.Count - 1)) { breakout = true; continue; } breakout = (files[i].Length != files[i + 1].Length); } } Console.WriteLine("Completed!"); foreach (var SizeGroup in SizeHashName) { foreach (var HashGroup in SizeGroup.Value) { var SGK = (long)SizeGroup.Key; var HGVC = (long)HashGroup.Value.Count; if (HGVC > 1) { Console.WriteLine("{0:N0} Duplicate files. {1:N0} Bytes each. {2:N0} Bytes total : ", HGVC, SGK, SGK*HGVC); foreach (var Filenfo in HashGroup.Value) { Console.WriteLine(Filenfo.FullName); numOfDupes++; dupeBytes += Filenfo.Length; if (optionsbools["-delete"]) if (DeleteDupe(Filenfo)) { bytesrecovered += Filenfo.Length; } } } } } Console.WriteLine("\\n "); Console.WriteLine("Files checked : {0:N0}", files.Count); // display statistics and return to OS. Console.WriteLine("Duplicate files : {0:N0}", numOfDupes); Console.WriteLine("Duplicate bytes : {0:N0}", dupeBytes); Console.WriteLine("Deleted duplicates : {0:N0}", deletedfiles); Console.WriteLine("Bytes recovered : {0:N0}", bytesrecovered); Console.WriteLine("Execution time : " + (DateTime.Now - startTime)); } private static void WriteErr(string Str) { if (!optionsbools["-noerr"]) Console.WriteLine(Str); } private static Boolean DeleteDupe(FileInfo Filenfo) { Console.Write("Delete this file <y/N> <ENTER>?"); delconfirm = Console.ReadLine(); if ((delconfirm[0] == 'Y') || (delconfirm[0] == 'y')) { try { Filenfo.Delete(); Console.WriteLine("File Successfully deleted."); deletedfiles++; return true; } catch (Exception e) { Console.WriteLine("File could not be deleted: " + e.Message); } } return false; } private static Boolean CheckNames(string fullname) { var filePart = Path.GetFileName(fullname); var dirPart = Path.GetDirectoryName(fullname); if (CheckNamesWorker(fullname,"-x")) return false; if (CheckNamesWorker(filePart,"-xf")) return false; if (CheckNamesWorker(dirPart,"-xd")) return false; if (!CheckNamesWorker(fullname,"-i")) return false; if (!CheckNamesWorker(filePart,"-if")) return false; if (!CheckNamesWorker(dirPart,"-id")) return false; return true; } private static Boolean CheckNamesWorker(string filestr, string key) { foreach (var filepath in optionspaths[key]) { if (filestr.ToLower().StartsWith(filepath)) return true; } foreach (var rgx in optionsregex[key+"r"]) { if (rgx.IsMatch(filestr)) return true; } return (key[1] == 'i' && optionspaths[key].Count == 0 && optionsregex[key + "r"].Count == 0); // If checking [i]ncludes, return true if 0 paths/regex to check, else false } private static void getFiles(List<string> pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList) { foreach (string d in pathRec) { getFiles(d, searchPattern, recursiveFlag, returnList); } } private static void getFiles(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList) { foreach (string d in pathRec) { getFiles(d, searchPattern, recursiveFlag, returnList); } } private static void getFiles(string pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfo> returnList) { string dirPart; string filePart; if (File.Exists(pathRec)) { try { FileInfo addf = (new FileInfo(pathRec)); if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) && CheckNames(addf.FullName)) returnList.Add(addf); } catch (Exception e) { WriteErr("Add file error: " + e.Message); } } else if (Directory.Exists(pathRec)) { try { DirectoryInfo Dir = new DirectoryInfo(pathRec); foreach (FileInfo addf in (Dir.GetFiles(searchPattern))) { if (((addf.Attributes & FileAttributes.ReparsePoint) == 0) && CheckNames(addf.FullName)) returnList.Add(addf); } } catch (Exception e) { WriteErr("Add files from Directory error: " + e.Message); } if (recursiveFlag) { try { getFiles((Directory.GetDirectories(pathRec)), searchPattern, recursiveFlag, returnList); } catch (Exception e) { WriteErr("Add Directory error: " + e.Message); } } } else { try { filePart = Path.GetFileName(pathRec); dirPart = Path.GetDirectoryName(pathRec); } catch (Exception e) { WriteErr("Parse error on: " + pathRec); WriteErr(@"Make sure you don't end a directory with a \\ when using quotes. The console arg parser doesn't accept that."); WriteErr("Exception: " + e.Message); return; } if (filePart.IndexOfAny(new char[] {'?','*'}) >= 0) { if ((dirPart == null) || (dirPart == "")) dirPart = Directory.GetCurrentDirectory(); if (Directory.Exists(dirPart)) { getFiles(dirPart, filePart, recursiveFlag, returnList); return; } } WriteErr("Invalid file path, directory path, file specification, or program option specified: " + pathRec); } } } }
PowerShellCorpus/PoshCode/Findup_14.ps1
Findup_14.ps1
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.Runtime.InteropServices; using Microsoft.Win32; using System.IO; namespace Findup { public class FileInfoExt { public FileInfoExt(FileInfo fi) { FI = fi; } public byte[] SHA512_1st1K; public byte[] SHA512_All; public FileInfo FI { get; private set; } public bool Matched { get; set; } } class Findup { const int HashLen = 512/8; // 64-byte hash for SHA512. public static System.Boolean noerr = false; public static void Main(string[] args) { Console.WriteLine("Findup.exe v1.0 - use -help for usage information. Created in 2010 by James Gentile."); Console.WriteLine(" "); string[] paths = new string[0]; System.Boolean recurse = false; System.Boolean delete = false; System.Boolean noprompt = false; System.Boolean b4b = false; string fname; List<FileInfoExt> files = new List<FileInfoExt>(); long bytesInDupes = 0; // bytes in all the duplicates long bytesRec = 0; // number of bytes recovered. int delFiles = 0; // number of files deleted. int numOfDupes = 0; // number of duplicate files found. int c = 0; int i = 0; string deleteConfirm; for (i = 0; i < args.Length; i++) { if ((System.String.Compare(args[i], "-help", true) == 0) || (System.String.Compare(args[i], "-h", true) == 0)) { Console.WriteLine("Usage: findup.exe <file/directory #1> <file/directory #2> ... <file/directory #N> [-recurse] [-delete] [-noprompt] [-b4b]"); Console.WriteLine(" "); Console.WriteLine("Options: -help - displays this help infomration."); Console.WriteLine(" -recurse - recurses through subdirectories when directories or file specifications (e.g. *.txt) are specified."); Console.WriteLine(" -delete - deletes duplicates with confirmation prompt."); Console.WriteLine(" -noprompt - when used with -delete option, deletes files without confirmation prompt."); Console.WriteLine(" -noerr - discards error messages."); Console.WriteLine(" -b4b - do a byte-for-byte comparison, instead of SHA-512 hashing. Slower in some cases, faster in others, and most secure."); Console.WriteLine(" "); Console.WriteLine("Examples: findup.exe c:\\\\finances -recurse -noerr"); Console.WriteLine(" findup.exe c:\\\\users\\\\alice\\\\plan.txt d:\\\\data -recurse -delete -noprompt"); Console.WriteLine(" findup.exe c:\\\\data *.txt c:\\\\reports\\\\quarter.doc -b4b"); Console.WriteLine(" "); return; } if (System.String.Compare(args[i], "-recurse", true) == 0) { recurse = true; continue; } if (System.String.Compare(args[i], "-delete", true) == 0) { delete = true; continue; } if (System.String.Compare(args[i], "-noprompt", true) == 0) { noprompt = true; continue; } if (System.String.Compare(args[i], "-b4b", true) == 0) { b4b = true; continue; } if (System.String.Compare(args[i], "-noerr", true) == 0) { noerr = true; continue; } Array.Resize(ref paths, paths.Length + 1); paths[c] = args[i]; c++; } if (paths.Length == 0) { WriteErr("No files, file specifications, or directories specified. Try findup.exe -help"); return; } getFiles(paths, "*.*", recurse, files); if (files.Count < 2) { WriteErr("Findup.exe needs at least 2 files to compare. try findup.exe -help"); return; } for (i = 0; i < files.Count; i++) // cycle through all files, except those already matched. { fname = files[i].FI.FullName; if (fname.Length > Console.WindowWidth - 4) fname = fname.Remove(Console.WindowWidth - 4) + "..."; fname = fname.PadRight((Console.WindowWidth - 1)); Console.Write(fname + "\\r"); // display current file name, truncated if necessary. if (files[i].Matched == true) continue; for (c = i + 1; c < files.Count; c++) // cycle through all files not checked, except those matched. { if (files[c].Matched == true) continue; if (files[i].FI.Length != files[c].FI.Length) // If file size matches, then check hash. continue; if (System.String.Compare(files[i].FI.FullName, files[c].FI.FullName, true) == 0) // don't count the same file as a match. continue; if (files[i].SHA512_1st1K == null) // check/hash first 1K first. if (Compute1KHash(files[i]) == false) continue; if (files[c].SHA512_1st1K == null) if (Compute1KHash(files[c]) == false) continue; if (CompareBytes(files[i].SHA512_1st1K, files[c].SHA512_1st1K) == false) // if the 1st 1K has the same hash.. continue; if (b4b == true) // byte for byte comparison specified? { if (B4b(files[i].FI.FullName, files[c].FI.FullName) == false) // call the byte for byte comparison function continue; } else if (files[i].FI.Length > 1024) // skip hashing the file again if < 1024 bytes. { if (files[i].SHA512_All == null) // check/hash the rest of the files. if (ComputeFullHash(files[i]) == false) continue; if (files[c].SHA512_All == null) if (ComputeFullHash(files[c]) == false) continue; if (CompareBytes(files[i].SHA512_All, files[c].SHA512_All) == false) continue; } Console.WriteLine(" Match: " + files[i].FI.FullName); Console.WriteLine(" with: " + files[c].FI.FullName); Console.WriteLine(" Size: {0:N0}",files[i].FI.Length); files[c].Matched = true; // do not check or match against this file again. numOfDupes++; // increase count of matches. bytesInDupes += files[c].FI.Length; // accumulate number of bytes in duplicates. if (delete != true) // if delete is specified, try to delete the duplicate file. continue; if (noprompt == false) { Console.Write("Delete the duplicate file <y/N>?"); deleteConfirm = Console.ReadLine(); if ((deleteConfirm[0] != 'Y') && (deleteConfirm[0] != 'y')) // if user typed 'Y' then delete the file. continue; } try { File.Delete(files[c].FI.FullName); Console.WriteLine("Deleted: " + files[c].FI.FullName); bytesRec += files[c].FI.Length; // record bytes recovered. delFiles++; } catch (Exception e) { WriteErr("File delete error: " + e.Message); } } } Console.WriteLine("\\n "); Console.WriteLine("Files checked : {0:N0}", files.Count); Console.WriteLine("Duplicate files : {0:N0}", numOfDupes); Console.WriteLine("Duplicate bytes : {0:N0}", bytesInDupes); Console.WriteLine("Duplicates deleted : {0:N0}", delFiles); Console.WriteLine("Recovered bytes : {0:N0}", bytesRec); return; // Exit after displaying statistics. } private static Boolean B4b(string path1, string path2) { try { using (var stream = File.OpenRead(path1)) { using (var stream2 = File.OpenRead(path2)) { while (stream.Position != stream.Length) { var length = stream.Read(largeBuf, 0, largeBuf.Length); var length2 = stream2.Read(largeBuf2, 0, largeBuf2.Length); if (length != length2) return false; if (CompareBytes(largeBuf, largeBuf2, length) == false) return false; } } } return true; } catch (Exception e) { WriteErr("Byte for Byte comparison failed: " + e.Message); return false; } } private static Boolean CompareBytes(byte[] byteArray1, byte[] byteArray2, int Len = HashLen) { int i = 0; while (i < Len) { if (byteArray1[i] != byteArray2[i]) return false; i++; } return true ; } private static readonly byte[] readBuf = new byte[1024]; private static readonly byte[] largeBuf = new byte[1024*10]; private static readonly byte[] largeBuf2 = new byte[1024*10]; private static void WriteErr(string Str) { if (noerr == false) Console.WriteLine(Str); } private static bool Compute1KHash(FileInfoExt path) { try { using (var fstream = File.OpenRead(path.FI.FullName)) { var length = fstream.Read(readBuf, 0, readBuf.Length); var _SHA512 = SHA512.Create(); _SHA512.TransformFinalBlock(readBuf, 0, length); path.SHA512_1st1K = _SHA512.Hash; return true; } } catch (Exception e) { WriteErr("Hash Error: " + e.Message); path.Matched = true; // since the file error'ed out, don't check against it again. return false; } } private static bool ComputeFullHash(FileInfoExt path) { try { var _SHA512 = SHA512.Create(); using (var fstream = File.OpenRead(path.FI.FullName)) { _SHA512.ComputeHash(fstream); } path.SHA512_All = _SHA512.Hash; return true; } catch (Exception e) { WriteErr("Hash error: " + e.Message); path.Matched = true; return false; } } private static void getFiles(string[] pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfoExt> returnList) { foreach (string d in pathRec) { getFiles(d, searchPattern, recursiveFlag, returnList); } return; } private static void getFiles(string pathRec, string searchPattern, Boolean recursiveFlag, List<FileInfoExt> returnList) { string dirPart; string filePart; if (File.Exists(pathRec)) { try { FileInfo addf = (new FileInfo(pathRec)); if ((addf.Attributes & FileAttributes.ReparsePoint) == 0) returnList.Add(new FileInfoExt(addf)); } catch (Exception e) { WriteErr("Add file error: " + e.Message); } } else if (Directory.Exists(pathRec)) { try { DirectoryInfo Dir = new DirectoryInfo(pathRec); foreach (FileInfo addf in (Dir.GetFiles(searchPattern))) { if ((addf.Attributes & FileAttributes.ReparsePoint) == 0) returnList.Add(new FileInfoExt(addf)); } } catch (Exception e) { WriteErr("Add files from Directory error: " + e.Message); } if (recursiveFlag == true) { try { getFiles((Directory.GetDirectories(pathRec)), searchPattern, recursiveFlag, returnList); } catch (Exception e) { WriteErr("Add Directory error: " + e.Message); } } } else { try { filePart = Path.GetFileName(pathRec); dirPart = Path.GetDirectoryName(pathRec); } catch (Exception e) { WriteErr("Parse error on: " + pathRec); WriteErr(@"Make sure you don't end a directory with a \\ when using quotes. The console arg parser doesn't accept that."); WriteErr("Exception: " + e.Message); return; } if (filePart.IndexOfAny(new char[] {'?','*'}) >= 0) { if ((dirPart == null) || (dirPart == "")) dirPart = Directory.GetCurrentDirectory(); if (Directory.Exists(dirPart)) { getFiles(dirPart, filePart, recursiveFlag, returnList); return; } } WriteErr("Invalid file path, directory path, file specification, or program option specified: " + pathRec); } } } }
PowerShellCorpus/PoshCode/Get-DistanceOnEarth.ps1
Get-DistanceOnEarth.ps1
function Get-DistanceOnEarth { <# .SYNOPSIS Calculates distance between points on the Earth. .DESCRIPTION Implementation of the Haversine equation to calculate distance over the surface of a sphere. .INPUTTYPE Pipeline object with the following parameters: LATITUDE1 LONGITUDE1 LATITUDE2 LONGITUDE2 #> Begin { $toRad = 0.0174532925 # radians in 1 degree $R = 3963.1676 # approx. radius of earth in milies #$R = 6378.1 # approx. radius of earth in km } Process { $lat1 = $_.LATITUDE1 $lon1 = $_.LONGITUDE1 $lat2 = $_.LATITUDE2 $lon2 = $_.LONGITUDE2 $dLat = ($lat2 - $lat1) * $toRad $dLon = ($lon2 - $lon1) * $toRad $a = ( ( ([Math]::Sin($dLat/2)) * ([Math]::Sin($dLat/2)) ) + ([Math]::Cos($lat1 * $toRad) * [Math]::Cos($lat2 * $toRad) * ( ([Math]::Sin($dLon/2)) * ([Math]::Sin($dLon/2)) ))) $c = 2 * [Math]::Atan2([Math]::Sqrt($a), [Math]::Sqrt(1-$a)) $d = $R * $c $d = [Math]::Round($d,3) $_ | Add-Member -MemberType NoteProperty -Name Distance -Value $d Write-Output $_ } }
PowerShellCorpus/PoshCode/Change-ServicePassword.ps1
Change-ServicePassword.ps1
Param([string]$server,[string]$service,[string]$user,[string]$password) Begin{ function ChangeServicePassword{ Param([string]$srv,[string]$ms,[string]$usr,[string]$pwd) # Setup for WMI $class = "Win32_Service" $method = "change" $computer = $srv $filter = "Name=`'$ms`'" # Getting Service Via WMI $MyService = get-WmiObject $class -computer $computer -filter $filter # Setting Parameters for Change Method $inparams = $MyService.psbase.GetMethodParameters($method) $inparams["StartName"] = $usr $inparams["StartPassword"] = $pwd # Calling Change Method and Return $results $result = $MyService.psbase.InvokeMethod($method,$inparams,$null) if($result.ReturnValue -eq 0) { return $true } else { return $false } } Write-Host $process = @() } Process{ if($_){ if($_.ServerName){ $process += $_.ServerName } else{ $process += $_ } } } End{ if($Server){$Process += $Server} if($process.Length -eq 0){$Process += get-content env:COMPUTERNAME} foreach($s in $process) { if(ChangeServicePass -Srv $s -ms $service -usr $user -pwd $password) { Write-host "Service [$Service] changed on Server [$s] now using [$user]" } else { Write-Host "Service Change Failed on Server[$s]" } Write-Host } }
PowerShellCorpus/PoshCode/SnapReminder.ps1
SnapReminder.ps1
# - SnapReminder V1.0 By Virtu-Al - http://virtu-al.net # # Please use the below variables to define your settings before use # $smtpServer = "mysmtpserver.mydomain.com" $MailFrom = "me@mydomain.com" $VISRV = "MYVISERVER" function Find-User ($username){ if ($username -ne $null) { $usr = (($username.split("\\"))[1]) $root = [ADSI]"" $filter = ("(&(objectCategory=user)(samAccountName=$Usr))") $ds = new-object system.DirectoryServices.DirectorySearcher($root,$filter) $ds.PageSize = 1000 $ds.FindOne() } } 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).AddSeconds(-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 $snapshot = Get-SnapshotTree $vm.Snapshot.RootSnapshotList $_.Result $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 SnapMail ($Mailto, $snapshot) { $msg = new-object Net.Mail.MailMessage $smtp = new-object Net.Mail.SmtpClient($smtpServer) $msg.From = $MailFrom $msg.To.Add($Mailto) $msg.Subject = "Snapshot Reminder" $MailText = @" This is a reminder that you have a snapshot active on $($snapshot.VM) which was taken on $($snapshot.Created). Name: $($snapshot.Name) Description: $($snapshot.Description) "@ $msg.Body = $MailText $smtp.Send($msg) } Connect-VIServer $VISRV foreach ($snap in (Get-VM | Get-Snapshot | Where {$_.Created -lt ((Get-Date).AddDays(-14))})){ $SnapshotInfo = Get-SnapshotExtra $snap $mailto = ((Find-User $SnapshotInfo.Creator).Properties.mail) SnapMail $mailto $SnapshotInfo }
PowerShellCorpus/PoshCode/TabExpansion_2.ps1
TabExpansion_2.ps1
## Tab-Completion ################# ## Please dot souce this script file. ## In first loading, it may take a several minutes, in order to generate ProgIDs and TypeNames list. ## What this can do is: ## ## [datetime]::n<tab> ## [datetime]::now.d<tab> ## $foo[0].<tab> ## $foo[0].n.b<tab> ## $function:a<tab> ## $env:a<tab> ## [System.Type].a<tab> ## [datetime].Assembly.a<tab> ## ).a<tab> # shows System.Type properties and methods... ## #native command name expansion ## fsu<tab> ## #command option name expansion (for fsutil ipconfig net powershell only) ## fsutil <tab> ## ipconfig <tab> ## net <tab> ## powershell <tab> ## #TypeNames expansion ## [Dec<tab> ## [Microsoft.PowerShell.Com<tab> ## New-Object -TypeName IO.Dir<tab> ## New-Object System.Management.Auto<tab> ## #ProgIDs expansion ## New-Object -Com shel<tab> ## #Enum option expansion ## Set-ExecutionPolicy <tab> ## Set-ExecutionPolicy All<tab> ## Set-ExcusionPolisy -ex <tab> ## Get-TraceSourceÅ@Inte<tab> ## iex -Err <tab> -wa Sil<tab> ## #WmiClasses expansion ## Get-WmiObject -class Win32_<tab> ## gwmi __Instance<tab> ## #Encoding expansion ## [Out-File | Export-CSV | Select-String | Export-Clixml] -enc <tab> ## [Add-Content | Get-Content | Set-Content} -Encoding Big<tab> ## #PSProvider name expansion ## [Get-Location | Get-PSDrive | Get-PSProvider | New-PSDrive | Remove-PSDrive] [-PSProvider] <tab> ## Get-PSProvider <tab> ## pwd -psp al<tab> ## #PSDrive name expansion ## [Get-PSDrive | New-PSDrive | Remove-PSDrive] [-Name] <tab> ## Get-PSDrive <tab> ## pwd -psd <tab> ## #PSSnapin name expansion ## [Add-PSSnapin | Get-PSSnapin | Remove-PSSnapin ] [-Name] <tab> ## Get-Command -PSSnapin <tab> ## Remove-PSSnapin <tab> ## Get-PSSnapin M<tab> ## #Eventlog name and expansion ## Get-Eventlog -Log <tab> ## Get-Eventlog w<tab> ## #Eventlog's entrytype expansion ## Get-EventLog -EntryType <tab> ## Get-EventLog -EntryType Er<tab> ## Get-EventLog -Ent <tab> ## #Service name expansion ## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-Name] <tab> ## New-Service -DependsOn <tab> ## New-Service -Dep e<tab> ## Get-Service -n <tab> ## Get-Service <tab>,a<tab>,p<tab> ## gsv <tab> ## #Service display name expansion ## [Get-Service | Restart-Service | Resume-Service | Start-Service | Stop-Service | Suspend-Service] [-DisplayName] <tab> ## Get-Service -Dis <tab> ## gsv -Dis <tab>,w<tab>,b<tab> ## #Cmdlet and Topic name expansion ## Get-Help [-Name] about_<tab> ## Get-Help <tab> ## #Category name expansion ## Get-Help -Category c<tab>,<tab> ## #Command name expansion ## Get-Command [-Name] <tab> ## Get-Command -Name <tab> ## gcm a<tab>,<tab> ## #Scope expansion ## [Clear-Variable | Export-Alias | Get-Alias | Get-PSDrive | Get-Variable | Import-Alias ## New-Alias | New-PSDrive | New-Variable | Remove-Variable | Set-Alias | Set-Variable] -Scope <tab> ## Clear-Variable -Scope G<tab> ## Set-Alias -s <tab> ## #Process name expansion ## [Get-Process | Stop-Process] [-Name] <tab> ## Stop-Process -Name <tab> ## Stop-Process -N pow<tab> ## Get-Process <tab> ## ps power<tab> ## #Trace sources expansion ## [Trace-Command | Get-TraceSource | Set-TraceSource] [-Name] <tab>,a<tab>,p<tab> ## #Trace -ListenerOption expansion ## [Set-TraceSource | Trace-Command] -ListenerOption <tab> ## Set-TraceSource -Lis <tab>,n<tab> ## #Trace -Option expansion ## [Set-TraceSource | Trace-Command] -Option <tab> ## Set-TraceSource -op <tab>,con<tab> ## #ItemType expansion ## New-Item -Item <tab> ## ni -ItemType d<tab> ## #ErrorAction and WarningAction option expansion ## CMDLET [-ErrorAction | -WarningAction] <tab> ## CMDLET -Error s<tab> ## CMDLET -ea con<tab> ## CMDLET -wa <tab> ## #Continuous expansion with comma when parameter can treat multiple option ## # if there are spaces, occur display bug in the line ## # if strings contains '$' or '-', not work ## Get-Command -CommandType <tab>,<tab><tab>,cm<tab> ## pwd -psp <tab>,f<tab>,va<tab> ## Get-EventLog -EntryType <tab>,i<tab>,s<tab> ## #Enum expansion in method call expression ## # this needs one or more spaces after left parenthesis or comma ## $str = "day night" ## $str.Split( " ",<space>rem<tab> ## >>> $str.Split( " ", "RemoveEmptyEntries" ) <Enter> ERROR ## $str.Split( " ", "RemoveEmptyEntries" -as<space><tab> ## >>> $str.Split( " ", "RemoveEmptyEntries" -as [System.StringSplitOptions] ) <Enter> Success ## $type = [System.Type] ## $type.GetMembers(<space>Def<tab> ## [IO.Directory]::GetFiles( "C:\\", "*",<space>All<tab> ## # this can do continuous enum expansion with comma and no spaces ## $type.GetMembers( "IgnoreCase<comma>Dec<tab><comma>In<tab>" ## [IO.Directory]::GetAccessControl( "C:\\",<space>au<tab><comma>ac<tab><comma>G<tab> ### Generate ProgIDs list... if ($_ProgID -eq $null) { $_HKCR = [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\") [Object[]] $_ProgID = $null foreach ( $_subkey in $_HKCR.GetSubKeyNames() ) { foreach ( $_i in [Microsoft.Win32.Registry]::ClassesRoot.OpenSubKey("CLSID\\$_subkey\\ProgID") ) { if ($_i -ne $null) { $_ProgID += $_i.GetValue("") } } } '$_ProgID was updated...' | Out-Host $_ProgID = $_ProgID|sort -Unique Export-Clixml -InputObject $_TypeNames -Path $PSHOME\\ProgIDs.txt Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_ProgID = Import-Clixml -Path C:\\WINDOWS\\system32\\windowspowershell\\v1.0\\ProgIDs.txt;' } ### Generate TypeNames list... if ( $_TypeNames -eq $null ) { [Object[]] $_TypeNames = $null foreach ( $_asm in [AppDomain]::CurrentDomain.GetAssemblies() ) { foreach ( $_type in $_asm.GetTypes() ) { $_TypeNames += $_type.FullName } } '$_TypeNames was updated...' | Out-Host $_TypeNames = $_TypeNames | sort -Unique Export-Clixml -InputObject $_TypeNames -Path $PSHOME\\TypeNames.txt Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_TypeNames = Import-Clixml -Path $PSHOME\\TypeNames.txt;' } if ( $_TypeNames_System -eq $null ) { [Object[]] $_TypeNames_System = $null foreach ( $_type in $_TypeNames -like "System.*" ) { $_TypeNames_System += $_type.Substring(7) } '$_TypeNames_System was updated...' | Out-Host Export-Clixml -InputObject $_TypeNames_System -Path $PSHOME\\TypeNames_System.txt Add-Content -Path $PSHOME\\profile.ps1 -Value ';$_TypeNames_System = Import-Clixml -Path $PSHOME\\TypeNames_System.txt;' } ### Generate WMIClasses list... if ( $_WMIClasses -eq $null ) { [Object[]] $_WMIClasses = $null foreach ( $_class in gwmi -List ) { $_WMIClasses += $_class.Name } $_WMIClasses = $_WMIClasses | sort -Unique '$_WMIClasses was updated...' | Out-Host Set-Content -Value $_WMIClasses -Path $PSHOME\\WMIClasses.txt } $global:_snapin = $null function TabExpansion { # This is the default function to use for tab expansion. It handles simple # member expansion on variables, variable name expansion and parameter completion # on commands. It doesn't understand strings so strings containing ; | ( or { may # cause expansion to fail. param($line, $lastWord) & { # Helper function to write out the matching set of members. It depends # on dynamic scoping to get $_base, _$expression and $_pat function Write-Members ($sep='.') { # evaluate the expression to get the object to examine... Invoke-Expression ('$_val=' + $_expression) $_method = [Management.Automation.PSMemberTypes] ` 'Method,CodeMethod,ScriptMethod,ParameterizedProperty' if ($sep -eq '.') { $members = ( [Object[]](Get-Member -InputObject $_val.PSextended $_pat) + [Object[]](Get-Member -InputObject $_val.PSadapted $_pat) + [Object[]](Get-Member -InputObject $_val.PSbase $_pat) ) | sort MemberType,Name -Unique foreach ($_m in $members) { if ($_m.MemberType -band $_method) { # Return a method... $_base + $_expression + $sep + $_m.name + '(' } else { # Return a property... $_base + $_expression + $sep + $_m.name } } } else { foreach ($_m in Get-Member -Static -InputObject $_val $_pat | Sort-Object membertype,name) { if ($_m.MemberType -band $_method) { # Return a method... $_base + $_expression + $sep + $_m.name + '(' } else { # Return a property... $_base + $_expression + $sep + $_m.name } } } } switch -regex ($lastWord) { # Handle property and method expansion rooted at variables... # e.g. $a.b.<tab> '(^.*)(\\$(\\w|\\.)+)\\.(\\w*)$' { $_base = $matches[1] $_expression = $matches[2] [void] ( iex "$_expression.IsDataLanguageOnly" ) # for [ScriptBlock] $_pat = $matches[4] + '*' Write-Members break; } # Handle simple property and method expansion on static members... # e.g. [datetime]::n<tab> '(^.*)(\\[(\\w|\\.)+\\])\\:\\:(\\w*)$' { $_base = $matches[1] $_expression = $matches[2] $_pat = $matches[4] + '*' Write-Members '::' break; } # Handle complex property and method expansion on static members # where there are intermediate properties... # e.g. [datetime]::now.d<tab> '(^.*)(\\[(\\w|\\.)+\\]\\:\\:(\\w+\\.)+)(\\w*)$' { $_base = $matches[1] # everything before the expression $_expression = $matches[2].TrimEnd('.') # expression less trailing '.' $_pat = $matches[5] + '*' # the member to look for... Write-Members break; } # Handle variable name expansion... '(^.*\\$)(\\w+)$' { $_prefix = $matches[1] $_varName = $matches[2] foreach ($_v in Get-ChildItem ('variable:' + $_varName + '*')) { $_prefix + $_v.name } break; } # Handle env&function drives variable name expansion... '(^.*\\$)(.*\\:)(\\w+)$' { $_prefix = $matches[1] $_drive = $matches[2] $_varName = $matches[3] if ($_drive -eq "env:" -or $_drive -eq "function:") { foreach ($_v in Get-ChildItem ($_drive + $_varName + '*')) { $_prefix + $_drive + $_v.name } } break; } # Handle array's element property and method expansion... # e.g. foo[0].a<tab> '(^.*)(\\$(\\w|\\.)+\\[(\\w|\\.)+\\])\\.(\\w*)$' { $_base = $matches[1] $_expression = $matches[2] $_pat = $Matches[$matches.Count-1] + '*' Write-Members break; } # Handle array's element property and method expansion # where there are intermediate properties... # e.g. foo[0].n.b<tab> '(^.*)((\\$(\\w|\\.)+\\[(\\w|\\.)+\\])\\.(\\w+\\.)+)(\\w*)$' { $_base = $matches[1] $_expression = $matches[2].TrimEnd('.') $_pat = $Matches[$matches.Count-1] + '*' Write-Members break; } # Handle property and method expansion rooted at type object... # e.g. [System.Type].a<tab> '(^\\[(\\w|\\.)+\\])\\.(\\w*)$' { if ( $(iex $Matches[1]) -isnot [System.Type] ) { break; } $_expression = $Matches[1] $_pat = $Matches[$matches.Count-1] + '*' Write-Members break; } # Handle complex property and method expansion on type object members # where there are intermediate properties... # e.g. [datetime].Assembly.a<tab> '^(\\[(\\w|\\.)+\\]\\.(\\w+\\.)+)(\\w*)$' { $_expression = $matches[1].TrimEnd('.') # expression less trailing '.' $_pat = $matches[4] + '*' # the member to look for... if ( $(iex $_expression) -eq $null ) { break; } Write-Members break; } # Handle property and method expansion rooted at close parenthes... # e.g. (123).a<tab> '^(.*)\\)((\\w|\\.)*)\\.(\\w*)$' { $_base = $Matches[1] + ")" if ( $matches[3] -eq $null) { $_expression = '[System.Type]' } else { $_expression = '[System.Type]' + $Matches[2] } $_pat = $matches[4] + '*' iex "$_expression | Get-Member $_pat | sort MemberType,Name" | % { if ( $_.MemberType -like "*Method*" -or $_.MemberType -like "*Parameterized*" ) { $parenthes = "(" } if ( $Matches[2] -eq "" ) { $_base + "." + $_.Name + $parenthes } else { $_base + $Matches[2] + "." + $_.Name + $parenthes } } break; } # Handle .NET type name expansion ... # e.g. [Microsoft.PowerShell.Com<tab> '^\\[((\\w+\\.?)+)$' { $_opt = $matches[1] + '*' foreach ( $_exp in $_TypeNames_System -like $_opt ) { '[' + $_exp } foreach ( $_exp in $_TypeNames -like $_opt ) { '[' + $_exp } break; } # Do completion on parameters... '^-([\\w0-9]*)' { $_pat = $matches[1] + '*' # extract the command name from the string # first split the string into statements and pipeline elements # This doesn't handle strings however. $_cmdlet = [regex]::Split($line, '[|;=]')[-1] # Extract the trailing unclosed block e.g. ls | foreach { cp if ($_cmdlet -match '\\{([^\\{\\}]*)$') { $_cmdlet = $matches[1] } # Extract the longest unclosed parenthetical expression... if ($_cmdlet -match '\\(([^()]*)$') { $_cmdlet = $matches[1] } # take the first space separated token of the remaining string # as the command to look up. Trim any leading or trailing spaces # so you don't get leading empty elements. $_cmdlet = $_cmdlet.Trim().Split()[0] # now get the info object for it... $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0] } # expand the parameter sets and emit the matching elements foreach ($_n in $_cmdlet.ParameterSets | Select-Object -expand parameters | Sort-Object -Unique name) { $_n = $_n.name if ($_n -like $_pat) { '-' + $_n } } break; } # try to find a matching command... default { $lastex = [regex]::Split($line, '[|;=]')[-1] if ($lastex -match '[[$].*\\w+\\([^)]*-as\\s*$') { '['+ $global:_enum + ']' } elseif ( $lastex -match '([[$].*(\\w+))\\(([^)]*)$' ) { $_method = $Matches[1] if ( $Matches[3] -match "(.*)((`"|')(\\w+,)+(\\w*))$" ) { $continuous = $true $_opt = $Matches[5] + '*' $_base = $Matches[2].TrimStart('"') -replace '(.*,)\\w+$','$1' $position = $Matches[1].Split(",").Length } else { $continuous = $false $_opt = ($Matches[3].Split(',')[-1] -replace '^\\s*','') + "*" $position = $Matches[3].Split(",").Length } foreach ( $def in iex ($_method + ".OverloadDefinitions") ) { [void] ($def -match '\\((.*)\\)') foreach ( $param in [regex]::Split($Matches[1], ', ')[$position-1] ) { if ($param -eq $null -or $param -eq "") { continue; } $type = $param.split()[0] if ( $type -like '*`[*' -or $type -eq "Params" -or $type -eq "" ) { continue; } $fullname = @($_typenames -like "*$type*") foreach ( $name in $fullname ) { if ( $continuous -eq $true -and ( $name -as [System.Type] ).IsEnum ) { $output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$',($_base + '$1') $output | sort } elseif ( ( $name -as [System.Type] ).IsEnum ) { $global:_enum = $name $output = [Enum]::GetValues($name) -like $_opt -replace '^(.*)$','"$1"' $output | sort } } } } if ( $output -ne $null ) { break; } } if ( $line[-1] -eq " " ) { $_cmdlet = $line.TrimEnd(" ").Split()[-1] # now get the info object for it... $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0] } if ( "Set-ExecutionPolicy" -eq $_cmdlet.Name ) { "Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" | sort break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ) { Get-TraceSource | % { $_.Name } | sort -Unique break; } if ( "New-Object" -eq $_cmdlet.Name ) { $_TypeNames_System $_TypeNames break; } if ( $_cmdlet.Noun -like "*WMI*" ) { $_WMIClasses break; } if ( "Get-Process" -eq $_cmdlet.Name ) { Get-Process | % { $_.Name } | sort break; } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name ) { if ( $global:_snapin -ne $null ) { $global:_snapin break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin break; } } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" ) { Get-PSDrive | sort break; } if ( "Get-Eventlog" -eq $_cmdlet.Name ) { Get-EventLog -List | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name ) { Get-Help -Category all | % { $_.Name } | sort -Unique break; } if ( "Get-Service", "Restart-Service", "Resume-Service", "Start-Service", "Stop-Service", "Suspend-Service" ` -contains $_cmdlet.Name ) { Get-Service | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name ) { Get-Command -CommandType All | % { $_base + ($_.Name -replace '\\s','` ') } break; } } if ( $line[-1] -eq " " ) { # extract the command name from the string # first split the string into statements and pipeline elements # This doesn't handle strings however. $_cmdlet = [regex]::Split($line, '[|;=]')[-1] # Extract the trailing unclosed block e.g. ls | foreach { cp if ($_cmdlet -match '\\{([^\\{\\}]*)$') { $_cmdlet = $matches[1] } # Extract the longest unclosed parenthetical expression... if ($_cmdlet -match '\\(([^()]*)$') { $_cmdlet = $matches[1] } # take the first space separated token of the remaining string # as the command to look up. Trim any leading or trailing spaces # so you don't get leading empty elements. $_cmdlet = $_cmdlet.Trim().Split()[0] # now get the info object for it... $_cmdlet = @(Get-Command -type 'Application' $_cmdlet)[0] if ( $_cmdlet.Name -eq "powershell.exe" ) { "-PSConsoleFile", "-Version", "-NoLogo", "-NoExit", "-Sta", "-NoProfile", "-NonInteractive", "-InputFormat", "-OutputFormat", "-EncodedCommand", "-File", "-Command" | sort break; } if ( $_cmdlet.Name -eq "fsutil.exe" ) { "behavior query", "behavior set", "dirty query", "dirty set", "file findbysid", "file queryallocranges", "file setshortname", "file setvaliddata", "file setzerodata", "file createnew", "fsinfo drives", "fsinfo drivetype", "fsinfo volumeinfo", "fsinfo ntfsinfo", "fsinfo statistics", "hardlink create", "objectid query", "objectid set", "objectid delete", "objectid create", "quota disable", "quota track", "quota enforce", "quota violations", "quota modify", "quota query", "reparsepoint query", "reparsepoint delete", "sparse setflag", "sparse queryflag", "sparse queryrange", "sparse setrange", "usn createjournal", "usn deletejournal", "usn enumdata", "usn queryjournal", "usn readdata", "volume dismount", "volume diskfree" | sort break; } if ( $_cmdlet.Name -eq "net.exe" ) { "ACCOUNTS ", " COMPUTER ", " CONFIG ", " CONTINUE ", " FILE ", " GROUP ", " HELP ", "HELPMSG ", " LOCALGROUP ", " NAME ", " PAUSE ", " PRINT ", " SEND ", " SESSION ", "SHARE ", " START ", " STATISTICS ", " STOP ", " TIME ", " USE ", " USER ", " VIEW" | sort break; } if ( $_cmdlet.Name -eq "ipconfig.exe" ) { "/?", "/all", "/renew", "/release", "/flushdns", "/displaydns", "/registerdns", "/showclassid", "/setclassid" break; } } if ( $line -match '\\s+(\\w+(\\.|[^\\s\\.])*)$' ) { #$_opt = $Matches[1] + '*' $_cmdlet = $line.TrimEnd(" ").Split()[-2] $_opt = $Matches[1].Split(" ,")[-1] + '*' $_base = $Matches[1].Substring(0,$Matches[1].Length-$Matches[1].Split(" ,")[-1].length) # now get the info object for it... $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0] } if ( "Set-ExecutionPolicy" -eq $_cmdlet.Name ) { "Unrestricted", "RemoteSigned", "AllSigned", "Restricted", "Default" -like $_opt | sort break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ) { Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "New-Object" -eq $_cmdlet.Name ) { $_TypeNames_System -like $_opt $_TypeNames -like $_opt break; } if ( $_cmdlet.Name -like "*WMI*" ) { $_WMIClasses -like $_opt break; } if ( "Get-Process" -eq $_cmdlet.Name ) { Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" -contains $_cmdlet.Name ) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-PSProvider" -eq $_cmdlet.Name ) { Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Eventlog" -eq $_cmdlet.Name ) { Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name ) { Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique break; } if ( "Get-Service", "Restart-Service", "Resume-Service", "Start-Service", "Stop-Service", "Suspend-Service" ` -contains $_cmdlet.Name ) { Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name ) { Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') } break; } } if ( $line -match '(-(\\w+))\\s+([^-]*$)' ) { $_param = $matches[2] + '*' $_opt = $Matches[3].Split(" ,")[-1] + '*' $_base = $Matches[3].Substring(0,$Matches[3].Length-$Matches[3].Split(" ,")[-1].length) #$_opt = ($Matches[3] -replace '(^.*\\s*,?\\s*)\\w*$','$1') + '*' # extract the command name from the string # first split the string into statements and pipeline elements # This doesn't handle strings however. $_cmdlet = [regex]::Split($line, '[|;=]')[-1] # Extract the trailing unclosed block e.g. ls | foreach { cp if ($_cmdlet -match '\\{([^\\{\\}]*)$') { $_cmdlet = $matches[1] } # Extract the longest unclosed parenthetical expression... if ($_cmdlet -match '\\(([^()]*)$') { $_cmdlet = $matches[1] } # take the first space separated token of the remaining string # as the command to look up. Trim any leading or trailing spaces # so you don't get leading empty elements. $_cmdlet = $_cmdlet.Trim().Split()[0] # now get the info object for it... $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet)[0] # loop resolving aliases... while ($_cmdlet.CommandType -eq 'alias') { $_cmdlet = @(Get-Command -type 'cmdlet,alias' $_cmdlet.Definition)[0] } if ( $_param.TrimEnd("*") -eq "ea" -or $_param.TrimEnd("*") -eq "wa" ) { "SilentlyContinue", "Stop", "Continue", "Inquire" | ? { $_ -like $_opt } | sort -Unique break; } if ( "Out-File","Export-CSV","Select-String","Export-Clixml" -contains $_cmdlet.Name ` -and "Encoding" -like $_param) { "Unicode", "UTF7", "UTF8", "ASCII", "UTF32", "BigEndianUnicode", "Default", "OEM" | ? { $_ -like $_opt } | sort -Unique break; } if ( "Trace-Command","Get-TraceSource","Set-TraceSource" -contains $_cmdlet.Name ` -and "Name" -like $_param) { Get-TraceSource -Name $_opt | % { $_.Name } | sort -Unique | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "New-Object" -like $_cmdlet.Name ) { if ( "ComObject" -like $_param ) { $_ProgID -like $_opt | % { $_ -replace '\\s','` ' } break; } if ( "TypeName" -like $_param ) { $_TypeNames_System -like $_opt $_TypeNames -like $_opt break; } } if ( "New-Item" -eq $_cmdlet.Name ) { if ( "ItemType" -like $_param ) { "directory", "file" -like $_opt break; } } if ( "Get-Location", "Get-PSDrive", "Get-PSProvider", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name ` -and "PSProvider" -like $_param ) { Get-PSProvider -PSProvider $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Location" -eq $_cmdlet.Name -and "PSDrive" -like $_param ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-PSDrive", "New-PSDrive", "Remove-PSDrive" ` -contains $_cmdlet.Name -and "Name" -like $_param ) { Get-PSDrive -Name $_opt | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Command" -eq $_cmdlet.Name -and "PSSnapin" -like $_param) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + $_ } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } } if ( "Add-PSSnapin", "Get-PSSnapin", "Remove-PSSnapin" ` -contains $_cmdlet.Name -and "Name" -like $_param ) { if ( $global:_snapin -ne $null ) { $global:_snapin -like $_opt | % { $_base + ($_ -replace '\\s','` ') } break; } else { $global:_snapin = $(Get-PSSnapIn -Registered;Get-PSSnapIn)| sort Name -Unique; $global:_snapin -like $_opt | % { $_base + $_ } break; } } if ( "Clear-Variable", "Export-Alias", "Get-Alias", "Get-PSDrive", "Get-Variable", "Import-Alias", " New-Alias", "New-PSDrive", "New-Variable", "Remove-Variable", "Set-Alias", "Set-Variable" ` -contains $_cmdlet.Name -and "Scope" -like $_param ) { "Global", "Local", "Script" -like $_opt break; } if ( "Get-Process", "Stop-Process", "Wait-Process" -contains $_cmdlet.Name -and "Name" -like $_param ) { Get-Process $_opt | % { $_.Name } | sort | % { $_base + ($_ -replace '\\s','` ') } break; } if ( "Get-Eventlog" -eq $_cmdlet.Name -and "LogName" -like $_param ) { Get-EventLog -List | ? { $_.Log -like $_opt } | % { $_base + ($_.Log -replace '\\s','` ') } break; } if ( "Get-Help" -eq $_cmdlet.Name ) { if ( "Name" -like $_param ) { Get-Help -Category all -Name $_opt | % { $_.Name } | sort -Unique break; } if ( "Category" -like $_param ) { "Alias", "Cmdlet", "Provider", "General", "FAQ", "Glossary", "HelpFile", "All" -like $_opt | sort | % { $_base + $_ } break; } } if ( "Get-Service", "Restart-Service", "Resume-Service", "Start-Service", "Stop-Service", "Suspend-Service" ` -contains $_cmdlet.Name ) { if ( "Name" -like $_param ) { Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "DisplayName" -like $_param ) { Get-Service -Name $_opt | sort DisplayName | % { $_base + ($_.DisplayName -replace '\\s','` ') } break; } } if ( "New-Service" -eq $_cmdlet.Name -and "dependsOn" -like $_param ) { Get-Service -Name $_opt | sort Name | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( "Get-EventLog" -eq $_cmdlet.Name -and "EntryType" -like $_param ) { "Error", "Information", "FailureAudit", "SuccessAudit", "Warning" -like $_opt | sort | % { $_base + $_ } break; } if ( "Get-Command" -eq $_cmdlet.Name -and "Name" -like $_param ) { Get-Command -CommandType All -Name $_opt | % { $_base + ($_.Name -replace '\\s','` ') } break; } if ( $_cmdlet.Noun -like "*WMI*" ) { if ( "Class" -like $_param ) { $_WMIClasses -like $_opt break; } } select -InputObject $_cmdlet -ExpandProperty ParameterSets | select -ExpandProperty Parameters | ? { $_.Name -like $_param } | ? { $_.ParameterType.IsEnum } | % { [Enum]::GetNames($_.ParameterType) } | ? { $_ -like $_opt } | sort -Unique | % { $_base + $_ } } if ( $line[-1] -match "\\s" ) { break; } if ( $lastWord -ne $null -and $lastWord.IndexOfAny('/\\') -eq -1 ) { $command = $lastWord $pattern = $command + "*" gcm -Name $pattern -CommandType All | % { $_.Name } | sort -Unique } } } } }
PowerShellCorpus/PoshCode/_CTP3_ Invoke-ISE_1.ps1
_CTP3_ Invoke-ISE_1.ps1
Set-Alias ISE Invoke-ISE function Invoke-ISE () <# .SYNOPSIS start ISE from the PS-commandline .DESCRIPTION start ISE provide files as parameters or per pipe-line .NOTES Author : Bernd Kriszio - http://pauerschell.blogspot.com/ Requires : PowerShell V2 CTP3 .EXAMPLE Invoke-ISE $foo.ps1 .EXAMPLE Invoke-ISE foo.ps1 foobar.ps1 .EXAMPLE Invoke-ISE 'foo.ps1' 'foobar.ps1' .EXAMPLE get-childitem f*.ps1 | Invoke-ISE .EXAMPLE Invoke-ISE (dir f*.ps1) .EXAMPLE 'foo.ps1' | Invoke-ISE .EXAMPLE Invoke-ISE .LINK http://tfl09.blogspot.com/2009/01/parameter-attributes-in-powershell-v2.html http://blogs.microsoft.co.il/blogs/scriptfanatic/archive/2008/12/30/windows-powershell-integrated-scripting-environment-ise.aspx #> { param ( [Parameter(Position = 0, Mandatory=$false, ValueFromPipeline=$True, ValueFromRemainingArguments = $true)] [string[]]$file ) begin { $path="$pshome\\powershell_ise.exe" if ($file -eq $null){ & $path } } PROCESS { foreach($f in $file){ # note the comment of Mark Schill # & $path (resolve-path $f) # http://blogs.microsoft.co.il/blogs/scriptfanatic/archive/2008/12/30/windows-powershell-integrated-scripting-environment-ise.aspx#comments & $path ( ([system.IO.FileInfo]$f).FullName) } } }
PowerShellCorpus/PoshCode/SharePoint UserID grab_1.ps1
SharePoint UserID grab_1.ps1
## .\\SharePoint_Users_Read.ps1 "http://some.urlname.com/" "User Information List" "" ## .\\SharePoint_Users_Read.ps1 "http://some.urlname.com/" "User Information List" "user, someone" param( [string] $rqurdstrPath = $(Throw "--SharePoint Core Path required."), #required parameter [string] $rqurdstrListName = $(Throw "--SharePoint List Name required."), #required parameter [string] $strTargetUser = "" #non-required user name for ID Return ) Write-Host "Beginning Processing--`n" ## Global Variables ## $strUserIDReturn = "" write-host "rqurdstrPath: $rqurdstrPath " write-host "rqurdstrListName: $rqurdstrListName " ## Load SharePoint .NET Libraries ## [void][System.reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") $site = new-object Microsoft.SharePoint.SPSite($rqurdstrPath) $userlist = $site.RootWeb.Lists[$rqurdstrListName] write-host "site: $site " write-host "userlist: $userlist`n" # Print the ID and Title of each list item #$userlist.Items | Format-List -property ID, Title if($strTargetUser -eq "") { Write-Host "--Displaying all Portal Users" foreach($strItem in $userlist.Items) { [string]$strItem.ID + "--"+$strItem.Title } } else { write-host "--Targeting specific user to return ID" $intUserIDReturn = -1 foreach($strItem in $userlist.Items) { $intUserID=[int]$strItem.ID $strUserName=$strItem.Title if($strUserName -eq $strTargetUser) { $intUserIDReturn = $intUserID break; } } $intUserIDReturn } ## NOTE: don't forget to dispose your .NET objects! ## $site.RootWeb.Dispose() $site.Dispose() ## End Processing ## Write-Host "`nEnd Processing--`n"
PowerShellCorpus/PoshCode/Creating Bulk users.ps1
Creating Bulk users.ps1
The final.csv file is the name of file which i created and its located on the desktop of the window server. after running the script i received this error Import-Csv : Cannot open file "C:\\Users\\Administrator\\final.csv". At line:1 char:23 + $Password = Import-Csv <<<< final.csv| foreach { New-Mailbox -alias $_.Alias -name $_.Name -Database "mailbox database" -OrganizationalUnit Users -Password $Password -ResetPasswordOnNe + CategoryInfo : OpenError: (:) [Import-Csv], FileNotFoundException + FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.ImportCsvCommand
PowerShellCorpus/PoshCode/Check Modules path..ps1
Check Modules path..ps1
function Update-ModulePath { <# .Synopsis Command insures that path and the name of psm1 file are alike. .Description This function should help to troubleshoot modules. It loooks up path that should contain modules. For each .psm1 file found it checks if parent folder containing this file has same name. I created this function after I was banging my head for few hours why my module won't show up. After several approaches it came out clear that it was simple TYPO in file.psm1 name... .Example Update-ModulePath -Fix Files Will look all files and rename .psm1 files to match parent folder .Example Update-ModulePath -Fix Folder Will look all files and rename parent folder to match file names .Parameter Fix Switch to decide if we prefer to name folders or files to get all matches. #> [CmdletBinding()] param( [Parameter(Mandatory=$true)] [ValidateSet("Files","Folders")] [string]$Fix ) <# Steps to be taken: * enumerate all .psm1 files * check which one is misconfigured * rename file/ folder to fix this issue #> ForEach ($ModuleFile in @(Get-ChildItem -Recurse @($($env:PSModulePath).Split(";")) -filter *.psm1)) { if (($file = $ModuleFile.BaseName) -eq ($folder = $ModuleFile.Directory.ToString().Split('\\')[-1])) { Write-Verbose "$Modulefile.Name is fine" } else { Write-Verbose "$ModuleFile.Name is BAD" switch ($Fix) { "Files" { Write-Verbose "We rename file $file" $OldName = $ModuleFile.FullName $NewName = $OldName -replace "$file.psm1$", "$folder.psm1" } "Folders" { Write-Verbose "We rename folder $folder" $OldName = $ModuleFile.FullName -replace "\\\\$file.psm1", "" $NewName = $OldName -replace "$folder$", $file } } Write-Host "Renaming $OldName to $NewName" Rename-Item -Force $OldName $NewName } } }
PowerShellCorpus/PoshCode/Get-VMHostVersions.ps1
Get-VMHostVersions.ps1
#======================================================================== # Created on: 5/17/2012 2:03 PM # Created by: Clint Jones # Organization: Virtually Genius! # Filename: Get-VMHostVersions #======================================================================== #Import modules Add-PSSnapin "Vmware.VimAutomation.Core" #Path to the log files $log = "C:\\Scripts\\VMware\\Logs\\hostversions.txt" #Creates directory structure for log files $pathverif = Test-Path -Path c:\\scripts\\vmware\\logs switch ($pathverif) { True {} False {New-Item "c:\\scripts\\vmware\\logs" -ItemType directory} default {Write-Host "An error has occured when checking the file structure"} } #Connect to VMware servers $viserver = Read-Host "Enter VMware server:" $creds = Get-Credential Connect-ViServer -Server $viserver -Credential $creds #Get the version number of the host Get-VMHost | Select-Object Name, Version | Format-Table -AutoSize | Out-File -FilePath $log -Append
PowerShellCorpus/PoshCode/DHCP Failover Script.ps1
DHCP Failover Script.ps1
:: Purpose: DHCP server Watchdog & Failover script. Read notes below :: Requirements: 1. Domain administrator credentials & "Logon as a batch job" rights :: 2. Proper firewall configuration to allow connection :: 3. Proper permissions on the DHCP backup directory :: Author: vocatus :: Version: 1.1b - Changed DATE to CUR_DATE format to be consistent with all other scripts :: 1.1 - Comments work :: - Tuned some parameters (ping count on checking) :: - Some logging tweaks :: - Renamed FAILOVER_DELAY to FAILOVER_RECHECK_DELAY for clarity :: 1.0d Some logging tweaks :: 1.0c Some logging tweaks :: 1.0 Initial write :: Notes: I wrote this script after failing to find a satisfactory method of performing :: watchdog/failover between two Windows Server 2008 R2 DHCP servers. :: :: Use: This script has two modes: "Watchdog" and "Failover." :: - Watchdog checks the status of the remote DHCP service, logs it, and then grabs the remote DHCP db backup file and imports it. :: - Failover mode is activated when the script cannot determine the status of the remote DHCP server. The script then activates :: the local DHCP server with the latest backup copy it successfully retrieved from the primary server. :: :: Instructions: :: 1. Tune the variables in this script to your desired backup location and frequency :: 2. On the primary server: set the DHCP backup interval to your desired backup frequency. The value is in minutes; I recommend 5 minutes. :: You do this by modifying this registry key: HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\DHCPServer\\Parameters\\BackupInterval :: 3. On the backup server: set this script to run as a scheduled task. I recommend every 10 minutes. :: Notice: :: !! Make sure to set it only to run if it isn't already running! If there is a failover you could have :: Task Scheduler spawn a new instance of the script every n minutes and end up with hundreds of copies :: of this script running. :: Prep SETLOCAL @echo off cls set VERSION=1.1b title [DHCP Server Watchdog v%VERSION%] ::::::::::::::: :: Variables :: - Set these. Do not use trailing slashes (\\) in directory names (this is important!). ::::::::::::::: :: Remote server is the PRIMARY DHCP server we're watching. Use a hostname or IP address. set REMOTE_SERVER=mikado :: Location of the DHCP backup on the primary server :: Best practice is to leave this alone, unless you have a custom backup location. :: The script builds the backup line like this: \\\\%REMOTE_SERVER%\\c$\\%REMOTE_BACKUP_PATH% set REMOTE_BACKUP_PATH=Windows\\system32\\dhcp\\backup :: Location of your backup/standby file. I normally copy directly to my backup server's DHCP directory. :: The script builds the local backup line like this: c:\\windows\\system32\\dhcp\\[backup folders] set LOCAL_BACKUP_PATH=%SystemRoot%\\system32\\dhcp :: When a failover is triggered, how many seconds should we wait in between each attempt to contact the primary server again? set FAILOVER_RECHECK_DELAY=15 :: Log options. Don't put an extension on the log file name. (Important!) The script sets this later on. set LOGPATH=%SystemDrive%\\Logs set LOGFILE=%COMPUTERNAME%_DHCP_watchdog :: Max log file size allowed (in bytes) before rotation and archive. I recommend setting this to 2 MB (2097152). :: Example: 524288 is half a megabyte (~500KB) set LOG_MAX_SIZE=2097152 :: \\/ Don't touch anything below this line. If you do, you will break something. set CUR_DATE=%DATE:~-4%-%DATE:~4,2%-%DATE:~7,2% ::::::::::::::::::::::: :: LOG FILE HANDLING :: - This section handles the log file ::::::::::::::::::::::: :: Make the logfile if it doesn't exist if not exist %LOGPATH% mkdir %LOGPATH% if not exist %LOGPATH%\\%LOGFILE%.log goto new_log :: Check log size. If it hasn't exceeded our size limit, jump straight to Watchdog mode for %%R in (%LOGPATH%\\%LOGFILE%.log) do if %%~zR LSS %LOG_MAX_SIZE% goto newrun :: However, if the log was too big, go ahead and rotate it. pushd %LOGPATH% del %LOGFILE%.ancient 2>NUL rename %LOGFILE%.oldest %LOGFILE%.ancient 2>NUL rename %LOGFILE%.older %LOGFILE%.oldest 2>NUL rename %LOGFILE%.old %LOGFILE%.older 2>NUL rename %LOGFILE%.log %LOGFILE%.old 2>NUL popd :: And then create the header for the new log file :new_log echo ------------------------------------------------------------------------------------->> %LOGPATH%\\%LOGFILE%.log 2>&1 echo Initializing new DHCP Server Watchdog log on %CUR_DATE% at %TIME%, max log size %LOG_MAX_SIZE% bytes>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo ------------------------------------------------------------------------------------->> %LOGPATH%\\%LOGFILE%.log 2>&1 echo.>> %LOGPATH%\\%LOGFILE%.log 2>&1 :: New run section - if we just launched the script, write a header for this run :newrun echo ------------------------------------------------------------------------------------->> %LOGPATH%\\%LOGFILE%.log 2>&1 echo DHCP Server Watchdog v%VERSION%, %CUR_DATE%>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo Running as %USERDOMAIN%\\%USERNAME% on %COMPUTERNAME%>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo.>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo Job Options>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo Log location: %LOGPATH%\\%LOGFILE%.log>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo Log max size: %LOG_MAX_SIZE% bytes>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo Watching primary server: %REMOTE_SERVER%>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo Mirroring this DHCP db: %REMOTE_BACKUP_PATH%>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo Local backup location: %LOCAL_BACKUP_PATH%>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo ------------------------------------------------------------------------------------->> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% Starting Watchdog mode.>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo. echo DHCP Server Watchdog v%VERSION% echo Running as: %USERDOMAIN%\\%USERNAME% on %COMPUTERNAME% echo Log: %LOGPATH%\\%LOGFILE%.log ::::::::::::::::::: :: WATCHDOG MODE :: ::::::::::::::::::: :watchdog :: Ping the server to see if it's up echo. echo Verifying proper operation of DHCP server on %REMOTE_SERVER%, please wait... echo. echo %TIME% Pinging %REMOTE_SERVER%...>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% Pinging %REMOTE_SERVER%... ping %REMOTE_SERVER% -n 2 >NUL 2>&1 if %ERRORLEVEL%==1 echo %TIME% WARNING %REMOTE_SERVER% failed to respond to ping. && echo %TIME% WARNING %REMOTE_SERVER% failed to respond to ping.>> %LOGPATH%\\%LOGFILE%.log 2>&1 if not %ERRORLEVEL%==1 echo %TIME% SUCCESS %REMOTE_SERVER% responded to ping. && echo %TIME% SUCCESS %REMOTE_SERVER% responded to ping.>> %LOGPATH%\\%LOGFILE%.log 2>&1 :: Check & Log echo %TIME% Checking DHCP server status on %REMOTE_SERVER%...>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% Checking DHCP server status on %REMOTE_SERVER%... :: Reset ERRORLEVEL back to 0 ver > NUL :: Use "SC" to check the status of "Dhcpserver" service, find the "RUNNING" state, and act accordingly based on the return code sc \\\\%REMOTE_SERVER% query Dhcpserver | find "RUNNING" >NUL 2>&1 if %ERRORLEVEL%==0 echo %TIME% SUCCESS The DHCP service is running on %REMOTE_SERVER%.>> %LOGPATH%\\%LOGFILE%.log 2>&1 if %ERRORLEVEL%==0 echo %TIME% SUCCESS The DHCP service is running on %REMOTE_SERVER%. :: This section only executes if the test failed. if not %ERRORLEVEL%==0 ( echo %TIME% FAILURE The DHCP service is not running on %REMOTE_SERVER%.>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% Activating failover procedure. Local DHCP server will be initialized using most recent successful backup.>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% FAILURE The DHCP service is not running on %REMOTE_SERVER%. echo %TIME% Activating failover procedure. Local DHCP server will be initialized using most recent successful backup. goto failover ) :: Reset ERRORLEVEL back to 0 ver > NUL :: Fetch echo %TIME% Fetching DHCP database backup from %REMOTE_SERVER%...>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% Fetching DHCP database backup from %REMOTE_SERVER%... xcopy \\\\%REMOTE_SERVER%\\c$\\%REMOTE_BACKUP_PATH%\\* %LOCAL_BACKUP_PATH%\\backup_new_pending\\ /E /Y /Q >NUL :: If the copy SUCCEEDED, this executes if %ERRORLEVEL%==0 ( echo %TIME% SUCCESS Backup fetched from %REMOTE_SERVER%.>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% SUCCESS Backup fetched from %REMOTE_SERVER%. echo %TIME% Rotating database backups...>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% Rotating database backups... :: Rotate backups and use newest copy rmdir /S /Q %LOCAL_BACKUP_PATH%\\backup5 if exist %LOCAL_BACKUP_PATH%\\backup4 move /Y %LOCAL_BACKUP_PATH%\\backup4 %LOCAL_BACKUP_PATH%\\backup5 2>&1 if exist %LOCAL_BACKUP_PATH%\\backup3 move /Y %LOCAL_BACKUP_PATH%\\backup3 %LOCAL_BACKUP_PATH%\\backup4 2>&1 if exist %LOCAL_BACKUP_PATH%\\backup2 move /Y %LOCAL_BACKUP_PATH%\\backup2 %LOCAL_BACKUP_PATH%\\backup3 2>&1 if exist %LOCAL_BACKUP_PATH%\\backup move /Y %LOCAL_BACKUP_PATH%\\backup %LOCAL_BACKUP_PATH%\\backup2 2>&1 move /Y %LOCAL_BACKUP_PATH%\\backup_new_pending %LOCAL_BACKUP_PATH%\\backup >NUL echo %TIME% Database backups rotated.>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% Database backups rotated. ) :: If the copy FAILED, this executes: if not %ERRORLEVEL%==0 ( echo %TIME% WARNING There was an error copying the backup from %REMOTE_SERVER%.>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% You may want to look into this since we were able to check the DHCPserver service status but the file copy failed.>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% Skipping new database import due to copy failure.>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% Job complete with errors.>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% WARNING There was an error copying the backup from %REMOTE_SERVER%. echo %TIME% You may want to look into this since we were able to check the DHCPserver service status but the file copy failed. echo %TIME% Skipping new database import due to copy failure. echo %TIME% Job complete with errors. ) :: Import database ver > NUL echo %TIME% Starting local DHCP server to import new database...>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% Starting local DHCP server to import new database... net start Dhcpserver 2>&1 echo %TIME% Local DHCP server running. Performing import...>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% Local DHCP server running. Performing import... netsh dhcp server restore %LOCAL_BACKUP_PATH%\\backup echo %TIME% Import complete.>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% Import complete. echo %TIME% Stopping local DHCP server...>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% Stopping local DHCP server... net stop Dhcpserver 2>&1 echo %TIME% Local DHCP server stopped.>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% Local DHCP server stopped. echo %TIME% SUCCESS Job complete, DHCP database backed up and ready for use. Exiting.>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% SUCCESS Job complete, DHCP database backed up and ready for use. Exiting. goto EOF ::::::::::::::::::: :: FAILOVER MODE :: ::::::::::::::::::: :failover :: Log this AND display to console echo %TIME% WARNING Failover activated.>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% Starting local DHCP server using most recent successful backup...>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo. echo %TIME% WARNING Could not contact primary DHCP server "%REMOTE_SERVER%." Failover activated. echo %TIME% Starting local DHCP server using most recent successful backup... echo. net start Dhcpserver echo %TIME% Local DHCP server started.>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% Entering monitoring loop. Checking if %REMOTE_SERVER% is back up every %FAILOVER_RECHECK_DELAY% seconds...>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% Local DHCP server started. echo %TIME% Entering monitoring loop. Checking if %REMOTE_SERVER% is back up every %FAILOVER_RECHECK_DELAY% seconds... :failover_loop :: First we ping the server ver >NUL ping %REMOTE_SERVER% -n 3 >NUL 2>&1 :: If no ping response, this section executes if %ERRORLEVEL%==1 ( echo %TIME% FAILURE No ping response from %REMOTE_SERVER%. Waiting %FAILOVER_RECHECK_DELAY% seconds to check again.>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% FAILURE No ping response from %REMOTE_SERVER%. Waiting %FAILOVER_RECHECK_DELAY% seconds to check again. ping localhost -n %FAILOVER_RECHECK_DELAY% >NUL 2>&1 goto failover_loop ) :: If yes ping response, this section executes :: This declaration is required to get the nested IF ERRORLEVEL test to function correctly SETLOCAL ENABLEDELAYEDEXPANSION if not %ERRORLEVEL%==1 ( echo %TIME% NOTICE %REMOTE_SERVER% is responding to pings.>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% NOTICE %REMOTE_SERVER% is responding to pings. echo %TIME% Checking DHCP server status on %REMOTE_SERVER%...>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% Checking DHCP server status on %REMOTE_SERVER%... :: This section checks to see if the Dhcpserver service is back up and acts accordingly sc \\\\%REMOTE_SERVER% query Dhcpserver | find "RUNNING" >NUL 2>&1 :: The exclamation points around ERRORLEVEL here prevent it from incorrectly being expanded using the external ERRORLEVEL results from the first IF statement if !ERRORLEVEL!==0 ( echo %TIME% SUCCESS The DHCP service is running on %REMOTE_SERVER%.>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% SUCCESS The DHCP service is running on %REMOTE_SERVER%. echo %TIME% The primary DHCP server %REMOTE_SERVER% is back up. Stopping local DHCP service...>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% The primary DHCP server %REMOTE_SERVER% is back up. Stopping local DHCP service... net stop Dhcpserver echo %TIME% Recovery complete. Exiting.>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% Recovery complete. Exiting. goto EOF ) ) ENDLOCAL :: If the host responds to pings but the DHCP service isn't running, this executes echo %TIME% FAILURE %REMOTE_SERVER% is responding to pings, but DHCP isn't responding (yet?). Will try again in %FAILOVER_RECHECK_DELAY% seconds.>> %LOGPATH%\\%LOGFILE%.log 2>&1 echo %TIME% FAILURE %REMOTE_SERVER% is responding to pings, but DHCP isn't responding (yet?). Will try again in %FAILOVER_RECHECK_DELAY% seconds. ver >NUL goto failover_loop ENDLOCAL echo.>> %LOGPATH%\\%LOGFILE%.log 2>&1 :EOF
PowerShellCorpus/PoshCode/Set-LocalPassword_2.ps1
Set-LocalPassword_2.ps1
param( [switch]$Help , [string] $User , [string] $Password , [string[]] $ComputerNames = @() ) $usage = @' Get-OUComputerNames usage : [computerName1,computerName2,... | ] ./Set-LocalPassword.ps1 [-user] <userName> [-password] <password> [[-computers] computerName1,computerName2,...] returns : Sets local account passwords on one or more computers author : Nathan Hartley '@ if ($help) {Write-Host $usage;break} $ComputerNames += @($input) if (! $ComputerNames) { $ComputerNames = $env:computername } function ChangePassword ([string] $ChangeComputer, [string] $ChangeUser, [string] $ChangePassword) { "*** Setting password for $ChangeComputer/$ChangeUser" & { $ErrorActionPreference="silentlycontinue" ([ADSI] "WinNT://$computer/$user").SetPassword($password) if ($?) { " Success" } else { " Failed: $($error[0])" } } } ForEach ($computer in $ComputerNames) { ChangePassword $computer $user $password }
PowerShellCorpus/PoshCode/Log ports used by app.ps1
Log ports used by app.ps1
####################################################################################################################### # File: LogPortsUsedByApplication.ps1 # # Version: 1.1 # # Author: Alexander Petrovskiy # # Publisher: Alexander Petrovskiy, SoftwareTestingUsingPowerShell.WordPress.Com # # Copyright: © 2011 Alexander Petrovskiy, SoftwareTestingUsingPowerShell.WordPress.Com. All rights reserved. # # Usage: This scripts collects network connections information in two ways, # # using the netstat -ao command to display hostnames and # # .\\LogPortsUsedByApplication.ps1 $false # # using the netstat -ano command to provide only addresses # # .\\LogPortsUsedByApplication.ps1 $true # # or # # .\\LogPortsUsedByApplication.ps1 # # Please provide feedback in the SoftwareTestingUsingPowerShell.WordPress.Com blog. # ####################################################################################################################### param( [bool]$Numeric = $true ) cls Set-StrictMode -Version Latest #region user settings # type below anything that will be used further in the following command: # (Get-Process $applications[$i]).Id.ToString() [String[]]$applications = @( "ServiceName", "GUIApplicationName", "UtilityName" ); # type here anything that you need to extract as a string # i.e. hostname, IP address, port number or any their combination [String[]]$hosts = @( "hostname", "192.168.1.1", "192.168.100.100", "hostname.dnszone.com" ); #region user settings #region logs preparation [string]$netstatParameters = ""; [string]$logfileFull = ""; [string]$logfileSelected = ""; [string]$logfileSqueezed = ""; if ($Numeric){ $logfileFull = "$($Env:USERPROFILE)\\$($Env:COMPUTERNAME)_netstat_fullN.txt"; $logfileSelected = "$($Env:USERPROFILE)\\$($Env:COMPUTERNAME)_netstat_selectedN.txt"; $logfileSqueezed = "$($Env:USERPROFILE)\\$($Env:COMPUTERNAME)_netstat_squeezedN.txt"; $netstatParameters = "-ano";} else { $logfileFull = "$($Env:USERPROFILE)\\$($Env:COMPUTERNAME)_netstat_full.txt"; $logfileSelected = "$($Env:USERPROFILE)\\$($Env:COMPUTERNAME)_netstat_selected.txt"; $logfileSqueezed = "$($Env:USERPROFILE)\\$($Env:COMPUTERNAME)_netstat_squeezed.txt"; $netstatParameters = "-ao";} Remove-Item -Path $logfileFull -Force -ErrorAction:SilentlyContinue; Remove-Item -Path $logfileSelected -Force -ErrorAction:SilentlyContinue; Remove-Item -Path $logfileSqueezed -Force -ErrorAction:SilentlyContinue; $recordsDict = new-object "System.Collections.Generic.Dictionary``2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"; [String[]]$whatToSearch = $applications + $hosts; [string]$hostname = $Env:COMPUTERNAME + "`t"; #endregion logs preparation #region functions #region function Get-CurrentTime function Get-CurrentTime <# .SYNOPSIS The Get-CurrentTime function is used to write in the timestamp in the log file. .DESCRIPTION The Get-CurrentTime functions is used for getting the current time of operation. As s time source used [System.DateTime]::Now.TimeOfDay property. .EXAMPLE PS C:\\> Get-CurrentTime .OUTPUTS System.String #> { $timeOfDay = [System.DateTime]::Now.TimeOfDay; $time = "$($timeOfDay.Hours):$($timeOfDay.Minutes):$($timeOfDay.Seconds)`t"; return $time;} #endregion function Get-CurrentTime #endregion functions [bool]$updateReport = $false; netstat "$($netstatParameters)" 1 | ` %{ if ($_.Length -gt 0){ [string]$currentTime = Get-CurrentTime + "`t"; "$($hostname)$($currentTime)*`t$($_)" >> $logfileFull; for ($private:i = 0; $private:i -lt $applications.Length; $private:i++) { if ((Get-Process $applications[$private:i] -ErrorAction:SilentlyContinue) -ne $null) { if ($_.Contains((Get-Process $applications[$private:i]).Id.ToString())) { "$($hostname)$($currentTime)$($applications[$private:i])`t$($_)" >> $logfileSelected; try{ $recordsDict.Add("$($hostname)`t$($applications[$private:i])`t$($_)", ""); $updateReport = $true } catch{} } } } for ($private:i = 0; $private:i -lt $hosts.Length; $private:i++) { if ($_.Contains($hosts[$private:i])) { [string]$activityMarker = $_; if ($activityMarker -match "(?<=[\\x20])[\\d]+?$") { try{ $activityMarker = (Get-Process -Id $matches[0] -ErrorAction:SilentlyContinue).ProcessName; }catch{}} else{$activityMarker = $hosts[$private:i];} "$($hostname)$($currentTime)$($activityMarker)`t$($_)" >> $logfileSelected; try{ $recordsDict.Add("$($hostname)`t$($activityMarker)`t$($_)", ""); $updateReport = $true } catch{} } } if ($updateReport){ # re-write the squeezed report Remove-Item -Path "$($logfileSqueezed)_previous" ` -Force -ErrorAction:SilentlyContinue; Copy-Item -Path $logfileSqueezed -Destination "$($logfileSqueezed)_previous" Remove-Item -Path $logfileSqueezed -Force -ErrorAction:SilentlyContinue; foreach($key in $recordsDict.Keys) { "$($key)" >> $logfileSqueezed; } $updateReport = $false } } }
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 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=$true, Position=4, ParameterSetName="UrlCallback")] [Uri]$Url , [Parameter(Mandatory=$true, Position=4, ParameterSetName="DataCallback")] [string]$CallbackData , [Parameter(Mandatory=$true, Position=5, ParameterSetName="DataCallback")] [string]$CallbackType , [string]$Icon , [Growl.Connector.Priority]$Priority = "Normal" ) $notice = New-Object Growl.Connector.Notification $appName, $NoticeType, (Get-Date).Ticks.ToString(), $caption, $Message if($Icon) { $notice.Icon = Convert-Path (Resolve-Path $Icon) } if($Priority) { $notice.Priority = $Priority } if($DebugPreference -gt "SilentlyContinue") { Write-Output $notice } if( Test-Path Variable:Local:Url ) { $context = new-object Growl.Connector.CallbackContext ## These two things aren't used? Probably shouldn't so all this work :) $context.Data = $(if(Test-Path Variable:Local:CallbackData){$CallbackData}else{$Url.ToString()}) $context.Type = $(if(Test-Path Variable:Local:CallbackType){$CallbackType}else{"$NoticeType+Url"}) $urlCb = new-object Growl.Connector.UrlCallbackTarget Write-Host $Url -Fore Cyan $urlCb.Url = $Url $context.SetUrlCallbackTarget($urlcb) $script:PowerGrowler.Notify($notice, $context) } elseif( (Test-Path Variable:Local:CallbackData) -and (Test-Path Variable:Local:CallbackType) ) { $context = new-object Growl.Connector.CallbackContext $context.Data = $CallbackData $context.Type = $CallbackType Write-Host $context.GetUrlCallbackTarget() -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/Get-PrinterInfo.ps1
Get-PrinterInfo.ps1
$strComputer = "PrinterName" $Ports = get-wmiobject -class "win32_tcpipprinterport" -namespace "root\\CIMV2" -computername $strComputer $Printers = get-wmiobject -class "Win32_Printer" -namespace "root\\CIMV2" -computername $strComputer $ports | Select-Object Name,Hostaddress | Set-Variable port $Printers | Select-Object Name,PortName,DriverName,location,Description | Set-Variable print $num = 0 $hash = @{} do { $hash.Add($port.name[$num], $port.hostaddress[$num]) $num = $num + 1 } until ($num -eq $ports.Count) # Creates Table $table = New-Object system.Data.DataTable “$PrinterInfo” $colName = New-Object system.Data.DataColumn PrinterName,([string]) $colIP = New-Object system.Data.DataColumn IP,([string]) $colDrive = New-Object system.Data.DataColumn DriverName,([string]) $colLoc = New-Object system.Data.DataColumn location,([string]) $colDesc = New-Object system.Data.DataColumn Description,([string]) $table.columns.add($colName) $table.columns.add($colIP) $table.columns.add($colDrive) $table.columns.add($colLoc) $table.columns.add($colDesc) $num = 0 Do { $row = $table.NewRow() $row.PrinterName = $printers.name[$num] $row.IP = $hash.get_item($printers.PortName[$num]) $row.DriverName = $printers.drivername[$num] $row.Location = $printers.Location[$num] $row.Description = $printers.Description[$num] $table.Rows.Add($row) $num = $num + 1 } until ($num -eq $printers.Count) $table | Select-Object PrinterName,IP,DriverName,Location,Description | Export-Csv C:\\Printers.csv
PowerShellCorpus/PoshCode/Boots UI Update Sample.ps1
Boots UI Update Sample.ps1
Import-Module PowerBoots # This simulates a download function, say Jaykul's Get-Webfile # You can output current progress for a large file, or if it's an array of links then out put the current (index/length)% # You will need to run the function as a background thread in order for it to not interfere with the UI thread (freezes UI) when called from event handler. Function Start-FakeDownload { $global:job = Start-Job { foreach ($i in $(1..50)){ sleep 0.7 ($i/50)*100 } } } # GUI using boots. Registers controls as global variables. $global:Window = Boots -Async -Passthru -Title "Progress Meter" { StackPanel { ProgressBar -Height 25 -Width 250 -Name "Progress" | tee -var global:progress Button "Download" -Name "Download" | tee -var global:download Textblock | Tee -var global:status } } # Add event handler for the Download button. # Runs Background job and updates Ui $download.Add_Click({ # Prevents download from being pressed while running ... causes overload with $timer. $download.IsEnabled = $false # Get background job out and updates controls with value $updateblock = { # If job is running, or just completed. # Notice the -Keep usage. Job result/output clears everytime you Receive-Job. # -Keep allows us to get the result from the background job multiple times and also serves as a marker to figure out when the job completes if($($job.State -eq "Running") -or $($($job.State -eq "Completed") -and $($(Receive-Job $job -Keep)[-1] -eq 100))){ Invoke-BootsWindow $Window { $progress.Value = $(Receive-Job $job -Keep)[-1] $status.Text = "$($(Receive-Job $job)[-1])`% done" } } if($($job.State -eq "Completed") -and $($(Receive-Job $job) -eq $null)){ Invoke-BootsWindow $Window { $status.Text = "Download Complete" } $timer.Stop() $download.IsEnabled = $true } } $timer = new-object System.Windows.Threading.DispatcherTimer $timer.Interval = [TimeSpan]"0:0:3" $timer.Add_Tick( $updateBlock ) Start-FakeDownload $timer.start() })
PowerShellCorpus/PoshCode/isMSDTC.ps1
isMSDTC.ps1
#MSDTC is needed by SQL Server Linked Servers #This script checks whether MSDTC has been configured for network access #See KB http://support.microsoft.com/default.aspx?scid=kb;en-us;816701 for steps to enable #All values except AllowOnlySecureRpcCalls should be true param($computerName=$env:computerName) #On an x64 system the registry keys for MSDTC will only be accessible from an x64 shell. #See http://gallery.technet.microsoft.com/ScriptCenter/en-us/6062bbfc-53bf-4f92-994d-08f18c8324c0 for details and workaround #This script just checks for condition rather than workaround issue. $is64 = [bool](gwmi win32_operatingsystem -computer $computerName | ?{$_.caption -like "*x64*" -or $_.OSArchitecture -eq'64-bit'}) $isShell32 = [bool]((Get-Process -Id $PID | ?{$_.path -like "*SysWOW64*"}) -or !([IntPtr]::Size -eq 8)) if ($is64 -and $isShell32) {Write-Warning "Unable to open registry keys because $computerName is running an x64 OS. Script must be run from a PowerShell x64 shell" } else { $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine',$computerName) $msdtcKey = $reg.OpenSubKey("SOFTWARE\\\\Microsoft\\\\MSDTC") $securityKey = $msdtcKey.OpenSubKey("Security") new-object psobject -property @{ComputerName=$computerName;AllowOnlySecureRpcCalls=[bool]$msdtcKey.GetValue('AllowOnlySecureRpcCalls');TurnOffRpcSecurity=[bool]$msdtcKey.GetValue('TurnOffRpcSecurity'); NetworkDtcAccessAdmin=[bool]$securityKey.GetValue('NetworkDtcAccessAdmin');NetworkDtcAccessClients=[bool]$securityKey.GetValue('NetworkDtcAccessClients'); NetworkDtcAccessInbound=[bool]$securityKey.GetValue('NetworkDtcAccessInbound');NetworkDtcAccessOutbound=[bool]$securityKey.GetValue('NetworkDtcAccessOutbound'); NetworkDtcAccessTransactions=[bool]$securityKey.GetValue('NetworkDtcAccessTransactions');XaTransactions=[bool]$securityKey.GetValue('XaTransactions')} }
PowerShellCorpus/PoshCode/Get Network Utilization_1.ps1
Get Network Utilization_1.ps1
$cnt = 'Bytes Total/sec' $cat = 'Network Interface' $cnt2 = 'Current Bandwidth' foreach ($inst in ((new-object System.Diagnostics.PerformanceCounterCategory("network interface")).GetInstanceNames())){ $cur = New-Object system.Diagnostics.PerformanceCounter($cat,$cnt,$inst) $max = New-Object system.Diagnostics.PerformanceCounter($cat,$cnt2,$inst) $curnum = $cur.NextValue() $maxnum = $max.NextValue() $ObjUtil = New-Object System.Object $ObjUtil | Add-Member -MemberType NoteProperty -Name "Util" -Value ((( $curnum * 8 ) / $maxnum ) * 100) $ObjUtil | Add-Member -MemberType NoteProperty -Name "InstanceName" -Value $inst $ObjUtil }
PowerShellCorpus/PoshCode/Get-ScriptDirectory.ps1
Get-ScriptDirectory.ps1
function Get-ScriptDirectory { $invocation = (Get-Variable MyInvocation -Scope 1).Value $script = [IO.FileInfo] $invocation.MyCommand.Path if ([IO.File]::Exists($script)) { Return (Split-Path $script.Fullname) } else { return $null } }
PowerShellCorpus/PoshCode/Stored Credential Code.ps1
Stored Credential Code.ps1
#STORED CREDENTIAL CODE $AdminName = Read-Host "Enter your Admin AD username" $CredsFile = "C:\\$AdminName-PowershellCreds.txt" $FileExists = Test-Path $CredsFile if ($FileExists -eq $false) { Write-Host 'Credential file not found. Enter your password:' -ForegroundColor Red Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File $CredsFile $password = get-content $CredsFile | convertto-securestring $Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist domain\\$AdminName,$password} else {Write-Host 'Using your stored credential file' -ForegroundColor Green $password = get-content $CredsFile | convertto-securestring $Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist domain\\$AdminName,$password} sleep 2 Write-Host 'Connecting to Active Directory' #Establishes connection to Active Directory and Exchange with the specified user acccount and password. Connect-QADService -Service 'gbay-ad01' -Credential $Cred -ErrorAction Stop | out-Null $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://server.fqdn.com/PowerShell/ -Credential $Cred -Authentication Kerberos -ErrorAction SilentlyContinue Import-PSSession $Session -ErrorAction SilentlyContinue -AllowClobber if(!$?) {write-host "Failed importing the exchange pssession, exiting!" exit} #END OF STORED CREDENTIAL CODE
PowerShellCorpus/PoshCode/Get-GroupMembership_2.ps1
Get-GroupMembership_2.ps1
## Get-DistinguishedName -- look up a DN from a user's (login) name function Get-DistinguishedName { Param($UserName) $ads = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'') $ads.filter = "(&(objectClass=Person)(samAccountName=$UserName))" $s = $ads.FindOne() return $s.GetDirectoryEntry().DistinguishedName } ## Get-GroupMembership -- Get AD group membership recursively function Get-GroupMembership { Param($DNName,[int]$RecurseLimit=-1) $groups = ([adsi]"LDAP://$DNName").MemberOf if ($groups -and $RecurseLimit) { Foreach ($gr in $groups) { $groups += @(Get-GroupMembership $gr -RecurseLimit:$($RecurseLimit-1) | ? {$groups -notcontains $_}) } } return $groups } ## Usage: ################################################################################# ## $groups = Get-GroupMembership (Get-DistinguishedName Jaykul) ## # To turn recursion off: ## $groups = Get-GroupMembership (Get-DistinguishedName Jaykul) -RecurseLimit 0
PowerShellCorpus/PoshCode/Get-CryptoBytes_1.ps1
Get-CryptoBytes_1.ps1
function Get-CryptoBytes { #.Synopsis # Generate Cryptographically Random Bytes #.Description # Uses RNGCryptoServiceProvider to generate arrays of random bytes #.Parameter Count # How many bytes to generate #.Parameter AsString # Output hex-formatted strings instead of byte arrays param( [Parameter(ValueFromPipeline=$true)] [int[]]$count = 64 , [switch]$AsString ) begin { $RNGCrypto = New-Object System.Security.Cryptography.RNGCryptoServiceProvider $OFS = "" } process { foreach($length in $count) { $bytes = New-Object Byte[] $length $RNGCrypto.GetBytes($bytes) if($AsString){ Write-Output ("{0:X2}" -f $bytes) } else { Write-Output $bytes } } } end { $RNGCrypto = $null } }
PowerShellCorpus/PoshCode/Read-InputBox.ps1
Read-InputBox.ps1
##############################################################################\n##\n## Read-InputBox\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\nRead user input from a visual InputBox\n\n.EXAMPLE\n\nPS >$caption = "Please enter your name"\nPS >$name = Read-InputBox $caption\n\n#>\n\nparam(\n ## The title of the dialog when displayed\n [string] $Title = "Input Dialog"\n)\n\nSet-StrictMode -Version Latest\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 @(400,100)\n$form.FormBorderStyle = "FixedToolWindow"\n\n## Create the listbox to hold the items from the pipeline\n$textbox = New-Object Windows.Forms.TextBox\n$textbox.Top = 5\n$textbox.Left = 5\n$textBox.Width = 380\n$textbox.Anchor = "Left","Right"\n$form.Text = $Title\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 @(400,40)\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 - 10\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($buttonPanel)\n$form.Controls.Add($textbox)\n$form.AcceptButton = $okButton\n$form.CancelButton = $cancelButton\n$form.Add_Shown( { $form.Activate(); $textbox.Focus() } )\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 $textbox.Text\n}
PowerShellCorpus/PoshCode/Get-MailboxImportRequest_1.ps1
Get-MailboxImportRequest_1.ps1
# .Synopsis # Use the Get-MailboxImportRequestProgress cmdlet to view detailed information about pst import progress. # .Description # The Get-MailboxImportRequestProgress cmdlet displays statistics on imports currently in progress that help determine if a import is likely to complete successfully. To accureately evaluate the current progress of an import examine the durration it has been running and the number of times the estimated number of items have been transferred. # # The following may indicate an import is stalled and will neither Complete or Fail: # * Item % is over 200 # * ItemsLeft is -2000 or lower # * BytesTransferred is under 1MB and Durration is over 2 hours # # Using ScanPST may repair the damange to the pst and allow it to complete successfully. Otherwise, the only other option is to use the full Outlook client. # # .Example # Get-MailboxImportRequest -Status InProgress|Get-MailboxImportRequestProgress # .Example # Get-MailboxImportRequestProgress|ft -auto [CmdletBinding()] PARAM ( [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]$Identity ) BEGIN { # We need this because 2.0 broke adding default properties the old way. # https://connect.microsoft.com/PowerShell/feedback/details/487938/v2-0-rtm-defining-default-properties-for-custom-objects-no-longer-works Function Set-DefaultProperties { PARAM ( [string]$name, [string[]]$DefaultProperties ) $xml = "<?xml version='1.0' encoding='utf-8' ?><Types><Type>" $xml += "<Name>$($name)</Name>" $xml += "<Members><MemberSet><Name>PSStandardMembers</Name><Members>" $xml += "<PropertySet><Name>DefaultDisplayPropertySet</Name><ReferencedProperties>" foreach( $default in $DefaultProperties ) { $xml += "<Name>$($default)</Name>" } $xml += "</ReferencedProperties></PropertySet></Members></MemberSet></Members>" $xml += "</Type></Types>" $file = "$($env:Temp)\\$name.ps1xml" Out-File -FilePath $file -Encoding "UTF8" -InputObject $xml -Force $typeLoaded = $host.Runspace.RunspaceConfiguration.Types | where { $_.FileName -eq $file } if( $typeLoaded -ne $null ) { Write-Verbose "Type Loaded" Update-TypeData } else { Update-TypeData $file } } # Define the default property set $customObjectName = ’Microsoft.Exchange.MailboxReplicationService.MailboxImportRequest#Progress’ Set-DefaultProperties -Name $customObjectName @(‘TargetAlias','StatusDetail','BytesTransferred','ItemsTransferred','ItemsLeft','Item %','Total %','Durration') } PROCESS { # Mailbox Import requests were piped in if($_) { if($_.Identity.GetType() -eq [Microsoft.Exchange.MailboxReplicationService.RequestJobObjectId] -or $_.Identity.GetType() -eq [Microsoft.Exchange.MailboxReplicationService.RequestIndexEntryObjectId]) { $temp = $_|Get-MailboxImportRequestStatistics|select @{n="ItemsLeft";e={$_.estimatedtransferitemcount - $_.itemstransferred}},@{n="Item %";e={[int]($_.itemstransferred/$_.estimatedtransferitemcount * 100)}},@{n="Total %";e={$_.percentcomplete}},@{n="Durration";e={$_.TotalInProgressDuration}},* } else { Write-Warning "Invalid Mailbox Import Request ID"; return } # We just want all imports in progress } else { $temp = Get-MailboxImportRequest -status InProgress|Get-MailboxImportRequestStatistics|select @{n="ItemsLeft";e={$_.estimatedtransferitemcount - $_.itemstransferred}},@{n="Item %";e={[int]($_.itemstransferred/$_.estimatedtransferitemcount * 100)}},@{n="Total %";e={$_.percentcomplete}},@{n="Durration";e={$_.TotalInProgressDuration}},* } # Define the default property set $temp |% { $_.PSObject.TypeNames.Insert(0,$customObjectName) } $temp }
PowerShellCorpus/PoshCode/ActiveDirectoryFunctions_2.ps1
ActiveDirectoryFunctions_2.ps1
#.SYNOPSIS # Gets a directory entry from ActiveDirectory based on the login user name function Get-ADUser { [CmdletBinding()] param([string]$UserName=${Env:userName}) $ads = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'') $ads.filter = "(&(objectClass=Person)(samAccountName=$UserName))" $ads.FindAll().GetEnumerator() | %{ $_.GetDirectoryEntry() } } function Get-NTAccountName { [CmdletBinding()] param( [Parameter(ValueFromPipelineByPropertyName=$true)] [string]$Name ) process { $ads = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'') $ads.filter = "(|(name=$Name)(samAccountName=$Name))" $distinguishedName = $ads.FindOne().Properties["distinguishedname"] # Use the NameTranslate object. $objTrans = New-Object -comObject "NameTranslate" $objNT = $objTrans.GetType() # Invoke the Init method to Initialize NameTranslate by locating # the Global Catalog. Note the constant 3 is ADS_NAME_INITTYPE_GC. $null = $objNT.InvokeMember("Init", "InvokeMethod", $Null, $objTrans, (3, $Null)) # Use the Set method to specify the Distinguished Name of the current domain. # Note the constant 1 is ADS_NAME_TYPE_1779. $null = $objNT.InvokeMember("Set", "InvokeMethod", $Null, $objTrans, (1, "$distinguishedName")) # Use the Get method to retrieve the NetBIOS name of the current domain. # Note the constant 3 is ADS_NAME_TYPE_NT4. # The value retrieved includes a trailing backslash. $objNT.InvokeMember("Get", "InvokeMethod", $Null, $objTrans, 3) }} function Get-SID { [CmdletBinding()] param( [Parameter(ValueFromPipelineByPropertyName=$true)] [string]$Name ) process { $ads = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'') $ads.filter = "(|(name=$Name)(samAccountName=$Name))" new-object security.principal.securityidentifier $ads.FindOne().Properties["objectSID"][0], 0 }} #.SYNOPSIS # Gets a directory entry from ActiveDirectory based on the computer name function Get-ADComputer { [CmdletBinding()] param( [Parameter(ValueFromPipelineByPropertyName=$true)] [string]$ComputerName=${Env:ComputerName} ) $ads = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'') $ads.filter = "(&(objectClass=Computer)(name=$ComputerName))" $ads.FindAll().GetEnumerator() | %{ $Computer = $_.GetDirectoryEntry() $Computer = Resolve-PropertyValueCollection -InputObject $Computer Add-Member -InputObject $Computer -Type NoteProperty -Name SID -Value (new-object security.principal.securityidentifier $Computer.objectSID, 0) Add-Member -InputObject $Computer -Type NoteProperty -Name GUID -Value (new-object GUID (,[byte[]]$Computer.objectGUID)) Add-Member -InputObject $Computer -Type NoteProperty -Name CreatorSID -Value (new-object security.principal.securityidentifier $Computer."mS-DS-CreatorSID", 0) Add-Member -InputObject $Computer -Type NoteProperty -Name NTAccountName -Value (Get-NTAccountName $ComputerName) $Computer } } #.SYNOPSIS # Gets a directory entry from ActiveDirectory based on the group's friendly name function Get-ADGroup { [CmdletBinding()] param([string]$UserName) $ads = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'') $ads.filter = "(&(objectClass=Group)(samAccountName=$UserName))" $ads.FindAll().GetEnumerator() | %{ $_.GetDirectoryEntry() } } #.SYNOPSIS # Look up a DN from a user's (login) name function Get-DistinguishedName { [CmdletBinding()] param([string]$UserName) (Get-ADUser $UserName).DistinguishedName } #.SYNOPSIS # Get Active Directory group membership recursively #.EXAMPLE # $groups = Get-GroupMembership (Get-DistinguishedName Jaykul) #.EXAMPLE # $groups = Get-GroupMembership (Get-DistinguishedName Jaykul) -RecurseLimit 0 # # Gets the groups the user belongs to without recursing function Get-GroupMembership { [CmdletBinding()] param([string]$Name,[int]$RecurseLimit=-1) if(!$Name.StartsWith("CN=","InvariantCultureIgnoreCase")) { $Name = Get-DistinguishedName $Name } $groups = ([adsi]"LDAP://$Name").MemberOf if ($groups -and $RecurseLimit) { Foreach ($gr in $groups) { $groups += @(Get-GroupMembership $gr -RecurseLimit:$($RecurseLimit-1) | ? {$groups -notcontains $_}) } } return $groups | Convert-DistinguishedName } function Convert-DistinguishedName { [CmdletBinding()] param( [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Position=0)] [string]$name ) process { if(!$Name.StartsWith("CN=","InvariantCultureIgnoreCase")) { $Name = Get-DistinguishedName $Name } $name -replace "CN=","Name=" -replace "DC=","Domain=" -replace "OU=","Org=" | ConvertFrom-PropertyString -Delimiter "," | ForEach { $_.Domain = $_.Domain -join "."; $_ } | Add-Member NoteProperty DN $name -passthru } } function Resolve-PropertyValueCollection { param( [Parameter(ValueFromPipeline=$true)] $InputObject ) process { $SingleMembers = @() $MultiMembers = @() $InputObject | Get-Member -Type Property | ForEach-Object { $Name = $_.Name if($InputObject.($Name).Count -le 1) { $SingleMembers += $Name } else { $MultiMembers += $Name } } $OutputObject = Select-Object -InputObject $InputObject -Property $MultiMembers foreach($member in $singleMembers) { Add-Member -InputObject $OutputObject -Type NoteProperty -Name $Member -Value ($InputObject.$Member)[0] } $OutputObject } } #. SYNOPSIS # Pretty-print the vitals on a user... function Select-UserInfo { [CmdletBinding()] param( [Parameter(Mandatory=$true,Position=0,ParameterSetName="Input",ValueFromPipeline=$true)] [System.DirectoryServices.DirectoryEntry[]]$InputObject , [Parameter(Mandatory=$true,Position=0,ParameterSetName="Name",ValueFromPipelineByPropertyName=$true)] [string[]]$name ) process { switch($PSCmdlet.ParameterSetName) { "Name" { foreach($n in $Name) { Write-Verbose "Getting $n User Info" Get-ADUser $n | Resolve-PropertyValueCollection } } "Input" { foreach($io in $InputObject) { Write-Verbose "Converting User Info for $($io.displayName)" Resolve-PropertyValueCollection -InputObject $io } } } } } function Get-GroupMembers { [CmdletBinding()] param( [Parameter(Mandatory=$true,Position=0,ParameterSetName="Input",ValueFromPipeline=$true)] [string]$GroupName ) process { Foreach ($member in (Get-ADGroup $GroupName).Members() ) { new-object System.DirectoryServices.DirectoryEntry $member | Resolve-PropertyValueCollection } } }
PowerShellCorpus/PoshCode/3d3bbfa8-777b-4374-9eac-5350569d2cba.ps1
3d3bbfa8-777b-4374-9eac-5350569d2cba.ps1
param($Issue, $Credentials = $(Get-Credential), $BaseURI = "https://your.jira.server/jira") function ConvertTo-UnsecureString( [System.Security.SecureString][parameter(mandatory=$true)]$SecurePassword) { $unmanagedString = [System.IntPtr]::Zero; try { $unmanagedString = [Runtime.InteropServices.Marshal]::SecureStringToGlobalAllocUnicode($SecurePassword) return [Runtime.InteropServices.Marshal]::PtrToStringUni($unmanagedString) } finally { [Runtime.InteropServices.Marshal]::ZeroFreeGlobalAllocUnicode($unmanagedString) } } function ConvertTo-Base64($string) { $bytes = [System.Text.Encoding]::UTF8.GetBytes($string); $encoded = [System.Convert]::ToBase64String($bytes); return $encoded; } function ConvertFrom-Base64($string) { $bytes = [System.Convert]::FromBase64String($string); $decoded = [System.Text.Encoding]::UTF8.GetString($bytes); return $decoded; } function Get-HttpBasicHeader($Credentials, $Headers = @{}) { $b64 = ConvertTo-Base64 "$($Credentials.UserName):$(ConvertTo-UnsecureString $Credentials.Password)" $Headers["Authorization"] = "Basic $b64" return $Headers } if($Issue) { $uri = "$BaseURI/rest/api/2/issue/$Issue" } else { $uri = "$BaseURI/rest/api/2/mypermissions" } $headers = Get-HttpBasicHeader $Credentials Invoke-RestMethod -uri $uri -Headers $headers -ContentType "application/json"
PowerShellCorpus/PoshCode/Fix for datastore.ps1
Fix for datastore.ps1
#Generated Form Function function GenerateForm { ######################################################################## # THIS CODE IS MADE AVAILABLE AS IS, WITHOUT WARRANTY OF ANY KIND. THE ENTIRE RISK # OF THE USE OR THE RESULTS FROM THE USE OF THIS CODE REMAINS WITH THE USER. # # Code Generated By: Richard Yaw # Generated On: 23/09/2010 ######################################################################## #region Import the Assemblies [reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null [reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null #endregion #region Generated Form Objects $MigrationForm = New-Object System.Windows.Forms.Form $Header = new-object System.Windows.Forms.Label $MigrateButton = New-Object System.Windows.Forms.Button $ClusterListBox = New-Object System.Windows.Forms.ListBox $SourceHostListBox = New-Object System.Windows.Forms.ListBox $SourceDBListBox = New-Object System.Windows.Forms.CheckedListBox $SourceVMListBox = New-Object System.Windows.Forms.CheckedListBox $DestinationListBox = New-Object System.Windows.Forms.ListBox $vCenterLabel = New-Object System.Windows.Forms.Label $VCTextBox = New-Object System.Windows.Forms.TextBox $LoginButton = New-Object System.Windows.Forms.Button $ClearMsgButton = New-Object System.Windows.Forms.Button $UndoButton = New-Object System.Windows.Forms.Button $UndoALLButton = New-Object System.Windows.Forms.Button $SaveTaskButton = New-Object System.Windows.Forms.Button $ClusterLabel = New-Object System.Windows.Forms.Label $HostToHostButton = New-Object System.Windows.Forms.Button $VMToHostButton = New-Object System.Windows.Forms.Button $DBtoDBButton = New-Object System.Windows.Forms.Button $VMtoDBButton = New-Object System.Windows.Forms.Button $SourceButton = New-Object System.Windows.Forms.Button $DestinationButton = New-Object System.Windows.Forms.Button $ResetButton = New-Object System.Windows.Forms.Button $ChangeVCButton = New-Object System.Windows.Forms.Button $CloseButton = New-Object System.Windows.Forms.Button $MessagesLabel = New-Object System.Windows.Forms.Label $MessagesListBox = New-Object System.Windows.Forms.ListBox $TaskLabel = New-Object System.Windows.Forms.Label $TaskListBox = New-Object System.Windows.Forms.ListBox $InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState #endregion Generated Form Objects #---------------------------------------------- #Generated Event Script Blocks #---------------------------------------------- #Provide Custom Code for events specified in PrimalForms. $LoginButton_Click= { #TODO: Place custom script here If ($VCTextBox.Text -eq "") { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('Please Enter a Valid vCenter Server.') } Else { if ((Get-PSSnapin "VMware.VimAutomation.Core" -ErrorAction SilentlyContinue) -eq $null) { Add-PSSnapin "VMware.VimAutomation.Core" } #Connect to vCenter Connect-VIServer $VCTextBox.Text $ClusterListBox.Enabled = $true #Get Cluster Get-Cluster | % { [void]$ClusterListBox.items.add($_.Name) } If ($ClusterListBox.items -ne $null) { $LoginButton.Enabled = $false $VCTextBox.Enabled = $false $HostToHostButton.Enabled = $true $VMToHostButton.Enabled = $true $DBtoDBButton.Enabled = $true $VMtoDBButton.Enabled = $true $ResetButton.Enabled = $true $ChangeVCButton.Enabled = $true #Generate a log file for this session #$logfile = "C:\\TEMP\\EasyMigrate{0:dd-MM-yyyy_HHmmss}" -f (Get-Date) + ".log" #$logheader = "Easy Migration Tool v1.1 - Log generated on " + (Get-Date) #Out-File -InputObject $logheader -FilePath $logfile #Out-File -InputObject "" -Append -FilePath $logfile } $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $MigrationForm.WindowState = $InitialFormWindowState } } } $HostToHostButton_Click= { #TODO: Place custom script here $ClusterName = $ClusterListBox.SelectedItem If ($ClusterName -eq $null) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('Please Select a Cluster.') } Else { $SourceHostListBox.Enabled = $true $SourceHostListBox.Items.Clear() #Get Hostnames in a Cluster Get-Cluster -Name $ClusterName | Get-VMHost | % { [void]$SourceHostListBox.items.add($_.Name) } $ClusterListBox.Enabled = $false $HostToHostButton.Enabled = $false $VMToHostButton.Enabled = $false $DBtoDBButton.Enabled = $false $VMtoDBButton.Enabled = $false $SourceButton.Text = 'Source - Select One Host' $DestinationButton.Text = 'Destination Host' $SourceButton.Enabled = $true $HostToHostButton.BackColor = [System.Drawing.Color]::lightblue $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $MigrationForm.WindowState = $InitialFormWindowState } } } $VMToHostButton_Click= { #TODO: Place custom script here $ClusterName = $ClusterListBox.SelectedItem If ($ClusterName -eq $null) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('Please Select a Cluster.') } Else { $MigrationForm.Controls.Remove($SourceHostListBox) $MigrationForm.Controls.Add($SourceVMListBox) $SourceVMListBox.Enabled = $true $SourceVMListBox.Items.Clear() #Get VMs in a Cluster Get-Cluster -Name $ClusterName | Get-VM | % { [void]$SourceVMListBox.items.add($_.Name) } $ClusterListBox.Enabled = $false $HostToHostButton.Enabled = $false $VMToHostButton.Enabled = $false $DBtoDBButton.Enabled = $false $VMtoDBButton.Enabled = $false $SourceButton.Text = 'Source - Select VMs' $DestinationButton.Text = 'Destination Host' $SourceButton.Enabled = $true $VMToHostButton.BackColor = [System.Drawing.Color]::lightblue $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $MigrationForm.WindowState = $InitialFormWindowState } } } $DBtoDBButton_Click= { #TODO: Place custom script here $ClusterName = $ClusterListBox.SelectedItem If ($ClusterName -eq $null) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('Please Select a Cluster.') } Else { $MigrationForm.Controls.Remove($SourceHostListBox) $MigrationForm.Controls.Add($SourceDBListBox) $SourceDBListBox.Enabled = $true $SourceDBListBox.Items.Clear() #Get Datastores in a Cluster #Get-Datastore -Name *$ClusterName* | Where-Object {$_.Name -notlike "*SCR01"} | Where-Object {$_.Name -notlike "DAS*"} | % { [void]$SourceDBListBox.items.add($_.Name) } Get-cluster *$ClusterName* | get-vmhost | get-datastore | Where-Object {$_.Name -notlike "DAS*"} | % { [void]$SourceDBListBox.items.add($_.Name) } $ClusterListBox.Enabled = $false $HostToHostButton.Enabled = $false $VMToHostButton.Enabled = $false $DBtoDBButton.Enabled = $false $VMtoDBButton.Enabled = $false $SourceButton.Text = 'Source - Select a Datastore' $DestinationButton.Text = 'Destination Datastore' $SourceButton.Enabled = $true $DBtoDBButton.BackColor = [System.Drawing.Color]::lightblue $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $MigrationForm.WindowState = $InitialFormWindowState } } } $VMToDBButton_Click= { #TODO: Place custom script here $ClusterName = $ClusterListBox.SelectedItem If ($ClusterName -eq $null) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('Please Select a Cluster.') } Else { $MigrationForm.Controls.Remove($SourceHostListBox) $MigrationForm.Controls.Add($SourceVMListBox) $SourceVMListBox.Enabled = $true $SourceVMListBox.Items.Clear() #Get VMs in a Cluster Get-Cluster -Name $ClusterName | Get-VM | % { [void]$SourceVMListBox.items.add($_.Name) } $ClusterListBox.Enabled = $false $HostToHostButton.Enabled = $false $VMToHostButton.Enabled = $false $DBtoDBButton.Enabled = $false $VMtoDBButton.Enabled = $false $SourceButton.Text = 'Source - Select VMs' $DestinationButton.Text = 'Destination Datastore' $SourceButton.Enabled = $true $VMtoDBButton.BackColor = [System.Drawing.Color]::lightblue $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $MigrationForm.WindowState = $InitialFormWindowState } } } $SourceButton_OnClick= { #TODO: Place custom script here $ClusterName = $ClusterListBox.SelectedItem If ($SourceButton.Text -eq "Source - Select One Host") { $SourceHostname = $SourceHostListBox.SelectedItem If ($SourceHostname -eq $null) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('Please Select a Source Host.') } Else { #Get Hostnames in a Cluster Get-Cluster -Name $ClusterName | Get-VMHost | Where-Object {$_.Name -notlike "$SourceHostname"} | % { [void]$DestinationListBox.items.add($_.Name) } $SourceHostListBox.Enabled = $false $SourceButton.Enabled = $false $DestinationListBox.Enabled = $true $DestinationButton.Enabled = $true $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $MigrationForm.WindowState = $InitialFormWindowState } } } If ($SourceButton.Text -eq "Source - Select VMs") { $SourceVMname = $SourceVMListBox.SelectedItem If ($SourceVMname -eq $null) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('Please Select One or More VMs.') } Else { if ($DestinationButton.Text -like "Destination Host") { #Get Hostnames in a Cluster Get-Cluster -Name $ClusterName | Get-VMHost | % { [void]$DestinationListBox.items.add($_.Name) } } Else { #Get Datastores in a Cluster Get-Datastore -Name *$ClusterName* | Where-Object {$_.Name -notlike "*SCR01"} | Where-Object {$_.Name -notlike "DAS*"} | % { [void]$DestinationListBox.items.add($_.Name) } } $DestinationListBox.Enabled = $true $SourceVMListBox.Enabled = $false $SourceButton.Enabled = $false $DestinationButton.Enabled = $true $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $MigrationForm.WindowState = $InitialFormWindowState } } } If ($SourceButton.Text -like "Source - Select a Datastore") { $SourceDBname = $SourceDBListBox.SelectedItem If ($SourceDBname -eq $null) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('Please Select One Datastore.') } Else { #Get Datastores in a Cluster #Get-Datastore -Name *$ClusterName* | Where-Object {$_.Name -notlike "*SCR01"} | Where-Object {$_.Name -notlike "DAS*"} | Where-Object {$_.Name -notlike "$SourceDBname"} | % { [void]$DestinationListBox.items.add($_.Name) } Get-cluster *$ClusterName* | get-vmhost | get-datastore | Where-Object {$_.Name -notlike "*SCR01"} | Where-Object {$_.Name -notlike "DAS*"} | Where-Object {$_.Name -notlike "$SourceDBname"} | % { [void]$DestinationListBox.items.add($_.Name) } $SourceDBListBox.Enabled = $false $SourceButton.Enabled = $false $DestinationListBox.Enabled = $true $DestinationButton.Enabled = $true $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $MigrationForm.WindowState = $InitialFormWindowState } } } } $DestinationButton_OnClick= { #TODO: Place custom script here $DestinationName = $DestinationListBox.SelectedItem If ($DestinationName -eq $null) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('Please Select a Destination.') } Else { $DestinationListBox.Enabled = $false $DestinationButton.Enabled = $false $MigrateButton.Enabled = $true $OnLoadForm_StateCorrection= {#Correct the initial state of the form to prevent the .Net maximized form issue $MigrationForm.WindowState = $InitialFormWindowState } } } $MigrateButton_OnClick= { #TODO: Place custom script here If ($SourceButton.Text -eq "Source - Select One Host") { $SourceHostname = $SourceHostListBox.SelectedItem $DestinationName = $DestinationListBox.SelectedItem $VMs = Get-VMHost $SourceHostname | Get-VM foreach($VM in $VMs) { Get-VM -Name $VM | Move-VM -Destination (Get-VMHost $DestinationName) $d = Get-Date $TaskLine = "$d - $VM migrated successfully from $SourceHostName to $DestinationName" [void]$TaskListBox.items.add($TaskLine) } $SourceVMListBox.enabled = $true $SourceButton.enabled = $true $MigrateButton.Enabled = $false $DestinationListBox.Items.Clear() } If ($SourceButton.Text -eq "Source - Select VMs") { $DestinationName = $DestinationListBox.SelectedItem If($DestinationButton.Text -eq "Destination Host") { foreach($VM in $SourceVMListBox.CheckedItems) { $SourceName = Get-VM -Name $VM | Get-VMHost | % {$_.name} If($SourceName -ne $DestinationName) { Get-VM -Name $VM | Move-VM -Destination (Get-VMHost $DestinationName) $d = Get-Date $line = "$d - $VM migrated successfully from $SourceName to $DestinationName" [void]$TaskListBox.items.add($line) } Else { $d = Get-Date $MsgLine = "$d - Cannot migrate $VM because the source host and the destination host are the same." [void]$MessagesListBox.items.add($MsgLine) } } } Else { foreach($VM in $SourceVMListBox.CheckedItems) { $VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024 $DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB} $DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2} $DBAvailableSpace = $DBFreeSpace - $DBReserved If ($VMsize -gt $DBAvailableSpace) { $VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024) $DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024) $DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024) $d = Get-Date $MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)." [void]$MessagesListBox.items.add($MsgLine) } Else { $SourceName = Get-VM -Name $VM | Get-Datastore | % {$_.name} If($SourceName -ne $DestinationName) { Get-VM -Name $VM | Move-VM -Datastore ($DestinationName) $d = Get-Date $TaskLine = "$d - $VM migrated successfully from $SourceName to $DestinationName" [void]$TaskListBox.items.add($TaskLine) } Else { $d = Get-Date $MsgLine = "$d - Cannot migrate $VM because the source datastore and the destination datastore are the same." [void]$MessagesListBox.items.add($MsgLine) } } } } $SourceVMListBox.enabled = $true $SourceButton.enabled = $true $MigrateButton.Enabled = $false $DestinationListBox.Items.Clear() } If ($SourceButton.Text -eq "Source - Select a Datastore") { $SourceDBname = $SourceDBListBox.SelectedItem $DestinationName = $DestinationListBox.SelectedItem $VMs = Get-Datastore -Name $SourceDBname | Get-VM If($VMs.count -gt 0) { foreach($VM in $VMs) { $VMsize = ((Get-VM -Name $VM | Get-HardDisk | Measure-Object -property CapacityKB -Sum).Sum)/1024 $DBFreeSpace = Get-Datastore -Name $DestinationName | %{$_.FreeSpaceMB} $DBReserved = Get-Datastore -Name $DestinationName | %{$_.CapacityMB * 0.2} $DBAvailableSpace = $DBFreeSpace - $DBReserved If ($VMsize -gt $DBFreeSpace) { $VMSizeGB = "{0:N1}GB" -f ($VMsize / 1024) $DBFreeSpaceGB = "{0:N1} GB" -f ($DBFreeSpace / 1024) $DBAvailableSpaceGB = "{0:N1} GB" -f ($DBAvailableSpace / 1024) $d = Get-Date $MsgLine = "$d - Cannot migrate $VM (Size = $VMSizeGB) because there is insufficient disk space on $DestinationName (Available = $DBAvailableSpaceGB)." [void]$MessagesListBox.items.add($MsgLine) } Else { Get-VM -Name $VM | Move-VM -Datastore ($DestinationName) $d = Get-Date $line = "$d - $VM migrated successfully from $SourceDBName to $DestinationName" [void]$TaskListBox.items.add($line) } } } Else { $d = Get-Date $MsgLine = "$d - No VM is present on the source datastore $SourceDBname." [void]$MessagesListBox.items.add($MsgLine) } $SourceDBListBox.enabled = $true $SourceButton.enabled = $true $DestinationListBox.Items.Clear() $MigrateButton.Enabled = $false } } $RESETButton_OnClick= { #TODO: Place custom script here $ClusterListBox.Enabled = $true $HostToHostButton.Enabled = $true $VMToHostButton.Enabled = $true $DBtoDBButton.Enabled = $true $VMtoDBButton.Enabled = $true $SourceHostListBox.Items.Clear() $SourceDBListBox.Items.Clear() $SourceVMListBox.Items.Clear() $SourceButton.Enabled = $false $SourceButton.Text = 'Source' $DestinationListBox.Items.Clear() $DestinationButton.Enabled = $false $DestinationButton.Text = 'Destination' $MigrateButton.Enabled = $false $MigrationForm.Controls.Remove($SourceHostListBox) $MigrationForm.Controls.Remove($SourceVMListBox) $MigrationForm.Controls.Remove($SourceDBListBox) $MigrationForm.Controls.Add($SourceHostListBox) $HostToHostButton.BackColor = [System.Drawing.Color]::Transparent $VMToHostButton.BackColor = [System.Drawing.Color]::Transparent $DBtoDBButton.BackColor = [System.Drawing.Color]::Transparent $VMtoDBButton.BackColor = [System.Drawing.Color]::Transparent } $ChangeVCButton_OnClick= { #TODO: Place custom script here $VCTextBox.Text = "" $VCTextBox.Enabled = $true $LoginButton.Enabled = $true $ClusterListBox.Items.Clear() $ClusterListBox.Enabled = $false $HostToHostButton.Enabled = $false $VMToHostButton.Enabled = $false $DBtoDBButton.Enabled = $false $VMtoDBButton.Enabled = $false $SourceHostListBox.Items.Clear() $SourceDBListBox.Items.Clear() $SourceVMListBox.Items.Clear() $SourceButton.Enabled = $false $SourceButton.Text = 'Source' $DestinationListBox.Items.Clear() $DestinationButton.Enabled = $false $DestinationButton.Text = 'Destination' $MigrateButton.Enabled = $false $ResetButton.Enabled = $false $ChangeVCButton.Enabled = $false $MessagesListBox.Items.Clear() $TaskListBox.Items.Clear() $MigrationForm.Controls.Remove($SourceHostListBox) $MigrationForm.Controls.Remove($SourceVMListBox) $MigrationForm.Controls.Remove($SourceDBListBox) $MigrationForm.Controls.Add($SourceHostListBox) $HostToHostButton.BackColor = [System.Drawing.Color]::Transparent $VMToHostButton.BackColor = [System.Drawing.Color]::Transparent $DBtoDBButton.BackColor = [System.Drawing.Color]::Transparent $VMtoDBButton.BackColor = [System.Drawing.Color]::Transparent #Disconnect from vCenter server Disconnect-VIServer -Confirm:$false } $CloseButton_OnClick= { #TODO: Place custom script here If ($VCTextBox.Text -ne "") { #Disconnect from vCenter server Disconnect-VIServer -Confirm:$false } #Close Form $MigrationForm.close() } $ClearMsgButton_Click= { #TODO: Place custom script here If($MessagesListBox.items.count -eq 0) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('No messages to clear.') } Else { $MessagesListBox.items.clear() } } $UndoButton_Click= { #TODO: Place custom script here If ($TaskListBox.Items.Count -eq 0) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('The task list is empty.') } Else { If ($TaskListBox.SelectedItems.Count -eq 0) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('Please select one or more tasks.') } Else { foreach($Task in $TaskListBox.SelectedItems) { $Task = $Task.split(" ") $VM = $Task[3] $SourceName = $Task[9] $DestinationName = $Task[7] Get-VM -Name $VM | Move-VM -Destination (Get-VMhost $DestinationName) } While($TaskListBox.SelectedItems.Count -gt 0) { $TaskListBox.Items.Remove($TaskListBox.SelectedItems[0]) } } } } $UndoALLButton_Click= { #TODO: Place custom script here If ($TaskListBox.Items.Count -eq 0) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('The task list is empty.') } Else { foreach($Task in $TaskListBox.Items) { $Task = $Task.split(" ") $VM = $Task[3] $SourceName = $Task[9] $DestinationName = $Task[7] Get-VM -Name $VM | Move-VM -Destination (Get-VMhost $DestinationName) } $TaskListBox.Items.Clear() } } $SaveTaskButton_Click= { #TODO: Place custom script here If ($TaskListBox.items.count -eq 0) { [reflection.assembly]::loadwithpartialname('system.windows.forms') [system.Windows.Forms.MessageBox]::show('Nothing to save to log file.') } Else { $SaveFileD = new-object System.Windows.Forms.SaveFileDialog $SaveFileD.Filter = "All files (*.*)|*.*|log files (*.log)|*.log"; $SaveFileD.Title = "Save to a log file"; $SaveFileD.FilterIndex = 2; $SaveFileD.RestoreDirectory = $true; if ($SaveFileD.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) { $FileName = $SaveFileD.FileName $Tasks = $TaskListBox.items $logheader = "Easy Migration Tool v1.1 - Log generated on " + (Get-Date) #Save a log file for this session to a location selected by the user Out-File -InputObject $logheader -FilePath $Filename Out-File -InputObject "" -Append -FilePath $FileName Out-File -InputObject $Tasks -Append -FilePath $FileName } } } #---------------------------------------------- #region Generated Form Code # Start Main Form $MigrationForm.Text = 'Easy Migration Tool v1.1' $MigrationForm.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold) $MigrationForm.Name = 'EasyMigrationForm' $MigrationForm.StartPosition = "CenterScreen" $MigrationForm.FormBorderStyle = "FixedDialog" $MigrationForm.MaximizeBox = $false $MigrationForm.MinimizeBox = $false $MigrationForm.DataBindings.DefaultDataSourceUpdateMode = 0 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 1030 $System_Drawing_Size.Height = 500 $MigrationForm.ClientSize = $System_Drawing_Size # End Main Form #Start Easy_Migration Header $Header.Font = new-object System.Drawing.Font("Tahoma",10,[System.Drawing.FontStyle]::Bold) $Header.TextAlign = [System.Drawing.ContentAlignment]::MiddleLeft $Header.Text = 'Easy Migration Tool v1.1' $Header.Location = new-object System.Drawing.Point(150,15) $Header.Size = new-object System.Drawing.Size(230, 20) $MigrationForm.Controls.Add($Header) #End Easy_Migration Header # Start vCenter Server Label $vCenterLabel.TabIndex = 2 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 95 $System_Drawing_Size.Height = 20 $vCenterLabel.Size = $System_Drawing_Size $vCenterLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold) $vCenterLabel.Text = 'vCenter Server:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 15 $System_Drawing_Point.Y = 50 $vCenterLabel.Location = $System_Drawing_Point $vCenterLabel.DataBindings.DefaultDataSourceUpdateMode = 0 $vCenterLabel.Name = 'vCenterLabel' $MigrationForm.Controls.Add($vCenterLabel) # End vCenter Server Label # Start vCenter Textbox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 120 $System_Drawing_Size.Height = 20 $VCTextBox.Size = $System_Drawing_Size $VCTextBox.Font = new-object System.Drawing.Font("Tahoma",8) $VCTextBox.DataBindings.DefaultDataSourceUpdateMode = 0 $VCTextBox.Name = 'VCTextBox' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 110 $System_Drawing_Point.Y = 50 $VCTextBox.Location = $System_Drawing_Point $VCTextBox.TabIndex = 1 $MigrationForm.Controls.Add($VCTextBox) # End vCenter Textbox # Start Login Button $LoginButton.TabIndex = 0 $LoginButton.Name = 'LoginButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 95 $System_Drawing_Size.Height = 20 $LoginButton.Size = $System_Drawing_Size $LoginButton.Font = new-object System.Drawing.Font("Tahoma",8) $LoginButton.UseVisualStyleBackColor = $True $LoginButton.Text = 'Login' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 250 $System_Drawing_Point.Y = 50 $LoginButton.Location = $System_Drawing_Point $LoginButton.DataBindings.DefaultDataSourceUpdateMode = 0 $LoginButton.add_Click($LoginButton_Click) $MigrationForm.Controls.Add($LoginButton) # End Login Button # Start Change VC Button $ChangeVCButton.TabIndex = 19 $ChangeVCButton.Name = 'ChangeVCButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 95 $System_Drawing_Size.Height = 20 $ChangeVCButton.Size = $System_Drawing_Size $ChangeVCButton.Font = new-object System.Drawing.Font("Tahoma",8) $ChangeVCButton.UseVisualStyleBackColor = $True $ChangeVCButton.Text = 'Change vCenter' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 360 $System_Drawing_Point.Y = 50 $ChangeVCButton.Location = $System_Drawing_Point $ChangeVCButton.DataBindings.DefaultDataSourceUpdateMode = 0 $ChangeVCButton.add_Click($ChangeVCButton_OnClick) $ChangeVCButton.Enabled = $false $MigrationForm.Controls.Add($ChangeVCButton) # End Change VC Button # Start Cluster Listbox $ClusterLabel.TabIndex = 5 $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 85 $System_Drawing_Size.Height = 20 $ClusterLabel.Size = $System_Drawing_Size $ClusterLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold) $ClusterLabel.Text = 'Select Cluster:' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 20 $System_Drawing_Point.Y = 90 $ClusterLabel.Location = $System_Drawing_Point $ClusterLabel.DataBindings.DefaultDataSourceUpdateMode = 0 $ClusterLabel.Name = 'ClusterLabel' $MigrationForm.Controls.Add($ClusterLabel) $ClusterListBox.FormattingEnabled = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 120 $System_Drawing_Size.Height = 100 $ClusterListBox.Size = $System_Drawing_Size $ClusterListBox.Font = new-object System.Drawing.Font("Tahoma",8) $ClusterListBox.DataBindings.DefaultDataSourceUpdateMode = 0 $ClusterListBox.Name = 'ClusterListBox' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 110 $System_Drawing_Point.Y = 90 $ClusterListBox.Location = $System_Drawing_Point $ClusterListBox.MultiColumn = $false $ClusterListBox.TabIndex = 5 $ClusterListBox.Sorted = $True $MigrationForm.Controls.Add($ClusterListBox) # End Cluster Listbox # Start Host to Host Button $HostToHostButton.TabIndex = 3 $HostToHostButton.Name = 'HostToHostButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 130 $System_Drawing_Size.Height = 20 $HostToHostButton.Size = $System_Drawing_Size $HostToHostButton.Font = new-object System.Drawing.Font("Tahoma",8) $HostToHostButton.UseVisualStyleBackColor = $True $HostToHostButton.Text = 'Host to Host' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 250 $System_Drawing_Point.Y = 90 $HostToHostButton.Location = $System_Drawing_Point $HostToHostButton.DataBindings.DefaultDataSourceUpdateMode = 0 $HostToHostButton.add_Click($HostToHostButton_Click) $HostToHostButton.Enabled = $false $MigrationForm.Controls.Add($HostToHostButton) # End Host to Host Button # Start VM to Host Button $VMToHostButton.TabIndex = 3 $VMToHostButton.Name = 'VMToHostButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 130 $System_Drawing_Size.Height = 20 $VMToHostButton.Size = $System_Drawing_Size $VMToHostButton.Font = new-object System.Drawing.Font("Tahoma",8) $VMToHostButton.UseVisualStyleBackColor = $True $VMToHostButton.Text = 'VM to Host' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 250 $System_Drawing_Point.Y = 115 $VMToHostButton.Location = $System_Drawing_Point $VMToHostButton.DataBindings.DefaultDataSourceUpdateMode = 0 $VMToHostButton.add_Click($VMToHostButton_Click) $VMToHostButton.Enabled = $false $MigrationForm.Controls.Add($VMToHostButton) # End VM to Host Button # Start Datastore to Datastore Button $DBtoDBButton.TabIndex = 3 $DBtoDBButton.Name = 'DBtoDBButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 130 $System_Drawing_Size.Height = 20 $DBtoDBButton.Size = $System_Drawing_Size $DBtoDBButton.Font = new-object System.Drawing.Font("Tahoma",8) $DBtoDBButton.UseVisualStyleBackColor = $True $DBtoDBButton.Text = 'Datastore to Datastore' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 250 $System_Drawing_Point.Y = 140 $DBtoDBButton.Location = $System_Drawing_Point $DBtoDBButton.DataBindings.DefaultDataSourceUpdateMode = 0 $DBtoDBButton.add_Click($DBtoDBButton_Click) $DBtoDBButton.Enabled = $false $MigrationForm.Controls.Add($DBtoDBButton) # End Datastore to Datastore Button # Start VM to Datastore Button $VMtoDBButton.TabIndex = 3 $VMtoDBButton.Name = 'VMtoDBButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 130 $System_Drawing_Size.Height = 20 $VMtoDBButton.Size = $System_Drawing_Size $VMtoDBButton.Font = new-object System.Drawing.Font("Tahoma",8) $VMtoDBButton.UseVisualStyleBackColor = $True $VMtoDBButton.Text = 'VM to Datastore' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 250 $System_Drawing_Point.Y = 165 $VMtoDBButton.Location = $System_Drawing_Point $VMtoDBButton.DataBindings.DefaultDataSourceUpdateMode = 0 $VMtoDBButton.add_Click($VMtoDBButton_Click) $VMtoDBButton.Enabled = $false $MigrationForm.Controls.Add($VMtoDBButton) # End VM to Datastore Button # Start Source Host List Box $SourceHostListBox.FormattingEnabled = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 200 $System_Drawing_Size.Height = 200 $SourceHostListBox.Size = $System_Drawing_Size $SourceHostListBox.Font = new-object System.Drawing.Font("Tahoma",8) $SourceHostListBox.DataBindings.DefaultDataSourceUpdateMode = 0 $SourceHostListBox.Name = 'SourceHostListBox' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 30 $System_Drawing_Point.Y = 210 $SourceHostListBox.Location = $System_Drawing_Point $SourceHostListBox.MultiColumn = $false $SourceHostListBox.TabIndex = 5 $SourceHostListBox.Sorted = $True $MigrationForm.Controls.Add($SourceHostListBox) # End Source Host List Box # Start Source Datastore List Box $SourceDBListBox.FormattingEnabled = $True $SourceDBListBox.CheckOnClick = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 200 $System_Drawing_Size.Height = 200 $SourceDBListBox.Size = $System_Drawing_Size $SourceDBListBox.Font = new-object System.Drawing.Font("Tahoma",8) $SourceDBListBox.DataBindings.DefaultDataSourceUpdateMode = 0 $SourceDBListBox.Name = 'SourceDBListBox' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 30 $System_Drawing_Point.Y = 210 $SourceDBListBox.Location = $System_Drawing_Point $SourceDBListBox.MultiColumn = $false $SourceDBListBox.TabIndex = 5 $SourceDBListBox.Sorted = $True # End Source Datastore List Box # Start Source VM List Box $SourceVMListBox.FormattingEnabled = $True $SourceVMListBox.CheckOnClick = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 200 $System_Drawing_Size.Height = 200 $SourceVMListBox.Size = $System_Drawing_Size $SourceVMListBox.Font = new-object System.Drawing.Font("Tahoma",8) $SourceVMListBox.DataBindings.DefaultDataSourceUpdateMode = 0 $SourceVMListBox.Name = 'SourceVMListBox' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 30 $System_Drawing_Point.Y = 210 $SourceVMListBox.Location = $System_Drawing_Point $SourceVMListBox.MultiColumn = $false $SourceVMListBox.TabIndex = 5 $SourceVMListBox.Sorted = $True # End Source VM List Box # Start Source Button $SourceButton.TabIndex = 7 $SourceButton.Name = 'Source Button' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 200 $System_Drawing_Size.Height = 20 $SourceButton.Size = $System_Drawing_Size $SourceButton.Font = new-object System.Drawing.Font("Tahoma",8) $SourceButton.UseVisualStyleBackColor = $True $SourceButton.Text = 'Source' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 30 $System_Drawing_Point.Y = 415 $SourceButton.Location = $System_Drawing_Point $SourceButton.DataBindings.DefaultDataSourceUpdateMode = 0 $SourceButton.add_Click($SourceButton_OnClick) $SourceButton.Enabled = $false $MigrationForm.Controls.Add($SourceButton) # End Source Button # Start Destination List Box $DestinationListBox.FormattingEnabled = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 200 $System_Drawing_Size.Height = 200 $DestinationListBox.Size = $System_Drawing_Size $DestinationListBox.Font = new-object System.Drawing.Font("Tahoma",8) $DestinationListBox.DataBindings.DefaultDataSourceUpdateMode = 0 $DestinationListBox.Name = 'DestinationListBox' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 250 $System_Drawing_Point.Y = 210 $DestinationListBox.Location = $System_Drawing_Point $DestinationListBox.MultiColumn = $false $DestinationListBox.TabIndex = 5 $DestinationListBox.Sorted = $True $MigrationForm.Controls.Add($DestinationListBox) # End Destination List Box # Start Destination Button $DestinationButton.TabIndex = 7 $DestinationButton.Name = 'Destination Button' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 200 $System_Drawing_Size.Height = 20 $DestinationButton.Size = $System_Drawing_Size $DestinationButton.Font = new-object System.Drawing.Font("Tahoma",8) $DestinationButton.UseVisualStyleBackColor = $True $DestinationButton.Text = 'Destination' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 250 $System_Drawing_Point.Y = 415 $DestinationButton.Location = $System_Drawing_Point $DestinationButton.DataBindings.DefaultDataSourceUpdateMode = 0 $DestinationButton.add_Click($DestinationButton_OnClick) $DestinationButton.Enabled = $false $MigrationForm.Controls.Add($DestinationButton) # End Destination Button # Start Migrate Button $MigrateButton.TabIndex = 7 $MigrateButton.Name = 'MigrateButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 130 $System_Drawing_Size.Height = 25 $MigrateButton.Size = $System_Drawing_Size $MigrateButton.Font = new-object System.Drawing.Font("Tahoma",8) $MigrateButton.UseVisualStyleBackColor = $True $MigrateButton.Text = 'Migrate' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 30 $System_Drawing_Point.Y = 450 $MigrateButton.Location = $System_Drawing_Point $MigrateButton.DataBindings.DefaultDataSourceUpdateMode = 0 $MigrateButton.add_Click($MigrateButton_OnClick) $MigrateButton.Enabled = $false $MigrationForm.Controls.Add($MigrateButton) # End Migrate Button # Start RESET Button $ResetButton.TabIndex = 19 $ResetButton.Name = 'ResetButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 140 $System_Drawing_Size.Height = 25 $ResetButton.Size = $System_Drawing_Size $ResetButton.Font = new-object System.Drawing.Font("Tahoma",8) $ResetButton.UseVisualStyleBackColor = $True $ResetButton.Text = 'Reset' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 170 $System_Drawing_Point.Y = 450 $ResetButton.Location = $System_Drawing_Point $ResetButton.DataBindings.DefaultDataSourceUpdateMode = 0 $ResetButton.add_Click($ResetButton_OnClick) $ResetButton.Enabled = $false $MigrationForm.Controls.Add($ResetButton) # End RESET Button # Start CLOSE Button $CloseButton.TabIndex = 19 $CloseButton.Name = 'CloseButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 130 $System_Drawing_Size.Height = 25 $CloseButton.Size = $System_Drawing_Size $CloseButton.Font = new-object System.Drawing.Font("Tahoma",8) $CloseButton.UseVisualStyleBackColor = $True $CloseButton.Text = 'Close' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 320 $System_Drawing_Point.Y = 450 $CloseButton.Location = $System_Drawing_Point $CloseButton.DataBindings.DefaultDataSourceUpdateMode = 0 $CloseButton.add_Click($CloseButton_OnClick) $MigrationForm.Controls.Add($CloseButton) # End CLOSE Button # Start Messages ListBox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 80 $System_Drawing_Size.Height = 20 $MessagesLabel.Size = $System_Drawing_Size $MessagesLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold) $MessagesLabel.Text = 'Messages' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 480 $System_Drawing_Point.Y = 50 $MessagesLabel.Location = $System_Drawing_Point $MessagesLabel.DataBindings.DefaultDataSourceUpdateMode = 0 $MessagesLabel.Name = 'MessagesLabel' $MigrationForm.Controls.Add($MessagesLabel) $MessagesListBox.FormattingEnabled = $True $MessagesListBox.SelectionMode = "None" $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 525 $System_Drawing_Size.Height = 140 $MessagesListBox.Size = $System_Drawing_Size $MessagesListBox.Font = new-object System.Drawing.Font("Tahoma",8) $MessagesListBox.DataBindings.DefaultDataSourceUpdateMode = 0 $MessagesListBox.Name = 'MessagesListBox' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 480 $System_Drawing_Point.Y = 70 $MessagesListBox.Location = $System_Drawing_Point $MessagesListBox.MultiColumn = $false $MessagesListBox.HorizontalScrollbar = $true $MigrationForm.Controls.Add($MessagesListBox) # End Messages ListBox # Start Task ListBox $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 80 $System_Drawing_Size.Height = 20 $TaskLabel.Size = $System_Drawing_Size $TaskLabel.Font = new-object System.Drawing.Font("Tahoma",8,[System.Drawing.FontStyle]::Bold) $TaskLabel.Text = 'Recent Tasks' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 480 $System_Drawing_Point.Y = 215 $TaskLabel.Location = $System_Drawing_Point $TaskLabel.DataBindings.DefaultDataSourceUpdateMode = 0 $TaskLabel.Name = 'TaskLabel' $MigrationForm.Controls.Add($TaskLabel) $TaskListBox.FormattingEnabled = $True $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 525 $System_Drawing_Size.Height = 200 $TaskListBox.Size = $System_Drawing_Size $TaskListBox.Font = new-object System.Drawing.Font("Tahoma",8) $TaskListBox.DataBindings.DefaultDataSourceUpdateMode = 0 $TaskListBox.Name = 'TaskListBox' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 480 $System_Drawing_Point.Y = 235 $TaskListBox.Location = $System_Drawing_Point $TaskListBox.MultiColumn = $false $TaskListBox.HorizontalScrollbar = $true $TaskListBox.SelectionMode = "MultiExtended" $MigrationForm.Controls.Add($TaskListBox) # End Task ListBox # Start Clear Messages Button $ClearMsgButton.TabIndex = 0 $ClearMsgButton.Name = 'ClearMsgButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 120 $System_Drawing_Size.Height = 25 $ClearMsgButton.Size = $System_Drawing_Size $ClearMsgButton.Font = new-object System.Drawing.Font("Tahoma",8) $ClearMsgButton.UseVisualStyleBackColor = $True $ClearMsgButton.Text = 'Clear Messages' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 480 $System_Drawing_Point.Y = 450 $ClearMsgButton.Location = $System_Drawing_Point $ClearMsgButton.DataBindings.DefaultDataSourceUpdateMode = 0 $ClearMsgButton.add_Click($ClearMsgButton_Click) $MigrationForm.Controls.Add($ClearMsgButton) # End Clear Messages Button # Start Undo Button $UndoButton.TabIndex = 0 $UndoButton.Name = 'UndoButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 120 $System_Drawing_Size.Height = 25 $UndoButton.Size = $System_Drawing_Size $UndoButton.Font = new-object System.Drawing.Font("Tahoma",8) $UndoButton.UseVisualStyleBackColor = $True $UndoButton.Text = 'Undo' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 615 $System_Drawing_Point.Y = 450 $UndoButton.Location = $System_Drawing_Point $UndoButton.DataBindings.DefaultDataSourceUpdateMode = 0 $UndoButton.add_Click($UndoButton_Click) $MigrationForm.Controls.Add($UndoButton) # End Undo Button # Start UndoALL Button $UndoALLButton.TabIndex = 0 $UndoALLButton.Name = 'UndoALLButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 120 $System_Drawing_Size.Height = 25 $UndoALLButton.Size = $System_Drawing_Size $UndoALLButton.Font = new-object System.Drawing.Font("Tahoma",8) $UndoALLButton.UseVisualStyleBackColor = $True $UndoALLButton.Text = 'Undo ALL' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 750 $System_Drawing_Point.Y = 450 $UndoALLButton.Location = $System_Drawing_Point $UndoALLButton.DataBindings.DefaultDataSourceUpdateMode = 0 $UndoALLButton.add_Click($UndoALLButton_Click) $MigrationForm.Controls.Add($UndoALLButton) # End UndoALL Button # Start Save Task Button $SaveTaskButton.TabIndex = 0 $SaveTaskButton.Name = 'SaveTaskButton' $System_Drawing_Size = New-Object System.Drawing.Size $System_Drawing_Size.Width = 120 $System_Drawing_Size.Height = 25 $SaveTaskButton.Size = $System_Drawing_Size $SaveTaskButton.Font = new-object System.Drawing.Font("Tahoma",8) $SaveTaskButton.UseVisualStyleBackColor = $True $SaveTaskButton.Text = 'Save Tasks' $System_Drawing_Point = New-Object System.Drawing.Point $System_Drawing_Point.X = 885 $System_Drawing_Point.Y = 450 $SaveTaskButton.Location = $System_Drawing_Point $SaveTaskButton.DataBindings.DefaultDataSourceUpdateMode = 0 $SaveTaskButton.add_Click($SaveTaskButton_Click) $MigrationForm.Controls.Add($SaveTaskButton) # End Save Task Button #endregion Generated Form Code #Save the initial state of the form $InitialFormWindowState = $MigrationForm.WindowState #Init the OnLoad event to correct the initial state of the form $MigrationForm.add_Load($OnLoadForm_StateCorrection) #Show the Form $MigrationForm.ShowDialog()| Out-Null } #End Function #Call the Function GenerateForm
PowerShellCorpus/PoshCode/862a7a2f-5e6b-4cca-95e3-31247e664396.ps1
862a7a2f-5e6b-4cca-95e3-31247e664396.ps1
#Get information on everybodies inbox and spit it out with total sizes #in MB. Sorts the list by StorageLimitStatus #NOTE THAT I HAD TO USE ASCII WITH OUT-FILE AS NO OTHER ENCODING WOULD #PROPERLY IMPORT CSV INTO EXCEL #create a date var to stick in the filename $date = get-date -Format MM-dd-yyyy #create a outfile var so we only have to update it in one spot $OUTFILE = "C:\\Net_Admin_Stuff\\usage_reports\\daily_storage_limits\\Daily_Storage_Limits-$date.csv" #Create the default db send/receive quota divided by 1024 to convert KB to MB. $DEFAULTSENDQUOTA = 510000/1024 #Create a header to display at the top. $HEADER = "Display Name,Storage Limit Status,Item Count,Total Item Size (MB),Deleted Item Count,Total Deleted Item Size (MB),Prohibit Send/Receive Quota (MB),Quota Source" $HEADER | Out-File $OUTFILE -Append -Encoding Ascii #Get mailbox stats for all users, sort by Storage Limit Status and go through each users objects Get-MailboxStatistics | where {$_.ObjectClass -eq 'Mailbox'} | Sort-Object StorageLimitStatus | ForEach-Object { #Get the current user so we can grab some information from the get-mailbox command $CURUSER = get-mailbox -Identity $_.Identity #if the current user is using db defaults it will show a value of unlimited, which can't be calculated. #Push the default value into the field when this happens #Label where the source of the quota came from If ($CURUSER.UseDatabaseQuotaDefaults -eq $true) { $QUOTASRC = $CURUSER.Database $SENDQUOTA = $DEFAULTSENDQUOTA } else { $QUOTASRC = "User Profile" $SENDQUOTA = $CURUSER.ProhibitSendReceiveQuota.Value.ToMB() } #Generate useable vars for each of the objects that we're going to work with. $DNAME = $_.DisplayName; $SLSTATUS = $_.StorageLimitStatus; $ICOUNT = $_.ItemCount; $TISIZE = $_.TotalItemSize.Value.ToMB(); $DICOUNT = $_.DeletedItemCount; $TDISIZE = $_.TotalDeletedItemSize.Value.ToMB(); #spit out our information into a single row "$DNAME,$SLSTATUS,$ICOUNT,$TISIZE,$DICOUNT,$TDISIZE,$SENDQUOTA,$QUOTASRC" } | Out-File $OUTFILE -Append -Encoding Ascii
PowerShellCorpus/PoshCode/init_repoclones.ps1
init_repoclones.ps1
<# .SYNOPSIS Makes a local copy of one or more remote svn repositories. .DESCRIPTION Makes a local copy of one or more remote svn repositories. .INPUTS None You cannot pipe objects to init-repoclones.ps1 .OUTPUTS None .EXAMPLE #> param ( [string[]] $Repos = @('protobuf', 'mb-unit', 'opennode2'), [string] $RemoteRepoFormat = 'http://{0}.googlecode.com/svn/', [string] $LocalRepoBasePath = (Split-Path (Get-Variable MyInvocation).Value.MyCommand.Path), [switch] $DeleteExisting ) # check that we have the svn executables we need @('svnsync.exe', 'svnadmin.exe') | % { if (-not (Get-Command $_ -ErrorAction SilentlyContinue)) { Write-Host "The executable `"$($_)`" is required by this script and was not found on the path."; exit 1; } } $Repos | % { $localRepoPath = (Join-Path $($LocalRepoBasePath) $_); $localRepoUri = ([uri]($localRepoPath)).AbsoluteUri; $remoteRepo = [string]::Format($RemoteRepoFormat, $_); if (Test-Path $localRepoPath) { if ($DeleteExisting) { Write-Host "$($localRepoPath) already exists. Deleting . . ."; rm -r -f $localRepoPath; } else { Write-Host "$($localRepoPath) already exists. Skipping initialization . . ."; } } else { Write-Host "Cloning $($remoteRepo) into $($localRepoPath)" & svnadmin create $localRepoPath; [IO.File]::WriteAllText((Join-Path $localRepoPath 'hooks\\pre-revprop-change.bat'), 'exit 0'); & svnsync init $localRepoUri $remoteRepo; } & svnsync sync $localRepoUri $remoteRepo; }
PowerShellCorpus/PoshCode/Install-Patches.ps1
Install-Patches.ps1
<# Save this with a .PSM1 extension and use Import-Module to properly load the functions. ie: Install-Patches.psm1 Import-Module Install-Patches.psm1 #> #Validate user is an Administrator Write-Verbose "Checking Administrator credentials" If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(` [Security.Principal.WindowsBuiltInRole] "Administrator")) { Write-Warning "You are not running this as an Administrator!`nPlease re-run this with an Administrator account." Break } Function Create-UpdateVBS { Param ($computername) #Create Here-String of vbscode to create file on remote system $vbsstring = @" ON ERROR RESUME NEXT CONST ForAppending = 8 CONST ForWriting = 2 CONST ForReading = 1 strlocalhost = "." Set oShell = CreateObject("WScript.Shell") set ofso = createobject("scripting.filesystemobject") Set updateSession = CreateObject("Microsoft.Update.Session") Set updateSearcher = updateSession.CreateupdateSearcher() Set updatesToInstall = CreateObject("Microsoft.Update.UpdateColl") Set searchResult = updateSearcher.Search("IsInstalled=0 and Type='Software'") Set objWMI = GetObject("winmgmts:\\\\" & strlocalhost & "\\root\\CIMV2") set colitems = objWMI.ExecQuery("SELECT Name FROM Win32_ComputerSystem") For Each objcol in colitems strcomputer = objcol.Name Next set objtextfile = ofso.createtextfile("C:\\" & strcomputer & "_patchlog.csv", True) objtextfile.writeline "Computer,Title,KB,InstallResultCode" If searchresult.updates.count = 0 Then Wscript.echo "No updates to install." objtextfile.writeline strcomputer & ",NA,NA,NA" Wscript.Quit Else For I = 0 To searchResult.Updates.Count-1 set update = searchResult.Updates.Item(I) If update.IsDownloaded = true Then updatesToInstall.Add(update) End If Next End If err.clear Wscript.Echo "Installing Updates" Set installer = updateSession.CreateUpdateInstaller() installer.Updates = updatesToInstall Set installationResult = installer.Install() If err.number <> 0 Then objtextfile.writeline strcomputer & "," & update.Title & ",NA," & err.number Else For I = 0 to updatesToInstall.Count - 1 objtextfile.writeline strcomputer & "," & updatesToInstall.Item(i).Title & ",NA," & installationResult.GetUpdateResult(i).ResultCode Next End If Wscript.Quit "@ Write-Verbose "Creating vbscript file on $computer" Try { $vbsstring | Out-File "\\\\$computername\\c$\\update.vbs" -Force Return $True } Catch { Write-Warning "Unable to create update.vbs!" Return $False } } Function Format-InstallPatchLog { [cmdletbinding()] param ($computername) #Create empty collection $installreport = @() #Check for logfile If (Test-Path "\\\\$computername\\c$\\$($computername)_patchlog.csv") { #Retrieve the logfile from remote server [array]$CSVreport = Import-Csv "\\\\$computername\\c$\\$($computername)_patchlog.csv" If ($csvreport[0].title -ne "NA") { #Iterate through all items in patchlog ForEach ($log in $CSVreport) { $temp = "" | Select Computer,Title,KB,InstallResultCode $temp.Computer = $log.Computer $temp.Title = $log.title.split('\\(')[0] $temp.KB = ($log.title.split('\\(')[1]).split('\\)')[0] Switch ($log.InstallResultCode) { 1 {$temp.InstallResultCode = "No Reboot required"} 2 {$temp.InstallResultCode = "Reboot Required"} 4 {$temp.InstallResultCode = "Failed to Install Patch"} "-2145124316" {$temp.InstallResultCode = "Update is not available to install"} Default {$temp.InstallResultCode = "Unable to determine Result Code"} } $installreport += $temp } } Else { $temp = "" | Select Computer, Title, KB,InstallResultCode $temp.Computer = $computername $temp.Title = "NA" $temp.KB = "NA" $temp.InstallResultCode = "NA" $installreport += $temp } } Else { $temp = "" | Select Computer, Title, KB,InstallResultCode $temp.Computer = $computername $temp.Title = "NA" $temp.KB = "NA" $temp.InstallResultCode = "NA" $installreport += $temp } Write-Output $installreport } Function Install-Patches { <# .SYNOPSIS Install patches on a local or remote computer and generates a report. .DESCRIPTION Install patches on a local or remote computer and generates a report with status of installation. .PARAMETER Computername Name of the computer to install patches on. .NOTES Name: Install-Patches Author: Boe Prox DateCreated: 19May2011 .LINK https://boeprox.wordpress.com .EXAMPLE Install-Patches -Computername Server1 Description ----------- Installs patches on Server1 and displays report with installation status. .EXAMPLE Install-Patches -Computername Server1,Server2,Server3 Description ----------- Installs patches on Server1,Server2 and Server3 and displays report with installation status. #> [cmdletbinding()] Param( [Parameter(Mandatory = $True,Position = 0,ValueFromPipeline = $True)] [string[]]$Computername ) Begin { If (-Not (Test-Path psexec.exe)) { Write-Warning "PSExec not in same directory as script!" Break } } Process { ForEach ($computer in $computername) { If ((Test-Connection -ComputerName $computer -Count 1 -Quiet)) { Write-Verbose "Creating update.vbs file on remote server." If (Create-UpdateVBS -computer $computer) { Write-Verbose "Patching computer: $($computer)" .\\psexec.exe -accepteula -s -i \\\\$computer cscript.exe C:\\update.vbs If ($LASTEXITCODE -eq 0) { Write-Verbose "Successful run of install script!" Write-Verbose "Formatting log file and adding to report" Format-InstallPatchLog -computer $computer } Else { Write-Warning "Unsuccessful run of install script!" $report = "" | Select Computer,Title,KB,IsDownloaded,InstallResultCode $report.Computer = $computer $report.Title = "ERROR" $report.KB = "ERROR" $report.IsDownloaded = "ERROR" $report.InstallResultCode = "ERROR" Write-Output $report } } Else { Write-Warning "Unable to install patches on $computer" $report = "" | Select Computer,Title,KB,IsDownloaded,InstallResultCode $report.Computer = $computer $report.Title = "ERROR" $report.KB = "ERROR" $report.IsDownloaded = "ERROR" $report.InstallResultCode = "ERROR" Write-Output $report } } Else { Write-Warning "$($Computer): Unable to connect!" } } } } Export-ModuleMember Install-Patches
PowerShellCorpus/PoshCode/exclude properties_.ps1
exclude properties_.ps1
$server = "dcserver1.mafoberg.net" $session = new-pssession -computer $server -cred $creds icm -Session $session -ScriptBlock { import-module activedirectory (get-ADUser -filter "*" -properties GivenName, SurName, EmailAddress | select -ExcludeProperty PSComputerName, RunspaceId, PSShowComputerName ) } | select -ExcludeProperty PSComputerName, RunspaceId, PSShowComputerName Remove-PSSession $session
PowerShellCorpus/PoshCode/Check-LotusHealth.ps1
Check-LotusHealth.ps1
# ============================================================================================== # # Microsoft PowerShell Source File -- Created with SAPIEN Technologies PrimalScript 4.1 # # NAME: Check-LotusHealth.ps1 # # AUTHOR: Jeremy D. Pavleck , Pavleck.NET # DATE : 5/19/2008 # # COMMENT: This script queries the ports of a Lotus notes environment, verifying that the various # services are up and running, such as LDAP, SameTime, SMTP, Notes, SSL, etc. Script has been # cleansed of customer data, but placeholder values were left in place to show how to use it. # Odds are this will need customization in your environment. # # ============================================================================================== # Construct constants Set-Variable -name SMTPPort -value 25 -option constant Set-Variable -name WWWPort -value 80 -option constant Set-Variable -name LDAPPort -value 389 -option constant Set-Variable -name Port410 -value 410 -option constant Set-Variable -name SSLPort -value 443 -option constant Set-Variable -name NOTESPort -value 1352 -option constant # Create hashtables to hold failed checks, sametime specific fails, and successes $afails = @{} $astfails = @{} $agood = @{} # Instantiate array to hold server information $aservers = @{} # Now, to populate it # We will monitor one or more of the following ports - SMTP (25), WWW (80), LDAP (389) # Port 410, SSL (443), Notes (1352) or several SameTime ports. $aservers["SERVER01"] = @{Notes=$True;} $aservers["SERVER02"] = @{SMTP=$True; WWW=$True; Notes=$True;} $aservers["SERVER03"] = @{SMTP=$True; WWW=$True; Notes=$True;} $aservers["SERVER04"] = @{WWW=$True; Notes=$True;} $aservers["SERVER05"] = @{WWW=$True; Notes=$True;} $aservers["SERVER06"] = @{Notes=$True;} $aservers["SERVER07"] = @{Notes=$True;} $aservers["SERVER08"] = @{Notes=$True;} $aservers["SERVER09"] = @{Notes=$True;} $aservers["SERVER10"] = @{Notes=$True;} $aservers["SERVER11"] = @{Notes=$True;} $aservers["SERVER12"] = @{Notes=$True;} $aservers["SERVER13"] = @{Notes=$True;} $aservers["SERVER14"] = @{Notes=$True;} $aservers["SERVER15"] = @{Notes=$True;} $aservers["SERVER16"] = @{Notes=$True;} $aservers["SERVER17"] = @{Notes=$True;} $aservers["SERVER18"] = @{Notes=$True;} $aservers["SERVER19"] = @{Notes=$True;} $aservers["SERVER20"] = @{SMTP=$True; Notes=$True;} $aservers["SERVER21"] = @{SMTP=$True; Notes=$True;} $aservers["SERVER22"] = @{SMTP=$True; Notes=$True;} $aservers["SERVER23"] = @{SMTP=$True; Notes=$True;} $aservers["SERVER24"] = @{WWW=$True; SSL=$True; Notes=$True;} $aservers["SERVER25"] = @{Notes=$True;} $aservers["SERVER26"] = @{WWW=$True; Notes=$True; SameTime=$True;} # And so on and so forth # Array of SameTime ports - if SameTime is on a server, then all of these ports will be there. # So we'll just make a seperate array holding them to make it easier $astime = 1516, 1533, 8081, 8082, 1503, 554 # function Ping-Port is used to connect to the server on the designated port. # Returns $True if it connect, $False if not. function Ping-Port([string]$server, [int]$port) { $tcpClient = New-Object System.Net.Sockets.TcpClient trap { # Generic trap object, we don't care what the error is, the check still fails. $False continue; } $tcpClient.Connect($server,$port) if ($tcpClient.Connected) {$True} } # Create Ping object # This function only checks for a server response function Ping-Server([string]$server) { $ping = New-Object System.Net.NetworkInformation.Ping trap { # Generic trap object, we don't care what the error is, the check still fails. $False continue; } If ($ping.send($server).status -eq "Success") {$True} $ping = $null } # Now, here we go # First we will iterate through all of the servers, then iterate through each server # If we have a particular port marked as supposed to being available, then we attempt to # ping it, otherwise we move onto the next item. # We also attempt to ping the server itself first - if that fails, we automagically # mark all of the ports as failed. It is completely possible that your particular # environment may block pings, if so you'll need to adjust this. $aservers.Keys | ForEach-Object { If (Ping-Server $_) { Write-Host "$_ responded." -ForeGroundColor Green $agood[$_] += @{HOST=$True;} If ($aservers[$_].notes) { # If Lotus Notes is on this machine If (Ping-Port $_ $NOTESPort) { # Check it Write-Host "$_: Lotus Notes Port ($NOTESPort) Responding" -ForeGroundColor Green $agood[$_] += @{NOTES=$True;} } else { Write-Host "$_: Host is reported to have Notes ($NOTESPort) but it is not responding." -ForeGroundColor Red $afails[$_] += @{NOTES=$True;} } } If ($aservers[$_].smtp) { # If SMTP is here If (Ping-Port $_ $SMTPPort) { # Check it Write-Host "$_: SMTP ($SMTPPort) Responding" -Foregroundcolor green $agood[$_] += @{SMTP=$True;} } else { Write-Host "$_: Host is reported to have SMTP, but it is not responding." -Foregroundcolor red $afails[$_] += @{SMTP=$True;} } } If ($aservers[$_].www) { # If WWW is here If (Ping-Port $_ $WWWPort) { #Check it Write-Host "$_: WWW ($WWWPort) Responding" -foregroundcolor green $agood[$_] += @{WWW=$True;} } else { Write-Host "$_: Host is reported to have WWW, but it is not responding." -foregroundcolor red $afails[$_] += @{WWW=$True;} } } If ($aservers[$_].ldap) { # If LDAP is here If (Ping-Port $_ $LDAPPort) { # check it Write-Host "$_: LDAP ($LDAPPOrt) Responding" -foregroundcolor green $agood[$_] += @{LDAP=$True;} } else { Write-Host "$_: Host is reported to have LDAP, but it is not responding." -foregroundcolor red $afails[$_] += @{LDAP=$True;} } } If ($aservers[$_].port410) { # If port 410 is here If (Ping-Port $_ $port410) { # check it Write-Host "$_: Port 410 ($port410) Responding" -foregroundcolor green $agood[$_] += @{Port410=$True;} } else { Write-Host "$_: Host is reported to have port 410, but it is not responding." -foregroundcolor red $afails[$_] += @{Port410=$True;} } } If ($aservers[$_].ssl) { # If SSL is here If (Ping-Port $_ $SSLPort) { # check it Write-Host "$_: SSL ($SSLPort) Responding" -foregroundcolor green $agood[$_] += @{SSL=$True;} } else { Write-Host "$_: Host is reported to have SSL, but it is not responding." -foregroundcolor red $afails[$_] += @{SSL=$True;} } } If ($aservers[$_].sametime) { # If SameTime is here $st = $_ $astime | ForEach-Object { If (Ping-Port $st $_) { Write-Host "$st: SameTime Port $_ Success." -foregroundcolor green } else { Write-Host "$st: SameTime Port $_ Not Responding." -foregroundcolor red $astfails[$st] += @{$_=$True;} } } } } else { Write-Host "Host $_ is not responding." -ForeGroundColor Red $afails[$_] += @{HOST=$True;} } } If ($afails.count -gt 0) { Write-Host "`n`nCompleted - Errors reported - the following ping tests failed:" -ForeGroundColor Magenta Write-Host "`nServer `t`tFailed Ports" -Foregroundcolor Magenta Write-Host "----------------------------------------" -ForegroundColor Magenta $afails.Keys | ForEach-Object { Write-host "$($_): `t$($afails[$_].Keys)" -ForeGroundColor Magenta } } else { Write-Host "`n`nCompleted - All ports are responding." -ForegroundColor Green } If ($astfails.count -gt 0) { Write-Host "Errors reported within the SameTime environment" -Foregroundcolor Magents } else { Write-Host "SameTime Environment is fully responsive." -ForegroundColor Green }
PowerShellCorpus/PoshCode/Enable_Configure SNMP_3.ps1
Enable_Configure SNMP_3.ps1
#Powershell Script To Install SNMP Services (SNMP Service, SNMP WMI Provider) #Variables :) $pmanagers = "ADD YOUR MANAGER(s)" $commstring = "ADD YOUR COMM STRING" #Import ServerManger Module Import-Module ServerManager #Check If SNMP Services Are Already Installed $check = Get-WindowsFeature | Where-Object {$_.Name -eq "SNMP-Services"} If ($check.Installed -ne "True") { #Install/Enable SNMP Services Add-WindowsFeature SNMP-Services | Out-Null } ##Verify Windows Servcies Are Enabled If ($check.Installed -eq "True"){ #Set SNMP Permitted Manager(s) ** WARNING : This will over write current settings ** reg add "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\SNMP\\Parameters\\PermittedManagers" /v 1 /t REG_SZ /d localhost /f | Out-Null #Used as counter for incremting permitted managers $i = 2 Foreach ($manager in $pmanagers){ reg add "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\SNMP\\Parameters\\PermittedManagers" /v $i /t REG_SZ /d $manager /f | Out-Null $i++ } #Set SNMP Community String(s)- *Read Only* Foreach ( $string in $commstring){ reg add "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\SNMP\\Parameters\\ValidCommunities" /v $string /t REG_DWORD /d 4 /f | Out-Null } } Else {Write-Host "Error: SNMP Services Not Installed"}
PowerShellCorpus/PoshCode/Hash Checker.ps1
Hash Checker.ps1
#.Synopsis # Test the HMAC hash(es) of a file #.Description # Takes the HMAC hash of a file using specified algorithm, and optionally, compare it to a baseline hash #.Example # Test-Hash npp.5.3.1.Installer.exe -HashFile npp.5.3.1.release.md5 # # Searches the provided hash file for a line matching the "npp.5.3.1.Installer.exe" file name # and take the hash of the file (using the extension of the HashFile as the Type of Hash). # #.Example # Test-Hash npp.5.3.1.Installer.exe 360293affe09ffc229a3f75411ffa9a1 MD5 # # Takes the MD5 hash and compares it to the provided hash # #.Example # Test-Hash npp.5.3.1.Installer.exe 5e6c2045f4ddffd459e6282f3ff1bd32b7f67517 # # Tests all of the hashes against the provided (Sha1) hash # function Test-Hash { #[CmdletBinding(DefaultParameterSetName="NoExpectation")] PARAM( #[Parameter(Position=0,Mandatory=$true)] [string]$FileName , #[Parameter(Position=2,Mandatory=$true,ParameterSetName="ManualHash")] [string]$ExpectedHash = $(if($HashFileName){ ((Get-Content $HashFileName) -match $FileName)[0].split(" ")[0] }) , #[Parameter(Position=1,Mandatory=$true,ParameterSetName="FromHashFile")] [string]$HashFileName , #[Parameter(Position=1,Mandatory=$true,ParameterSetName="ManualHash")] [string[]]$TypeOfHash = $(if($HashFileName){ [IO.Path]::GetExtension((Convert-Path $HashFileName)).Substring(1) } else { "MD5","SHA1","SHA256","SHA384","SHA512","RIPEMD160" }) ) $ofs="" $hashes = @{} foreach($Type in $TypeOfHash) { [string]$hash = [Security.Cryptography.HashAlgorithm]::Create( $Type ).ComputeHash( [IO.File]::ReadAllBytes( (Convert-Path $FileName) ) ) | ForEach { "{0:x2}" -f $_ } $hashes.$Type = $hash } if($ExpectedHash) { ($hashes.Values -eq $hash).Count -ge 1 } else { foreach($hash in $hashes.GetEnumerator()) { "{0,-8}{1}" -f $hash.Name, $hash.Value } } }
PowerShellCorpus/PoshCode/List Windows File Shares.ps1
List Windows File Shares.ps1
Get-WmiObject Win32_Share -computerName SERVERNAME | Select Name, Caption, Path | Export-csv "c:\\temp\\SERVERNAME.csv" -NoTypeInformation
PowerShellCorpus/PoshCode/Install-ISPackage_1.ps1
Install-ISPackage_1.ps1
####################### <# .SYNOPSIS Installs an SSIS package to a SQL Server store. .DESCRIPTION The Install-ISPackage script installs an Dtsx file to a SQL Server store using the command-line utility dtutil. Works for 2005 and higher .EXAMPLE ./install-ispackage.ps1 -DtsxFullName "C:\\Users\\Public\\bin\\SSIS\\sqlpsx1.dtsx" -ServerInstance "Z001\\SQL1" -PackageFullName "SQLPSX\\sqlpsx1" This command install the sqlpsx1.dtsx package to SQL Server instance Z001\\SQL1 under the SQLPSX folder as sqlpsx1. If SQLPSX folder does not exist it will be created. .NOTES Version History v1.0 - Chad Miller - 6/26/2012 - Initial release v1.1 - Chad Miller - 7/05/2012 - Updated to output object. Fixed lastexitcode check in test functions v1.2 - Chad Miller - 7/09/2012 - Added SqlVersion and Dtutil Path logic v1.3 - Chad Miller - 7/10/2012 - Fixed 2005 path logic v1.4 - Chad Miller - 9/25/2012 - Fixed 2012 path logic v1.5 - Chad Miller - 11/20/2012 - Fixed issues with root path deployments #> param( [Parameter(Position=0, Mandatory=$true)] [string] $DtsxFullName, [Parameter(Position=1, Mandatory=$true)] [string] $ServerInstance, [Parameter(Position=2, Mandatory=$true)] [string] $PackageFullName ) $ErrorActionPreference = "Stop" $Script:dtutil = $null $exitCode = @{ 0="The utility executed successfully." 1="The utility failed." 4="The utility cannot locate the requested package." 5="The utility cannot load the requested package." 6="The utility cannot resolve the command line because it contains either syntactic or semantic errors"} ####################### function Get-SqlVersion { param($ServerInstance) write-verbose "sqlcmd -S `"$ServerInstance`" -d `"master`" -Q `"SET NOCOUNT ON; SELECT SERVERPROPERTY('ProductVersion')`" -h -1 -W" $SqlVersion = sqlcmd -S "$ServerInstance" -d "master" -Q "SET NOCOUNT ON; SELECT SERVERPROPERTY('ProductVersion')" -h -1 -W if ($lastexitcode -ne 0) { throw $SqlVersion } else { $SqlVersion } } #Get-SqlVersion ####################### function Set-DtutilPath { param($SqlVersion) $paths = [Environment]::GetEnvironmentVariable("Path", "Machine") -split ";" if ($SqlVersion -like "9*") { $Script:dtutil = $paths | where { $_ -like "*Program Files\\Microsoft SQL Server\\90\\DTS\\Binn\\" } if ($Script:dtutil -eq $null) { throw "SQL Server 2005 Version of dtutil not found." } } elseif ($SqlVersion -like "10*") { $Script:dtutil = $paths | where { $_ -like "*Program Files\\Microsoft SQL Server\\100\\DTS\\Binn\\" } if ($Script:dtutil -eq $null) { throw "SQL Server 2008 or 2008R2 Version of dtutil not found." } } elseif ($SqlVersion -like "11*") { $Script:dtutil = $paths | where { $_ -like "*Program Files\\Microsoft SQL Server\\110\\DTS\\Binn\\" } if ($Script:dtutil -eq $null) { throw "SQL Server 2012 Version of dtutil not found." } } if ($Script:dtutil -eq $null) { throw "Unable to find path to dtutil.exe. Verify dtutil installed." } else { $Script:dtutil += 'dtutil.exe' } } #Set-DtutilPath ####################### function install-package { param($DtsxFullName, $ServerInstance, $PackageFullName) $result = & $Script:dtutil /File "$DtsxFullName" /DestServer "$ServerInstance" /Copy SQL`;"$PackageFullName" /Quiet $result = $result -join "`n" new-object psobject -property @{ ExitCode = $lastexitcode ExitDescription = "$($exitcode[$lastexitcode])" Command = "$Script:dtutil /File `"$DtsxFullName`" /DestServer `"$ServerInstance`" /Copy SQL;`"$PackageFullName`" /Quiet" Result = $result Success = ($lastexitcode -eq 0)} if ($lastexitcode -ne 0) { throw $exitcode[$lastexitcode] } } #install-package ####################### function test-path { param($ServerInstance, $FolderPath) write-verbose "$Script:dtutil /SourceServer `"$ServerInstance`" /FExists SQL`;`"$FolderPath`"" $result = & $Script:dtutil /SourceServer "$ServerInstance" /FExists SQL`;"$FolderPath" if ($lastexitcode -gt 1) { $result = $result -join "`n" throw "$result `n $($exitcode[$lastexitcode])" } if ($result -and $result[4] -eq "The specified folder exists.") { $true } else { $false } } #test-path ####################### function test-packagepath { param($ServerInstance, $PackageFullName) write-verbose "$Script:dtutil /SourceServer `"$ServerInstance`" /SQL `"$PackageFullName`" /EXISTS" $result = & $Script:dtutil /SourceServer "$ServerInstance" /SQL "$PackageFullName" /EXISTS if ($lastexitcode -gt 1) { $result = $result -join "`n" throw "$result `n $($exitcode[$lastexitcode])" } new-object psobject -property @{ ExitCode = $lastexitcode ExitDescription = "$($exitcode[$lastexitcode])" Command = "$Script:dtutil /SourceServer `"$ServerInstance`" /SQL `"$PackageFullName`" /EXISTS" Result = $result[4] Success = ($lastexitcode -eq 0 -and $result -and $result[4] -eq "The specified package exists.")} } #test-packagepath ####################### function new-folder { param($ServerInstance, $ParentFolderPath, $NewFolderName) $result = & $Script:dtutil /SourceServer "$ServerInstance" /FCreate SQL`;"$ParentFolderPath"`;"$NewFolderName" $result = $result -join "`n" new-object psobject -property @{ ExitCode = $lastexitcode ExitDescription = "$($exitcode[$lastexitcode])" Command = "$Script:dtutil /SourceServer `"$ServerInstance`" /FCreate SQL;`"$ParentFolderPath`";`"$NewFolderName`"" Result = $result Success = ($lastexitcode -eq 0)} if ($lastexitcode -ne 0) { throw $exitcode[$lastexitcode] } } #new-folder ####################### function Get-FolderList { param($PackageFullName) if ($PackageFullName -match '\\\\') { $folders = $PackageFullName -split "\\\\" 0..$($folders.Length -2) | foreach { new-object psobject -property @{ Parent=$(if($_-gt 0) { $($folders[0..$($_ -1)] -join "\\") } else { "\\" }) FullPath=$($folders[0..$_] -join "\\") Child=$folders[$_]}} } } #Get-FolderList ####################### ## MAIN ## ####################### try { #1. Get Sql Version $SqlVersion = Get-SqlVersion -ServerInstance $ServerInstance #2. Set Dtutil Path based on Sql Version Set-DtutilPath -SqlVersion $SqlVersion #3. Get SSIS Folder List, verify exists and created missing folders Get-FolderList -PackageFullName $PackageFullName | where { $_.FullPath -ne "" -and $(test-path -ServerInstance $ServerInstance -FolderPath $_.FullPath) -eq $false } | foreach { new-folder -ServerInstance $ServerInstance -ParentFolderPath $_.Parent -NewFolderName $_.Child } #4. Install SSIS Package install-package -DtsxFullName $DtsxFullName -ServerInstance $ServerInstance -PackageFullName $PackageFullName #5. Verify Package test-packagepath -ServerInstance $ServerInstance -PackageFullName $PackageFullName } catch { write-error "$_ `n $("Failed to install DtsxFullName {0} to ServerInstance {1} PackageFullName {2}" -f $DtsxFullName,$ServerInstance,$PackageFullName)" }
PowerShellCorpus/PoshCode/Issue-PendingRequest.ps1
Issue-PendingRequest.ps1
##################################################################### # Issue certificate.ps1 # Version 1.5 # # Issues certificate request from a pending request # # For this function to succeed, the certificate request must be pending # # Vadims Podans (c) 2010 # http://en-us.sysadmins.lv/ ##################################################################### #requires -Version 2.0 function Issue-PendingRequest { [CmdletBinding()] param( [Parameter(Mandatory = $true, ValueFomPipeline = $true)] [string]$CAConfig, [Parameter(Mandatory = $true)] [int]$RequestID ) try {$CertAdmin = New-Object -ComObject CertificateAuthority.Admin} catch {Write-Warning "Unable to instantiate ICertAdmin2 object!"; return} try { $status = switch ($CertAdmin.ResubmitRequest($CAConfig,$RequestID)) { 0 {"The request was not completed."} 1 {"The request failed."} 2 {"The request was denied"} 3 {"The certificate was issued."} 4 {"The certificate was issued separately."} 5 {"The request was taken under submission."} 6 {"The certificate is revoked."} } } catch {$_; return} Write-Host "Operation status for the request '$RequestID': $ststus" }
PowerShellCorpus/PoshCode/format-iislog for AWStat.ps1
format-iislog for AWStat.ps1
param ( [Parameter( Mandatory=$true, Position = 0, ValueFromPipeline=$true, HelpMessage="Specifies the path to the IIS *.log file to import. You can also pipe a path to Import-Iss-Log." )] [ValidateNotNullOrEmpty()] [string] $Path, [Parameter( Mandatory=$true, Position = 1, ValueFromPipeline=$true, HelpMessage="Specifies the desired field names. Must be in the following format: #Fields: fname1 fname2" )] [ValidateNotNullOrEmpty()] [string] $NewPath, [Parameter( Mandatory=$true, Position = 2, ValueFromPipeline=$true, HelpMessage="Specifies the output location for the modified log file." )] [ValidateNotNullOrEmpty()] [string] $OutPath, [Parameter( Position = 3, HelpMessage="Specifies the delimiter that separates the property values in the IIS *.log file. The default is a spacebar." )] [ValidateNotNullOrEmpty()] [string] $Delimiter = " ", [Parameter(HelpMessage="The character encoding for the IIS *log file. The default is the UTF8.")] [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding] $Encoding = [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]::UTF8 ) begin { $fieldNames = @() $newfieldnames = @() } process { #add headers to new output file (get-content $path)[0..2] | Out-File $outpath -Append -encoding Default $newpath | Out-File $outpath -Append -encoding Default #populate $newfieldnames from the mandatory parameter $newpath $newfieldNames = @($newpath.Substring("#Fields: ".Length).Split($Delimiter)); foreach($line in Get-Content -Path $Path) { # Indentify / parse the log header to determine field names if($line.StartsWith("#Fields: ")) { $fieldNames = @($line.Substring("#Fields: ".Length).Split($Delimiter)); } # Identify / parse the "non log header" lines to determine field values elseif(-not $line.StartsWith("#")) { $logline = "" $fieldValues = @($line.Split($Delimiter)); #Initialize a hashtable to hold fields and values #Default value is a hyphen #Only fields specified in the $newpath parameter are initialized $output = @{} foreach ($item in $newfieldnames) { switch($item) { "date"{ $output.add("date", "-")} "time"{ $output.add("time", "-")} "s-ip"{ $output.add("s-ip", "-")} "cs-method"{ $output.add("cs-method", "-")} "cs-uri-stem"{ $output.add("cs-uri-stem", "-")} "cs-uri-query"{ $output.add("cs-uri-query", "-")} "s-port"{ $output.add("s-port", "-")} "cs-username"{ $output.add("cs-username", "-")} "c-ip"{ $output.add("c-ip", "-")} "cs-version"{ $output.add("cs-version", "-")} "cs(User-Agent)"{ $output.add("cs(User-Agent)", "-")} "sc-status"{ $output.add("sc-status", "-")} "sc-substatus"{ $output.add("sc-substatus", "-")} "sc-win32-status"{ $output.add("sc-win32-status", "-")} "sc-bytes"{ $output.add("sc-bytes", "-")} "time-taken"{ $output.add("time-taken", "-")} "cs-host"{ $output.add("cs-host", "-")} "cs(Cookie)"{ $output.add("cs(Cookie)", "-")} "cs(Referer)"{ $output.add("cs(Referer)", "-")} "s-sitename"{ $output.add("s-sitename", "-")} "s-computername"{ $output.add("s-computername", "-")} "cs-bytes"{ $output.add("cs-bytes", "-")} } } #Add every field from old log file to the $ouptuts hashtable #Portions of the hash table which are not over written at this point retain the default value (hyphen) for($i = 0; $i -lt $fieldnames.Length; $i++) { $name = $fieldNames[$i] $value = $fieldValues[$i] switch($name) { "date"{ $output['date'] = $value} "time"{ $output['time'] = $value} "s-ip"{ $output['s-ip'] = $value} "cs-method"{ $output['cs-method'] = $value} "cs-uri-stem"{ $output['cs-uri-stem'] = $value} "cs-uri-query"{ $output['cs-uri-query'] = $value} "s-port"{ $output['s-port'] = $value} "cs-username"{ $output['cs-username'] = $value} "c-ip"{ $output['c-ip'] = $value} "cs-version"{ $output['cs-version'] = $value} "cs(User-Agent)"{ $output['cs(User-Agent)'] = $value} "sc-status"{ $output['sc-status'] = $value} "sc-substatus"{ $output['sc-substatus'] = $value} "sc-win32-status"{ $output['sc-win32-status'] = $value} "sc-bytes"{ $output['sc-bytes'] = $value} "time-taken"{ $output['time-taken'] = $value} "cs-host"{ $output['cs-host'] = $value} "cs(Cookie)"{ $output['cs(Cookie)'] = $value} "cs(Referer)"{ $output['cs(Referer)'] = $value} "s-sitename"{ $output['s-sitename'] = $value} "s-computername"{ $output['s-computername'] = $value} "cs-bytes"{ $output['cs-bytes'] = $value} } } #$output $linewriter = $null #Write lines to new log file #Only call upon keys (from output hash) which correspond to desired $newfieldnames as specified in $newpath parameter. #Unwanted fields from old log are inherently dropped #Newly included fields not present in old log are inherently replaced by hypens foreach ($item in $newfieldnames) { $linewriter += $output[$item] $linewriter += " " } $linewriter |%{$_ -replace " $",""}| Out-File $outpath -Append -encoding Default } } } # usage example #.\\import-iislog-final.ps1 "C:\\Old Logs\\u_ex120218.log" "#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs-version cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status sc-bytes time-taken" "C:\\Revised Logs\\u_ex120218.log" #foreach ($log in (gci "c:\\Old Logs")) {.\\import-iislog-final.ps1 $log.fullname "#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs-version cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status sc-bytes time-taken" "C:\\Revised Logs\\$log"}
PowerShellCorpus/PoshCode/DriveSpace_1.format.ps1xml.ps1
DriveSpace_1.format.ps1xml.ps1
<?xml version="1.0" encoding="utf-8" ?> <Configuration> <ViewDefinitions> <View> <Name>SpaceGraph</Name> <ViewSelectedBy> <TypeName>System.Management.ManagementObject#root\\cimv2\\Win32_LogicalDisk</TypeName> </ViewSelectedBy> <WideControl> <WideEntries> <WideEntry> <WideItem> <ScriptBlock> $G, $Drive, $Width = "$([char]9608)", $_, ($Host.UI.RawUI.BufferSize.Width/2) # Write-Verbose "G: $G`nDrive: $Drive`nWidth:$Width`n$FreeBar`n$UsedBar" write-host $("[{0}] {1} " -f $drive.systemname.PadRight($longest.length),$drive.DeviceID) -NoNewline if($drive.Size) { $UsedSpace = $drive.Size - $drive.Freespace $FreeBar = $g * ($Width * [Math]::Round($drive.FreeSpace / $drive.Size, 2)) $UsedBar = $g * ($Width * [Math]::Round($UsedSpace / $drive.Size, 2)) write-host $UsedBar -ForegroundColor red -NoNewline write-host $FreeBar -ForegroundColor darkgreen -NoNewline write-host (" {0:P} free ({1:N} GB) {2}" -f ($drive.FreeSpace / $drive.Size), ($drive.FreeSpace/1GB), $drive.Description) -NoNewline } return $null </ScriptBlock> </WideItem> </WideEntry> </WideEntries> </WideControl> </View> </ViewDefinitions> </Configuration>
PowerShellCorpus/PoshCode/Get-Gender.ps1
Get-Gender.ps1
function get-gender { param([string]$name) if($name.Length -lt 2) { throw "You need at least two letters in the name" } $name = "$($name[0])".ToUpper() + $name.SubString(1).ToLower() $page = get-web "http://www.babynameaddicts.com/cgi-bin/search.pl?gender=ALL;searchfield=Names;origins=ALL;searchtype=matching;searchtext=$name" switch( $page.SelectNodes( "//table//font[ b/descendant::font[contains(text(),'$name')]]" ) | select -expand color ) { "fucshia" { "Female" } "#088dd0" { "Male" } } }
PowerShellCorpus/PoshCode/Convert-BounceToX_6.ps1
Convert-BounceToX_6.ps1
# $Id: Convert-BounceToX500.ps1 610 2010-11-16 00:39:19Z jon $ # $Revision: 610 $ #.Synopsis # Convert Bounce to X500 #.Description # Convert URL Encoded address in a Bounce message to an X500 address # that can be added as an alias to the mail-enabled object #.Parameter bounceAddress # URL Encoded bounce message address# #.Example # Convert-BounceToX500 "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com" #.Example # "IMCEAEX-_O=CONTOSO_OU=First+20Administrative+20Group_cn=Recipients_cn=john+5Fjacob+2Esmith@contoso.com"|Convert-BounceToX500 [CmdletBinding()] PARAM ( [Parameter(Mandatory=$true,ValueFromPipeline=$true)][string]$bounceAddress ) BEGIN { Add-Type -AssemblyName System.Web|Out-Null } PROCESS { if($_) {$bounceAddress = $_} $bounceAddress = $bounceAddress -Replace "%2B","%" # This is a urlEncoded "+" $bounceAddress = $bounceAddress -Replace "%3D","=" $bounceAddress = $bounceAddress -Replace "\\+","%" $bounceAddress = $bounceAddress -Replace "_O=","/O=" $bounceAddress = $bounceAddress -Replace "_OU=","/OU=" $bounceAddress = $bounceAddress -Replace "_CN=","/CN=" if([Web.HttpUtility]::UrlDecode($bounceAddress) -match "(/o=.*)@[\\w\\d.]+$"){$matches[1]} }
PowerShellCorpus/PoshCode/Reflection.ps1
Reflection.ps1
#requires -version 2.0 #History: # 1.0 - First public release (March 19, 2010) function Get-Type { <# .Synopsis Gets the types that are currenty loaded in .NET, or gets information about a specific type .Description Gets all of the loaded types, or gets the possible values for an enumerated type or value. .Example # Gets all loaded types Get-Type .Example # Gets types from System.Management.Automation Get-Type -Assembly ([PSObject].Assembly) .Example # Gets all of the possible values for the ApartmentState property [Threading.Thread]::CurrentThread.ApartmentState | Get-Type .Example # Gets all of the possible values for an apartmentstate [Threading.ApartmentState] | Get-Type #> [CmdletBinding(DefaultParameterSetName="Assembly")] param( # The assembly to collect types from [Parameter(ParameterSetName="Assembly", ValueFromPipeline=$true, Position=0)] [Reflection.Assembly[]]$Assembly , # The enumerated value to get all of the possibilties of [Parameter(ParameterSetName="Enum", ValueFromPipeline=$true, Position=0)] [Enum]$Enum , # Returns possible values if the Type was an enumerated value # Otherwise, returns the static members of the type [Parameter(ParameterSetName="Type", ValueFromPipeline=$true, Position=0)] [Type[]]$Type ) process { switch ($psCmdlet.ParameterSetName) { Assembly { if (! $psBoundParameters.Count -and ! $args.Count) { $Assembly = [AppDomain]::CurrentDomain.GetAssemblies() } foreach ($asm in $assembly) { if ($asm) { $asm.GetTypes() } } } Type { foreach ($t in $type) { if ($t.IsEnum) { [Enum]::GetValues($t) } else { $t | Get-Member -static } } } Enum { [Enum]::GetValues($enum.GetType()) } } } } function Add-Assembly { #.Synopsis # Load assemblies #.Description # Load assemblies from a folder #.Parameter Path # Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.). #.Parameter Passthru # Returns System.Runtime objects that represent the types that were added. By default, this cmdlet does not generate any output. # Aliased to -Types #.Parameter Recurse # Gets the items in the specified locations and in all child items of the locations. # # Recurse works only when the path points to a container that has child items, such as C:\\Windows or C:\\Windows\\*, and not when it points to items that do not have child items, such as C:\\Windows\\*.dll param( [Parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true, Position=0)] [Alias("PSPath")] [string[]]$Path = "." , [Alias("Types")] [Switch]$Passthru , [Switch]$Recurse ) process { foreach($file in Get-ChildItem $Path -Filter *.dll -Recurse:$Recurse) { Add-Type -Path $file.FullName -Passthru:$Passthru | Where { $_.IsPublic } } } } function Get-Assembly { <# .Synopsis Get a list of assemblies available in the runspace .Description Returns AssemblyInfo for all the assemblies available in the current AppDomain, optionally filtered by partial name match .Parameter Name A regex to filter the returned assemblies. This is matched against the .FullName of the assembly. #> param( [Parameter(ValueFromPipeline=$true, Position=0)] [string]$Name = '' ) process { [appdomain]::CurrentDomain.GetAssemblies() |? {$_.FullName -match $Name} } } Set-Alias gasm Get-Assembly function Get-Constructor { <# .Synopsis Get a list of constructors for a type .Description Returns AssemblyInfo for all the assemblies available in the current AppDomain, optionally filtered by partial name match .Parameter Name A regex to filter the returned assemblies. This is matched against the .FullName of the assembly. #> param( [Parameter(ValueFromPipeline=$true, Position=0)] [Type]$type ) process { $type.GetConstructors() | Format-Table @{ l="$($type.Name) Constructors" e={ ($_.GetParameters() | % { $_.ToString() }) -Join ", " } } } } Set-Alias gctor Get-Constructor
PowerShellCorpus/PoshCode/LetterDiamondOneliner v_1.ps1
LetterDiamondOneliner v_1.ps1
&{param([char]$c)[int]$s=65;$p=$c-$s;$r=,(' '*$p+[char]$s);$r+=@(do{"{0,$p} {1}{0}"-f([char]++$s),(' '*$f++)}until(!--$p));$r;$r[-2..-99]}Z # trimmed 130 chars w/o arg &{param([char]$c)$p=$c-($s=65);$r=,(' '*$p+[char]$s);do{$r+="{0,$p} {1}{0}"-f([char]++$s),(' '*$f++)}until(!--$p);$r;$r[-2..-99]}J
PowerShellCorpus/PoshCode/Workstation_users Matrix.ps1
Workstation_users Matrix.ps1
#################################################################### # #Script will list all selected workstations and currently logged on user. #Results will be output to a file. A query can be placed on a previous search. #Currently script only works when run directly from a DC #Author: Adam Liquorish #Date: 15/10/2011 #################################################################### $username=read-host "Enter username to query corresponding computer" $infromfile=read-host "Would you like to just find a user-computer in an existing file.YES/NO" if($infromfile -eq "No") { $path=read-host "Enter path to save all files ie.c:\\Temp\\" $LDAPPath=read-host "Specify LDAP path ie ou=test,dc=domain,dc=com" $pathcomputers=$path+"computers.txt" $pathcompuserfull=$path+"compuserlistfull.txt" $pathresults=$path+"results.txt" #Get computers from a defined LDAP Path $dict=@() $computers=foreach(comp in (get-adcomputer -filter * -searchbase "$LDAPPath")){$comp.name} $computers>$pathcomputers write-host "List of computers scanned has been ouput to $pathcomputers" #Use list of computers to conduct a WMI lookup of logged on users foreach($comp in $computers) { $cs-gwmi win32_computersystem -comp $comp $dict+=@{$cs.username=$cs.name} } $dict>$pathcompuserfull write-host "user to computerlist has been ouput to $pathcompuserfull" #Lookup user to computer list and find specified user $results=foreach($user in $dict) { if($user.keys -like "*$username") { new-object -typename psobject -property @{user=$user.keys;computer=$user.values} } } $results>$pathresults write-host "Results output to $pathresults" write-host "Results found are.." -foregroundcolor blue $results } else { #Input user to computer list from a file and lookup specified user. $inpath=read-host "enter input folder path for file. Folder must contain a file called compuserlistfull.txt" $pathcompuserfullin=$inpath+"compuserlistfull.txt" $dict=@() $dict=get-content $pathcompuserfullin $results=foreach($user in $dict) { if($user -like "*$username*") { new-object -typename psobject -property @{user=$user} } } $results }